TweetFollow Us on Twitter

VBL with Mach1
Volume Number:2
Issue Number:6
Column Tag:Threaded Code

Install a VBL Task with Mach1

By Jörg Langowski, EMBL, c/o I.L.L., Grenoble, Cedex, France, Editorial Board

Installing a Forth VBL Task - another CRT saver

Bob Denny's Article on vertical blanking tasks (MT V1#9) has been a constant challenge to me ever since it appeared. It seemed that there are certain things that one just could not do in Forth - the installation of an independently running task in the system heap being one of them. After all, where do you put the Forth runtime support when you leave Forth and want the task to run?

Another thing that would be difficult to do in Forth, for example, would be a desk accessory. In general, any tasks that will run independently and concurrently in the Mac operating system are almost impossible to handle with a language that needs a runtime interpreter to work.

After Mach1 came in, one could sort of see the light at the end of the tunnel. Here was a Forth that created real 68000 machine language output, and in principle its code could run anywhere without ever needing any runtime package. Maybe this makes some of the 'impossible' things that I mentioned less impossible.

Still, Mach1 does contain runtime support. Multitasking is the most important one, but by no means all, even the LOOP of a DO...LOOP structure is compiled as a JSR to a kernel routine.

The first rule for creating programs that are not only 'stand-alone applications', but self-contained code, is to avoid all references to kernel routines from within the program. This general statement will hold for any Forth system; given a Forth assembler, enough patience and a good set of macro definitions one will always be able to write code that is self-contained and won't need the runtime interpreter (e.g. using inline macros similar to the ones defined in MT V1#9, Forth column). Mach1 code doesn't contain too many references to its kernel anyway, so it should be much easier to accomplish what we try to do.

Our problem is to create a piece of code that does exactly what Bob Denny's CRT saver does: intercepts the GetNextEvent trap and updates a counter to keep track of when the last non-null event happened, and a VBL task that looks at that counter and blanks the screen whenever a certain time has elapsed after the last non-null event. Furthermore, the GetNextEvent intercept routine will repaint the screen after it has been blanked when a new non-null event occurs.

For the purpose of illustration, Listing 1 shows some Mach1 code that installs a very similar screen blanker as a background task under Mach1. This is the simple way to do it and will of course run only within the Mach1 system.

Short explanation of the program: the blankout routine opens a new GrafPort and paints its portRect (default size: whole screen) with the default pattern (black).

This routine is installed into one background task, CRTsaver, that checks continuously whether the time after the last 'relevant' event is larger than a preset value and blanks the screen if it is; thereafter, it unblanks the screen when a new event is received. The task's infinite loop contains a PAUSE to give control back to the scheduler.

The second background task, eventmonitor, checks for events by calling EventAvail. Whenever a 'relevant' event occurs, it is intercepted by this routine and the event tracking counter last.action updated.

Try and install these routines on your Mach1 system, and you'll have a fine CRT saver. Note that the multitasking system is not running while the screen is dark; I did this to keep it completely blank. You can insert a PAUSE in the event waiting loop of do.blank; in that case, all tasks will keep running, but you'll have a small white rectangle on the black screen (the cursor which is still active).

Installing the CRT saver as an independent VBL task

The example in Listing 1 contains many things that will just not work independently of the Mach1 runtime package:

- background tasks;

- variable definitions, which are kept separate from the main code block;

- JSR references to the kernel are not contained here, but could be easily in other tasks (as mentioned, a simple DO...LOOP);

- there are certain trap calls that are incompatible with the VBL task mechanism; as mentioned in IM, trap routines that move, purge or reallocate memory may not be called from a VBL task, the reason being that if the task happens to interrupt the memory manager and then calls the memory manager itself, very strange effects may result.

The list of 'forbidden' routines (IM, Addison-Wesley Vol. III in the appendix) is impressive, and EventAvail is one of them. The Quickdraw calls in blankout are also forbidden.

-The Mach1 data stack is maintained through the A6 register. In self-contained code, this register will have to be set up to point to a local stack area when the code is first entered. Also, for safety reasons the complete register file should be saved on entering and restored on exit.

An impressive list of restrictions; however, the example in Listing 2 shows that it is not that bad after all.

First, we may not use variables anymore. Any variable storage space should be defined within our piece of code. This can be done using create or header. References to variables thus defined must be through ['] (in colon definitions) or ' (in direct execution). If a create variable is referenced by name in a colon definition, a JSR to its code is compiled. create's own code again references the kernel and therefore cannot be used for self-contained programs.

If you use variables in this way, you can't call them directly by name after storing something there, because the create execution code will be overwritten. You'll always have to 'tick' their addresses on the stack.

Second, the screen blanker has to be rewritten; we store the black pattern into the screen area directly instead of calling Quickdraw routines, which may not be used. This is a little slower (Quickdraw really deserves its name), making the blanking less 'instantaneous'. Also, we may not use a DO...LOOP (reference to the kernel), so the blanking loop is implemented using BEGIN...UNTIL, a little more cumbersome, but still readable; and self-contained. See the definition of blankout in Listing 2. Note that HideCursor is not in the list of 'forbidden' traps.

Third, we cannot intercept events from within the VBL task using EventAvail. This is the reason why in Bob Denny's example from V1#9 a GetNextEvent filter procedure was used. We'll have to do the same thing.

The GNEFilter procedure

A short review of the method to install a GetNextEvent hook:

There is an (undocumented) system global at $29A which contains a location that GetNextEvent jumps to right after removing an Event from the queue. Through this hook, one can install a routine that will be called whenever GetNextEvent receives an event. A pointer to the event record is contained in A1. At the end of this routine, of course, one will have to jump to the location that was contained in $29A.

The GNE hook routine that we are going to install will, each time a non-null event is received, update the last.action counter with the current number of system ticks and repaint the screen if it was blank. In order to keep the definition short, we call traps directly instead of going through the Mach1 'glue' mechanism.

The GNEintfc routine saves most of the registers and restores them after exiting. A local stack (100 bytes) is set up for the Mach1 A6 stack pointer. Some inline assembly code is used to move arguments between the A7 and A6 stacks, and to setup a jump vector at the end of the routine.

The vertical blanking task

one.run is the heart of the vertical blanking task that will be the other part of the CRT saver. It checks whether one minute has passed since the last non-null event and blanks the screen in that case. Furthermore, it then sets a global flag, dark, to indicate to GNEintfc that the screen is dark. At the end of each run, screen blanked or not, the task reschedules itself by resetting the counter in its VBL queue element. Registers are saved and restored, and the routine also uses the local stack. (Note: writing this I realize that in the case that the GetNextEvent filter is interrupted by the vertical blanking and one.run is run during that same interrupt, it will use the same local stack. This might create a problem; so far the CRT saver has not crashed on me. You might think of duplicating the stack area so that the two routines use independent stacks.)

Installation of the CRT saver in the system heap

Of course, the code that we defined so far is local to the Mach1 system and will disappear as soon as Mach1 is exited. If we happened to install the CRT saver before, too bad! Most certainly the system won't survive this kind of abuse. Therefore it remains to copy the routines to a safe place in memory; we'll move them to the system heap before installing. The code that we have to copy is marked by the two headers START and END. The word install.blanker gets a pointer to a chunk of system heap (END - START) bytes long and copies the code to it. The offset is placed into the variable (yes, here we may use a good old variable) blockoffset. All references to the copied routines during installation (for initialization of flags and counters, and for the address passed to the VBL queue element) are made through the original addresses offset by this value.

After the installation (install.blanker and install.GNEfilter), you may leave Mach1, wait one minute and see your screen go dark. Any keypress or mouseclick will make reappear whatever was there.

Turnkeying the CRT saver installer

The word CRTsaver installs the tasks and quits Mach1. This word is used for turnkeying the program:

turnkey CRTsaver CRT

will create an application file CRT, 19K long (Mach1 runtime overhead of 16K) which installs the CRT saver.

Listing 1: CRT saver background task to run in the Mach1 system
( CRT saver task, © 1986 JL for MacTutor)
only forth definitions
also assembler also mac

hex
904 constant currentA5
9EE constant grayRgn
16A constant Ticks
 74 constant screenbits
 10 constant portrect

decimal

( first define port structure )
header screenport
     2 allot ( device )
    14 allot ( bitmap )
     8 allot ( portrect   )
    84 allot ( remaining bytes )


( *** now define background task that does the blanking *** )

variable last.action
variable max.ticks
3600 max.ticks !  ( 1 minute in ticks )

header myevents
    2 allot ( code )
    4 allot ( message )
    4 allot ( when )
    4 allot ( where )
    2 allot ( modifiers )

: relevant.action
    138 ( disk + key + mouse ) 
    ['] myevents call EventAvail
;

: redraw
    call drawmenubar
    call frontWindow
    grayRgn @ call paintBehind
    call showcursor
;

: blankout
    call hidecursor
    ['] screenport call openport
    ['] screenport portrect + call paintrect
    BEGIN relevant.action UNTIL
    ticks @ last.action !
    ['] screenport call setport
    redraw 
;

: monitor.events
    activate
    BEGIN
    PAUSE
    relevant.action 
        IF ticks @ last.action ! THEN
    AGAIN
;

: do.blank
    activate
    BEGIN
    PAUSE
    ticks @ last.action @ - max.ticks @ >
        IF blankout THEN
    AGAIN
;

400 1000 background CRTsaver
CRTsaver build
400 1000 background eventmonitor
eventmonitor build

: saver.start
    ticks @ last.action !
    eventmonitor monitor.events
    CRTsaver do.blank
;

Listing 2: CRT saver, written in Forth, for installation into system 
heap and Mach1 - independent execution

( CRT saver task for installation into VBLTask queue, © 1986 JL for MacTutor 
)
only forth definitions
also assembler also mac

hex
29A constant JGNEFilter
824 constant screenbase
904 constant currentA5
9EE constant grayRgn
16A constant Ticks
 74 constant screenbits
 10 constant portrect
FFFFFFFF constant minusone

.TRAP   _drawmenubar    $A937
.TRAP   _frontwindow    $A924
.TRAP   _paintbehind    $A90D
.TRAP   _newptr,sys     $A51E
.TRAP   _showcursor     $A853

CODE save.regs
    MOVE.W  SR,-(A7)
    MOVEM.L A1-A6/D0-D7,-(A7)
    RTS
END-CODE    MACH

CODE restore.regs
    MOVEM.L (A7)+,A1-A6/D0-D7
    MOVE.W  (A7)+,SR
    RTS
END-CODE    MACH

CODE getA1
    MOVE.L  A1,-(A6)
    RTS
END-CODE    MACH

decimal

header START

( *** we need a local stack after the relocation *** )    
 
header local.stack 100 allot

CODE setup.local.stack
    LEA -8(PC),A6 ( stack grows downward from here )
    RTS
END-CODE

( *** define port structure + some global variables *** )

header screenport
     2 allot ( device )
    14 allot ( bitmap )
     8 allot ( portrect   )
    84 allot ( remaining bytes )

header myevents
    2 allot ( code )
    4 allot ( message )
    4 allot ( when )
    4 allot ( where )
    2 allot ( modifiers )

( *** VBL queue element to be installed *** )

header VBLqelem
    4 allot ( qLink )
    2 allot ( qType )
    4 allot ( vblAddr )
    2 allot ( vblCount )
    2 allot ( vblPhase )

 1 constant vType
 4 constant qType
 6 constant vblAddr
10 constant vblCount
12 constant vblPhase
     
( *** GetNextEvent filter proc definitions *** )

header SavedJGNEFilter 4 allot
header dark  4 allot     
header last.action 4 allot
header max.ticks   4 allot
   3600 ' max.ticks !  ( 1 min in ticks )


: GNEIntfc
    save.regs
    setup.local.stack
    
    getA1 w@ ( event received? )
      IF ticks @ ['] last.action !
        ['] dark @
        IF 
            0 ['] dark !
            _drawmenubar
            CLR.L    -(A7)
            _frontwindow 
            grayrgn @
            MOVE.L   (A6)+,-(A7)
            _paintbehind
            _showcursor
        THEN
      THEN

    ['] SavedJGNEFilter @
    MOVE.L  (A6)+,A0
    restore.regs
    JMP     (A0)
;
    

( *** definitions for VBLtask that does the blanking *** )

: blankout 
    call hidecursor
    screenbase @ 21888 + 
    screenbase @
    BEGIN
        minusone over !
        4 + 2dup < 
    UNTIL 2drop 
    1 ['] dark !
;

: one.run
    save.regs
    setup.local.stack
    ticks @ ['] last.action @ - ['] max.ticks @ >
    ['] dark @ 0=
    AND
    IF  blankout  THEN
    60 ['] VBLqelem vblCount + w! ( reschedule )
    restore.regs
;

header END


( *** install CRT blanker task 'one.run' into VBL queue *** )

variable blockoffset

: get.sys.block  
    ['] end ['] start - 
    MOVE.L (A6)+,D0
    _newptr,sys ( get memory block in system heap )
    MOVE.L A0,-(A6)
;
    
: install.blanker   { | pointer offset -- }
    get.sys.block   -> pointer
    pointer IF
        0 ['] dark !
        ticks @ ['] last.action !
        pointer ['] start -  -> offset
        offset blockoffset !
        ['] start pointer ['] end ['] start - cmove
    ( now make all the moves on the relocated block )
        ['] VBLqelem offset +
        dup qtype + vtype swap w!
        dup vblAddr + ['] one.run offset + swap !
        dup vblCount + 60 swap w!
        dup vblPhase + 5 swap w!
        call Vinstall drop
    ELSE ." Not enough system heap for installation." cr
    THEN
;

: install.GNEfilter
    JGNEFilter @ ['] SavedJGNEFilter blockoffset @ + !
    ['] GNEIntfc blockoffset @ + JGNEFilter !
;

: remove.blanker
    ['] VBLqelem blockoffset @ + call Vremove drop
;

: remove.GNEfilter
    ['] SavedJGNEFilter blockoffset @ +  JGNEFilter ! 
;

: CRTsaver 
    install.blanker
    install.GNEfilter
    bye
;
 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Latest Forum Discussions

See All

Fresh From the Land Down Under – The Tou...
After a two week hiatus, we are back with another episode of The TouchArcade Show. Eli is fresh off his trip to Australia, which according to him is very similar to America but more upside down. Also kangaroos all over. Other topics this week... | Read more »
TouchArcade Game of the Week: ‘Dungeon T...
I’m a little conflicted on this week’s pick. Pretty much everyone knows the legend of Dungeon Raid, the match-3 RPG hybrid that took the world by storm way back in 2011. Everyone at the time was obsessed with it, but for whatever reason the... | Read more »
SwitchArcade Round-Up: Reviews Featuring...
Hello gentle readers, and welcome to the SwitchArcade Round-Up for July 19th, 2024. In today’s article, we finish up the week with the unusual appearance of a review. I’ve spent my time with Hot Lap Racing, and I’m ready to give my verdict. After... | Read more »
Draknek Interview: Alan Hazelden on Thin...
Ever since I played my first release from Draknek & Friends years ago, I knew I wanted to sit down with Alan Hazelden and chat about the team, puzzle games, and much more. | Read more »
The Latest ‘Marvel Snap’ OTA Update Buff...
I don’t know about all of you, my fellow Marvel Snap (Free) players, but these days when I see a balance update I find myself clenching my… teeth and bracing for the impact to my decks. They’ve been pretty spicy of late, after all. How will the... | Read more »
‘Honkai Star Rail’ Version 2.4 “Finest D...
HoYoverse just announced the Honkai Star Rail (Free) version 2.4 “Finest Duel Under the Pristine Blue" update alongside a surprising collaboration. Honkai Star Rail 2.4 follows the 2.3 “Farewell, Penacony" update. Read about that here. | Read more »
‘Vampire Survivors+’ on Apple Arcade Wil...
Earlier this month, Apple revealed that poncle’s excellent Vampire Survivors+ () would be heading to Apple Arcade as a new App Store Great. I reached out to poncle to check in on the DLC for Vampire Survivors+ because only the first two DLCs were... | Read more »
Homerun Clash 2: Legends Derby opens for...
Since launching in 2018, Homerun Clash has performed admirably for HAEGIN, racking up 12 million players all eager to prove they could be the next baseball champions. Well, the title will soon be up for grabs again, as Homerun Clash 2: Legends... | Read more »
‘Neverness to Everness’ Is a Free To Pla...
Perfect World Games and Hotta Studio (Tower of Fantasy) announced a new free to play open world RPG in the form of Neverness to Everness a few days ago (via Gematsu). Neverness to Everness has an urban setting, and the two reveal trailers for it... | Read more »
Meditative Puzzler ‘Ouros’ Coming to iOS...
Ouros is a mediative puzzle game from developer Michael Kamm that launched on PC just a couple of months back, and today it has been revealed that the title is now heading to iOS and Android devices next month. Which is good news I say because this... | Read more »

Price Scanner via MacPrices.net

Amazon is still selling 16-inch MacBook Pros...
Prime Day in July is over, but Amazon is still selling 16-inch Apple MacBook Pros for $500-$600 off MSRP. Shipping is free. These are the lowest prices available this weekend for new 16″ Apple... Read more
Walmart continues to sell clearance 13-inch M...
Walmart continues to offer clearance, but new, Apple 13″ M1 MacBook Airs (8GB RAM, 256GB SSD) online for $699, $300 off original MSRP, in Space Gray, Silver, and Gold colors. These are new MacBooks... Read more
Apple is offering steep discounts, up to $600...
Apple has standard-configuration 16″ M3 Max MacBook Pros available, Certified Refurbished, starting at $2969 and ranging up to $600 off MSRP. Each model features a new outer case, shipping is free,... Read more
Save up to $480 with these 14-inch M3 Pro/M3...
Apple has 14″ M3 Pro and M3 Max MacBook Pros in stock today and available, Certified Refurbished, starting at $1699 and ranging up to $480 off MSRP. Each model features a new outer case, shipping is... Read more
Amazon has clearance 9th-generation WiFi iPad...
Amazon has Apple’s 9th generation 10.2″ WiFi iPads on sale for $80-$100 off MSRP, starting only $249. Their prices are the lowest available for new iPads anywhere: – 10″ 64GB WiFi iPad (Space Gray or... Read more
Apple is offering a $50 discount on 2nd-gener...
Apple has Certified Refurbished White and Midnight HomePods available for $249, Certified Refurbished. That’s $50 off MSRP and the lowest price currently available for a full-size Apple HomePod today... Read more
The latest MacBook Pro sale at Amazon: 16-inc...
Amazon is offering instant discounts on 16″ M3 Pro and 16″ M3 Max MacBook Pros ranging up to $400 off MSRP as part of their early July 4th sale. Shipping is free. These are the lowest prices... Read more
14-inch M3 Pro MacBook Pros with 36GB of RAM...
B&H Photo has 14″ M3 Pro MacBook Pros with 36GB of RAM and 512GB or 1TB SSDs in stock today and on sale for $200 off Apple’s MSRP, each including free 1-2 day shipping: – 14″ M3 Pro MacBook Pro (... Read more
14-inch M3 MacBook Pros with 16GB of RAM on s...
B&H Photo has 14″ M3 MacBook Pros with 16GB of RAM and 512GB or 1TB SSDs in stock today and on sale for $150-$200 off Apple’s MSRP, each including free 1-2 day shipping: – 14″ M3 MacBook Pro (... Read more
Amazon is offering $170-$200 discounts on new...
Amazon is offering a $170-$200 discount on every configuration and color of Apple’s M3-powered 15″ MacBook Airs. Prices start at $1129 for models with 8GB of RAM and 256GB of storage: – 15″ M3... Read more

Jobs Board

*Apple* Systems Engineer - Chenega Corporati...
…LLC,** a **Chenega Professional Services** ' company, is looking for a ** Apple Systems Engineer** to support the Information Technology Operations and Maintenance Read more
Solutions Engineer - *Apple* - SHI (United...
**Job Summary** An Apple Solution Engineer's primary role is tosupport SHI customers in their efforts to select, deploy, and manage Apple operating systems and Read more
*Apple* / Mac Administrator - JAMF Pro - Ame...
Amentum is seeking an ** Apple / Mac Administrator - JAMF Pro** to provide support with the Apple Ecosystem to include hardware and software to join our team and Read more
Operations Associate - *Apple* Blossom Mall...
Operations Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
Cashier - *Apple* Blossom Mall - JCPenney (...
Cashier - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Blossom Mall Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.