all repos — mgba @ 0fdc3436895a2b21afdf17069e24681f3093d211

mGBA Game Boy Advance Emulator

src/gb/video.c (view raw)

  1/* Copyright (c) 2013-2016 Jeffrey Pfau
  2 *
  3 * This Source Code Form is subject to the terms of the Mozilla Public
  4 * License, v. 2.0. If a copy of the MPL was not distributed with this
  5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
  6#include <mgba/internal/gb/video.h>
  7
  8#include <mgba/core/sync.h>
  9#include <mgba/core/thread.h>
 10#include <mgba/core/cache-set.h>
 11#include <mgba/internal/gb/gb.h>
 12#include <mgba/internal/gb/io.h>
 13#include <mgba/internal/gb/renderers/cache-set.h>
 14#include <mgba/internal/gb/serialize.h>
 15#include <mgba/internal/sm83/sm83.h>
 16
 17#include <mgba-util/memory.h>
 18
 19static void GBVideoDummyRendererInit(struct GBVideoRenderer* renderer, enum GBModel model, bool borders);
 20static void GBVideoDummyRendererDeinit(struct GBVideoRenderer* renderer);
 21static uint8_t GBVideoDummyRendererWriteVideoRegister(struct GBVideoRenderer* renderer, uint16_t address, uint8_t value);
 22static void GBVideoDummyRendererWriteSGBPacket(struct GBVideoRenderer* renderer, uint8_t* data);
 23static void GBVideoDummyRendererWritePalette(struct GBVideoRenderer* renderer, int index, uint16_t value);
 24static void GBVideoDummyRendererWriteVRAM(struct GBVideoRenderer* renderer, uint16_t address);
 25static void GBVideoDummyRendererWriteOAM(struct GBVideoRenderer* renderer, uint16_t oam);
 26static void GBVideoDummyRendererDrawRange(struct GBVideoRenderer* renderer, int startX, int endX, int y, struct GBObj* obj, size_t oamMax);
 27static void GBVideoDummyRendererFinishScanline(struct GBVideoRenderer* renderer, int y);
 28static void GBVideoDummyRendererFinishFrame(struct GBVideoRenderer* renderer);
 29static void GBVideoDummyRendererEnableSGBBorder(struct GBVideoRenderer* renderer, bool enable);
 30static void GBVideoDummyRendererGetPixels(struct GBVideoRenderer* renderer, size_t* stride, const void** pixels);
 31static void GBVideoDummyRendererPutPixels(struct GBVideoRenderer* renderer, size_t stride, const void* pixels);
 32
 33static void _cleanOAM(struct GBVideo* video, int y);
 34
 35static void _endMode0(struct mTiming* timing, void* context, uint32_t cyclesLate);
 36static void _endMode1(struct mTiming* timing, void* context, uint32_t cyclesLate);
 37static void _endMode2(struct mTiming* timing, void* context, uint32_t cyclesLate);
 38static void _endMode3(struct mTiming* timing, void* context, uint32_t cyclesLate);
 39static void _updateFrameCount(struct mTiming* timing, void* context, uint32_t cyclesLate);
 40
 41static struct GBVideoRenderer dummyRenderer = {
 42	.init = GBVideoDummyRendererInit,
 43	.deinit = GBVideoDummyRendererDeinit,
 44	.writeVideoRegister = GBVideoDummyRendererWriteVideoRegister,
 45	.writeSGBPacket = GBVideoDummyRendererWriteSGBPacket,
 46	.writeVRAM = GBVideoDummyRendererWriteVRAM,
 47	.writeOAM = GBVideoDummyRendererWriteOAM,
 48	.writePalette = GBVideoDummyRendererWritePalette,
 49	.drawRange = GBVideoDummyRendererDrawRange,
 50	.finishScanline = GBVideoDummyRendererFinishScanline,
 51	.finishFrame = GBVideoDummyRendererFinishFrame,
 52	.enableSGBBorder = GBVideoDummyRendererEnableSGBBorder,
 53	.getPixels = GBVideoDummyRendererGetPixels,
 54	.putPixels = GBVideoDummyRendererPutPixels,
 55};
 56
 57void GBVideoInit(struct GBVideo* video) {
 58	video->renderer = &dummyRenderer;
 59	video->renderer->cache = NULL;
 60	video->renderer->sgbRenderMode = 0;
 61	video->vram = anonymousMemoryMap(GB_SIZE_VRAM);
 62	video->frameskip = 0;
 63
 64	video->modeEvent.context = video;
 65	video->modeEvent.name = "GB Video Mode";
 66	video->modeEvent.callback = NULL;
 67	video->modeEvent.priority = 8;
 68	video->frameEvent.context = video;
 69	video->frameEvent.name = "GB Video Frame";
 70	video->frameEvent.callback = _updateFrameCount;
 71	video->frameEvent.priority = 9;
 72
 73	video->dmgPalette[0] = 0x7FFF;
 74	video->dmgPalette[1] = 0x56B5;
 75	video->dmgPalette[2] = 0x294A;
 76	video->dmgPalette[3] = 0x0000;
 77	video->dmgPalette[4] = 0x7FFF;
 78	video->dmgPalette[5] = 0x56B5;
 79	video->dmgPalette[6] = 0x294A;
 80	video->dmgPalette[7] = 0x0000;
 81	video->dmgPalette[8] = 0x7FFF;
 82	video->dmgPalette[9] = 0x56B5;
 83	video->dmgPalette[10] = 0x294A;
 84	video->dmgPalette[11] = 0x0000;
 85
 86	video->sgbBorders = true;
 87
 88	video->renderer->sgbCharRam = NULL;
 89	video->renderer->sgbMapRam = NULL;
 90	video->renderer->sgbPalRam = NULL;
 91	video->renderer->sgbAttributes = NULL;
 92	video->renderer->sgbAttributeFiles = NULL;
 93}
 94
 95void GBVideoReset(struct GBVideo* video) {
 96	video->ly = 0;
 97	video->x = 0;
 98	video->mode = 1;
 99	video->stat = 1;
100
101	video->frameCounter = 0;
102	video->frameskipCounter = 0;
103
104	GBVideoSwitchBank(video, 0);
105	video->renderer->vram = video->vram;
106	memset(&video->oam, 0, sizeof(video->oam));
107	video->renderer->oam = &video->oam;
108	memset(&video->palette, 0, sizeof(video->palette));
109
110	if (video->p->model & GB_MODEL_SGB) {
111		video->renderer->sgbCharRam = anonymousMemoryMap(SGB_SIZE_CHAR_RAM);
112		video->renderer->sgbMapRam = anonymousMemoryMap(SGB_SIZE_MAP_RAM);
113		video->renderer->sgbPalRam = anonymousMemoryMap(SGB_SIZE_PAL_RAM);
114		video->renderer->sgbAttributeFiles = anonymousMemoryMap(SGB_SIZE_ATF_RAM);
115		video->renderer->sgbAttributes = malloc(90 * 45);
116		memset(video->renderer->sgbAttributes, 0, 90 * 45);
117		video->sgbCommandHeader = 0;
118		video->sgbBufferIndex = 0;
119	}
120
121	video->palette[0] = video->dmgPalette[0];
122	video->palette[1] = video->dmgPalette[1];
123	video->palette[2] = video->dmgPalette[2];
124	video->palette[3] = video->dmgPalette[3];
125	video->palette[8 * 4 + 0] = video->dmgPalette[4];
126	video->palette[8 * 4 + 1] = video->dmgPalette[5];
127	video->palette[8 * 4 + 2] = video->dmgPalette[6];
128	video->palette[8 * 4 + 3] = video->dmgPalette[7];
129	video->palette[9 * 4 + 0] = video->dmgPalette[8];
130	video->palette[9 * 4 + 1] = video->dmgPalette[9];
131	video->palette[9 * 4 + 2] = video->dmgPalette[10];
132	video->palette[9 * 4 + 3] = video->dmgPalette[11];
133
134	video->renderer->deinit(video->renderer);
135	video->renderer->init(video->renderer, video->p->model, video->sgbBorders);
136
137	video->renderer->writePalette(video->renderer, 0, video->palette[0]);
138	video->renderer->writePalette(video->renderer, 1, video->palette[1]);
139	video->renderer->writePalette(video->renderer, 2, video->palette[2]);
140	video->renderer->writePalette(video->renderer, 3, video->palette[3]);
141	video->renderer->writePalette(video->renderer, 8 * 4 + 0, video->palette[8 * 4 + 0]);
142	video->renderer->writePalette(video->renderer, 8 * 4 + 1, video->palette[8 * 4 + 1]);
143	video->renderer->writePalette(video->renderer, 8 * 4 + 2, video->palette[8 * 4 + 2]);
144	video->renderer->writePalette(video->renderer, 8 * 4 + 3, video->palette[8 * 4 + 3]);
145	video->renderer->writePalette(video->renderer, 9 * 4 + 0, video->palette[9 * 4 + 0]);
146	video->renderer->writePalette(video->renderer, 9 * 4 + 1, video->palette[9 * 4 + 1]);
147	video->renderer->writePalette(video->renderer, 9 * 4 + 2, video->palette[9 * 4 + 2]);
148	video->renderer->writePalette(video->renderer, 9 * 4 + 3, video->palette[9 * 4 + 3]);
149}
150
151void GBVideoDeinit(struct GBVideo* video) {
152	video->renderer->deinit(video->renderer);
153	mappedMemoryFree(video->vram, GB_SIZE_VRAM);
154	if (video->renderer->sgbCharRam) {
155		mappedMemoryFree(video->renderer->sgbCharRam, SGB_SIZE_CHAR_RAM);
156		video->renderer->sgbCharRam = NULL;
157	}
158	if (video->renderer->sgbMapRam) {
159		mappedMemoryFree(video->renderer->sgbMapRam, SGB_SIZE_MAP_RAM);
160		video->renderer->sgbMapRam = NULL;
161	}
162	if (video->renderer->sgbPalRam) {
163		mappedMemoryFree(video->renderer->sgbPalRam, SGB_SIZE_PAL_RAM);
164		video->renderer->sgbPalRam = NULL;
165	}
166	if (video->renderer->sgbAttributeFiles) {
167		mappedMemoryFree(video->renderer->sgbAttributeFiles, SGB_SIZE_ATF_RAM);
168		video->renderer->sgbAttributeFiles = NULL;
169	}
170	if (video->renderer->sgbAttributes) {
171		free(video->renderer->sgbAttributes);
172		video->renderer->sgbAttributes = NULL;
173	}
174}
175
176void GBVideoAssociateRenderer(struct GBVideo* video, struct GBVideoRenderer* renderer) {
177	video->renderer->deinit(video->renderer);
178	renderer->cache = video->renderer->cache;
179	renderer->sgbRenderMode = video->renderer->sgbRenderMode;
180	renderer->sgbCharRam = video->renderer->sgbCharRam;
181	renderer->sgbMapRam = video->renderer->sgbMapRam;
182	renderer->sgbPalRam = video->renderer->sgbPalRam;
183	renderer->sgbAttributeFiles = video->renderer->sgbAttributeFiles;
184	renderer->sgbAttributes = video->renderer->sgbAttributes;
185	video->renderer = renderer;
186	renderer->vram = video->vram;
187	video->renderer->init(video->renderer, video->p->model, video->sgbBorders);
188}
189
190static bool _statIRQAsserted(GBRegisterSTAT stat) {
191	// TODO: variable for the IRQ line value?
192	if (GBRegisterSTATIsLYCIRQ(stat) && GBRegisterSTATIsLYC(stat)) {
193		return true;
194	}
195	switch (GBRegisterSTATGetMode(stat)) {
196	case 0:
197		if (GBRegisterSTATIsHblankIRQ(stat)) {
198			return true;
199		}
200		break;
201	case 1:
202		if (GBRegisterSTATIsVblankIRQ(stat)) {
203			return true;
204		}
205		break;
206	case 2:
207		if (GBRegisterSTATIsOAMIRQ(stat)) {
208			return true;
209		}
210		break;
211	case 3:
212		break;
213	}
214	return false;
215}
216
217void GBVideoSkipBIOS(struct GBVideo* video) {
218	video->mode = 1;
219	video->modeEvent.callback = _endMode1;
220
221	int32_t next;
222	if (video->p->model == GB_MODEL_CGB) {
223		video->ly = GB_VIDEO_VERTICAL_PIXELS;
224		video->p->memory.io[REG_LY] = video->ly;
225		video->stat = GBRegisterSTATClearLYC(video->stat);
226		next = 20;
227	} else {
228		video->ly = GB_VIDEO_VERTICAL_TOTAL_PIXELS;
229		video->p->memory.io[REG_LY] = 0;
230		next = 56;
231	}
232	video->stat = GBRegisterSTATSetMode(video->stat, video->mode);
233
234	video->p->memory.io[REG_IF] |= (1 << GB_IRQ_VBLANK);
235	GBUpdateIRQs(video->p);
236	video->p->memory.io[REG_STAT] = video->stat;
237	mTimingDeschedule(&video->p->timing, &video->modeEvent);
238	mTimingSchedule(&video->p->timing, &video->modeEvent, next);
239}
240
241void _endMode0(struct mTiming* timing, void* context, uint32_t cyclesLate) {
242	struct GBVideo* video = context;
243	if (video->frameskipCounter <= 0) {
244		video->renderer->finishScanline(video->renderer, video->ly);
245	}
246	int lyc = video->p->memory.io[REG_LYC];
247	int32_t next;
248	++video->ly;
249	video->p->memory.io[REG_LY] = video->ly;
250	GBRegisterSTAT oldStat = video->stat;
251	if (video->ly < GB_VIDEO_VERTICAL_PIXELS) {
252		next = GB_VIDEO_MODE_2_LENGTH;
253		video->mode = 2;
254		video->modeEvent.callback = _endMode2;
255	} else {
256		next = GB_VIDEO_HORIZONTAL_LENGTH;
257		video->mode = 1;
258		video->modeEvent.callback = _endMode1;
259
260		mTimingDeschedule(&video->p->timing, &video->frameEvent);
261		mTimingSchedule(&video->p->timing, &video->frameEvent, -cyclesLate);
262
263		if (!_statIRQAsserted(oldStat) && GBRegisterSTATIsOAMIRQ(video->stat)) {
264			video->p->memory.io[REG_IF] |= (1 << GB_IRQ_LCDSTAT);
265		}
266		video->p->memory.io[REG_IF] |= (1 << GB_IRQ_VBLANK);
267	}
268	video->stat = GBRegisterSTATSetMode(video->stat, video->mode);
269	if (!_statIRQAsserted(oldStat) && _statIRQAsserted(video->stat)) {
270		video->p->memory.io[REG_IF] |= (1 << GB_IRQ_LCDSTAT);
271	}
272
273	// LYC stat is delayed 1 T-cycle
274	oldStat = video->stat;
275	video->stat = GBRegisterSTATSetLYC(video->stat, lyc == video->ly);
276	if (!_statIRQAsserted(oldStat) && _statIRQAsserted(video->stat)) {
277		video->p->memory.io[REG_IF] |= (1 << GB_IRQ_LCDSTAT);
278	}
279
280	GBUpdateIRQs(video->p);
281	video->p->memory.io[REG_STAT] = video->stat;
282	mTimingSchedule(timing, &video->modeEvent, (next << video->p->doubleSpeed) - cyclesLate);
283}
284
285void _endMode1(struct mTiming* timing, void* context, uint32_t cyclesLate) {
286	struct GBVideo* video = context;
287	if (!GBRegisterLCDCIsEnable(video->p->memory.io[REG_LCDC])) {
288		return;
289	}
290	int lyc = video->p->memory.io[REG_LYC];
291	// TODO: One M-cycle delay
292	++video->ly;
293	int32_t next;
294	if (video->ly == GB_VIDEO_VERTICAL_TOTAL_PIXELS + 1) {
295		video->ly = 0;
296		video->p->memory.io[REG_LY] = video->ly;
297		next = GB_VIDEO_MODE_2_LENGTH;
298		video->mode = 2;
299		video->modeEvent.callback = _endMode2;
300	} else if (video->ly == GB_VIDEO_VERTICAL_TOTAL_PIXELS) {
301		video->p->memory.io[REG_LY] = 0;
302		next = GB_VIDEO_HORIZONTAL_LENGTH - 8;
303	} else if (video->ly == GB_VIDEO_VERTICAL_TOTAL_PIXELS - 1) {
304		video->p->memory.io[REG_LY] = video->ly;
305		next = 8;
306	} else {
307		video->p->memory.io[REG_LY] = video->ly;
308		next = GB_VIDEO_HORIZONTAL_LENGTH;
309	}
310
311	GBRegisterSTAT oldStat = video->stat;
312	video->stat = GBRegisterSTATSetMode(video->stat, video->mode);
313	video->stat = GBRegisterSTATSetLYC(video->stat, lyc == video->p->memory.io[REG_LY]);
314	if (!_statIRQAsserted(oldStat) && _statIRQAsserted(video->stat)) {
315		video->p->memory.io[REG_IF] |= (1 << GB_IRQ_LCDSTAT);
316		GBUpdateIRQs(video->p);
317	}
318	video->p->memory.io[REG_STAT] = video->stat;
319	mTimingSchedule(timing, &video->modeEvent, (next << video->p->doubleSpeed) - cyclesLate);
320}
321
322void _endMode2(struct mTiming* timing, void* context, uint32_t cyclesLate) {
323	struct GBVideo* video = context;
324	_cleanOAM(video, video->ly);
325	video->x = -(video->p->memory.io[REG_SCX] & 7);
326	video->dotClock = mTimingCurrentTime(timing) - cyclesLate + 5 - (video->x << video->p->doubleSpeed);
327	int32_t next = GB_VIDEO_MODE_3_LENGTH_BASE + video->objMax * 6 - video->x;
328	video->mode = 3;
329	video->modeEvent.callback = _endMode3;
330	GBRegisterSTAT oldStat = video->stat;
331	video->stat = GBRegisterSTATSetMode(video->stat, video->mode);
332	if (!_statIRQAsserted(oldStat) && _statIRQAsserted(video->stat)) {
333		video->p->memory.io[REG_IF] |= (1 << GB_IRQ_LCDSTAT);
334		GBUpdateIRQs(video->p);
335	}
336	video->p->memory.io[REG_STAT] = video->stat;
337	mTimingSchedule(timing, &video->modeEvent, (next << video->p->doubleSpeed) - cyclesLate);
338}
339
340void _endMode3(struct mTiming* timing, void* context, uint32_t cyclesLate) {
341	struct GBVideo* video = context;
342	GBVideoProcessDots(video, cyclesLate);
343	if (video->ly < GB_VIDEO_VERTICAL_PIXELS && video->p->memory.isHdma && video->p->memory.io[REG_HDMA5] != 0xFF) {
344		video->p->memory.hdmaRemaining = 0x10;
345		video->p->cpuBlocked = true;
346		mTimingDeschedule(timing, &video->p->memory.hdmaEvent);
347		mTimingSchedule(timing, &video->p->memory.hdmaEvent, 0);
348	}
349	video->mode = 0;
350	video->modeEvent.callback = _endMode0;
351	GBRegisterSTAT oldStat = video->stat;
352	video->stat = GBRegisterSTATSetMode(video->stat, video->mode);
353	if (!_statIRQAsserted(oldStat) && _statIRQAsserted(video->stat)) {
354		video->p->memory.io[REG_IF] |= (1 << GB_IRQ_LCDSTAT);
355		GBUpdateIRQs(video->p);
356	}
357	video->p->memory.io[REG_STAT] = video->stat;
358	// TODO: Cache SCX & 7 in case it changes
359	int32_t next = GB_VIDEO_MODE_0_LENGTH_BASE - video->objMax * 6 - (video->p->memory.io[REG_SCX] & 7);
360	mTimingSchedule(timing, &video->modeEvent, (next << video->p->doubleSpeed) - cyclesLate);
361}
362
363void _updateFrameCount(struct mTiming* timing, void* context, uint32_t cyclesLate) {
364	UNUSED(cyclesLate);
365	struct GBVideo* video = context;
366	if (video->p->cpu->executionState != SM83_CORE_FETCH) {
367		mTimingSchedule(timing, &video->frameEvent, 4 - ((video->p->cpu->executionState + 1) & 3));
368		return;
369	}
370	if (!GBRegisterLCDCIsEnable(video->p->memory.io[REG_LCDC])) {
371		mTimingSchedule(timing, &video->frameEvent, GB_VIDEO_TOTAL_LENGTH);
372	}
373
374	--video->frameskipCounter;
375	if (video->frameskipCounter < 0) {
376		video->renderer->finishFrame(video->renderer);
377		video->frameskipCounter = video->frameskip;
378	}
379	GBFrameEnded(video->p);
380	mCoreSyncPostFrame(video->p->sync);
381	++video->frameCounter;
382	video->p->earlyExit = true;
383
384	GBFrameStarted(video->p);
385}
386
387static void _cleanOAM(struct GBVideo* video, int y) {
388	// TODO: GBC differences
389	// TODO: Optimize
390	video->objMax = 0;
391	int spriteHeight = 8;
392	if (GBRegisterLCDCIsObjSize(video->p->memory.io[REG_LCDC])) {
393		spriteHeight = 16;
394	}
395	int o = 0;
396	int i;
397	for (i = 0; i < 40; ++i) {
398		uint8_t oy = video->oam.obj[i].y;
399		if (y < oy - 16 || y >= oy - 16 + spriteHeight) {
400			continue;
401		}
402		// TODO: Sort
403		video->objThisLine[o] = video->oam.obj[i];
404		++o;
405		if (o == 10) {
406			break;
407		}
408	}
409	video->objMax = o;
410}
411
412void GBVideoProcessDots(struct GBVideo* video, uint32_t cyclesLate) {
413	if (video->mode != 3) {
414		return;
415	}
416	int oldX = video->x;
417	video->x = (int32_t) (mTimingCurrentTime(&video->p->timing) - cyclesLate - video->dotClock) >> video->p->doubleSpeed;
418	if (video->x > GB_VIDEO_HORIZONTAL_PIXELS) {
419		video->x = GB_VIDEO_HORIZONTAL_PIXELS;
420	} else if (video->x < 0) {
421		return;
422	}
423	if (oldX < 0) {
424		oldX = 0;
425	}
426	if (video->frameskipCounter <= 0) {
427		video->renderer->drawRange(video->renderer, oldX, video->x, video->ly, video->objThisLine, video->objMax);
428	}
429}
430
431void GBVideoWriteLCDC(struct GBVideo* video, GBRegisterLCDC value) {
432	if (!GBRegisterLCDCIsEnable(video->p->memory.io[REG_LCDC]) && GBRegisterLCDCIsEnable(value)) {
433		video->mode = 2;
434		video->modeEvent.callback = _endMode2;
435		int32_t next = GB_VIDEO_MODE_2_LENGTH - 5; // TODO: Why is this fudge factor needed? Might be related to T-cycles for load/store differing
436		mTimingDeschedule(&video->p->timing, &video->modeEvent);
437		mTimingSchedule(&video->p->timing, &video->modeEvent, next << video->p->doubleSpeed);
438
439		video->ly = 0;
440		video->p->memory.io[REG_LY] = 0;
441		GBRegisterSTAT oldStat = video->stat;
442		video->stat = GBRegisterSTATSetMode(video->stat, 0);
443		video->stat = GBRegisterSTATSetLYC(video->stat, video->ly == video->p->memory.io[REG_LYC]);
444		if (!_statIRQAsserted(oldStat) && _statIRQAsserted(video->stat)) {
445			video->p->memory.io[REG_IF] |= (1 << GB_IRQ_LCDSTAT);
446			GBUpdateIRQs(video->p);
447		}
448		video->p->memory.io[REG_STAT] = video->stat;
449		video->renderer->writePalette(video->renderer, 0, video->palette[0]);
450
451		mTimingDeschedule(&video->p->timing, &video->frameEvent);
452	}
453	if (GBRegisterLCDCIsEnable(video->p->memory.io[REG_LCDC]) && !GBRegisterLCDCIsEnable(value)) {
454		// TODO: Fix serialization; this gets internal and visible modes out of sync
455		video->mode = 0;
456		video->stat = GBRegisterSTATSetMode(video->stat, 0);
457		video->p->memory.io[REG_STAT] = video->stat;
458		video->ly = 0;
459		video->p->memory.io[REG_LY] = 0;
460		video->renderer->writePalette(video->renderer, 0, video->dmgPalette[0]);
461	
462		mTimingDeschedule(&video->p->timing, &video->modeEvent);
463		mTimingDeschedule(&video->p->timing, &video->frameEvent);
464		mTimingSchedule(&video->p->timing, &video->frameEvent, GB_VIDEO_TOTAL_LENGTH);
465	}
466	video->p->memory.io[REG_STAT] = video->stat;
467}
468
469void GBVideoWriteSTAT(struct GBVideo* video, GBRegisterSTAT value) {
470	GBRegisterSTAT oldStat = video->stat;
471	video->stat = (video->stat & 0x7) | (value & 0x78);
472	if (!GBRegisterLCDCIsEnable(video->p->memory.io[REG_LCDC]) || video->p->model >= GB_MODEL_CGB) {
473		return;
474	}
475	if (!_statIRQAsserted(oldStat) && video->mode < 3) {
476		// TODO: variable for the IRQ line value?
477		video->p->memory.io[REG_IF] |= (1 << GB_IRQ_LCDSTAT);
478		GBUpdateIRQs(video->p);
479	}
480}
481
482void GBVideoWriteLYC(struct GBVideo* video, uint8_t value) {
483	GBRegisterSTAT oldStat = video->stat;
484	if (GBRegisterLCDCIsEnable(video->p->memory.io[REG_LCDC])) {
485		video->stat = GBRegisterSTATSetLYC(video->stat, value == video->ly);
486		if (!_statIRQAsserted(oldStat) && _statIRQAsserted(video->stat)) {
487			video->p->memory.io[REG_IF] |= (1 << GB_IRQ_LCDSTAT);
488			GBUpdateIRQs(video->p);
489		}
490	}
491	video->p->memory.io[REG_STAT] = video->stat;
492}
493
494void GBVideoWritePalette(struct GBVideo* video, uint16_t address, uint8_t value) {
495	if (video->p->model < GB_MODEL_SGB) {
496		switch (address) {
497		case REG_BGP:
498			video->palette[0] = video->dmgPalette[value & 3];
499			video->palette[1] = video->dmgPalette[(value >> 2) & 3];
500			video->palette[2] = video->dmgPalette[(value >> 4) & 3];
501			video->palette[3] = video->dmgPalette[(value >> 6) & 3];
502			video->renderer->writePalette(video->renderer, 0, video->palette[0]);
503			video->renderer->writePalette(video->renderer, 1, video->palette[1]);
504			video->renderer->writePalette(video->renderer, 2, video->palette[2]);
505			video->renderer->writePalette(video->renderer, 3, video->palette[3]);
506			break;
507		case REG_OBP0:
508			video->palette[8 * 4 + 0] = video->dmgPalette[(value & 3) + 4];
509			video->palette[8 * 4 + 1] = video->dmgPalette[((value >> 2) & 3) + 4];
510			video->palette[8 * 4 + 2] = video->dmgPalette[((value >> 4) & 3) + 4];
511			video->palette[8 * 4 + 3] = video->dmgPalette[((value >> 6) & 3) + 4];
512			video->renderer->writePalette(video->renderer, 8 * 4 + 0, video->palette[8 * 4 + 0]);
513			video->renderer->writePalette(video->renderer, 8 * 4 + 1, video->palette[8 * 4 + 1]);
514			video->renderer->writePalette(video->renderer, 8 * 4 + 2, video->palette[8 * 4 + 2]);
515			video->renderer->writePalette(video->renderer, 8 * 4 + 3, video->palette[8 * 4 + 3]);
516			break;
517		case REG_OBP1:
518			video->palette[9 * 4 + 0] = video->dmgPalette[(value & 3) + 8];
519			video->palette[9 * 4 + 1] = video->dmgPalette[((value >> 2) & 3) + 8];
520			video->palette[9 * 4 + 2] = video->dmgPalette[((value >> 4) & 3) + 8];
521			video->palette[9 * 4 + 3] = video->dmgPalette[((value >> 6) & 3) + 8];
522			video->renderer->writePalette(video->renderer, 9 * 4 + 0, video->palette[9 * 4 + 0]);
523			video->renderer->writePalette(video->renderer, 9 * 4 + 1, video->palette[9 * 4 + 1]);
524			video->renderer->writePalette(video->renderer, 9 * 4 + 2, video->palette[9 * 4 + 2]);
525			video->renderer->writePalette(video->renderer, 9 * 4 + 3, video->palette[9 * 4 + 3]);
526			break;
527		}
528	} else if (video->p->model & GB_MODEL_SGB) {
529		video->renderer->writeVideoRegister(video->renderer, address, value);
530	} else {
531		switch (address) {
532		case REG_BCPD:
533			if (video->mode != 3) {
534				if (video->bcpIndex & 1) {
535					video->palette[video->bcpIndex >> 1] &= 0x00FF;
536					video->palette[video->bcpIndex >> 1] |= value << 8;
537				} else {
538					video->palette[video->bcpIndex >> 1] &= 0xFF00;
539					video->palette[video->bcpIndex >> 1] |= value;
540				}
541				video->renderer->writePalette(video->renderer, video->bcpIndex >> 1, video->palette[video->bcpIndex >> 1]);
542			}
543			if (video->bcpIncrement) {
544				++video->bcpIndex;
545				video->bcpIndex &= 0x3F;
546				video->p->memory.io[REG_BCPS] &= 0x80;
547				video->p->memory.io[REG_BCPS] |= video->bcpIndex;
548			}
549			video->p->memory.io[REG_BCPD] = video->palette[video->bcpIndex >> 1] >> (8 * (video->bcpIndex & 1));
550			break;
551		case REG_OCPD:
552			if (video->mode != 3) {
553				if (video->ocpIndex & 1) {
554					video->palette[8 * 4 + (video->ocpIndex >> 1)] &= 0x00FF;
555					video->palette[8 * 4 + (video->ocpIndex >> 1)] |= value << 8;
556				} else {
557					video->palette[8 * 4 + (video->ocpIndex >> 1)] &= 0xFF00;
558					video->palette[8 * 4 + (video->ocpIndex >> 1)] |= value;
559				}
560				video->renderer->writePalette(video->renderer, 8 * 4 + (video->ocpIndex >> 1), video->palette[8 * 4 + (video->ocpIndex >> 1)]);
561			}
562			if (video->ocpIncrement) {
563				++video->ocpIndex;
564				video->ocpIndex &= 0x3F;
565				video->p->memory.io[REG_OCPS] &= 0x80;
566				video->p->memory.io[REG_OCPS] |= video->ocpIndex;
567			}
568			video->p->memory.io[REG_OCPD] = video->palette[8 * 4 + (video->ocpIndex >> 1)] >> (8 * (video->ocpIndex & 1));
569			break;
570		}
571	}
572}
573
574void GBVideoSwitchBank(struct GBVideo* video, uint8_t value) {
575	value &= 1;
576	video->vramBank = &video->vram[value * GB_SIZE_VRAM_BANK0];
577	video->vramCurrentBank = value;
578}
579
580void GBVideoSetPalette(struct GBVideo* video, unsigned index, uint32_t color) {
581	if (index >= 12) {
582		return;
583	}
584	video->dmgPalette[index] = M_RGB8_TO_RGB5(color);
585}
586
587void GBVideoDisableCGB(struct GBVideo* video) {
588	video->dmgPalette[0] = video->palette[0];
589	video->dmgPalette[1] = video->palette[1];
590	video->dmgPalette[2] = video->palette[2];
591	video->dmgPalette[3] = video->palette[3];
592	video->dmgPalette[4] = video->palette[8 * 4 + 0];
593	video->dmgPalette[5] = video->palette[8 * 4 + 1];
594	video->dmgPalette[6] = video->palette[8 * 4 + 2];
595	video->dmgPalette[7] = video->palette[8 * 4 + 3];
596	video->dmgPalette[8] = video->palette[9 * 4 + 0];
597	video->dmgPalette[9] = video->palette[9 * 4 + 1];
598	video->dmgPalette[10] = video->palette[9 * 4 + 2];
599	video->dmgPalette[11] = video->palette[9 * 4 + 3];
600	video->renderer->deinit(video->renderer);
601	video->renderer->init(video->renderer, video->p->model, video->sgbBorders);
602}
603
604void GBVideoWriteSGBPacket(struct GBVideo* video, uint8_t* data) {
605	int i;
606	if (!(video->sgbCommandHeader & 7)) {
607		video->sgbBufferIndex = 0;
608		if ((data[0] >> 3) > SGB_OBJ_TRN) {
609			video->sgbCommandHeader = 0;
610			return;
611		}
612		video->sgbCommandHeader = data[0];
613	}
614	--video->sgbCommandHeader;
615	memcpy(&video->sgbPacketBuffer[video->sgbBufferIndex << 4], data, 16);
616	++video->sgbBufferIndex;
617	if (video->sgbCommandHeader & 7) {
618		return;
619	}
620	switch (video->sgbCommandHeader >> 3) {
621	case SGB_PAL01:
622		video->palette[0] = video->sgbPacketBuffer[1] | (video->sgbPacketBuffer[2] << 8);
623		video->palette[1] = video->sgbPacketBuffer[3] | (video->sgbPacketBuffer[4] << 8);
624		video->palette[2] = video->sgbPacketBuffer[5] | (video->sgbPacketBuffer[6] << 8);
625		video->palette[3] = video->sgbPacketBuffer[7] | (video->sgbPacketBuffer[8] << 8);
626
627		video->palette[4] = video->sgbPacketBuffer[1] | (video->sgbPacketBuffer[2] << 8);
628		video->palette[5] = video->sgbPacketBuffer[9] | (video->sgbPacketBuffer[10] << 8);
629		video->palette[6] = video->sgbPacketBuffer[11] | (video->sgbPacketBuffer[12] << 8);
630		video->palette[7] = video->sgbPacketBuffer[13] | (video->sgbPacketBuffer[14] << 8);
631
632		video->palette[8] = video->sgbPacketBuffer[1] | (video->sgbPacketBuffer[2] << 8);
633		video->palette[12] = video->sgbPacketBuffer[1] | (video->sgbPacketBuffer[2] << 8);
634
635		video->renderer->writePalette(video->renderer, 0, video->palette[0]);
636		video->renderer->writePalette(video->renderer, 1, video->palette[1]);
637		video->renderer->writePalette(video->renderer, 2, video->palette[2]);
638		video->renderer->writePalette(video->renderer, 3, video->palette[3]);
639		video->renderer->writePalette(video->renderer, 4, video->palette[4]);
640		video->renderer->writePalette(video->renderer, 5, video->palette[5]);
641		video->renderer->writePalette(video->renderer, 6, video->palette[6]);
642		video->renderer->writePalette(video->renderer, 7, video->palette[7]);
643		video->renderer->writePalette(video->renderer, 8, video->palette[8]);
644		video->renderer->writePalette(video->renderer, 12, video->palette[12]);
645		break;
646	case SGB_PAL23:
647		video->palette[9] = video->sgbPacketBuffer[3] | (video->sgbPacketBuffer[4] << 8);
648		video->palette[10] = video->sgbPacketBuffer[5] | (video->sgbPacketBuffer[6] << 8);
649		video->palette[11] = video->sgbPacketBuffer[7] | (video->sgbPacketBuffer[8] << 8);
650
651		video->palette[13] = video->sgbPacketBuffer[9] | (video->sgbPacketBuffer[10] << 8);
652		video->palette[14] = video->sgbPacketBuffer[11] | (video->sgbPacketBuffer[12] << 8);
653		video->palette[15] = video->sgbPacketBuffer[13] | (video->sgbPacketBuffer[14] << 8);
654		video->renderer->writePalette(video->renderer, 9, video->palette[9]);
655		video->renderer->writePalette(video->renderer, 10, video->palette[10]);
656		video->renderer->writePalette(video->renderer, 11, video->palette[11]);
657		video->renderer->writePalette(video->renderer, 13, video->palette[13]);
658		video->renderer->writePalette(video->renderer, 14, video->palette[14]);
659		video->renderer->writePalette(video->renderer, 15, video->palette[15]);
660		break;
661	case SGB_PAL03:
662		video->palette[0] = video->sgbPacketBuffer[1] | (video->sgbPacketBuffer[2] << 8);
663		video->palette[1] = video->sgbPacketBuffer[3] | (video->sgbPacketBuffer[4] << 8);
664		video->palette[2] = video->sgbPacketBuffer[5] | (video->sgbPacketBuffer[6] << 8);
665		video->palette[3] = video->sgbPacketBuffer[7] | (video->sgbPacketBuffer[8] << 8);
666
667		video->palette[4] = video->sgbPacketBuffer[1] | (video->sgbPacketBuffer[2] << 8);
668		video->palette[8] = video->sgbPacketBuffer[1] | (video->sgbPacketBuffer[2] << 8);
669
670		video->palette[12] = video->sgbPacketBuffer[1] | (video->sgbPacketBuffer[2] << 8);
671		video->palette[13] = video->sgbPacketBuffer[9] | (video->sgbPacketBuffer[10] << 8);
672		video->palette[14] = video->sgbPacketBuffer[11] | (video->sgbPacketBuffer[12] << 8);
673		video->palette[15] = video->sgbPacketBuffer[13] | (video->sgbPacketBuffer[14] << 8);
674		video->renderer->writePalette(video->renderer, 0, video->palette[0]);
675		video->renderer->writePalette(video->renderer, 1, video->palette[1]);
676		video->renderer->writePalette(video->renderer, 2, video->palette[2]);
677		video->renderer->writePalette(video->renderer, 3, video->palette[3]);
678		video->renderer->writePalette(video->renderer, 4, video->palette[4]);
679		video->renderer->writePalette(video->renderer, 8, video->palette[8]);
680		video->renderer->writePalette(video->renderer, 12, video->palette[12]);
681		video->renderer->writePalette(video->renderer, 13, video->palette[13]);
682		video->renderer->writePalette(video->renderer, 14, video->palette[14]);
683		video->renderer->writePalette(video->renderer, 15, video->palette[15]);
684		break;
685	case SGB_PAL12:
686		video->palette[5] = video->sgbPacketBuffer[3] | (video->sgbPacketBuffer[4] << 8);
687		video->palette[6] = video->sgbPacketBuffer[5] | (video->sgbPacketBuffer[6] << 8);
688		video->palette[7] = video->sgbPacketBuffer[7] | (video->sgbPacketBuffer[8] << 8);
689
690		video->palette[9] = video->sgbPacketBuffer[9] | (video->sgbPacketBuffer[10] << 8);
691		video->palette[10] = video->sgbPacketBuffer[11] | (video->sgbPacketBuffer[12] << 8);
692		video->palette[11] = video->sgbPacketBuffer[13] | (video->sgbPacketBuffer[14] << 8);
693		video->renderer->writePalette(video->renderer, 5, video->palette[5]);
694		video->renderer->writePalette(video->renderer, 6, video->palette[6]);
695		video->renderer->writePalette(video->renderer, 7, video->palette[7]);
696		video->renderer->writePalette(video->renderer, 9, video->palette[9]);
697		video->renderer->writePalette(video->renderer, 10, video->palette[10]);
698		video->renderer->writePalette(video->renderer, 11, video->palette[11]);
699		break;
700	case SGB_PAL_SET:
701		for (i = 0; i < 4; ++i) {
702			uint16_t entry = (video->sgbPacketBuffer[2 + (i * 2)] << 8) | video->sgbPacketBuffer[1 + (i * 2)];
703			if (entry >= 0x200) {
704				mLOG(GB, STUB, "Unimplemented SGB palette overflow: %03X", entry);
705				continue;
706			}
707			LOAD_16LE(video->palette[i * 4 + 0], entry * 8 + 0, video->renderer->sgbPalRam);
708			video->renderer->writePalette(video->renderer, i * 4 + 0, video->palette[i * 4 + 0]);
709			LOAD_16LE(video->palette[i * 4 + 1], entry * 8 + 2, video->renderer->sgbPalRam);
710			video->renderer->writePalette(video->renderer, i * 4 + 1, video->palette[i * 4 + 1]);
711			LOAD_16LE(video->palette[i * 4 + 2], entry * 8 + 4, video->renderer->sgbPalRam);
712			video->renderer->writePalette(video->renderer, i * 4 + 2, video->palette[i * 4 + 2]);
713			LOAD_16LE(video->palette[i * 4 + 3], entry * 8 + 6, video->renderer->sgbPalRam);
714			video->renderer->writePalette(video->renderer, i * 4 + 3, video->palette[i * 4 + 3]);
715		}
716		break;
717	case SGB_ATTR_BLK:
718	case SGB_ATTR_DIV:
719	case SGB_ATTR_CHR:
720	case SGB_ATTR_LIN:
721	case SGB_PAL_TRN:
722	case SGB_ATRC_EN:
723	case SGB_CHR_TRN:
724	case SGB_PCT_TRN:
725	case SGB_ATTR_TRN:
726	case SGB_ATTR_SET:
727		break;
728	case SGB_MLT_REQ:
729		if ((video->sgbPacketBuffer[1] & 0x3) == 2) { // XXX: This unmasked increment appears to be an SGB hardware bug
730			++video->p->sgbCurrentController;
731		}
732		video->p->sgbControllers = video->sgbPacketBuffer[1] & 0x3;
733		video->p->sgbCurrentController &= video->p->sgbControllers;
734		return;
735	case SGB_MASK_EN:
736		video->renderer->sgbRenderMode = video->sgbPacketBuffer[1] & 0x3;
737		break;
738	default:
739		mLOG(GB, STUB, "Unimplemented SGB command: %02X", video->sgbPacketBuffer[0] >> 3);
740		return;
741	}
742	video->renderer->writeSGBPacket(video->renderer, video->sgbPacketBuffer);
743}
744
745static void GBVideoDummyRendererInit(struct GBVideoRenderer* renderer, enum GBModel model, bool borders) {
746	UNUSED(renderer);
747	UNUSED(model);
748	UNUSED(borders);
749	// Nothing to do
750}
751
752static void GBVideoDummyRendererDeinit(struct GBVideoRenderer* renderer) {
753	UNUSED(renderer);
754	// Nothing to do
755}
756
757static uint8_t GBVideoDummyRendererWriteVideoRegister(struct GBVideoRenderer* renderer, uint16_t address, uint8_t value) {
758	if (renderer->cache) {
759		GBVideoCacheWriteVideoRegister(renderer->cache, address, value);
760	}
761	return value;
762}
763
764static void GBVideoDummyRendererWriteSGBPacket(struct GBVideoRenderer* renderer, uint8_t* data) {
765	UNUSED(renderer);
766	UNUSED(data);
767}
768
769static void GBVideoDummyRendererWriteVRAM(struct GBVideoRenderer* renderer, uint16_t address) {
770	if (renderer->cache) {
771		mCacheSetWriteVRAM(renderer->cache, address);
772	}
773}
774
775static void GBVideoDummyRendererWriteOAM(struct GBVideoRenderer* renderer, uint16_t oam) {
776	UNUSED(renderer);
777	UNUSED(oam);
778	// Nothing to do
779}
780
781static void GBVideoDummyRendererWritePalette(struct GBVideoRenderer* renderer, int index, uint16_t value) {
782	if (renderer->cache) {
783		mCacheSetWritePalette(renderer->cache, index, mColorFrom555(value));
784	}
785}
786
787static void GBVideoDummyRendererDrawRange(struct GBVideoRenderer* renderer, int startX, int endX, int y, struct GBObj* obj, size_t oamMax) {
788	UNUSED(renderer);
789	UNUSED(endX);
790	UNUSED(startX);
791	UNUSED(y);
792	UNUSED(obj);
793	UNUSED(oamMax);
794	// Nothing to do
795}
796
797static void GBVideoDummyRendererFinishScanline(struct GBVideoRenderer* renderer, int y) {
798	UNUSED(renderer);
799	UNUSED(y);
800	// Nothing to do
801}
802
803static void GBVideoDummyRendererFinishFrame(struct GBVideoRenderer* renderer) {
804	UNUSED(renderer);
805	// Nothing to do
806}
807
808static void GBVideoDummyRendererEnableSGBBorder(struct GBVideoRenderer* renderer, bool enable) {
809	UNUSED(renderer);
810	UNUSED(enable);
811	// Nothing to do
812}
813
814static void GBVideoDummyRendererGetPixels(struct GBVideoRenderer* renderer, size_t* stride, const void** pixels) {
815	UNUSED(renderer);
816	UNUSED(stride);
817	UNUSED(pixels);
818	// Nothing to do
819}
820
821static void GBVideoDummyRendererPutPixels(struct GBVideoRenderer* renderer, size_t stride, const void* pixels) {
822	UNUSED(renderer);
823	UNUSED(stride);
824	UNUSED(pixels);
825	// Nothing to do
826}
827
828void GBVideoSerialize(const struct GBVideo* video, struct GBSerializedState* state) {
829	STORE_16LE(video->x, 0, &state->video.x);
830	STORE_16LE(video->ly, 0, &state->video.ly);
831	STORE_32LE(video->frameCounter, 0, &state->video.frameCounter);
832	STORE_32LE(video->dotClock, 0, &state->video.dotCounter);
833	state->video.vramCurrentBank = video->vramCurrentBank;
834
835	GBSerializedVideoFlags flags = 0;
836	flags = GBSerializedVideoFlagsSetBcpIncrement(flags, video->bcpIncrement);
837	flags = GBSerializedVideoFlagsSetOcpIncrement(flags, video->ocpIncrement);
838	flags = GBSerializedVideoFlagsSetMode(flags, video->mode);
839	flags = GBSerializedVideoFlagsSetNotModeEventScheduled(flags, !mTimingIsScheduled(&video->p->timing, &video->modeEvent));
840	flags = GBSerializedVideoFlagsSetNotFrameEventScheduled(flags, !mTimingIsScheduled(&video->p->timing, &video->frameEvent));
841	state->video.flags = flags;
842	STORE_16LE(video->bcpIndex, 0, &state->video.bcpIndex);
843	STORE_16LE(video->ocpIndex, 0, &state->video.ocpIndex);
844
845	size_t i;
846	for (i = 0; i < 64; ++i) {
847		STORE_16LE(video->palette[i], i * 2, state->video.palette);
848	}
849
850	STORE_32LE(video->modeEvent.when - mTimingCurrentTime(&video->p->timing), 0, &state->video.nextMode);
851	STORE_32LE(video->frameEvent.when - mTimingCurrentTime(&video->p->timing), 0, &state->video.nextFrame);
852
853	memcpy(state->vram, video->vram, GB_SIZE_VRAM);
854	memcpy(state->oam, &video->oam.raw, GB_SIZE_OAM);
855}
856
857void GBVideoDeserialize(struct GBVideo* video, const struct GBSerializedState* state) {
858	LOAD_16LE(video->x, 0, &state->video.x);
859	LOAD_16LE(video->ly, 0, &state->video.ly);
860	LOAD_32LE(video->frameCounter, 0, &state->video.frameCounter);
861	LOAD_32LE(video->dotClock, 0, &state->video.dotCounter);
862	video->vramCurrentBank = state->video.vramCurrentBank;
863
864	GBSerializedVideoFlags flags = state->video.flags;
865	video->bcpIncrement = GBSerializedVideoFlagsGetBcpIncrement(flags);
866	video->ocpIncrement = GBSerializedVideoFlagsGetOcpIncrement(flags);
867	video->mode = GBSerializedVideoFlagsGetMode(flags);
868	LOAD_16LE(video->bcpIndex, 0, &state->video.bcpIndex);
869	video->bcpIndex &= 0x3F;
870	LOAD_16LE(video->ocpIndex, 0, &state->video.ocpIndex);
871	video->ocpIndex &= 0x3F;
872
873	switch (video->mode) {
874	case 0:
875		video->modeEvent.callback = _endMode0;
876		break;
877	case 1:
878		video->modeEvent.callback = _endMode1;
879		break;
880	case 2:
881		video->modeEvent.callback = _endMode2;
882		break;
883	case 3:
884		video->modeEvent.callback = _endMode3;
885		break;
886	}
887
888	uint32_t when;
889	if (!GBSerializedVideoFlagsIsNotModeEventScheduled(flags)) {
890		LOAD_32LE(when, 0, &state->video.nextMode);
891		mTimingSchedule(&video->p->timing, &video->modeEvent, when);
892	}
893	if (!GBSerializedVideoFlagsIsNotFrameEventScheduled(flags)) {
894		LOAD_32LE(when, 0, &state->video.nextFrame);
895		mTimingSchedule(&video->p->timing, &video->frameEvent, when);
896	}
897
898	video->renderer->deinit(video->renderer);
899	video->renderer->init(video->renderer, video->p->model, video->sgbBorders);
900
901	size_t i;
902	for (i = 0; i < 64; ++i) {
903		LOAD_16LE(video->palette[i], i * 2, state->video.palette);
904		video->renderer->writePalette(video->renderer, i, video->palette[i]);
905	}
906
907	memcpy(video->vram, state->vram, GB_SIZE_VRAM);
908	memcpy(&video->oam.raw, state->oam, GB_SIZE_OAM);
909
910	_cleanOAM(video, video->ly);
911	GBVideoSwitchBank(video, video->vramCurrentBank);
912}