
.include "fb32x32.inc"

.include "globals.inc"

tmpvec   = localram
step     = tmpvec + 2
pingdone = step +1

.segment "DATA"

img6502s:
.incbin "gfx/6502s.bin"

myschedule:
   .word $0000, setup
   .word $0001, brighten
   .word $0080, crossfade
   .word $00c0, ping
   .word $00c1, nothing
   .word $0100, darken
   .word $013f, schedulenext

.segment "CODE"

setup:
   ; must be run as first part
   ; or rewrite usage of framebuffer
   stz   step
   ldx   #$00
:
   lda   img6502s+$000,x
   and   #$0f
   sta   FRAMEBUFFER+$000,x
   lda   img6502s+$100,x
   and   #$0f
   sta   FRAMEBUFFER+$100,x
   lda   img6502s+$000,x
   lsr
   lsr
   lsr
   lsr
   sta   FRAMEBUFFER+$200,x
   lda   img6502s+$100,x
   lsr
   lsr
   lsr
   lsr
   sta   FRAMEBUFFER+$300,x
   inx
   bne   :-

   ; easter egg: switch graphics when 65ce02 is detected
   lda   CPUID
   and   #$08
   beq   :+
   lda   #$4a              ; lsr
   sta   @conv+0
   sta   @conv+1
:
   ldx   #$04
   ldy   #$00
   stz   tmpvec+0
   lda   #>FRAMEBUFFER
   sta   tmpvec+1
:
   lda   (tmpvec),y
@conv:
   and   #$03
   sta   (tmpvec),y
   iny
   bne   :-
   inc   tmpvec+1
   dex
   bne   :-
   rts

colormap6502:
   ; IN
   ; A=brightness mos6502
   ; X=brightness wdc65c02

   ldy   #$01
   sty   FB32X32_CCOLMAP_IDX

   ; color idx 0 is always black
   stz   FB32X32_CCOLMAP_R
   stz   FB32X32_CCOLMAP_G
   stz   FB32X32_CCOLMAP_B

   ; color idx 1 is MOS 6502
   sta   FB32X32_CCOLMAP_R
   sta   FB32X32_CCOLMAP_G
   sta   FB32X32_CCOLMAP_B

   ; color idx 2 is WDC 65C02
   stx   FB32X32_CCOLMAP_R
   stx   FB32X32_CCOLMAP_G
   stx   FB32X32_CCOLMAP_B

   stx   tmp8
   cmp   tmp8
   bcs   :+
   txa
:
   ; color idx 3 is brigher one
   sta   FB32X32_CCOLMAP_R
   sta   FB32X32_CCOLMAP_G
   sta   FB32X32_CCOLMAP_B

nothing:
   rts

intro6502:
   lda   #<myschedule
   ldx   #>myschedule
   jmp   subschedule

brighten:
   lda   frmcnt
   lsr
   lsr
   cmp   #$0f
   bcc   :+
   lda   #$0f
:
   tax
   lda   #$00
   jsr   colormap6502
   jmp   update

crossfade:
   lda   frmcnt
   lsr
   lsr
   and   #$0f
   eor   #$0f
   tax
   eor   #$0f
   jsr   colormap6502
   bra   update

darken:
   lda   frmcnt
   lsr
   lsr
   and   #$0f
   eor   #$0f
   ldx   #$00
   jsr   colormap6502
   bra   update

ping:
   lda   #<playping
   ldx   #>playping
   jmp   precalcstart

runping:
   ; run in prg mode handler
   jsr   playping
   lda   #$80
   sta   pingdone
   rts

update:
   lda   #>FRAMEBUFFER
   stz   FB32X32_SRC+0
   sta   FB32X32_SRC+1

   stz   FB32X32_DEST_X
   stz   FB32X32_DEST_Y

   lda   #$1f
   sta   FB32X32_WIDTH
   sta   FB32X32_HEIGHT
   sta   FB32X32_STEP

   ; needs to be done after colormap changes
   lda   #$01
   sta   FB32X32_COLMAP

   stz   FB32X32_COPY
   rts
