all repos — mgba @ df9616c15c58454332c0dfb7f2b37e0098f518b9

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