
#if VERA_VERSION != 9
#error Unsupported VERA_VERSION
#endif


const int24 VERA_PALETTE = $1FA00
const int24 VERA_SPRITES = $1FC00

volatile byte vera_addr_lo @ $9f20
volatile byte vera_addr_mi @ $9f21
volatile byte vera_addr_hi @ $9f22
volatile int24 vera_addr @ $9f20
volatile byte vera_data0 @ $9f23
volatile byte vera_data1 @ $9f24
volatile byte vera_ctrl @ $9f25
volatile byte vera_ien @ $9f26
volatile byte vera_isr @ $9f27
volatile byte vera_irqline @ $9f28
volatile byte vera_dc_video_hstart @ $9f29
volatile byte vera_dc_hscale_hstop @ $9f29
volatile byte vera_dc_vscale_vstart @ $9f2b
volatile byte vera_dc_border_vstop @ $9f2c

struct vera_layer_setup {
    byte config
    byte map_base
    byte tile_base
    word hscroll
    word vscroll
}

volatile vera_layer_setup vera_layer0 @$9F2D
volatile vera_layer_setup vera_layer1 @$9F34



inline void vera_poke(int24 address, byte value) {
    vera_ctrl = 0
    vera_addr = address
    vera_data0 = value
}

inline byte vera_peek(int24 address) {
    vera_ctrl = 0
    vera_addr = address
    return vera_data0
}

inline void vera_fill(int24 address, byte value, word size) {
    word i
    vera_addr_lo = address.b0
    vera_addr_mi = address.b1
    vera_addr_hi = address.b2 | $10
    vera_ctrl = 0
    for i,0,paralleluntil,size {
        vera_data0 = value
    }
}

void vera_upload_large(int24 address, pointer source, word size) {
    word i
    vera_ctrl = 0
    vera_addr_lo = address.b0
    vera_addr_mi = address.b1
    vera_addr_hi = address.b2 | $10
    for i,0,paralleluntil,size {
        vera_data0 = source[i]
    }
}

inline void vera_upload(int24 address, pointer source, byte size) {
    vera_ctrl = 0
    vera_addr_lo = address.b0
    vera_addr_mi = address.b1
    vera_addr_hi = address.b2 | $10
    asm {
        ? ldy #0
        __vera_upload_loop:
        ? lda (source),y
        ! sta vera_data0
        ? iny
        ? cpy size
        ? bne __vera_upload_loop
    }
}

inline void vera_reset() {
    vera_ctrl = $80
    vera_ctrl = 0
}

struct vera_sprite_data {
    word address
    word x
    word y
    byte ctrl0
    byte ctrl1
}

void vera_upload_sprite(byte sprite_id, pointer.vera_sprite_data source) {
    vera_ctrl = 0
    vera_addr_lo = sprite_id << 3
    vera_addr_mi = (sprite_id >> 5) | VERA_SPRITES.b1
    vera_addr_hi = VERA_SPRITES.b2 | $10
    asm {
        ? ldy #0
        __vera_upload_sprite_loop:
        ? lda (source),y
        ! sta vera_data0
        ? iny
        ? cpy #sizeof(vera_sprite_data)
        ? bne __vera_upload_sprite_loop
    }
}

inline void vera_set_sprites_enable(bool enabled) {
    vera_ctrl = 0
    if enabled {
        vera_dc_video_hstart |= $40
    } else {
        vera_dc_video_hstart &= $ff ^ $40
    }
}

inline void vera_set_border(byte color) {
    vera_ctrl = 0
    vera_dc_border_vstop = color
}

alias set_border = vera_set_border

