;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; FMV code for Sega Master System FMV demo
; Written by Alex Marshall <trap15@raidenii.net>
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

fmv_dat_up_loop:
.rept $300
	outi
	out	(vdp_data), a
.endr
fmv_dat_up_loop_e:
	ret

fmv_pal_up_loop:
.rept $10
	outi
.endr
fmv_pal_up_loop_e:
	ret

; HL = Data
.macro	fmv_keyframe
	ld	a, $00
	out	(vdp_ctrl), a
	ld	a, $70
	out	(vdp_ctrl), a
	xor	a
	ld	c, vdp_data
.rept $300
	outi
	out	(vdp_data), a
.endr
	ld	a, $00
	out	(vdp_ctrl), a
	ld	a, $78
	out	(vdp_ctrl), a
	xor	a
.rept $300
	outi
	out	(vdp_data), a
.endr
.if HEIGHT2X == 1
	ld	a, $00
	out	(vdp_ctrl), a
	ld	a, $60
	out	(vdp_ctrl), a
	xor	a
.rept $300
	outi
	out	(vdp_data), a
.endr
	ld	a, $00
	out	(vdp_ctrl), a
	ld	a, $68
	out	(vdp_ctrl), a
	xor	a
	call	fmv_dat_up_loop
.endif
.endm

; A  = 0
; BC = -size*4
; DE = Offset
; HL = Data
.macro	fmv_deltaframe
	call	fmv_deltaframe_internal
.endm

fmv_deltaframe_internal:
	ld	ix, fmv_dat_up_loop_e	; 14
	add	ix, bc			; 15
	ld	c, vdp_ctrl		; 4
	out	(c), e			; 12
	out	(c), d			; 12
	ld	c, vdp_data		; 7
	jp	(ix)			; 8

; A  = 0
; BC = -size*2
; DE = Offset
; HL = Data
.macro	fmv_palette
	call	fmv_palette_internal
.endm

fmv_palette_internal:
	ld	ix, fmv_pal_up_loop_e	; 14
	add	ix, bc			; 15
	ld	c, vdp_ctrl		; 4
	out	(c), e			; 12
	out	(c), d			; 12
	ld	c, vdp_data		; 7
	jp	(ix)			; 8


; Upload the FMV stuff
fmv_init:
; Upload palette
	ld	hl, $C000
	rst	$10

	ld	b, 16
	ld	hl, fmv_palette
-
	ld	a, (hl)
	out	(vdp_data), a
	inc	hl
	djnz	-

; Upload tiles
	ld	hl, $4000
	rst	$10

	ld	c, 16
--
	ld	b, 16
-
	ld	a, 16
	sub	b
	ld	l, a
	ld	a, 16
	sub	c
	ld	h, 0
	add	a, a
	add	a, a
	add	a, a
	add	a, a
	add	a, l
	ld	l, a
	add	hl, hl
	add	hl, hl
	ex	de, hl
	ld	ix, tile_lut
	add	ix, de
.rept 8
	ld	a, (ix+0)
	out	(vdp_data), a
	ld	a, (ix+1)
	out	(vdp_data), a
	ld	a, (ix+2)
	out	(vdp_data), a
	ld	a, (ix+3)
	out	(vdp_data), a
.endr
	dec	b
	jp	nz, -

	dec	c
	jp	nz, --

fmv_start:
	ld	hl, fmv_data
	ld	(fmvptr), hl

	xor	a
	ld	(wait), a

	ret

fmv_update_main:
	ld	hl, (fmvptr)
	ld	a, (hl)
	inc	hl
	ld	c, a
	and	$3F
	ld	(ix+0), a
	ld	a, c
	and	$C0
	ld	ixh, cmdtbl>>8
	ld	ixl, a
	ld	e, (ix+0)
	ld	d, (ix+1)
	ex	de, hl
	jp	(hl)


fmv_palette:
	.db	$00, $02, $04, $06
	.db	$08, $0A, $0C, $0E
	.db	$20, $22, $24, $26
	.db	$28, $2A, $2C, $2E

deltacmd_entry:
	ex	de, hl
	ld	sp, hl
	pop	de
	pop	bc
	pop	hl
	xor	a
	ld	sp, $DFF0
	fmv_deltaframe
	ld	(fmvptr), hl
	jp	fmv_update

keyfrmcmd_entry:
	ex	de, hl
	fmv_keyframe
	ld	(fmvptr), hl
	jp	fmv_update

palcmd_entry:
	ex	de, hl
	ld	e, (hl)
	inc	hl
	ld	d, $C0
	ld	c, (hl)
	inc	hl
	inc	c
	jp	p, +
	dec	c
	ld	b, $FF
	xor	a
	fmv_palette
+
	ld	(fmvptr), hl
	jp	fmv_update

bankcmd_entry:
	ld	a, (de)
	ld	(mapper_slot2), a
	call	fmv_start
	jp	fmv_update

raster_tbl:
.if HEIGHT2X == 1
.rept	24
	.dw	$8209
	.dw	$820B
	.dw	$820D
	.dw	$820F
.endr
.else
.rept	48
	.dw	$820D
	.dw	$820F
.endr
.endif

