
.include "fb32x32.inc"

.include "globals.inc"

bl_x0       := functionram+$20
bl_y0       := functionram+$21
bl_x1       := functionram+$22
bl_y1       := functionram+$23
dx          := functionram+$24
dy          := functionram+$25

bresenhelp:
.if 1
   lda   bl_x1
   sec
   sbc   bl_x0
   bcs   :+
   eor   #$ff
   adc   #$01              ; clc due to branch
:
   sta   dx

   lda   bl_y1
   sec
   sbc   bl_y0
   bcs   :+
   eor   #$ff
   adc   #$01              ; clc due to branch
:
   sta   dy
.else
   lda   bl_x0
   cmp   bl_x1
   bcc   :+
   ; x0 > x1 -> swap
   ldx   bl_x1
   sta   bl_x1
   stx   bl_x0
:
   lda   bl_y0
   cmp   bl_y1
   bcc   :+
   ; y0 > y1 -> swap
   ldx   bl_y1
   sta   bl_y1
   stx   bl_y0
:
   ; calc dx and dy
   lda   bl_x1
   sec
   sbc   bl_x0
   sta   dx
   lda   bl_y1
   sec
   sbc   bl_y0
   sta   dy
   stz   TRAP
.endif

   lda   dx
   cmp   dy
   bcs   :+
   ; dx > dy -> swap
   lda   bl_x0
   ldx   bl_x1
   stx   bl_x0
   sta   bl_x1
   lda   bl_y0
   ldx   bl_y1
   stx   bl_y0
   sta   bl_y1
   lda   dx
   ldx   dy
   stx   dx
   sta   dy
:
   ldx   dx

   asl   dx
   asl   dy
@loop:
   tay                     ; dummy to set flags according to A
   stz   bresensteps,x     ; initial: clear out to $00
   ;lda   D
   bmi   @nostep
   dec   bresensteps,x     ; set to $FF
   ;lda   D
   sec
   sbc   dx
@nostep:
   clc
   adc   dy
   ;sta   D

   dex
   bpl   @loop
   rts

t_bresenham:
   lda   #$1f
   stz   bl_x0
   stz   bl_y0
   sta   bl_y1
   lsr
   sta   bl_x1
   jsr   bresenhelp
   stz   TRAP
   rts

box_fb:
   lda   #<FRAMEBUFFER
   ldx   #>FRAMEBUFFER
box:
   sta   vector+0
   stx   vector+1





line:
   ; 8 octants
   ; dx < 0 | dy < 0 | dx < dy |
   ;      0 |      0 |       0 | best case: step = +1, bres = +20
   ;      0 |      0 |       1 | step = +20, bres = +1
   ;      0 |      1 |       0 | step = -1, bres = -20
   ;      0 |      1 |       1 | step = -20, bres = -1
   ;      1 |      x |       x | swap x and y
@restart:
   lda   bl_y1
   sec
   sbc   bl_y0
   sta   dy

   lda   bl_x1
   sec
   sbc   bl_x0
   sta   dx

   bpl   @noswap

   lda   bl_x0
   ldx   bl_x1
   sta   bl_x1
   stx   bl_x0

   lda   bl_y0
   ldx   bl_y1
   sta   bl_y1
   stx   bl_y0

   bra   @restart

@noswap:
   lda   dy
   bpl   :+
:
