SaveKey Framework

Previous topic - Next topic

0 Members and 1 Guest are viewing this topic.

Andrew Davie

Here's a 'framework' for installation of SaveKey support in CDFJ games. This is from functional code in GridLock, and appears to be reasonably elegant.

The SaveKey communication is done in the .asm file(s). Essentially, at reset/boot, the code checks for a SaveKey installed in the right joystick port. If found, the code then checks to see if the SaveKey 'slot' (the area assigned to the game) is valid (via an ID byte). If not present, then the slot is initialised.

The contents of the SaveKey are read into zero page variables, and then immediately passed to the ARM/C code (through shared RAM) for any processing that is needed. At that point, the ARM/C SystemReset() code is called and the game can begin.

During gameplay, the .asm code cyclically rolls through the shared/RAM SaveKey block to see if there are any changed values (as compared with the local zero page copy). If there is a change, then the changed byte is written to the SaveKey. This allows reasonably prompt updates to the SaveKey content with very little time penalty (relatively - just one SaveKey write).

OK, here we go.

First we need to include the attached files as part of the .asm code.  The 'savekey.asm' needs to be included in the middle of the 6502 source, anywhere in the address space with other code.  The other files 'i2c_v2_3.inc' and 'cdfdriver20190317.bin' need to sit in the root directory of your project, with the source code (if you have things organised that way).  Anyway, somewhere they can be included/linked.

So, let's start with the .asm file zero page definitions...

        SEG.U VARS
        ORG $80

kernel                 ds 1       ; 0 copyright, 1 menu, 2 game, 3 stats
currentKernel          ds 1
scanSK                 ds 1

#if __ENABLE_SAVEKEY
SAVEKEY_SIZE = ((100+7)/8)

    ; Local (zp) vars where SK is initially read to on startup
    ; These are transferred to ARM/C via transfer to "RAM" variables via DSPTR setup and then DSWRITEs

SAVEKEY_START

SAVEKEY_IDENT          ds 1
SAVEKEY_PERFECT        ds SAVEKEY_SIZE
SAVEKEY_UNLOCKED       ds SAVEKEY_SIZE
SAVEKEY_SOLVED         ds SAVEKEY_SIZE
SAVEKEY_LAST           ds 1
SAVEKEY_USED_SOLVES    ds 1
SAVEKEY_ENABLE_ICC     ds 1
SAVEKEY_SEEN_TROPHY    ds 1
SAVEKEY_TOTAL_SOLVES   ds 1
SAVEKEY_COUNT          ds 2

SAVEKEY_END

    ; following must be contiguous to above...
    ; it is NOT stored on the SaveKey, but IS passed to the ARM/C code

SAVEKEY_RESET          ds 1            ; 0 = not reset, else SK was initialised
#endif


        echo "----",($00FE - *) , "bytes of RAM left (space reserved for 2 byte stack)"


The above example is from GriLock - you see I have quite a lot of variables there. You will, of course, add/delete variables for your game. The essential ones are the labels (not variables, just markers) SK_START and SK_END - these must bracket ALL variables which actually reside on the SaveKey for the code to work.

So these are the local zero page RAM copy of the contents of the SaveKey slot for your game. Now the slot is 'allocated' by a maintainer (historically Albert Yarusso at AtariAge), but you may have some difficulty with prompt responses to requests; the allocation list is, I understand, being updated/reviewed and Al is of course a busy guy.  There are some 'slots' you can use for testing/development until you have a final allocation.

So, a 'slot' is basically just 64 bytes in the SaveKey persistent memory, where your game data is stored. You can allocate more than one slot to your game - but that would be discouraged; many games need to share the address space and we don't want overlap. So, try and keep persistent variables to 64 bytes if youcan.

Anyway, a slot is identified both by ordinal number, and address.  The SaveKey Allocation ListSaveKey allocation list (as I write) appears to be somewhat neglected (last updated April 14 2024). Anyway, with this sample code you can find the SaveKey address in 'savekey.asm' at the top; the labels you change are:

; Note: $3000 is scratchpad on SaveKey - you need to ask Albert Yarusso for a slot

SAVEKEY_ADR         = $3000                     ; slot address
_SK_VERSION_ID      = 0x1                       ; unique "version" ID byte for slot

_SK_VERSION_ID a unique value (0-255) identifying your SK slot as initialised. Note, it is possible but unlikely when you put a new SaveKey in for the first time that the value on the SaveKey is already this value, in which case the SaveKey autodetect of init status will fail and the SaveKey will remain uninitialised with incorrect slot content. Unfortunate, but can be fixed by holding down RESET when powering on which will FORCE a slot initialise.
Suggestion: start at 1, and increment every time you decide your SK needs to store something new (i.e., adding another persistent value type).  Reasons for this -- the code on boot checks for this ident value and if the slot does not contain it, then the code will initialise the SK slot automatically. This means that all you need to do if you change the variables you load/save (in terms of if you add a new variable or delete a variable), then you just change the _SK_VERSION_ID to one more and next time your run then the SK will be reset/initialised properly and you won't run into problems with your playtesters (or you!) accidentally loading bad values on boot (i.e., values from previous variable stomping on new variable value). In other words, the mapping from SK data to the zp data will be correct, not offset.

SAVEKEY_ADR is the SaveKey memory address of the slot you are using. In the attached, it's set to $3000, which is a scratchpad area. You need to write to Al and get an allocation for your game when it's nearing completion. Under no circumstances should you use a slot already allocated to another game!

OK, let's look at the boot process; where the 6507 jumps to its reset vector and our program actually starts. Here's what I have...

InitSystem
                    cld


        ; Remarkable system clear by Omegamatrix
        ; SP=$FF, X=A=0

.clear_machine      ldx #$A                ; ASL opcode = $0A
                    inx
                    txs
                    pha
                    bne .clear_machine+1    ; jump between operator and operand to do ASL

                    stx SETMODE            ; <-- x=0  "Fast Fetch" enable
                    ;stx kernel              ; "copyright" ==0 by sys clear

#if __ENABLE_SAVEKEY
                    jsr saveKey
#endif

                    ldy #_FN_SYSTEM_RESET
                    jsr CallArmCode




You can see I have a define __ENABLE_SAVEKEY which lets me conditional assemble the SaveKey functionality. You can discard that if you want. The essential bit here is that immediately after we initialise the memory and get the '2600 into a known state, we call the SaveKey code ('saveKey') which is at the top of 'savekey.asm'

Let's look at the basic function of that...

;-------------------------------------------------------------------------------

saveKey             SUBROUTINE

    ; Detect if a SaveKey is present, and populate the zero page variables with
    ; the slot contents (or 0 if no SaveKey).

                    ldx #FASTOFF
                    stx SETMODE                 ; fast fetch OFF for savekey code compatibility

                    jsr ReadSaveKey

    ; Copy the zero page variables to the Display RAM mirror variables

                    lda #>_DS_SK
                    sta DSPTR
                    lda #<_DS_SK
                    sta DSPTR

                    ldx #0
.sendSK             lda SAVEKEY_START,x
                    sta DSWRITE
                    inx
                    cpx #SAVEKEY_BYTES + 1      ; +1 for SAVEKEY_RESET status var for ARM/C
                    bcc .sendSK
 

    ; Give the ARM/C code a chance to do any post-SaveKey-load initialisation

                    ldx #>_DS_TO_ARM
                    stx DSPTR
                    ldx #<_DS_TO_ARM
                    stx DSPTR

                    lda #_FN_LOAD_SAVEKEY
                    sta DSWRITE                 ; --> _RUN_FUNC (OS or VB)

                    jsr runARM

                    lda #FASTON
                    sta SETMODE                 ; "Fast Fetch" enable for rest of game

                    rts

The crux of this is that it calls ReadSaveKey, which does the actual communication with the SaveKey. It does the optional initialisation and loads the content of the SaveKey slot into the zero page variable block. Once it returns we know a few things...

1) The SaveKey slot, if present, is guaranteed to be compatible with the game (i.e., it's valid)
2) If the slot was invalid it was initialised to a blank state
3) The zero page variables (between SK_START and SK_END) have been filled with content from the slot
4) The variable SAVEKEY_RESET is set to 1 if the SaveKey slot was not valid, and has been initialised

Next up, the zero page block is copied to the RAM transfer area (that is, the RAM that the C code can see). This is done using DSPTR transfer -- essentially the C code will access via RAM[addr]. But we make all that easy - keep reading.

So here's my definition of that RAM transfer area ("Display Data"). Note that because the variables are prefixed with an underscore, they will be visible to the ARM/C code.

;===============================================================================
; Display Data
;----------------------------------------
;   4K of RAM shared between the 6507 and ARM.
;
;   NOTE: anything prefixed with _ ends up in main/defines_from_dasm_for_c.h
;         so that the C code will have the same values as the 6507 code
;===============================================================================

    SEG.U DISPLAYDATA
    ORG $0000

#if __ENABLE_SAVEKEY
_DS_SK

_SK_ID              ds 1
_SK_PER             ds SAVEKEY_SIZE
_SK_UNL             ds SAVEKEY_SIZE
_SK_SLV             ds SAVEKEY_SIZE
_SK_LAST            ds 1
_SK_USED_SOLVES     ds 1
_SK_ENABLE_ICC      ds 1
_SK_SEEN_TROPHY     ds 1
_SK_TOTAL_SOLVES    ds 1
_SK_COUNT           ds 2

_SK_RESET           ds 1
#endif

_DS_TO_ARM

_RUN_FUNC           ds 1        ; function to run
_SWCHA              ds 1        ; joystick directions to ARM code
_SWCHB              ds 1        ; console switches to ARM code
_INPT4              ds 1        ; left firebutton state to ARM code
;_INPT5              ds 1        ; right firebutton state to ARM code

;_HIGHSCORE          ds 3


_DS_FROM_ARM
; whatever your game needs here...


So as noted, we now have an effective mirror of the SaveKey data. There's the original data on the SaveKey, of course. And there's the zero page copy of that which has just been read off the SaveKey, and now there's also the mirror in the 'shared' RAM that the ARM code can see. This is handy because the C code doesn't need to EVER tell the asm code to write SaveKey stuff - it's automatic. That's achieved by the assembler code checking (only one byte per frame) the zero page data against the mirror data - IFF the data has changed, then it knows to write the changed byte to the SaveKey. All the C code needs to do is change the value in the mirror location. Thus in C, 'RAM[_SK_COUNT] = count;' is sufficient to update the SaveKey itself. Very elegant.

OK, back to the startup code above - after the zero page copy of the SaveKey data is sent to the shared RAM (via DSWRITE), we give the C code an opportunity to do something about it on startup. That's where we call 'jsr runARM' in the code above. We've setup the function ID and call the ARM code (here's how that's done...)


runARM              ldy #$FF                        ; FF = Run ARM code w/out digital audio interrupts
                    sty CALLFN                      ; runs main() in the C code (6507 is $EA-locked)

    ; EA-wait resumes here

                    rts


On the C side of things, here's what main() does in order to vector to the correct function handler (in this case the function being called is _FN_LOAD_SAVEKEY)

static void (*const runFunc[])() = {

    SystemReset,      // 0 _FN_SYSTEM_RESET
    MenuOverscan,      // 1 _FN_MENU_OS
    MenuVerticalBlank, // 2 _FN_MENU_VB
    SchedulerMenu,    // 3 _FN_MENU_IDLE
    initNextLife,      // 4 _FN_INIT_GAME_KERNEL
    GameOverscan,      // 5 _FN_GAME_OS
    GameVerticalBlank, // 6 _FN_GAME_VB
    GameIdle,          // 7 _FN_GAME_IDLE
    loadSaveKey,      // 8 _FN_LOAD_SAVEKEY
};

int main() { // <-- 6507/ARM interfaced here!

    (*runFunc[RAM[_RUN_FUNC]])();
    return 0;
}


That's a neat/elegant use of a table of function pointers. Essentially, it's just retrieving the function number we wrote to the shared RAM via DSWRITE, and using it as an index to the function table. In this case, we're calling 'loadSaveKey()' which is this...

void loadSaveKey() {
    saveKeyEnableICC = RAM[_SK_ENABLE_ICC];

    // for (int i = 0; i < SAVEKEY_SIZE; i++) {
    //    saveKeyPerfect[i] = RAM[_SK_PER + i];
    //    saveKeyUnlocked[i] = RAM[_SK_UNL + i];
    //    saveKeySolved[i] = RAM[_SK_SLV + i];
    // }

    // I maintain a "# times played" counter...
    // increment counter

    int count = RAM[_SK_COUNT] + 256 * RAM[_SK_COUNT + 1] + 1;
    RAM[_SK_COUNT] = count;
    RAM[_SK_COUNT + 1] = count >> 8;
}

Note that the C code can detect if the SaveKey  was reset by looking at RAM[_SK_RESET] being non-zero, and if the SaveKey contains valid data by RAM[_SK_ID] == _SK_VERSION_ID.

There's an example there of reading data from the mirrored SaveKey data (RAM[_SK_EBABLE_ICC]) to a local variable, and an example of updating/writing the SaveKey data (I have a 16 bit counter which increments every time you boot the machine).  As you see, all you do is write the value; the SaveKey gets updated automatically.

So, how does that automatic update happen? It's in the asm code which continually polls the display data mirror RAM to compare changes against the zero page copy. That's the asm function 'scanAndUpdateSaveKey' in savekey.asm which needs to be called once per frame (basically in overscan or vertical blank). The code cycles through the savekey variables, checking one per frame for a change. If there's a change, then the changed value is written to the physical SaveKey.


So, that's about it. It seems more complex than it is. There's just a few things to organise but once it's all setup it works beautifully. One note: don't trust all the comments; some of the code isn't mine, and things often change after comments are written. Feel free to ask any questions; I'll be happy to try and help.









Andrew Davie

#1
Notes:

in ReadSaveKey there's a bit of code that will reset/zap the SaveKey slot for the game if the RESET button is held down on boot. There's also game-specific inits. That is, if you've just plugged in a brand new SaveKey which does not have your game's slot initialised... then there are likely some variables on the SaveKey you want initialised to non-zero. You put those in right there... there are some commented-out examples: see the following code...

ReadSaveKey         SUBROUTINE

    ; will exit with SAVEKEY_IDENT = _SK_GRIDLOCK_ID if valid

    ; pre-clear flags buffers...

                    ldx #SAVEKEY_BYTES          ; (+1) to include _SAVEKEY_RESET
                    lda #0
.clearFlagsKey      sta SAVEKEY_IDENT,x
                    dex
                    bpl .clearFlagsKey

    ; Note: _SAVEKEY_IDENT = 0 at this point

    ; non-zero inits go HERE. The rest are already 0
    ; Now unlock the first 10 levels (game specific code!)
   
                    ; lda #%11111111
                    ; sta SAVEKEY_UNLOCKED
                    ; lda #%11
                    ; sta SAVEKEY_UNLOCKED+1

                    ; lda #1
                    ; sta SAVEKEY_TOTAL_SOLVES
                    ; sta SAVEKEY_ENABLE_ICC

.verify             jsr SetupSaveKey
                    bcc .noSKfound


Andrew Davie