;
;  global.macros
;  BuGS
;
;  Created by Jeremy Rand on 2020-07-30.
;Copyright © 2020 Jeremy Rand. All rights reserved.
;


        macro
        _drawDirtyGameRow &rowNum
        short i,m
        lda >BORDER_COLOUR_REGISTER
        and #$f0
        sta >BORDER_COLOUR_REGISTER
        long i,m
_drawDirtyGameRow_wait&rowNum anop
; This code loads into the accumulator the line currently being drawn to the
; screen by HW.  It allows code to race just behind the beam and redraw the
; screen.
;
; Based on code found here:
;   https://iigs.dreamhosters.com/gte/blitter.html
;
; Unlike that code, it does not change the baseline of the values.  According
; to GS technote 39, this number ranges from $fa to $1ff.  Scan line zero is
; $100 and scan line 199 is $1c7.  We will race the beam by comparing to these
; offset numbers.
;
; Also according to that technote, it looks like these numbers are different
; in PAL mode.  TODO - Do I need something here to handle PAL correctly?
        lda   >VERTICAL_COUNTER     ; load the counter value
        and   #$80ff                ; mask out the VBL bits
        asl   a                     ; shift the word around
        adc   #0                    ; move MSB -> LSB
        
        lcla &scanLineNum
&scanLineNum seta &rowNum
&scanLineNum seta &scanLineNum*8
&scanLineNum seta &scanLineNum+264
        cmp #&scanLineNum
        blt _drawDirtyGameRow_wait&rowNum
        
        short i,m
        lda >BORDER_COLOUR_REGISTER
        ora #$0f
        sta >BORDER_COLOUR_REGISTER
        long i,m
        
        lcla &tileOffset
&tileOffset seta &rowNum*50
        lcla &lastTileOffset
&lastTileOffset seta 50+&tileOffset

.drawDirtyGameRowLoop
        lda tileDirty+&tileOffset
        beq _drawDirtyGameRow_skip&tileOffset
        stz tileDirty+&tileOffset
        ldy tileScreenOffset+&tileOffset
        lda tileType+&tileOffset
        jsl drawTile
        
_drawDirtyGameRow_skip&tileOffset anop
&tileOffset seta &tileOffset+2
        aif &tileOffset<&lastTileOffset,.drawDirtyGameRowLoop
        
        mend

; This macro uses the X register as an index into the tile offsets.  This is
; needed for segments because each segment has their own dirty tile offsets.
        macro
        _dirtyGameTileWithX &tileOffset
        ldy &tileOffset,x
        lda #TILE_STATE_DIRTY
        sta tileDirty,y
        mend
        
        
        macro
        _dirtyGameOrNonGameTile &tileOffset

        ldx &tileOffset
        cpx #RHS_FIRST_TILE_OFFSET
        bge _dirtyGameTile_nonGame&SYSCNT
        lda #TILE_STATE_DIRTY
        sta tileDirty,x
        bra _dirtyGameTile_skip&SYSCNT

_dirtyGameTile_nonGame&SYSCNT anop
        lda tileDirty,x
        bne _dirtyGameTile_skip&SYSCNT
        lda #TILE_STATE_DIRTY
        sta tileDirty,x
        
        ldy numDirtyNonGameTiles
        txa
        sta dirtyNonGameTiles,y
        iny
        iny
        sty numDirtyNonGameTiles
        
_dirtyGameTile_skip&SYSCNT anop
        mend
