all repos — mgba @ 7640c386847d5fc32b1adce76ee0afe2934e233e

mGBA Game Boy Advance Emulator

src/gba/renderers/gl.c (view raw)

   1/* Copyright (c) 2013-2019 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/gba/renderers/gl.h>
   7
   8#if defined(BUILD_GLES2) || defined(BUILD_GLES3)
   9
  10#include <mgba/core/cache-set.h>
  11#include <mgba/internal/arm/macros.h>
  12#include <mgba/internal/gba/io.h>
  13#include <mgba/internal/gba/renderers/cache-set.h>
  14#include <mgba-util/memory.h>
  15
  16static void GBAVideoGLRendererInit(struct GBAVideoRenderer* renderer);
  17static void GBAVideoGLRendererDeinit(struct GBAVideoRenderer* renderer);
  18static void GBAVideoGLRendererReset(struct GBAVideoRenderer* renderer);
  19static void GBAVideoGLRendererWriteVRAM(struct GBAVideoRenderer* renderer, uint32_t address);
  20static void GBAVideoGLRendererWriteOAM(struct GBAVideoRenderer* renderer, uint32_t oam);
  21static void GBAVideoGLRendererWritePalette(struct GBAVideoRenderer* renderer, uint32_t address, uint16_t value);
  22static uint16_t GBAVideoGLRendererWriteVideoRegister(struct GBAVideoRenderer* renderer, uint32_t address, uint16_t value);
  23static void GBAVideoGLRendererDrawScanline(struct GBAVideoRenderer* renderer, int y);
  24static void GBAVideoGLRendererFinishFrame(struct GBAVideoRenderer* renderer);
  25static void GBAVideoGLRendererGetPixels(struct GBAVideoRenderer* renderer, size_t* stride, const void** pixels);
  26static void GBAVideoGLRendererPutPixels(struct GBAVideoRenderer* renderer, size_t stride, const void* pixels);
  27
  28static void GBAVideoGLRendererUpdateDISPCNT(struct GBAVideoGLRenderer* renderer);
  29static void GBAVideoGLRendererWriteBGCNT(struct GBAVideoGLBackground* bg, uint16_t value);
  30static void GBAVideoGLRendererWriteBGX_LO(struct GBAVideoGLBackground* bg, uint16_t value);
  31static void GBAVideoGLRendererWriteBGX_HI(struct GBAVideoGLBackground* bg, uint16_t value);
  32static void GBAVideoGLRendererWriteBGY_LO(struct GBAVideoGLBackground* bg, uint16_t value);
  33static void GBAVideoGLRendererWriteBGY_HI(struct GBAVideoGLBackground* bg, uint16_t value);
  34static void GBAVideoGLRendererWriteBLDCNT(struct GBAVideoGLRenderer* renderer, uint16_t value);
  35
  36static void GBAVideoGLRendererDrawSprite(struct GBAVideoGLRenderer* renderer, struct GBAObj* sprite, int y, int spriteY);
  37static void GBAVideoGLRendererDrawBackgroundMode0(struct GBAVideoGLRenderer* renderer, struct GBAVideoGLBackground* background, int y);
  38static void GBAVideoGLRendererDrawBackgroundMode2(struct GBAVideoGLRenderer* renderer, struct GBAVideoGLBackground* background, int y);
  39static void GBAVideoGLRendererDrawBackgroundMode3(struct GBAVideoGLRenderer* renderer, struct GBAVideoGLBackground* background, int y);
  40static void GBAVideoGLRendererDrawBackgroundMode4(struct GBAVideoGLRenderer* renderer, struct GBAVideoGLBackground* background, int y);
  41static void GBAVideoGLRendererDrawBackgroundMode5(struct GBAVideoGLRenderer* renderer, struct GBAVideoGLBackground* background, int y);
  42static void GBAVideoGLRendererDrawWindow(struct GBAVideoGLRenderer* renderer, int y);
  43
  44static void _cleanRegister(struct GBAVideoGLRenderer* renderer, int address, uint16_t value);
  45static void _drawScanlines(struct GBAVideoGLRenderer* renderer, int lastY);
  46static void _finalizeLayers(struct GBAVideoGLRenderer* renderer);
  47
  48#define TEST_LAYER_ENABLED(X) !glRenderer->d.disableBG[X] && glRenderer->bg[X].enabled == 4
  49
  50struct GBAVideoGLUniform {
  51	const char* name;
  52	int type;
  53};
  54
  55#define PALETTE_ENTRY "#define PALETTE_ENTRY(x) (vec3((ivec3(0x1F, 0x3E0, 0x7C00) & (x)) >> ivec3(0, 5, 10)) / 31.)\n"
  56
  57static const GLchar* const _gles3Header =
  58	"#version 300 es\n"
  59	"#define OUT(n) layout(location = n)\n"
  60	PALETTE_ENTRY
  61	"precision highp float;\n"
  62	"precision highp int;\n"
  63	"precision highp sampler2D;\n"
  64	"precision highp isampler2D;\n";
  65
  66static const GLchar* const _gl3Header =
  67	"#version 150 core\n"
  68	"#define OUT(n)\n"
  69	PALETTE_ENTRY
  70	"precision highp float;\n";
  71
  72static const char* const _vertexShader =
  73	"in vec2 position;\n"
  74	"uniform ivec2 loc;\n"
  75	"uniform ivec2 maxPos;\n"
  76	"out vec2 texCoord;\n"
  77
  78	"void main() {\n"
  79	"	vec2 local = vec2(position.x, float(position.y * float(loc.x) + float(loc.y)) / float(maxPos.y));\n"
  80	"	gl_Position = vec4((local * 2. - 1.) * vec2(sign(maxPos)), 0., 1.);\n"
  81	"	texCoord = local * vec2(abs(maxPos));\n"
  82	"}";
  83
  84static const char* const _renderTile16 =
  85	"vec4 renderTile(int tile, int paletteId, ivec2 localCoord) {\n"
  86	"	int address = charBase + tile * 16 + (localCoord.x >> 2) + (localCoord.y << 1);\n"
  87	"	int halfrow = texelFetch(vram, ivec2(address & 255, address >> 8), 0).r;\n"
  88	"	int entry = (halfrow >> (4 * (localCoord.x & 3))) & 15;\n"
  89	"	if (entry == 0) {\n"
  90	"		discard;\n"
  91	"	}\n"
  92	"	int paletteEntry = palette[paletteId * 16 + entry];\n"
  93	"	vec4 color = vec4(PALETTE_ENTRY(paletteEntry), 1.);\n"
  94	"	return color;\n"
  95	"}";
  96
  97static const char* const _renderTile256 =
  98	"vec4 renderTile(int tile, int paletteId, ivec2 localCoord) {\n"
  99	"	int address = charBase + tile * 32 + (localCoord.x >> 1) + (localCoord.y << 2);\n"
 100	"	int halfrow = texelFetch(vram, ivec2(address & 255, address >> 8), 0).r;\n"
 101	"	int entry = (halfrow >> (8 * (localCoord.x & 1))) & 255;\n"
 102	"	if (entry == 0) {\n"
 103	"		discard;\n"
 104	"	}\n"
 105	"	int paletteEntry = palette[entry];\n"
 106	"	vec4 color = vec4(PALETTE_ENTRY(paletteEntry), 1.);\n"
 107	"	return color;\n"
 108	"}";
 109
 110static const struct GBAVideoGLUniform _uniformsMode0[] = {
 111	{ "loc", GBA_GL_VS_LOC, },
 112	{ "maxPos", GBA_GL_VS_MAXPOS, },
 113	{ "vram", GBA_GL_BG_VRAM, },
 114	{ "palette", GBA_GL_BG_PALETTE, },
 115	{ "screenBase", GBA_GL_BG_SCREENBASE, },
 116	{ "charBase", GBA_GL_BG_CHARBASE, },
 117	{ "size", GBA_GL_BG_SIZE, },
 118	{ "offset", GBA_GL_BG_OFFSET, },
 119	{ "mosaic", GBA_GL_BG_MOSAIC, },
 120	{ 0 }
 121};
 122
 123static const char* const _renderMode0 =
 124	"in vec2 texCoord;\n"
 125	"uniform isampler2D vram;\n"
 126	"uniform int palette[256];\n"
 127	"uniform int screenBase;\n"
 128	"uniform int charBase;\n"
 129	"uniform int size;\n"
 130	"uniform int offset[160];\n"
 131	"uniform ivec2 mosaic;\n"
 132	"OUT(0) out vec4 color;\n"
 133
 134	"vec4 renderTile(int tile, int paletteId, ivec2 localCoord);\n"
 135
 136	"void main() {\n"
 137	"	ivec2 coord = ivec2(texCoord);\n"
 138	"	if (mosaic.x > 1) {\n"
 139	"		coord.x -= coord.x % mosaic.x;\n"
 140	"	}\n"
 141	"	if (mosaic.y > 1) {\n"
 142	"		coord.y -= coord.y % mosaic.y;\n"
 143	"	}\n"
 144	"	coord += (ivec2(0x1FF, 0x1FF000) & offset[int(texCoord.y)]) >> ivec2(0, 12);\n"
 145	"	ivec2 wrap = ivec2(255, 255);\n"
 146	"	int doty = 0;\n"
 147	"	if ((size & 1) == 1) {\n"
 148	"		wrap.x = 511;\n"
 149	"		++doty;\n"
 150	"	}\n"
 151	"	if ((size & 2) == 2) {\n"
 152	"		wrap.y = 511;\n"
 153	"		++doty;\n"
 154	"	}\n"
 155	"	coord &= wrap;\n"
 156	"	wrap = coord & 256;\n"
 157	"	coord &= 255;\n"
 158	"	coord.y += wrap.x + wrap.y * doty;\n"
 159	"	int mapAddress = screenBase + (coord.x >> 3) + (coord.y >> 3) * 32;\n"
 160	"	int map = texelFetch(vram, ivec2(mapAddress & 255, mapAddress >> 8), 0).r;\n"
 161	"	if ((map & 1024) == 1024) {\n"
 162	"		coord.x ^= 7;\n"
 163	"	}\n"
 164	"	if ((map & 2048) == 2048) {\n"
 165	"		coord.y ^= 7;\n"
 166	"	}\n"
 167	"	int tile = map & 1023;\n"
 168	"	color = renderTile(tile, map >> 12, coord & 7);\n"
 169	"}";
 170
 171static const char* const _fetchTileOverflow =
 172	"vec4 fetchTile(ivec2 coord) {\n"
 173	"	int sizeAdjusted = (0x8000 << size) - 1;\n"
 174	"	coord &= sizeAdjusted;\n"
 175	"	return renderTile(coord);\n"
 176	"}";
 177
 178static const char* const _fetchTileNoOverflow =
 179	"vec4 fetchTile(ivec2 coord) {\n"
 180	"	int sizeAdjusted = (0x8000 << size) - 1;\n"
 181	"	ivec2 outerCoord = coord & ~sizeAdjusted;\n"
 182	"	if ((outerCoord.x | outerCoord.y) != 0) {\n"
 183	"		discard;\n"
 184	"	}\n"
 185	"	return renderTile(coord);\n"
 186	"}";
 187
 188static const struct GBAVideoGLUniform _uniformsMode2[] = {
 189	{ "loc", GBA_GL_VS_LOC, },
 190	{ "maxPos", GBA_GL_VS_MAXPOS, },
 191	{ "vram", GBA_GL_BG_VRAM, },
 192	{ "palette", GBA_GL_BG_PALETTE, },
 193	{ "screenBase", GBA_GL_BG_SCREENBASE, },
 194	{ "charBase", GBA_GL_BG_CHARBASE, },
 195	{ "size", GBA_GL_BG_SIZE, },
 196	{ "offset", GBA_GL_BG_OFFSET, },
 197	{ "transform", GBA_GL_BG_TRANSFORM, },
 198	{ "range", GBA_GL_BG_RANGE, },
 199	{ "mosaic", GBA_GL_BG_MOSAIC, },
 200	{ 0 }
 201};
 202
 203static const char* const _interpolate =
 204	"vec2 interpolate(ivec2 arr[4], float x) {\n"
 205	"	float x1m = 1. - x;\n"
 206	"	return x1m * x1m * x1m * vec2(arr[0]) +"
 207		" 3. * x1m * x1m * x   * vec2(arr[1]) +"
 208		" 3. * x1m * x   * x   * vec2(arr[2]) +"
 209		"      x   * x   * x   * vec2(arr[3]);\n"
 210	"}\n"
 211
 212	"void loadAffine(int y, out ivec2 mat[4], out ivec2 aff[4]) {\n"
 213	"	int start = max(range.x, y - 3);\n"
 214	"	mat[0] = transform[start + 0].xy;\n"
 215	"	aff[0] = transform[start + 0].zw;\n"
 216	"	mat[1] = transform[start + 1].xy;\n"
 217	"	aff[1] = transform[start + 1].zw;\n"
 218	"	mat[2] = transform[start + 2].xy;\n"
 219	"	aff[2] = transform[start + 2].zw;\n"
 220	"	mat[3] = transform[start + 3].xy;\n"
 221	"	aff[3] = transform[start + 3].zw;\n"
 222	"}\n";
 223
 224static const char* const _renderMode2 =
 225	"in vec2 texCoord;\n"
 226	"uniform isampler2D vram;\n"
 227	"uniform int palette[256];\n"
 228	"uniform int screenBase;\n"
 229	"uniform int charBase;\n"
 230	"uniform int size;\n"
 231	"uniform ivec4 transform[160];\n"
 232	"uniform ivec2 range;\n"
 233	"uniform ivec2 mosaic;\n"
 234	"OUT(0) out vec4 color;\n"
 235
 236	"vec4 fetchTile(ivec2 coord);\n"
 237	"vec2 interpolate(ivec2 arr[4], float x);\n"
 238	"void loadAffine(int y, out ivec2 mat[4], out ivec2 aff[4]);\n"
 239
 240	"vec4 renderTile(ivec2 coord) {\n"
 241	"	int map = (coord.x >> 11) + (((coord.y >> 7) & 0x7F0) << size);\n"
 242	"	int mapAddress = screenBase + (map >> 1);\n"
 243	"	int twomaps = texelFetch(vram, ivec2(mapAddress & 255, mapAddress >> 8), 0).r;\n"
 244	"	int tile = (twomaps >> (8 * (map & 1))) & 255;\n"
 245	"	int address = charBase + tile * 32 + ((coord.x >> 9) & 3) + ((coord.y >> 6) & 0x1C);\n"
 246	"	int halfrow = texelFetch(vram, ivec2(address & 255, address >> 8), 0).r;\n"
 247	"	int entry = (halfrow >> (8 * ((coord.x >> 8) & 1))) & 255;\n"
 248	"	if (entry == 0) {\n"
 249	"		discard;\n"
 250	"	}\n"
 251	"	int paletteEntry = palette[entry];\n"
 252	"	vec4 color = vec4(PALETTE_ENTRY(paletteEntry), 1.);\n"
 253	"	return color;\n"
 254	"}\n"
 255
 256	"void main() {\n"
 257	"	ivec2 mat[4];\n"
 258	"	ivec2 offset[4];\n"
 259	"	vec2 incoord = texCoord;\n"
 260	"	if (mosaic.x > 1) {\n"
 261	"		incoord.x = floor(incoord.x - float(int(incoord.x) % mosaic.x));\n"
 262	"	}\n"
 263	"	if (mosaic.y > 1) {\n"
 264	"		incoord.y = floor(incoord.y - float(int(incoord.y) % mosaic.y));\n"
 265	"	}\n"
 266	"	loadAffine(int(incoord.y), mat, offset);\n"
 267	"	float y = fract(incoord.y);\n"
 268	"	float start = 0.75;\n"
 269	"	if (int(incoord.y) - range.x < 4) {\n"
 270	"		y = incoord.y - float(range.x);\n"
 271	"		start = 0.;\n"
 272	"	}\n"
 273	"	float lin = start + y * 0.25;\n"
 274	"	vec2 mixedTransform = interpolate(mat, lin);\n"
 275	"	vec2 mixedOffset = interpolate(offset, lin);\n"
 276	"	color = fetchTile(ivec2(mixedTransform * incoord.x + mixedOffset));\n"
 277	"}";
 278
 279static const struct GBAVideoGLUniform _uniformsMode35[] = {
 280	{ "loc", GBA_GL_VS_LOC, },
 281	{ "maxPos", GBA_GL_VS_MAXPOS, },
 282	{ "vram", GBA_GL_BG_VRAM, },
 283	{ "charBase", GBA_GL_BG_CHARBASE, },
 284	{ "size", GBA_GL_BG_SIZE, },
 285	{ "offset", GBA_GL_BG_OFFSET, },
 286	{ "transform", GBA_GL_BG_TRANSFORM, },
 287	{ "range", GBA_GL_BG_RANGE, },
 288	{ "mosaic", GBA_GL_BG_MOSAIC, },
 289	{ 0 }
 290};
 291
 292static const char* const _renderMode35 =
 293	"in vec2 texCoord;\n"
 294	"uniform isampler2D vram;\n"
 295	"uniform int charBase;\n"
 296	"uniform ivec2 size;\n"
 297	"uniform ivec4 transform[160];\n"
 298	"uniform ivec2 range;\n"
 299	"uniform ivec2 mosaic;\n"
 300	"OUT(0) out vec4 color;\n"
 301
 302	"vec2 interpolate(ivec2 arr[4], float x);\n"
 303	"void loadAffine(int y, out ivec2 mat[4], out ivec2 aff[4]);\n"
 304
 305	"void main() {\n"
 306	"	ivec2 mat[4];\n"
 307	"	ivec2 offset[4];\n"
 308	"	vec2 incoord = texCoord;\n"
 309	"	if (mosaic.x > 1) {\n"
 310	"		incoord.x = floor(incoord.x - float(int(incoord.x) % mosaic.x));\n"
 311	"	}\n"
 312	"	if (mosaic.y > 1) {\n"
 313	"		incoord.y = floor(incoord.y - float(int(incoord.y) % mosaic.y));\n"
 314	"	}\n"
 315	"	loadAffine(int(incoord.y), mat, offset);\n"
 316	"	float y = fract(incoord.y);\n"
 317	"	float start = 0.75;\n"
 318	"	if (int(incoord.y) - range.x < 4) {\n"
 319	"		y = incoord.y - float(range.x);\n"
 320	"		start = 0.;\n"
 321	"	}\n"
 322	"	float lin = start + y * 0.25;\n"
 323	"	vec2 mixedTransform = interpolate(mat, lin);\n"
 324	"	vec2 mixedOffset = interpolate(offset, lin);\n"
 325	"	ivec2 coord = ivec2(mixedTransform * incoord.x + mixedOffset);\n"
 326	"	if (coord.x < 0 || coord.x >= (size.x << 8)) {\n"
 327	"		discard;\n"
 328	"	}\n"
 329	"	if (coord.y < 0 || coord.y >= (size.y << 8)) {\n"
 330	"		discard;\n"
 331	"	}\n"
 332	"	int address = charBase + (coord.x >> 8) + (coord.y >> 8) * size.x;\n"
 333	"	int entry = texelFetch(vram, ivec2(address & 255, address >> 8), 0).r;\n"
 334	"	color = vec4(float(entry & 0x1F) / 31., float((entry >> 5) & 0x1F) / 31., float((entry >> 10) & 0x1F) / 31., 1.);\n"
 335	"}";
 336
 337static const struct GBAVideoGLUniform _uniformsMode4[] = {
 338	{ "loc", GBA_GL_VS_LOC, },
 339	{ "maxPos", GBA_GL_VS_MAXPOS, },
 340	{ "vram", GBA_GL_BG_VRAM, },
 341	{ "palette", GBA_GL_BG_PALETTE, },
 342	{ "charBase", GBA_GL_BG_CHARBASE, },
 343	{ "size", GBA_GL_BG_SIZE, },
 344	{ "offset", GBA_GL_BG_OFFSET, },
 345	{ "transform", GBA_GL_BG_TRANSFORM, },
 346	{ "range", GBA_GL_BG_RANGE, },
 347	{ "mosaic", GBA_GL_BG_MOSAIC, },
 348	{ 0 }
 349};
 350
 351static const char* const _renderMode4 =
 352	"in vec2 texCoord;\n"
 353	"uniform isampler2D vram;\n"
 354	"uniform int palette[256];\n"
 355	"uniform int charBase;\n"
 356	"uniform ivec2 size;\n"
 357	"uniform ivec4 transform[160];\n"
 358	"uniform ivec2 range;\n"
 359	"uniform ivec2 mosaic;\n"
 360	"OUT(0) out vec4 color;\n"
 361
 362	"vec2 interpolate(ivec2 arr[4], float x);\n"
 363	"void loadAffine(int y, out ivec2 mat[4], out ivec2 aff[4]);\n"
 364
 365	"void main() {\n"
 366	"	ivec2 mat[4];\n"
 367	"	ivec2 offset[4];\n"
 368	"	vec2 incoord = texCoord;\n"
 369	"	if (mosaic.x > 1) {\n"
 370	"		incoord.x = floor(incoord.x - float(int(incoord.x) % mosaic.x));\n"
 371	"	}\n"
 372	"	if (mosaic.y > 1) {\n"
 373	"		incoord.y = floor(incoord.y - float(int(incoord.y) % mosaic.y));\n"
 374	"	}\n"
 375	"	loadAffine(int(incoord.y), mat, offset);\n"
 376	"	float y = fract(incoord.y);\n"
 377	"	float start = 0.75;\n"
 378	"	if (int(incoord.y) - range.x < 4) {\n"
 379	"		y = incoord.y - float(range.x);\n"
 380	"		start = 0.;\n"
 381	"	}\n"
 382	"	float lin = start + y * 0.25;\n"
 383	"	vec2 mixedTransform = interpolate(mat, lin);\n"
 384	"	vec2 mixedOffset = interpolate(offset, lin);\n"
 385	"	ivec2 coord = ivec2(mixedTransform * incoord.x + mixedOffset);\n"
 386	"	if (coord.x < 0 || coord.x >= (size.x << 8)) {\n"
 387	"		discard;\n"
 388	"	}\n"
 389	"	if (coord.y < 0 || coord.y >= (size.y << 8)) {\n"
 390	"		discard;\n"
 391	"	}\n"
 392	"	int address = charBase + (coord.x >> 8) + (coord.y >> 8) * size.x;\n"
 393	"	int twoEntries = texelFetch(vram, ivec2((address >> 1) & 255, address >> 9), 0).r;\n"
 394	"	int entry = (twoEntries >> (8 * (address & 1))) & 255;\n"
 395	"	if (entry == 0) {\n"
 396	"		discard;\n"
 397	"	}\n"
 398	"	int paletteEntry = palette[entry];\n"
 399	"	color = vec4(PALETTE_ENTRY(paletteEntry), 1.);\n"
 400	"}";
 401
 402static const struct GBAVideoGLUniform _uniformsObj[] = {
 403	{ "loc", GBA_GL_VS_LOC, },
 404	{ "maxPos", GBA_GL_VS_MAXPOS, },
 405	{ "vram", GBA_GL_OBJ_VRAM, },
 406	{ "palette", GBA_GL_OBJ_PALETTE, },
 407	{ "charBase", GBA_GL_OBJ_CHARBASE, },
 408	{ "stride", GBA_GL_OBJ_STRIDE, },
 409	{ "localPalette", GBA_GL_OBJ_LOCALPALETTE, },
 410	{ "inflags", GBA_GL_OBJ_INFLAGS, },
 411	{ "transform", GBA_GL_OBJ_TRANSFORM, },
 412	{ "dims", GBA_GL_OBJ_DIMS, },
 413	{ "objwin", GBA_GL_OBJ_OBJWIN, },
 414	{ "mosaic", GBA_GL_OBJ_MOSAIC, },
 415	{ "cyclesRemaining", GBA_GL_OBJ_CYCLES, },
 416	{ 0 }
 417};
 418
 419static const char* const _renderObj =
 420	"in vec2 texCoord;\n"
 421	"uniform isampler2D vram;\n"
 422	"uniform int palette[256];\n"
 423	"uniform int charBase;\n"
 424	"uniform int stride;\n"
 425	"uniform int localPalette;\n"
 426	"uniform ivec4 inflags;\n"
 427	"uniform mat2x2 transform;\n"
 428	"uniform ivec4 dims;\n"
 429	"uniform ivec3 objwin;\n"
 430	"uniform ivec4 mosaic;\n"
 431	"uniform int cyclesRemaining[160];\n"
 432	"OUT(0) out vec4 color;\n"
 433	"OUT(1) out ivec4 flags;\n"
 434	"OUT(2) out ivec4 window;\n"
 435
 436	"vec4 renderTile(int tile, int paletteId, ivec2 localCoord);\n"
 437
 438	"void main() {\n"
 439	"	vec2 incoord = texCoord;\n"
 440	"	if (mosaic.x > 1) {\n"
 441	"		int x = int(incoord.x);\n"
 442	"		incoord.x = float(clamp(x - (mosaic.z + x) % mosaic.x, 0, dims.z - 1));\n"
 443	"	} else if (mosaic.x < -1) {\n"
 444	"		int x = dims.z - int(incoord.x) - 1;\n"
 445	"		incoord.x = float(clamp(dims.z - x + (mosaic.z + x) % -mosaic.x - 1, 0, dims.z - 1));\n"
 446	"	}\n"
 447	"	if (cyclesRemaining[int(incoord.y) + mosaic.w] <= 0) {\n"
 448	"		discard;\n"
 449	"	}\n"
 450	"	if (mosaic.y > 1) {\n"
 451	"		int y = int(incoord.y);\n"
 452	"		incoord.y = float(clamp(y - (mosaic.w + y) % mosaic.y, 0, dims.w - 1));\n"
 453	"	}\n"
 454	"	ivec2 coord = ivec2(transform * (incoord - vec2(dims.zw) / 2.) + vec2(dims.xy) / 2.);\n"
 455	"	if ((coord & ~(dims.xy - 1)) != ivec2(0, 0)) {\n"
 456	"		discard;\n"
 457	"	}\n"
 458	"	vec4 pix = renderTile((coord.x >> 3) + (coord.y >> 3) * stride, localPalette, coord & 7);\n"
 459	"	color = pix;\n"
 460	"	flags = inflags;\n"
 461	"	gl_FragDepth = float(flags.x) / 16.;\n"
 462	"	window = ivec4(objwin, 0);\n"
 463	"}";
 464
 465static const struct GBAVideoGLUniform _uniformsObjPriority[] = {
 466	{ "loc", GBA_GL_VS_LOC, },
 467	{ "maxPos", GBA_GL_VS_MAXPOS, },
 468	{ "inflags", GBA_GL_OBJ_INFLAGS, },
 469	{ 0 }
 470};
 471
 472static const char* const _renderObjPriority =
 473	"in vec2 texCoord;\n"
 474	"uniform ivec4 inflags;\n"
 475	"OUT(0) out vec4 color;\n"
 476	"OUT(1) out ivec4 flags;\n"
 477
 478	"void main() {\n"
 479	"	flags = inflags;\n"
 480	"	gl_FragDepth = float(flags.x) / 16.;\n"
 481	"	color = vec4(0., 0., 0., 0.);"
 482	"}";
 483
 484static const struct GBAVideoGLUniform _uniformsWindow[] = {
 485	{ "loc", GBA_GL_VS_LOC, },
 486	{ "maxPos", GBA_GL_VS_MAXPOS, },
 487	{ "dispcnt", GBA_GL_WIN_DISPCNT, },
 488	{ "blend", GBA_GL_WIN_BLEND, },
 489	{ "flags", GBA_GL_WIN_FLAGS, },
 490	{ "win0", GBA_GL_WIN_WIN0, },
 491	{ "win1", GBA_GL_WIN_WIN1, },
 492	{ 0 }
 493};
 494
 495static const char* const _renderWindow =
 496	"in vec2 texCoord;\n"
 497	"uniform int dispcnt;\n"
 498	"uniform ivec2 blend;\n"
 499	"uniform ivec3 flags;\n"
 500	"uniform ivec4 win0[160];\n"
 501	"uniform ivec4 win1[160];\n"
 502	"OUT(0) out ivec4 window;\n"
 503
 504	"bool crop(vec4 windowParams) {\n"
 505	"	bvec4 compare = lessThan(texCoord.xxyy, windowParams);\n"
 506	"	compare = equal(compare, bvec4(true, false, true, false));\n"
 507	"	if (any(compare)) {\n"
 508	"		vec2 h = windowParams.xy;\n"
 509	"		vec2 v = windowParams.zw;\n"
 510	"		if (v.x > v.y) {\n"
 511	"			if (compare.z && compare.w) {\n"
 512	"				return false;\n"
 513	"			}\n"
 514	"		} else if (compare.z || compare.w) {\n"
 515	"			return false;\n"
 516	"		}\n"
 517	"		if (h.x > h.y) {\n"
 518	"			if (compare.x && compare.y) {\n"
 519	"				return false;\n"
 520	"			}\n"
 521	"		} else if (compare.x || compare.y) {\n"
 522	"			return false;\n"
 523	"		}\n"
 524	"	}\n"
 525	"	return true;\n"
 526	"}\n"
 527
 528	"vec4 interpolate(vec4 top, vec4 bottom) {\n"
 529	"	if (distance(top, bottom) > 40.) {\n"
 530	"		return top;\n"
 531	"	}\n"
 532	"	return vec4(mix(bottom.xy, top.xy, fract(texCoord.y)), top.zw);\n"
 533	"}\n"
 534
 535	"void main() {\n"
 536	"	ivec4 windowFlags = ivec4(flags.z, blend, 0);\n"
 537	"	int top = int(texCoord.y);\n"
 538	"	int bottom = max(top - 1, 0);\n"
 539	"	if ((dispcnt & 0x20) != 0 && crop(interpolate(vec4(win0[top]), vec4(win0[bottom])))) { \n"
 540	"		windowFlags.x = flags.x;\n"
 541	"	} else if ((dispcnt & 0x40) != 0 && crop(interpolate(vec4(win1[top]), vec4(win1[bottom])))) {\n"
 542	"		windowFlags.x = flags.y;\n"
 543	"	}\n"
 544	"	window = windowFlags;\n"
 545	"}\n";
 546
 547static const struct GBAVideoGLUniform _uniformsFinalize[] = {
 548	{ "loc", GBA_GL_VS_LOC, },
 549	{ "maxPos", GBA_GL_VS_MAXPOS, },
 550	{ "scale", GBA_GL_FINALIZE_SCALE, },
 551	{ "layers", GBA_GL_FINALIZE_LAYERS, },
 552	{ "objFlags", GBA_GL_FINALIZE_FLAGS, },
 553	{ "window", GBA_GL_FINALIZE_WINDOW, },
 554	{ "backdrop", GBA_GL_FINALIZE_BACKDROP, },
 555	{ "backdropFlags", GBA_GL_FINALIZE_BACKDROPFLAGS, },
 556	{ 0 }
 557};
 558
 559static const char* const _finalize =
 560	"in vec2 texCoord;\n"
 561	"uniform int scale;\n"
 562	"uniform sampler2D layers[5];\n"
 563	"uniform isampler2D objFlags;\n"
 564	"uniform isampler2D window;\n"
 565	"uniform sampler2D backdrop;\n"
 566	"uniform isampler2D backdropFlags;\n"
 567	"out vec4 color;\n"
 568
 569	"void composite(vec4 pixel, ivec4 flags, inout vec4 topPixel, inout ivec4 topFlags, inout vec4 bottomPixel, inout ivec4 bottomFlags) {\n"
 570	"	if (flags.x >= topFlags.x) {\n"
 571	"		if (flags.x >= bottomFlags.x) {\n"
 572	"			return;\n"
 573	"		}\n"
 574	"		bottomFlags = flags;\n"
 575	"		bottomPixel = pixel;\n"
 576	"	} else {\n"
 577	"		bottomFlags = topFlags;\n"
 578	"		topFlags = flags;\n"
 579	"		bottomPixel = topPixel;\n"
 580	"		topPixel = pixel;\n"
 581	"	}\n"
 582	"}\n"
 583
 584	"void main() {\n"
 585	"	vec4 topPixel = texelFetch(backdrop, ivec2(0, texCoord.y), 0);\n"
 586	"	vec4 bottomPixel = topPixel;\n"
 587	"	ivec4 topFlags = ivec4(texelFetch(backdropFlags, ivec2(0, texCoord.y), 0));\n"
 588	"	ivec4 bottomFlags = topFlags;\n"
 589	"	ivec2 coord = ivec2(texCoord * float(scale));\n"
 590	"	ivec4 windowFlags = texelFetch(window, coord, 0);\n"
 591	"	int layerWindow = windowFlags.x;\n"
 592	"	if ((layerWindow & 16) != 0) {\n"
 593	"		vec4 pix = texelFetch(layers[4], coord, 0);\n"
 594	"		if (pix.a != 0.) {\n"
 595	"			ivec4 inflags = ivec4(texelFetch(objFlags, coord, 0));\n"
 596	"			composite(pix, inflags, topPixel, topFlags, bottomPixel, bottomFlags);\n"
 597	"		}\n"
 598	"	}\n"
 599	"	if ((layerWindow & 1) != 0) {\n"
 600	"		vec4 pix = texelFetch(layers[0], coord, 0);\n"
 601	"		if (pix.a != 0.) {\n"
 602	"			ivec4 inflags = ivec4(texelFetch(backdropFlags, ivec2(1, texCoord.y), 0));\n"
 603	"			composite(pix, inflags, topPixel, topFlags, bottomPixel, bottomFlags);\n"
 604	"		}\n"
 605	"	}\n"
 606	"	if ((layerWindow & 2) != 0) {\n"
 607	"		vec4 pix = texelFetch(layers[1], coord, 0);\n"
 608	"		if (pix.a != 0.) {\n"
 609	"			ivec4 inflags = ivec4(texelFetch(backdropFlags, ivec2(2, texCoord.y), 0));\n"
 610	"			composite(pix, inflags, topPixel, topFlags, bottomPixel, bottomFlags);\n"
 611	"		}\n"
 612	"	}\n"
 613	"	if ((layerWindow & 4) != 0) {\n"
 614	"		vec4 pix = texelFetch(layers[2], coord, 0);\n"
 615	"		if (pix.a != 0.) {\n"
 616	"			ivec4 inflags = ivec4(texelFetch(backdropFlags, ivec2(3, texCoord.y), 0));\n"
 617	"			composite(pix, inflags, topPixel, topFlags, bottomPixel, bottomFlags);\n"
 618	"		}\n"
 619	"	}\n"
 620	"	if ((layerWindow & 8) != 0) {\n"
 621	"		vec4 pix = texelFetch(layers[3], coord, 0);\n"
 622	"		if (pix.a != 0.) {\n"
 623	"			ivec4 inflags = ivec4(texelFetch(backdropFlags, ivec2(4, texCoord.y), 0));\n"
 624	"			composite(pix, inflags, topPixel, topFlags, bottomPixel, bottomFlags);\n"
 625	"		}\n"
 626	"	}\n"
 627	"	if ((layerWindow & 32) == 0) {\n"
 628	"		topFlags.y &= ~1;\n"
 629	"	}\n"
 630	"	if (((topFlags.y & 13) == 5 || topFlags.w > 0) && (bottomFlags.y & 2) == 2) {\n"
 631	"		topPixel.rgb *= float(topFlags.z) / 16.;\n"
 632	"		topPixel.rgb += bottomPixel.rgb * float(windowFlags.y) / 16.;\n"
 633	"	} else if ((topFlags.y & 13) == 9) {\n"
 634	"		topPixel.rgb += (1. - topPixel.rgb) * float(windowFlags.z) / 16.;\n"
 635	"	} else if ((topFlags.y & 13) == 13) {\n"
 636	"		topPixel.rgb -= topPixel.rgb * float(windowFlags.z) / 16.;\n"
 637	"	}\n"
 638	"	color = topPixel;\n"
 639	"}";
 640
 641static const GLint _vertices[] = {
 642	0, 0,
 643	0, 1,
 644	1, 1,
 645	1, 0,
 646};
 647
 648void GBAVideoGLRendererCreate(struct GBAVideoGLRenderer* renderer) {
 649	renderer->d.init = GBAVideoGLRendererInit;
 650	renderer->d.reset = GBAVideoGLRendererReset;
 651	renderer->d.deinit = GBAVideoGLRendererDeinit;
 652	renderer->d.writeVideoRegister = GBAVideoGLRendererWriteVideoRegister;
 653	renderer->d.writeVRAM = GBAVideoGLRendererWriteVRAM;
 654	renderer->d.writeOAM = GBAVideoGLRendererWriteOAM;
 655	renderer->d.writePalette = GBAVideoGLRendererWritePalette;
 656	renderer->d.drawScanline = GBAVideoGLRendererDrawScanline;
 657	renderer->d.finishFrame = GBAVideoGLRendererFinishFrame;
 658	renderer->d.getPixels = GBAVideoGLRendererGetPixels;
 659	renderer->d.putPixels = GBAVideoGLRendererPutPixels;
 660
 661	renderer->d.disableBG[0] = false;
 662	renderer->d.disableBG[1] = false;
 663	renderer->d.disableBG[2] = false;
 664	renderer->d.disableBG[3] = false;
 665	renderer->d.disableOBJ = false;
 666
 667	renderer->d.highlightBG[0] = false;
 668	renderer->d.highlightBG[1] = false;
 669	renderer->d.highlightBG[2] = false;
 670	renderer->d.highlightBG[3] = false;
 671	int i;
 672	for (i = 0; i < 128; ++i) {
 673		renderer->d.highlightOBJ[i] = false;
 674	}
 675	renderer->d.highlightColor = M_COLOR_WHITE;
 676	renderer->d.highlightAmount = 0;
 677
 678	renderer->scale = 1;
 679}
 680
 681static void _compileShader(struct GBAVideoGLRenderer* glRenderer, struct GBAVideoGLShader* shader, const char** shaderBuffer, int shaderBufferLines, GLuint vs, const struct GBAVideoGLUniform* uniforms, const char* const* outFrags, char* log) {
 682	GLuint program = glCreateProgram();
 683	shader->program = program;
 684
 685	GLuint fs = glCreateShader(GL_FRAGMENT_SHADER);
 686	glAttachShader(program, vs);
 687	glAttachShader(program, fs);
 688	glShaderSource(fs, shaderBufferLines, shaderBuffer, 0);
 689	glCompileShader(fs);
 690	glGetShaderInfoLog(fs, 2048, 0, log);
 691	if (log[0]) {
 692		mLOG(GBA_VIDEO, ERROR, "Fragment shader compilation failure: %s", log);
 693	}
 694	size_t i;
 695#ifndef BUILD_GLES3
 696	for (i = 0; outFrags[i]; ++i) {
 697		glBindFragDataLocation(program, i, outFrags[i]);
 698	}
 699#else
 700	UNUSED(outFrags);
 701#endif
 702	glLinkProgram(program);
 703	glGetProgramInfoLog(program, 2048, 0, log);
 704	if (log[0]) {
 705		mLOG(GBA_VIDEO, ERROR, "Program link failure: %s", log);
 706	}
 707	glDeleteShader(fs);
 708
 709	glGenVertexArrays(1, &shader->vao);
 710	glBindVertexArray(shader->vao);
 711	glBindBuffer(GL_ARRAY_BUFFER, glRenderer->vbo);
 712	GLuint positionLocation = glGetAttribLocation(program, "position");
 713	glEnableVertexAttribArray(positionLocation);
 714	glVertexAttribPointer(positionLocation, 2, GL_INT, GL_FALSE, 0, NULL);
 715
 716	for (i = 0; uniforms[i].name; ++i) {
 717		shader->uniforms[uniforms[i].type] = glGetUniformLocation(program, uniforms[i].name);
 718	}
 719}
 720
 721static void _deleteShader(struct GBAVideoGLShader* shader) {
 722	glDeleteProgram(shader->program);
 723	glDeleteVertexArrays(1, &shader->vao);
 724}
 725
 726static void _initFramebufferTextureEx(GLuint tex, GLenum internalFormat, GLenum format, GLenum type, GLenum attachment, int scale) {
 727	glBindTexture(GL_TEXTURE_2D, tex);
 728	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
 729	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
 730	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
 731	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
 732	glTexImage2D(GL_TEXTURE_2D, 0, internalFormat, scale > 0 ? GBA_VIDEO_HORIZONTAL_PIXELS * scale : 8, GBA_VIDEO_VERTICAL_PIXELS * (scale > 0 ? scale : 1), 0, format, type, 0);
 733	glFramebufferTexture2D(GL_FRAMEBUFFER, attachment, GL_TEXTURE_2D, tex, 0);
 734}
 735
 736static void _initFramebufferTexture(GLuint tex, GLenum format, GLenum attachment, int scale) {
 737	_initFramebufferTextureEx(tex, format, format, GL_UNSIGNED_BYTE, attachment, scale);
 738}
 739
 740static void _initFramebuffers(struct GBAVideoGLRenderer* glRenderer) {
 741	glBindFramebuffer(GL_FRAMEBUFFER, glRenderer->fbo[GBA_GL_FBO_OBJ]);
 742	_initFramebufferTexture(glRenderer->layers[GBA_GL_TEX_OBJ_COLOR], GL_RGBA, GL_COLOR_ATTACHMENT0, glRenderer->scale);
 743	_initFramebufferTextureEx(glRenderer->layers[GBA_GL_TEX_OBJ_FLAGS], GL_RGBA8I, GL_RGBA_INTEGER, GL_BYTE, GL_COLOR_ATTACHMENT1, glRenderer->scale);
 744	_initFramebufferTextureEx(glRenderer->layers[GBA_GL_TEX_WINDOW], GL_RGBA8I, GL_RGBA_INTEGER, GL_BYTE, GL_COLOR_ATTACHMENT2, glRenderer->scale);
 745	_initFramebufferTextureEx(glRenderer->layers[GBA_GL_TEX_OBJ_DEPTH], GL_DEPTH24_STENCIL8, GL_DEPTH_STENCIL, GL_UNSIGNED_INT_24_8, GL_DEPTH_STENCIL_ATTACHMENT, glRenderer->scale);
 746
 747	glBindFramebuffer(GL_FRAMEBUFFER, glRenderer->fbo[GBA_GL_FBO_BACKDROP]);
 748	_initFramebufferTexture(glRenderer->layers[GBA_GL_TEX_BACKDROP_COLOR], GL_RGB, GL_COLOR_ATTACHMENT0, 0);
 749	_initFramebufferTextureEx(glRenderer->layers[GBA_GL_TEX_BACKDROP_FLAGS], GL_RGBA8I, GL_RGBA_INTEGER, GL_BYTE, GL_COLOR_ATTACHMENT1, 0);
 750
 751	glBindFramebuffer(GL_FRAMEBUFFER, glRenderer->fbo[GBA_GL_FBO_WINDOW]);
 752	glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, glRenderer->layers[GBA_GL_TEX_WINDOW], 0);
 753
 754	glBindFramebuffer(GL_FRAMEBUFFER, glRenderer->fbo[GBA_GL_FBO_OUTPUT]);
 755	_initFramebufferTexture(glRenderer->outputTex, GL_RGB, GL_COLOR_ATTACHMENT0, glRenderer->scale);
 756
 757	int i;
 758	for (i = 0; i < 4; ++i) {
 759		struct GBAVideoGLBackground* bg = &glRenderer->bg[i];
 760		glBindFramebuffer(GL_FRAMEBUFFER, bg->fbo);
 761		_initFramebufferTexture(bg->tex, GL_RGBA, GL_COLOR_ATTACHMENT0, glRenderer->scale);
 762	}
 763	glBindFramebuffer(GL_FRAMEBUFFER, 0);
 764}
 765
 766void GBAVideoGLRendererInit(struct GBAVideoRenderer* renderer) {
 767	struct GBAVideoGLRenderer* glRenderer = (struct GBAVideoGLRenderer*) renderer;
 768	glRenderer->temporaryBuffer = NULL;
 769
 770	glGenFramebuffers(GBA_GL_FBO_MAX, glRenderer->fbo);
 771	glGenTextures(GBA_GL_TEX_MAX, glRenderer->layers);
 772
 773	glGenTextures(1, &glRenderer->vramTex);
 774	glBindTexture(GL_TEXTURE_2D, glRenderer->vramTex);
 775	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
 776	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
 777	glTexImage2D(GL_TEXTURE_2D, 0, GL_R16UI, 256, 192, 0, GL_RED_INTEGER, GL_UNSIGNED_SHORT, 0);
 778
 779	glGenBuffers(1, &glRenderer->vbo);
 780	glBindBuffer(GL_ARRAY_BUFFER, glRenderer->vbo);
 781	glBufferData(GL_ARRAY_BUFFER, sizeof(_vertices), _vertices, GL_STATIC_DRAW);
 782
 783	int i;
 784	for (i = 0; i < 4; ++i) {
 785		struct GBAVideoGLBackground* bg = &glRenderer->bg[i];
 786		bg->index = i;
 787		bg->enabled = 0;
 788		bg->priority = 0;
 789		bg->charBase = 0;
 790		bg->mosaic = 0;
 791		bg->multipalette = 0;
 792		bg->screenBase = 0;
 793		bg->overflow = 0;
 794		bg->size = 0;
 795		bg->target1 = 0;
 796		bg->target2 = 0;
 797		bg->x = 0;
 798		bg->y = 0;
 799		bg->refx = 0;
 800		bg->refy = 0;
 801		bg->affine.dx = 256;
 802		bg->affine.dmx = 0;
 803		bg->affine.dy = 0;
 804		bg->affine.dmy = 256;
 805		bg->affine.sx = 0;
 806		bg->affine.sy = 0;
 807		glGenFramebuffers(1, &bg->fbo);
 808		glGenTextures(1, &bg->tex);
 809	}
 810
 811	_initFramebuffers(glRenderer);
 812
 813	char log[2048];
 814	const GLchar* shaderBuffer[4];
 815	const GLubyte* version = glGetString(GL_VERSION);
 816	if (strncmp((const char*) version, "OpenGL ES ", strlen("OpenGL ES "))) {
 817		shaderBuffer[0] = _gl3Header;
 818	} else {
 819		shaderBuffer[0] = _gles3Header;
 820	}
 821
 822	GLuint vs = glCreateShader(GL_VERTEX_SHADER);
 823	shaderBuffer[1] = _vertexShader;
 824	glShaderSource(vs, 2, shaderBuffer, 0);
 825	glCompileShader(vs);
 826	glGetShaderInfoLog(vs, 2048, 0, log);
 827	if (log[0]) {
 828		mLOG(GBA_VIDEO, ERROR, "Vertex shader compilation failure: %s", log);
 829	}
 830
 831	const char* const noWindow[] = {"color", "flags", NULL};
 832	const char* const window[] = {"color", "flags", "window", NULL};
 833	const char* const onlyWindow[] = {"window", NULL};
 834	const char* const onlyColor[] = {"color", NULL};
 835
 836	shaderBuffer[1] = _renderMode0;
 837
 838	shaderBuffer[2] = _renderTile16;
 839	_compileShader(glRenderer, &glRenderer->bgShader[0], shaderBuffer, 3, vs, _uniformsMode0, noWindow, log);
 840
 841	shaderBuffer[2] = _renderTile256;
 842	_compileShader(glRenderer, &glRenderer->bgShader[1], shaderBuffer, 3, vs, _uniformsMode0, noWindow, log);
 843
 844	shaderBuffer[1] = _renderMode2;
 845	shaderBuffer[2] = _interpolate;
 846
 847	shaderBuffer[3] = _fetchTileOverflow;
 848	_compileShader(glRenderer, &glRenderer->bgShader[2], shaderBuffer, 4, vs, _uniformsMode2, noWindow, log);
 849
 850	shaderBuffer[3] = _fetchTileNoOverflow;
 851	_compileShader(glRenderer, &glRenderer->bgShader[3], shaderBuffer, 4, vs, _uniformsMode2, noWindow, log);
 852
 853	shaderBuffer[1] = _renderMode4;
 854	shaderBuffer[2] = _interpolate;
 855	_compileShader(glRenderer, &glRenderer->bgShader[4], shaderBuffer, 3, vs, _uniformsMode4, noWindow, log);
 856
 857	shaderBuffer[1] = _renderMode35;
 858	shaderBuffer[2] = _interpolate;
 859	_compileShader(glRenderer, &glRenderer->bgShader[5], shaderBuffer, 3, vs, _uniformsMode35, noWindow, log);
 860
 861	shaderBuffer[1] = _renderObj;
 862
 863	shaderBuffer[2] = _renderTile16;
 864	_compileShader(glRenderer, &glRenderer->objShader[0], shaderBuffer, 3, vs, _uniformsObj, window, log);
 865
 866	shaderBuffer[2] = _renderTile256;
 867	_compileShader(glRenderer, &glRenderer->objShader[1], shaderBuffer, 3, vs, _uniformsObj, window, log);
 868
 869	shaderBuffer[1] = _renderObjPriority;
 870	_compileShader(glRenderer, &glRenderer->objShader[2], shaderBuffer, 2, vs, _uniformsObjPriority, noWindow, log);
 871
 872	shaderBuffer[1] = _renderWindow;
 873	_compileShader(glRenderer, &glRenderer->windowShader, shaderBuffer, 2, vs, _uniformsWindow, onlyWindow, log);
 874
 875	shaderBuffer[1] = _finalize;
 876	_compileShader(glRenderer, &glRenderer->finalizeShader, shaderBuffer, 2, vs, _uniformsFinalize, onlyColor, log);
 877
 878	glBindVertexArray(0);
 879	glDeleteShader(vs);
 880
 881	GBAVideoGLRendererReset(renderer);
 882}
 883
 884void GBAVideoGLRendererDeinit(struct GBAVideoRenderer* renderer) {
 885	struct GBAVideoGLRenderer* glRenderer = (struct GBAVideoGLRenderer*) renderer;
 886	if (glRenderer->temporaryBuffer) {
 887		mappedMemoryFree(glRenderer->temporaryBuffer, GBA_VIDEO_HORIZONTAL_PIXELS * GBA_VIDEO_VERTICAL_PIXELS * glRenderer->scale * glRenderer->scale);
 888	}
 889	glDeleteFramebuffers(GBA_GL_FBO_MAX, glRenderer->fbo);
 890	glDeleteTextures(GBA_GL_TEX_MAX, glRenderer->layers);
 891	glDeleteTextures(1, &glRenderer->vramTex);
 892	glDeleteBuffers(1, &glRenderer->vbo);
 893
 894	_deleteShader(&glRenderer->bgShader[0]);
 895	_deleteShader(&glRenderer->bgShader[1]);
 896	_deleteShader(&glRenderer->bgShader[2]);
 897	_deleteShader(&glRenderer->bgShader[3]);
 898	_deleteShader(&glRenderer->objShader[0]);
 899	_deleteShader(&glRenderer->objShader[1]);
 900	_deleteShader(&glRenderer->objShader[2]);
 901	_deleteShader(&glRenderer->finalizeShader);
 902
 903	int i;
 904	for (i = 0; i < 4; ++i) {
 905		struct GBAVideoGLBackground* bg = &glRenderer->bg[i];
 906		glDeleteFramebuffers(1, &bg->fbo);
 907		glDeleteTextures(1, &bg->tex);
 908	}
 909}
 910
 911void GBAVideoGLRendererReset(struct GBAVideoRenderer* renderer) {
 912	struct GBAVideoGLRenderer* glRenderer = (struct GBAVideoGLRenderer*) renderer;
 913
 914	glRenderer->oamDirty = true;
 915	glRenderer->paletteDirty = true;
 916	glRenderer->vramDirty = 0xFFFFFF;
 917	glRenderer->firstAffine = -1;
 918	glRenderer->firstY = -1;
 919	glRenderer->dispcnt = 0x0080;
 920	glRenderer->mosaic = 0;
 921	memset(glRenderer->shadowRegs, 0, sizeof(glRenderer->shadowRegs));
 922	glRenderer->regsDirty = 0xFFFFFFFFFFFEULL;
 923}
 924
 925void GBAVideoGLRendererWriteVRAM(struct GBAVideoRenderer* renderer, uint32_t address) {
 926	struct GBAVideoGLRenderer* glRenderer = (struct GBAVideoGLRenderer*) renderer;
 927	glRenderer->vramDirty |= 1 << (address >> 12);
 928}
 929
 930void GBAVideoGLRendererWriteOAM(struct GBAVideoRenderer* renderer, uint32_t oam) {
 931	UNUSED(oam);
 932	struct GBAVideoGLRenderer* glRenderer = (struct GBAVideoGLRenderer*) renderer;
 933	glRenderer->oamDirty = true;
 934}
 935
 936void GBAVideoGLRendererWritePalette(struct GBAVideoRenderer* renderer, uint32_t address, uint16_t value) {
 937	struct GBAVideoGLRenderer* glRenderer = (struct GBAVideoGLRenderer*) renderer;
 938	UNUSED(address);
 939	UNUSED(value);
 940	glRenderer->paletteDirty = true;
 941}
 942
 943uint16_t GBAVideoGLRendererWriteVideoRegister(struct GBAVideoRenderer* renderer, uint32_t address, uint16_t value) {
 944	struct GBAVideoGLRenderer* glRenderer = (struct GBAVideoGLRenderer*) renderer;
 945	if (renderer->cache) {
 946		GBAVideoCacheWriteVideoRegister(renderer->cache, address, value);
 947	}
 948
 949	bool dirty = false;
 950	switch (address) {
 951	case REG_DISPCNT:
 952		value &= 0xFFF7;
 953		dirty = true;
 954		break;
 955	case REG_BG0CNT:
 956	case REG_BG1CNT:
 957		value &= 0xDFFF;
 958		dirty = true;
 959		break;
 960	case REG_BG0HOFS:
 961		value &= 0x01FF;
 962		glRenderer->bg[0].x = value;
 963		dirty = false;
 964		break;
 965	case REG_BG0VOFS:
 966		value &= 0x01FF;
 967		glRenderer->bg[0].y = value;
 968		dirty = false;
 969		break;
 970	case REG_BG1HOFS:
 971		value &= 0x01FF;
 972		glRenderer->bg[1].x = value;
 973		dirty = false;
 974		break;
 975	case REG_BG1VOFS:
 976		value &= 0x01FF;
 977		glRenderer->bg[1].y = value;
 978		dirty = false;
 979		break;
 980	case REG_BG2HOFS:
 981		value &= 0x01FF;
 982		glRenderer->bg[2].x = value;
 983		dirty = false;
 984		break;
 985	case REG_BG2VOFS:
 986		value &= 0x01FF;
 987		glRenderer->bg[2].y = value;
 988		dirty = false;
 989		break;
 990	case REG_BG3HOFS:
 991		value &= 0x01FF;
 992		glRenderer->bg[3].x = value;
 993		dirty = false;
 994		break;
 995	case REG_BG3VOFS:
 996		value &= 0x01FF;
 997		glRenderer->bg[3].y = value;
 998		dirty = false;
 999		break;
1000	case REG_BG2PA:
1001		glRenderer->bg[2].affine.dx = value;
1002		break;
1003	case REG_BG2PB:
1004		glRenderer->bg[2].affine.dmx = value;
1005		break;
1006	case REG_BG2PC:
1007		glRenderer->bg[2].affine.dy = value;
1008		break;
1009	case REG_BG2PD:
1010		glRenderer->bg[2].affine.dmy = value;
1011		break;
1012	case REG_BG2X_LO:
1013		GBAVideoGLRendererWriteBGX_LO(&glRenderer->bg[2], value);
1014		break;
1015	case REG_BG2X_HI:
1016		GBAVideoGLRendererWriteBGX_HI(&glRenderer->bg[2], value);
1017		break;
1018	case REG_BG2Y_LO:
1019		GBAVideoGLRendererWriteBGY_LO(&glRenderer->bg[2], value);
1020		break;
1021	case REG_BG2Y_HI:
1022		GBAVideoGLRendererWriteBGY_HI(&glRenderer->bg[2], value);
1023		break;
1024	case REG_BG3PA:
1025		glRenderer->bg[3].affine.dx = value;
1026		break;
1027	case REG_BG3PB:
1028		glRenderer->bg[3].affine.dmx = value;
1029		break;
1030	case REG_BG3PC:
1031		glRenderer->bg[3].affine.dy = value;
1032		break;
1033	case REG_BG3PD:
1034		glRenderer->bg[3].affine.dmy = value;
1035		break;
1036	case REG_BG3X_LO:
1037		GBAVideoGLRendererWriteBGX_LO(&glRenderer->bg[3], value);
1038		break;
1039	case REG_BG3X_HI:
1040		GBAVideoGLRendererWriteBGX_HI(&glRenderer->bg[3], value);
1041		break;
1042	case REG_BG3Y_LO:
1043		GBAVideoGLRendererWriteBGY_LO(&glRenderer->bg[3], value);
1044		break;
1045	case REG_BG3Y_HI:
1046		GBAVideoGLRendererWriteBGY_HI(&glRenderer->bg[3], value);
1047		break;
1048	case REG_BLDALPHA:
1049		value &= 0x1F1F;
1050		dirty = true;
1051		break;
1052	case REG_BLDY:
1053		value &= 0x1F;
1054		if (value > 0x10) {
1055			value = 0x10;
1056		}
1057		dirty = true;
1058		break;
1059			case REG_WIN0H:
1060		glRenderer->winN[0].h.end = value;
1061		glRenderer->winN[0].h.start = value >> 8;
1062		if (glRenderer->winN[0].h.start > GBA_VIDEO_HORIZONTAL_PIXELS && glRenderer->winN[0].h.start > glRenderer->winN[0].h.end) {
1063			glRenderer->winN[0].h.start = 0;
1064		}
1065		if (glRenderer->winN[0].h.end > GBA_VIDEO_HORIZONTAL_PIXELS) {
1066			glRenderer->winN[0].h.end = GBA_VIDEO_HORIZONTAL_PIXELS;
1067			if (glRenderer->winN[0].h.start > GBA_VIDEO_HORIZONTAL_PIXELS) {
1068				glRenderer->winN[0].h.start = GBA_VIDEO_HORIZONTAL_PIXELS;
1069			}
1070		}
1071		break;
1072	case REG_WIN1H:
1073		glRenderer->winN[1].h.end = value;
1074		glRenderer->winN[1].h.start = value >> 8;
1075		if (glRenderer->winN[1].h.start > GBA_VIDEO_HORIZONTAL_PIXELS && glRenderer->winN[1].h.start > glRenderer->winN[1].h.end) {
1076			glRenderer->winN[1].h.start = 0;
1077		}
1078		if (glRenderer->winN[1].h.end > GBA_VIDEO_HORIZONTAL_PIXELS) {
1079			glRenderer->winN[1].h.end = GBA_VIDEO_HORIZONTAL_PIXELS;
1080			if (glRenderer->winN[1].h.start > GBA_VIDEO_HORIZONTAL_PIXELS) {
1081				glRenderer->winN[1].h.start = GBA_VIDEO_HORIZONTAL_PIXELS;
1082			}
1083		}
1084		break;
1085	case REG_WIN0V:
1086		glRenderer->winN[0].v.end = value;
1087		glRenderer->winN[0].v.start = value >> 8;
1088		if (glRenderer->winN[0].v.start > GBA_VIDEO_VERTICAL_PIXELS && glRenderer->winN[0].v.start > glRenderer->winN[0].v.end) {
1089			glRenderer->winN[0].v.start = 0;
1090		}
1091		if (glRenderer->winN[0].v.end > GBA_VIDEO_VERTICAL_PIXELS) {
1092			glRenderer->winN[0].v.end = GBA_VIDEO_VERTICAL_PIXELS;
1093			if (glRenderer->winN[0].v.start > GBA_VIDEO_VERTICAL_PIXELS) {
1094				glRenderer->winN[0].v.start = GBA_VIDEO_VERTICAL_PIXELS;
1095			}
1096		}
1097		break;
1098	case REG_WIN1V:
1099		glRenderer->winN[1].v.end = value;
1100		glRenderer->winN[1].v.start = value >> 8;
1101		if (glRenderer->winN[1].v.start > GBA_VIDEO_VERTICAL_PIXELS && glRenderer->winN[1].v.start > glRenderer->winN[1].v.end) {
1102			glRenderer->winN[1].v.start = 0;
1103		}
1104		if (glRenderer->winN[1].v.end > GBA_VIDEO_VERTICAL_PIXELS) {
1105			glRenderer->winN[1].v.end = GBA_VIDEO_VERTICAL_PIXELS;
1106			if (glRenderer->winN[1].v.start > GBA_VIDEO_VERTICAL_PIXELS) {
1107				glRenderer->winN[1].v.start = GBA_VIDEO_VERTICAL_PIXELS;
1108			}
1109		}
1110		break;
1111	case REG_WININ:
1112	case REG_WINOUT:
1113		value &= 0x3F3F;
1114		dirty = true;
1115		break;
1116	default:
1117		dirty = true;
1118		break;
1119	}
1120	if (glRenderer->shadowRegs[address >> 1] == value) {
1121		dirty = false;
1122	} else {
1123		glRenderer->shadowRegs[address >> 1] = value;
1124	}
1125	if (dirty) {
1126		glRenderer->regsDirty |= 1ULL << (address >> 1);
1127	}
1128	return value;
1129}
1130
1131void _cleanRegister(struct GBAVideoGLRenderer* glRenderer, int address, uint16_t value) {
1132	switch (address) {
1133	case REG_DISPCNT:
1134		glRenderer->dispcnt = value;
1135		GBAVideoGLRendererUpdateDISPCNT(glRenderer);
1136		break;
1137	case REG_BG0CNT:
1138		GBAVideoGLRendererWriteBGCNT(&glRenderer->bg[0], value);
1139		break;
1140	case REG_BG1CNT:
1141		GBAVideoGLRendererWriteBGCNT(&glRenderer->bg[1], value);
1142		break;
1143	case REG_BG2CNT:
1144		GBAVideoGLRendererWriteBGCNT(&glRenderer->bg[2], value);
1145		break;
1146	case REG_BG3CNT:
1147		GBAVideoGLRendererWriteBGCNT(&glRenderer->bg[3], value);
1148		break;
1149	case REG_BLDCNT:
1150		GBAVideoGLRendererWriteBLDCNT(glRenderer, value);
1151		break;
1152	case REG_BLDALPHA:
1153		glRenderer->blda = value & 0x1F;
1154		if (glRenderer->blda > 0x10) {
1155			glRenderer->blda = 0x10;
1156		}
1157		glRenderer->bldb = (value >> 8) & 0x1F;
1158		if (glRenderer->bldb > 0x10) {
1159			glRenderer->bldb = 0x10;
1160		}
1161		break;
1162	case REG_BLDY:
1163		glRenderer->bldy = value;
1164		break;
1165	case REG_WININ:
1166		glRenderer->winN[0].control = value;
1167		glRenderer->winN[1].control = value >> 8;
1168		break;
1169	case REG_WINOUT:
1170		glRenderer->winout = value;
1171		glRenderer->objwin = value >> 8;
1172		break;
1173	case REG_MOSAIC:
1174		glRenderer->mosaic = value;
1175		break;
1176	default:
1177		break;
1178	}
1179}
1180
1181static bool _dirtyMode0(struct GBAVideoGLRenderer* renderer, struct GBAVideoGLBackground* background, int y) {
1182	UNUSED(y);
1183	if (!background->enabled) {
1184		return false;
1185	}
1186	unsigned screenBase = background->screenBase >> 11; // Lops off one extra bit
1187	unsigned screenMask = (7 << screenBase) & 0xFFFF; // Technically overzealous
1188	if (renderer->vramDirty & screenMask) {
1189		return true;
1190	}
1191	unsigned charBase = background->charBase >> 11;
1192	unsigned charMask = (0xFFFF << charBase) & 0xFFFF;
1193	if (renderer->vramDirty & charMask) {
1194		return true;
1195	}
1196	return false;
1197}
1198
1199static bool _dirtyMode2(struct GBAVideoGLRenderer* renderer, struct GBAVideoGLBackground* background, int y) {
1200	UNUSED(y);
1201	if (!background->enabled) {
1202		return false;
1203	}
1204	unsigned screenBase = background->screenBase >> 11; // Lops off one extra bit
1205	unsigned screenMask = (0xF << screenBase) & 0xFFFF;
1206	if (renderer->vramDirty & screenMask) {
1207		return true;
1208	}
1209	unsigned charBase = background->charBase >> 11;
1210	unsigned charMask = (0x3FFF << charBase) & 0xFFFF;
1211	if (renderer->vramDirty & charMask) {
1212		return true;
1213	}
1214	return false;
1215}
1216
1217static bool _dirtyMode3(struct GBAVideoGLRenderer* renderer, struct GBAVideoGLBackground* background, int y) {
1218	UNUSED(y);
1219	if (!background->enabled) {
1220		return false;
1221	}
1222	if (renderer->vramDirty & 0xFFFFF) {
1223		return true;
1224	}
1225	return false;
1226}
1227
1228static bool _dirtyMode45(struct GBAVideoGLRenderer* renderer, struct GBAVideoGLBackground* background, int y) {
1229	UNUSED(y);
1230	if (!background->enabled) {
1231		return false;
1232	}
1233	int start = GBARegisterDISPCNTIsFrameSelect(renderer->dispcnt) ? 5 : 0;
1234	int mask = 0x3FF << start;
1235	if (renderer->vramDirty & mask) {
1236		return true;
1237	}
1238	return false;
1239}
1240
1241static bool _needsVramUpload(struct GBAVideoGLRenderer* renderer, int y) {
1242	if (!renderer->vramDirty) {
1243		return false;
1244	}
1245	if (y == 0) {
1246		return true;
1247	}
1248
1249	if (GBARegisterDISPCNTIsObjEnable(renderer->dispcnt) && renderer->vramDirty & 0xFF0000) {
1250		return true;
1251	}
1252
1253	bool dirty = false;
1254	switch (GBARegisterDISPCNTGetMode(renderer->dispcnt)) {
1255	case 0:
1256		dirty = dirty || _dirtyMode0(renderer, &renderer->bg[0], y);
1257		dirty = dirty || _dirtyMode0(renderer, &renderer->bg[1], y);
1258		dirty = dirty || _dirtyMode0(renderer, &renderer->bg[2], y);
1259		dirty = dirty || _dirtyMode0(renderer, &renderer->bg[3], y);
1260		break;
1261	case 1:
1262		dirty = dirty || _dirtyMode0(renderer, &renderer->bg[0], y);
1263		dirty = dirty || _dirtyMode0(renderer, &renderer->bg[1], y);
1264		dirty = dirty || _dirtyMode2(renderer, &renderer->bg[2], y);
1265		break;
1266	case 2:
1267		dirty = dirty || _dirtyMode2(renderer, &renderer->bg[2], y);
1268		dirty = dirty || _dirtyMode2(renderer, &renderer->bg[3], y);
1269		break;
1270	case 3:
1271		dirty = _dirtyMode3(renderer, &renderer->bg[2], y);
1272		break;
1273	case 4:
1274		dirty = _dirtyMode45(renderer, &renderer->bg[2], y);
1275		break;
1276	case 5:
1277		dirty = _dirtyMode45(renderer, &renderer->bg[2], y);
1278		break;
1279	}
1280	return dirty;
1281}
1282
1283void GBAVideoGLRendererDrawScanline(struct GBAVideoRenderer* renderer, int y) {
1284	struct GBAVideoGLRenderer* glRenderer = (struct GBAVideoGLRenderer*) renderer;
1285
1286	if (GBARegisterDISPCNTGetMode(glRenderer->dispcnt) != 0) {
1287		if (glRenderer->firstAffine < 0) {
1288			glRenderer->firstAffine = y;
1289		}
1290	} else {
1291		glRenderer->firstAffine = -1;
1292	}
1293
1294	if (glRenderer->paletteDirty || _needsVramUpload(glRenderer, y) || glRenderer->oamDirty || glRenderer->regsDirty) {
1295		if (glRenderer->firstY >= 0) {
1296			_drawScanlines(glRenderer, y - 1);
1297			glBindVertexArray(0);
1298		}
1299	}
1300	if (glRenderer->firstY < 0) {
1301		glRenderer->firstY = y;
1302	}
1303
1304	int i;
1305	for (i = 0; i < 0x30; ++i) {
1306		if (!(glRenderer->regsDirty & (1ULL << i))) {
1307			continue;
1308		}
1309		_cleanRegister(glRenderer, i << 1, glRenderer->shadowRegs[i]);
1310	}
1311	glRenderer->regsDirty = 0;
1312
1313	glRenderer->winNHistory[0][y * 4 + 0] = glRenderer->winN[0].h.start;
1314	glRenderer->winNHistory[0][y * 4 + 1] = glRenderer->winN[0].h.end;
1315	glRenderer->winNHistory[0][y * 4 + 2] = glRenderer->winN[0].v.start;
1316	glRenderer->winNHistory[0][y * 4 + 3] = glRenderer->winN[0].v.end;
1317	glRenderer->winNHistory[1][y * 4 + 0] = glRenderer->winN[1].h.start;
1318	glRenderer->winNHistory[1][y * 4 + 1] = glRenderer->winN[1].h.end;
1319	glRenderer->winNHistory[1][y * 4 + 2] = glRenderer->winN[1].v.start;
1320	glRenderer->winNHistory[1][y * 4 + 3] = glRenderer->winN[1].v.end;
1321
1322	glRenderer->bg[0].scanlineOffset[y] = glRenderer->bg[0].x;
1323	glRenderer->bg[0].scanlineOffset[y] |= glRenderer->bg[0].y << 12;
1324	glRenderer->bg[1].scanlineOffset[y] = glRenderer->bg[1].x;
1325	glRenderer->bg[1].scanlineOffset[y] |= glRenderer->bg[1].y << 12;
1326	glRenderer->bg[2].scanlineOffset[y] = glRenderer->bg[2].x;
1327	glRenderer->bg[2].scanlineOffset[y] |= glRenderer->bg[2].y << 12;
1328	glRenderer->bg[2].scanlineAffine[y * 4] = glRenderer->bg[2].affine.dx;
1329	glRenderer->bg[2].scanlineAffine[y * 4 + 1] = glRenderer->bg[2].affine.dy;
1330	glRenderer->bg[2].scanlineAffine[y * 4 + 2] = glRenderer->bg[2].affine.sx;
1331	glRenderer->bg[2].scanlineAffine[y * 4 + 3] = glRenderer->bg[2].affine.sy;
1332	glRenderer->bg[3].scanlineOffset[y] = glRenderer->bg[3].x;
1333	glRenderer->bg[3].scanlineOffset[y] |= glRenderer->bg[3].y << 12;
1334	glRenderer->bg[3].scanlineAffine[y * 4] = glRenderer->bg[3].affine.dx;
1335	glRenderer->bg[3].scanlineAffine[y * 4 + 1] = glRenderer->bg[3].affine.dy;
1336	glRenderer->bg[3].scanlineAffine[y * 4 + 2] = glRenderer->bg[3].affine.sx;
1337	glRenderer->bg[3].scanlineAffine[y * 4 + 3] = glRenderer->bg[3].affine.sy;
1338
1339	if (glRenderer->paletteDirty) {
1340		for (i = 0; i < 512; ++i) {
1341			glRenderer->shadowPalette[i] = glRenderer->d.palette[i];
1342		}
1343		glRenderer->paletteDirty = false;
1344	}
1345
1346	if (_needsVramUpload(glRenderer, y)) {
1347		int first = -1;
1348		glBindTexture(GL_TEXTURE_2D, glRenderer->vramTex);
1349		for (i = 0; i < 25; ++i) {
1350			if (!(glRenderer->vramDirty & (1 << i))) {
1351				if (first >= 0) {
1352					glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 8 * first, 256, 8 * (i - first), GL_RED_INTEGER, GL_UNSIGNED_SHORT, &glRenderer->d.vram[2048 * first]);
1353					first = -1;
1354				}
1355			} else if (first < 0) {
1356				first = i;
1357			}
1358		}
1359		glRenderer->vramDirty = 0;
1360	}
1361
1362	if (glRenderer->oamDirty) {
1363		glRenderer->oamMax = GBAVideoRendererCleanOAM(glRenderer->d.oam->obj, glRenderer->sprites, 0);
1364		glRenderer->oamDirty = false;
1365	}
1366
1367	if (y == 0) {
1368		glDisable(GL_SCISSOR_TEST);
1369		glClearColor(0, 0, 0, 0);
1370#ifdef BUILD_GLES3
1371		glClearDepthf(1.f);
1372#else
1373		glClearDepth(1);
1374#endif
1375		glClearStencil(0);
1376		glBindFramebuffer(GL_FRAMEBUFFER, glRenderer->fbo[GBA_GL_FBO_OBJ]);
1377		glDrawBuffers(1, (GLenum[]) { GL_COLOR_ATTACHMENT0 });
1378		glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
1379
1380		for (i = 0; i < 4; ++i) {
1381			glBindFramebuffer(GL_FRAMEBUFFER, glRenderer->bg[i].fbo);
1382			glDrawBuffers(1, (GLenum[]) { GL_COLOR_ATTACHMENT0 });
1383			glClear(GL_COLOR_BUFFER_BIT);
1384		}
1385
1386		int spriteCyclesRemaining = GBARegisterDISPCNTIsHblankIntervalFree(glRenderer->dispcnt) ? OBJ_HBLANK_FREE_LENGTH : OBJ_LENGTH;
1387		for (i = 0; i < GBA_VIDEO_VERTICAL_PIXELS; ++i) {
1388			glRenderer->spriteCycles[i] = spriteCyclesRemaining;
1389		}
1390	}
1391
1392	if (GBARegisterDISPCNTGetMode(glRenderer->dispcnt) != 0) {
1393		glRenderer->bg[2].affine.sx += glRenderer->bg[2].affine.dmx;
1394		glRenderer->bg[2].affine.sy += glRenderer->bg[2].affine.dmy;
1395		glRenderer->bg[3].affine.sx += glRenderer->bg[3].affine.dmx;
1396		glRenderer->bg[3].affine.sy += glRenderer->bg[3].affine.dmy;
1397	}
1398}
1399
1400void _drawScanlines(struct GBAVideoGLRenderer* glRenderer, int y) {
1401	glEnable(GL_SCISSOR_TEST);
1402
1403	uint32_t backdrop = M_RGB5_TO_RGB8(glRenderer->shadowPalette[0]);
1404	glViewport(0, 0, 1, GBA_VIDEO_VERTICAL_PIXELS);
1405	glScissor(0, glRenderer->firstY, 1, y - glRenderer->firstY + 1);
1406	glBindFramebuffer(GL_FRAMEBUFFER, glRenderer->fbo[GBA_GL_FBO_BACKDROP]);
1407	glDrawBuffers(2, (GLenum[]) { GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1 });
1408	glClearBufferfv(GL_COLOR, 0, (GLfloat[]) { ((backdrop >> 16) & 0xF8) / 248., ((backdrop >> 8) & 0xF8) / 248., (backdrop & 0xF8) / 248., 1.f });
1409	glClearBufferiv(GL_COLOR, 1, (GLint[]) { 32, glRenderer->target1Bd | (glRenderer->target2Bd * 2) | (glRenderer->blendEffect * 4), glRenderer->blda, 0 });
1410
1411	glDrawBuffers(2, (GLenum[]) { GL_NONE, GL_COLOR_ATTACHMENT1 });
1412	int i;
1413	for (i = 0; i < 4; ++i) {
1414		glScissor(i + 1, glRenderer->firstY, 1, y - glRenderer->firstY + 1);
1415		glClearBufferiv(GL_COLOR, 1, (GLint[]) { glRenderer->bg[i].priority,
1416		                                         glRenderer->bg[i].target1 | (glRenderer->bg[i].target2 << 1) | (glRenderer->blendEffect << 2),
1417		                                         glRenderer->blda, 0 });
1418	}
1419
1420	glDrawBuffers(1, (GLenum[]) { GL_COLOR_ATTACHMENT0 });
1421
1422	GBAVideoGLRendererDrawWindow(glRenderer, y);
1423	if (GBARegisterDISPCNTIsObjEnable(glRenderer->dispcnt) && !glRenderer->d.disableOBJ) {
1424		glStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE);
1425		glDepthFunc(GL_LESS);
1426		for (i = 0; i < glRenderer->oamMax; ++i) {
1427			struct GBAVideoRendererSprite* sprite = &glRenderer->sprites[i];
1428			if ((y < sprite->y && (sprite->endY - 256 < 0 || glRenderer->firstY >= sprite->endY - 256)) || glRenderer->firstY >= sprite->endY) {
1429				continue;
1430			}
1431
1432			GBAVideoGLRendererDrawSprite(glRenderer, &sprite->obj, y, sprite->y);
1433
1434			int startY = sprite->y;
1435			int endY = sprite->endY;
1436
1437			if (endY >= 256) {
1438				startY -= 256;
1439				endY -= 256;
1440			}
1441			if (startY < glRenderer->firstY) {
1442				startY = glRenderer->firstY;
1443			}
1444			if (endY > y) {
1445				endY = y;
1446			}
1447			int j;
1448			for (j = startY; j <= endY; ++j) {
1449				glRenderer->spriteCycles[j] -= sprite->cycles;
1450			}
1451		}
1452		glDisable(GL_DEPTH_TEST);
1453		glDisable(GL_STENCIL_TEST);
1454	}
1455
1456	if (TEST_LAYER_ENABLED(0) && GBARegisterDISPCNTGetMode(glRenderer->dispcnt) < 2) {
1457		GBAVideoGLRendererDrawBackgroundMode0(glRenderer, &glRenderer->bg[0], y);
1458	}
1459	if (TEST_LAYER_ENABLED(1) && GBARegisterDISPCNTGetMode(glRenderer->dispcnt) < 2) {
1460		GBAVideoGLRendererDrawBackgroundMode0(glRenderer, &glRenderer->bg[1], y);
1461	}
1462	if (TEST_LAYER_ENABLED(2)) {
1463		switch (GBARegisterDISPCNTGetMode(glRenderer->dispcnt)) {
1464		case 0:
1465			GBAVideoGLRendererDrawBackgroundMode0(glRenderer, &glRenderer->bg[2], y);
1466			break;
1467		case 1:
1468		case 2:
1469			GBAVideoGLRendererDrawBackgroundMode2(glRenderer, &glRenderer->bg[2], y);
1470			break;
1471		case 3:
1472			GBAVideoGLRendererDrawBackgroundMode3(glRenderer, &glRenderer->bg[2], y);
1473			break;
1474		case 4:
1475			GBAVideoGLRendererDrawBackgroundMode4(glRenderer, &glRenderer->bg[2], y);
1476			break;
1477		case 5:
1478			GBAVideoGLRendererDrawBackgroundMode5(glRenderer, &glRenderer->bg[2], y);
1479			break;
1480		}
1481	}
1482	if (TEST_LAYER_ENABLED(3)) {
1483		switch (GBARegisterDISPCNTGetMode(glRenderer->dispcnt)) {
1484		case 0:
1485			GBAVideoGLRendererDrawBackgroundMode0(glRenderer, &glRenderer->bg[3], y);
1486			break;
1487		case 2:
1488			GBAVideoGLRendererDrawBackgroundMode2(glRenderer, &glRenderer->bg[3], y);
1489			break;
1490		}
1491	}
1492	glRenderer->firstY = -1;
1493}
1494
1495void GBAVideoGLRendererFinishFrame(struct GBAVideoRenderer* renderer) {
1496	struct GBAVideoGLRenderer* glRenderer = (struct GBAVideoGLRenderer*) renderer;
1497	_drawScanlines(glRenderer, GBA_VIDEO_VERTICAL_PIXELS - 1);
1498	_finalizeLayers(glRenderer);
1499	glDisable(GL_SCISSOR_TEST);
1500	glBindVertexArray(0);
1501	glRenderer->firstAffine = -1;
1502	glRenderer->firstY = -1;
1503	glRenderer->bg[2].affine.sx = glRenderer->bg[2].refx;
1504	glRenderer->bg[2].affine.sy = glRenderer->bg[2].refy;
1505	glRenderer->bg[3].affine.sx = glRenderer->bg[3].refx;
1506	glRenderer->bg[3].affine.sy = glRenderer->bg[3].refy;
1507}
1508
1509void GBAVideoGLRendererGetPixels(struct GBAVideoRenderer* renderer, size_t* stride, const void** pixels) {
1510	struct GBAVideoGLRenderer* glRenderer = (struct GBAVideoGLRenderer*) renderer;
1511	*stride = GBA_VIDEO_HORIZONTAL_PIXELS * glRenderer->scale;
1512	if (!glRenderer->temporaryBuffer) {
1513		glRenderer->temporaryBuffer = anonymousMemoryMap(GBA_VIDEO_HORIZONTAL_PIXELS * GBA_VIDEO_VERTICAL_PIXELS * glRenderer->scale * glRenderer->scale * BYTES_PER_PIXEL);
1514	}
1515	glFinish();
1516	glBindFramebuffer(GL_FRAMEBUFFER, glRenderer->fbo[GBA_GL_FBO_OUTPUT]);
1517	glPixelStorei(GL_PACK_ROW_LENGTH, GBA_VIDEO_HORIZONTAL_PIXELS * glRenderer->scale);
1518	glPixelStorei(GL_PACK_ALIGNMENT, 1);
1519	glReadPixels(0, 0, GBA_VIDEO_HORIZONTAL_PIXELS * glRenderer->scale, GBA_VIDEO_VERTICAL_PIXELS * glRenderer->scale, GL_RGBA, GL_UNSIGNED_BYTE, (void*) glRenderer->temporaryBuffer);
1520	*pixels = glRenderer->temporaryBuffer;
1521}
1522
1523void GBAVideoGLRendererPutPixels(struct GBAVideoRenderer* renderer, size_t stride, const void* pixels) {
1524	// TODO
1525	UNUSED(renderer);
1526	UNUSED(stride);
1527	UNUSED(pixels);
1528}
1529
1530static void _enableBg(struct GBAVideoGLRenderer* renderer, int bg, bool active) {
1531	int wasActive = renderer->bg[bg].enabled;
1532	if (!active) {
1533		renderer->bg[bg].enabled = 0;
1534	} else if (!wasActive && active) {
1535		/*if (renderer->nextY == 0 || GBARegisterDISPCNTGetMode(renderer->dispcnt) > 2) {
1536			// TODO: Investigate in more depth how switching background works in different modes
1537			renderer->bg[bg].enabled = 4;
1538		} else {
1539			renderer->bg[bg].enabled = 1;
1540		}*/
1541		renderer->bg[bg].enabled = 4;
1542	}
1543}
1544
1545static void GBAVideoGLRendererUpdateDISPCNT(struct GBAVideoGLRenderer* renderer) {
1546	_enableBg(renderer, 0, GBARegisterDISPCNTGetBg0Enable(renderer->dispcnt));
1547	_enableBg(renderer, 1, GBARegisterDISPCNTGetBg1Enable(renderer->dispcnt));
1548	_enableBg(renderer, 2, GBARegisterDISPCNTGetBg2Enable(renderer->dispcnt));
1549	_enableBg(renderer, 3, GBARegisterDISPCNTGetBg3Enable(renderer->dispcnt));
1550}
1551
1552static void GBAVideoGLRendererWriteBGCNT(struct GBAVideoGLBackground* bg, uint16_t value) {
1553	bg->priority = GBARegisterBGCNTGetPriority(value);
1554	bg->charBase = GBARegisterBGCNTGetCharBase(value) << 13;
1555	bg->mosaic = GBARegisterBGCNTGetMosaic(value);
1556	bg->multipalette = GBARegisterBGCNTGet256Color(value);
1557	bg->screenBase = GBARegisterBGCNTGetScreenBase(value) << 10;
1558	bg->overflow = GBARegisterBGCNTGetOverflow(value);
1559	bg->size = GBARegisterBGCNTGetSize(value);
1560}
1561
1562static void GBAVideoGLRendererWriteBGX_LO(struct GBAVideoGLBackground* bg, uint16_t value) {
1563	bg->refx = (bg->refx & 0xFFFF0000) | value;
1564	bg->affine.sx = bg->refx;
1565}
1566
1567static void GBAVideoGLRendererWriteBGX_HI(struct GBAVideoGLBackground* bg, uint16_t value) {
1568	bg->refx = (bg->refx & 0x0000FFFF) | (value << 16);
1569	bg->refx <<= 4;
1570	bg->refx >>= 4;
1571	bg->affine.sx = bg->refx;
1572}
1573
1574static void GBAVideoGLRendererWriteBGY_LO(struct GBAVideoGLBackground* bg, uint16_t value) {
1575	bg->refy = (bg->refy & 0xFFFF0000) | value;
1576	bg->affine.sy = bg->refy;
1577}
1578
1579static void GBAVideoGLRendererWriteBGY_HI(struct GBAVideoGLBackground* bg, uint16_t value) {
1580	bg->refy = (bg->refy & 0x0000FFFF) | (value << 16);
1581	bg->refy <<= 4;
1582	bg->refy >>= 4;
1583	bg->affine.sy = bg->refy;
1584}
1585
1586static void GBAVideoGLRendererWriteBLDCNT(struct GBAVideoGLRenderer* renderer, uint16_t value) {
1587	renderer->bg[0].target1 = GBARegisterBLDCNTGetTarget1Bg0(value);
1588	renderer->bg[1].target1 = GBARegisterBLDCNTGetTarget1Bg1(value);
1589	renderer->bg[2].target1 = GBARegisterBLDCNTGetTarget1Bg2(value);
1590	renderer->bg[3].target1 = GBARegisterBLDCNTGetTarget1Bg3(value);
1591	renderer->bg[0].target2 = GBARegisterBLDCNTGetTarget2Bg0(value);
1592	renderer->bg[1].target2 = GBARegisterBLDCNTGetTarget2Bg1(value);
1593	renderer->bg[2].target2 = GBARegisterBLDCNTGetTarget2Bg2(value);
1594	renderer->bg[3].target2 = GBARegisterBLDCNTGetTarget2Bg3(value);
1595
1596	renderer->blendEffect = GBARegisterBLDCNTGetEffect(value);
1597	renderer->target1Obj = GBARegisterBLDCNTGetTarget1Obj(value);
1598	renderer->target1Bd = GBARegisterBLDCNTGetTarget1Bd(value);
1599	renderer->target2Obj = GBARegisterBLDCNTGetTarget2Obj(value);
1600	renderer->target2Bd = GBARegisterBLDCNTGetTarget2Bd(value);
1601}
1602
1603void _finalizeLayers(struct GBAVideoGLRenderer* renderer) {
1604	const GLuint* uniforms = renderer->finalizeShader.uniforms;
1605	glBindFramebuffer(GL_FRAMEBUFFER, renderer->fbo[GBA_GL_FBO_OUTPUT]);
1606	glViewport(0, 0, GBA_VIDEO_HORIZONTAL_PIXELS * renderer->scale, GBA_VIDEO_VERTICAL_PIXELS * renderer->scale);
1607	glScissor(0, 0, GBA_VIDEO_HORIZONTAL_PIXELS * renderer->scale, GBA_VIDEO_VERTICAL_PIXELS * renderer->scale);
1608	if (GBARegisterDISPCNTIsForcedBlank(renderer->dispcnt)) {
1609		glClearColor(1.f, 1.f, 1.f, 1.f);
1610		glClear(GL_COLOR_BUFFER_BIT);
1611	} else {
1612		glUseProgram(renderer->finalizeShader.program);
1613		glBindVertexArray(renderer->finalizeShader.vao);
1614		glActiveTexture(GL_TEXTURE0);
1615		glBindTexture(GL_TEXTURE_2D, renderer->layers[GBA_GL_TEX_WINDOW]);
1616		glActiveTexture(GL_TEXTURE0 + 1);
1617		glBindTexture(GL_TEXTURE_2D, renderer->layers[GBA_GL_TEX_OBJ_COLOR]);
1618		glActiveTexture(GL_TEXTURE0 + 2);
1619		glBindTexture(GL_TEXTURE_2D, renderer->layers[GBA_GL_TEX_OBJ_FLAGS]);
1620		glActiveTexture(GL_TEXTURE0 + 3);
1621		glBindTexture(GL_TEXTURE_2D, renderer->bg[0].tex);
1622		glActiveTexture(GL_TEXTURE0 + 4);
1623		glBindTexture(GL_TEXTURE_2D, renderer->bg[1].tex);
1624		glActiveTexture(GL_TEXTURE0 + 5);
1625		glBindTexture(GL_TEXTURE_2D, renderer->bg[2].tex);
1626		glActiveTexture(GL_TEXTURE0 + 6);
1627		glBindTexture(GL_TEXTURE_2D, renderer->bg[3].tex);
1628		glActiveTexture(GL_TEXTURE0 + 7);
1629		glBindTexture(GL_TEXTURE_2D, renderer->layers[GBA_GL_TEX_BACKDROP_COLOR]);
1630		glActiveTexture(GL_TEXTURE0 + 8);
1631		glBindTexture(GL_TEXTURE_2D, renderer->layers[GBA_GL_TEX_BACKDROP_FLAGS]);
1632
1633		glUniform2i(uniforms[GBA_GL_VS_LOC], GBA_VIDEO_VERTICAL_PIXELS, 0);
1634		glUniform2i(uniforms[GBA_GL_VS_MAXPOS], GBA_VIDEO_HORIZONTAL_PIXELS, GBA_VIDEO_VERTICAL_PIXELS);
1635		glUniform1i(uniforms[GBA_GL_FINALIZE_SCALE], renderer->scale);
1636		glUniform1iv(uniforms[GBA_GL_FINALIZE_LAYERS], 5, (GLint[]) { 3, 4, 5, 6, 1 });
1637		glUniform1i(uniforms[GBA_GL_FINALIZE_FLAGS], 2);
1638		glUniform1i(uniforms[GBA_GL_FINALIZE_WINDOW], 0);
1639		glUniform1i(uniforms[GBA_GL_FINALIZE_WINDOW], 0);
1640		glUniform1i(uniforms[GBA_GL_FINALIZE_BACKDROP], 7);
1641		glUniform1i(uniforms[GBA_GL_FINALIZE_BACKDROPFLAGS], 8);
1642		glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
1643	}
1644	glBindFramebuffer(GL_FRAMEBUFFER, 0);
1645}
1646
1647void GBAVideoGLRendererDrawSprite(struct GBAVideoGLRenderer* renderer, struct GBAObj* sprite, int y, int spriteY) {
1648	int width = GBAVideoObjSizes[GBAObjAttributesAGetShape(sprite->a) * 4 + GBAObjAttributesBGetSize(sprite->b)][0];
1649	int height = GBAVideoObjSizes[GBAObjAttributesAGetShape(sprite->a) * 4 + GBAObjAttributesBGetSize(sprite->b)][1];
1650	int32_t x = (uint32_t) GBAObjAttributesBGetX(sprite->b) << 23;
1651	x >>= 23;
1652
1653	if (GBARegisterDISPCNTGetMode(renderer->dispcnt) >= 3 && GBAObjAttributesCGetTile(sprite->c) < 512) {
1654		return;
1655	}
1656
1657	int align = GBAObjAttributesAIs256Color(sprite->a) && !GBARegisterDISPCNTIsObjCharacterMapping(renderer->dispcnt);
1658	unsigned charBase = (BASE_TILE >> 1) + (GBAObjAttributesCGetTile(sprite->c) & ~align) * 0x10;
1659	int stride = GBARegisterDISPCNTIsObjCharacterMapping(renderer->dispcnt) ? (width >> 3) : (0x20 >> GBAObjAttributesAGet256Color(sprite->a));
1660
1661	int totalWidth = width;
1662	int totalHeight = height;
1663	if (GBAObjAttributesAIsTransformed(sprite->a) && GBAObjAttributesAIsDoubleSize(sprite->a)) {
1664		totalWidth <<= 1;
1665		totalHeight <<= 1;
1666	}
1667
1668	if (spriteY + totalHeight >= 256) {
1669		spriteY -= 256;
1670	}
1671
1672	const struct GBAVideoGLShader* shader = &renderer->objShader[GBAObjAttributesAGet256Color(sprite->a)];
1673	const GLuint* uniforms = shader->uniforms;
1674	glBindFramebuffer(GL_FRAMEBUFFER, renderer->fbo[GBA_GL_FBO_OBJ]);
1675	glViewport(x * renderer->scale, spriteY * renderer->scale, totalWidth * renderer->scale, totalHeight * renderer->scale);
1676	glScissor(x * renderer->scale, renderer->firstY * renderer->scale, totalWidth * renderer->scale, (y - renderer->firstY + 1) * renderer->scale);
1677	glUseProgram(shader->program);
1678	glBindVertexArray(shader->vao);
1679	glActiveTexture(GL_TEXTURE0);
1680	glBindTexture(GL_TEXTURE_2D, renderer->vramTex);
1681	glUniform2i(uniforms[GBA_GL_VS_LOC], totalHeight, 0);
1682	glUniform2i(uniforms[GBA_GL_VS_MAXPOS], totalWidth, totalHeight);
1683	glUniform1i(uniforms[GBA_GL_OBJ_VRAM], 0);
1684	glUniform1iv(uniforms[GBA_GL_OBJ_PALETTE], 256, &renderer->shadowPalette[256]);
1685	glUniform1i(uniforms[GBA_GL_OBJ_CHARBASE], charBase);
1686	glUniform1i(uniforms[GBA_GL_OBJ_STRIDE], stride);
1687	glUniform1i(uniforms[GBA_GL_OBJ_LOCALPALETTE], GBAObjAttributesCGetPalette(sprite->c));
1688	glUniform4i(uniforms[GBA_GL_OBJ_INFLAGS], GBAObjAttributesCGetPriority(sprite->c),
1689	                                          (renderer->target1Obj || GBAObjAttributesAGetMode(sprite->a) == OBJ_MODE_SEMITRANSPARENT) | (renderer->target2Obj * 2) | (renderer->blendEffect * 4),
1690	                                          renderer->blda, GBAObjAttributesAGetMode(sprite->a) == OBJ_MODE_SEMITRANSPARENT);
1691	glUniform1iv(uniforms[GBA_GL_OBJ_CYCLES], GBA_VIDEO_VERTICAL_PIXELS, renderer->spriteCycles);
1692	if (GBAObjAttributesAIsTransformed(sprite->a)) {
1693		struct GBAOAMMatrix mat;
1694		LOAD_16(mat.a, 0, &renderer->d.oam->mat[GBAObjAttributesBGetMatIndex(sprite->b)].a);
1695		LOAD_16(mat.b, 0, &renderer->d.oam->mat[GBAObjAttributesBGetMatIndex(sprite->b)].b);
1696		LOAD_16(mat.c, 0, &renderer->d.oam->mat[GBAObjAttributesBGetMatIndex(sprite->b)].c);
1697		LOAD_16(mat.d, 0, &renderer->d.oam->mat[GBAObjAttributesBGetMatIndex(sprite->b)].d);
1698
1699		glUniformMatrix2fv(uniforms[GBA_GL_OBJ_TRANSFORM], 1, GL_FALSE, (GLfloat[]) { mat.a / 256.f, mat.c / 256.f, mat.b / 256.f, mat.d / 256.f });
1700	} else {
1701		int flipX = 1;
1702		int flipY = 1;
1703		if (GBAObjAttributesBIsHFlip(sprite->b)) {
1704			flipX = -1;
1705		}
1706		if (GBAObjAttributesBIsVFlip(sprite->b)) {
1707			flipY = -1;
1708		}
1709		glUniformMatrix2fv(uniforms[GBA_GL_OBJ_TRANSFORM], 1, GL_FALSE, (GLfloat[]) { flipX, 0, 0, flipY });
1710	}
1711	glUniform4i(uniforms[GBA_GL_OBJ_DIMS], width, height, totalWidth, totalHeight);
1712	glDisable(GL_STENCIL_TEST);
1713	if (GBAObjAttributesAGetMode(sprite->a) == OBJ_MODE_OBJWIN) {
1714		// OBJWIN writes do not affect pixel priority
1715		glDisable(GL_DEPTH_TEST);
1716		glDepthMask(GL_FALSE);
1717		glStencilMask(0);
1718		int window = renderer->objwin & 0x3F;
1719		glUniform3i(uniforms[GBA_GL_OBJ_OBJWIN], window, renderer->bldb, renderer->bldy);
1720		glDrawBuffers(3, (GLenum[]) { GL_NONE, GL_NONE, GL_COLOR_ATTACHMENT2 });
1721	} else {
1722		glEnable(GL_DEPTH_TEST);
1723		glDepthMask(GL_TRUE);
1724		glStencilMask(1);
1725		glStencilFunc(GL_ALWAYS, 1, 1);
1726		glUniform3i(uniforms[GBA_GL_OBJ_OBJWIN], 0, 0, 0);
1727		glDrawBuffers(2, (GLenum[]) { GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1 });
1728	}
1729	if (GBAObjAttributesAIsMosaic(sprite->a) && GBAObjAttributesAGetMode(sprite->a) != OBJ_MODE_OBJWIN) {
1730		int mosaicH = GBAMosaicControlGetObjH(renderer->mosaic) + 1;
1731		if (GBAObjAttributesBIsHFlip(sprite->b)) {
1732			mosaicH = -mosaicH;
1733		}
1734		glUniform4i(uniforms[GBA_GL_OBJ_MOSAIC], mosaicH, GBAMosaicControlGetObjV(renderer->mosaic) + 1, x, spriteY);
1735	} else {
1736		glUniform4i(uniforms[GBA_GL_OBJ_MOSAIC], 0, 0, x, spriteY);
1737	}
1738	if (GBAObjAttributesAGetMode(sprite->a) != OBJ_MODE_OBJWIN || GBARegisterDISPCNTIsObjwinEnable(renderer->dispcnt)) {
1739		glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
1740	}
1741
1742	if (GBAObjAttributesAGetMode(sprite->a) != OBJ_MODE_OBJWIN) {
1743		// Update the pixel priority for already-written pixels
1744		shader = &renderer->objShader[2];
1745		uniforms = shader->uniforms;
1746		glEnable(GL_STENCIL_TEST);
1747		glStencilFunc(GL_EQUAL, 1, 1);
1748		glUseProgram(shader->program);
1749		glDrawBuffers(2, (GLenum[]) { GL_NONE, GL_COLOR_ATTACHMENT1 });
1750		glBindVertexArray(shader->vao);
1751		glUniform2i(uniforms[GBA_GL_VS_LOC], totalHeight, 0);
1752		glUniform2i(uniforms[GBA_GL_VS_MAXPOS], totalWidth, totalHeight);
1753		glUniform4i(uniforms[GBA_GL_OBJ_INFLAGS], GBAObjAttributesCGetPriority(sprite->c),
1754		                                          (renderer->target1Obj || GBAObjAttributesAGetMode(sprite->a) == OBJ_MODE_SEMITRANSPARENT) | (renderer->target2Obj * 2) | (renderer->blendEffect * 4),
1755		                                          renderer->blda, GBAObjAttributesAGetMode(sprite->a) == OBJ_MODE_SEMITRANSPARENT);
1756		glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
1757	}
1758
1759	glDrawBuffers(1, (GLenum[]) { GL_COLOR_ATTACHMENT0 });
1760}
1761
1762void _prepareBackground(struct GBAVideoGLRenderer* renderer, struct GBAVideoGLBackground* background, const GLuint* uniforms) {
1763	glBindFramebuffer(GL_FRAMEBUFFER, background->fbo);
1764	glViewport(0, 0, GBA_VIDEO_HORIZONTAL_PIXELS * renderer->scale, GBA_VIDEO_VERTICAL_PIXELS * renderer->scale);
1765	glActiveTexture(GL_TEXTURE0);
1766	glBindTexture(GL_TEXTURE_2D, renderer->vramTex);
1767	glUniform2i(uniforms[GBA_GL_VS_MAXPOS], GBA_VIDEO_HORIZONTAL_PIXELS, GBA_VIDEO_VERTICAL_PIXELS);
1768	glUniform1i(uniforms[GBA_GL_BG_VRAM], 0);
1769	glUniform1iv(uniforms[GBA_GL_OBJ_PALETTE], 256, renderer->shadowPalette);
1770	if (background->mosaic) {
1771		glUniform2i(uniforms[GBA_GL_BG_MOSAIC], GBAMosaicControlGetBgV(renderer->mosaic) + 1, GBAMosaicControlGetBgH(renderer->mosaic) + 1);
1772	} else {
1773		glUniform2i(uniforms[GBA_GL_BG_MOSAIC], 0, 0);
1774	}
1775	glDrawBuffers(1, (GLenum[]) { GL_COLOR_ATTACHMENT0 });
1776}
1777
1778void GBAVideoGLRendererDrawBackgroundMode0(struct GBAVideoGLRenderer* renderer, struct GBAVideoGLBackground* background, int y) {
1779	const struct GBAVideoGLShader* shader = &renderer->bgShader[background->multipalette ? 1 : 0];
1780	const GLuint* uniforms = shader->uniforms;
1781	glUseProgram(shader->program);
1782	glBindVertexArray(shader->vao);
1783	_prepareBackground(renderer, background, uniforms);
1784	glUniform1i(uniforms[GBA_GL_BG_SCREENBASE], background->screenBase);
1785	glUniform1i(uniforms[GBA_GL_BG_CHARBASE], background->charBase);
1786	glUniform1i(uniforms[GBA_GL_BG_SIZE], background->size);
1787	glUniform1iv(uniforms[GBA_GL_BG_OFFSET], GBA_VIDEO_VERTICAL_PIXELS, background->scanlineOffset);
1788
1789	glScissor(0, renderer->firstY * renderer->scale, GBA_VIDEO_HORIZONTAL_PIXELS * renderer->scale, (y - renderer->firstY + 1) * renderer->scale);
1790	glUniform2i(uniforms[GBA_GL_VS_LOC], y - renderer->firstY + 1, renderer->firstY);
1791	glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
1792
1793	glDrawBuffers(1, (GLenum[]) { GL_COLOR_ATTACHMENT0 });
1794}
1795
1796void _prepareTransform(struct GBAVideoGLRenderer* renderer, struct GBAVideoGLBackground* background, const GLuint* uniforms, int y) {
1797	glScissor(0, renderer->firstY * renderer->scale, GBA_VIDEO_HORIZONTAL_PIXELS * renderer->scale, renderer->scale * (y - renderer->firstY + 1));
1798	glUniform2i(uniforms[GBA_GL_VS_LOC], y - renderer->firstY + 1, renderer->firstY);
1799	glUniform2i(uniforms[GBA_GL_BG_RANGE], renderer->firstAffine, y);
1800
1801	glUniform4iv(uniforms[GBA_GL_BG_TRANSFORM], GBA_VIDEO_VERTICAL_PIXELS, background->scanlineAffine);
1802	_prepareBackground(renderer, background, uniforms);
1803}
1804
1805void GBAVideoGLRendererDrawBackgroundMode2(struct GBAVideoGLRenderer* renderer, struct GBAVideoGLBackground* background, int y) {
1806	const struct GBAVideoGLShader* shader = &renderer->bgShader[background->overflow ? 2 : 3];
1807	const GLuint* uniforms = shader->uniforms;
1808	glUseProgram(shader->program);
1809	glBindVertexArray(shader->vao);
1810	_prepareTransform(renderer, background, uniforms, y);
1811	glUniform1i(uniforms[GBA_GL_BG_SCREENBASE], background->screenBase);
1812	glUniform1i(uniforms[GBA_GL_BG_CHARBASE], background->charBase);
1813	glUniform1i(uniforms[GBA_GL_BG_SIZE], background->size);
1814	glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
1815	glDrawBuffers(1, (GLenum[]) { GL_COLOR_ATTACHMENT0 });
1816}
1817
1818void GBAVideoGLRendererDrawBackgroundMode3(struct GBAVideoGLRenderer* renderer, struct GBAVideoGLBackground* background, int y) {
1819	const struct GBAVideoGLShader* shader = &renderer->bgShader[5];
1820	const GLuint* uniforms = shader->uniforms;
1821	glBindFramebuffer(GL_FRAMEBUFFER, background->fbo);
1822	glViewport(0, 0, GBA_VIDEO_HORIZONTAL_PIXELS * renderer->scale, GBA_VIDEO_VERTICAL_PIXELS * renderer->scale);
1823	glUseProgram(shader->program);
1824	glBindVertexArray(shader->vao);
1825	_prepareTransform(renderer, background, uniforms, y);
1826	glUniform1i(uniforms[GBA_GL_BG_CHARBASE], 0);
1827	glUniform2i(uniforms[GBA_GL_BG_SIZE], GBA_VIDEO_HORIZONTAL_PIXELS, GBA_VIDEO_VERTICAL_PIXELS);
1828	glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
1829	glDrawBuffers(1, (GLenum[]) { GL_COLOR_ATTACHMENT0 });
1830}
1831
1832void GBAVideoGLRendererDrawBackgroundMode4(struct GBAVideoGLRenderer* renderer, struct GBAVideoGLBackground* background, int y) {
1833	const struct GBAVideoGLShader* shader = &renderer->bgShader[4];
1834	const GLuint* uniforms = shader->uniforms;
1835	glBindFramebuffer(GL_FRAMEBUFFER, background->fbo);
1836	glViewport(0, 0, GBA_VIDEO_HORIZONTAL_PIXELS * renderer->scale, GBA_VIDEO_VERTICAL_PIXELS * renderer->scale);
1837	glUseProgram(shader->program);
1838	glBindVertexArray(shader->vao);
1839	_prepareTransform(renderer, background, uniforms, y);
1840	glUniform1i(uniforms[GBA_GL_BG_CHARBASE], GBARegisterDISPCNTIsFrameSelect(renderer->dispcnt) ? 0xA000 : 0);
1841	glUniform2i(uniforms[GBA_GL_BG_SIZE], GBA_VIDEO_HORIZONTAL_PIXELS, GBA_VIDEO_VERTICAL_PIXELS);
1842	glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
1843	glDrawBuffers(1, (GLenum[]) { GL_COLOR_ATTACHMENT0 });
1844}
1845
1846void GBAVideoGLRendererDrawBackgroundMode5(struct GBAVideoGLRenderer* renderer, struct GBAVideoGLBackground* background, int y) {
1847	const struct GBAVideoGLShader* shader = &renderer->bgShader[5];
1848	const GLuint* uniforms = shader->uniforms;
1849	glBindFramebuffer(GL_FRAMEBUFFER, background->fbo);
1850	glViewport(0, 0, GBA_VIDEO_HORIZONTAL_PIXELS * renderer->scale, GBA_VIDEO_VERTICAL_PIXELS * renderer->scale);
1851	glUseProgram(shader->program);
1852	glBindVertexArray(shader->vao);
1853	_prepareTransform(renderer, background, uniforms, y);
1854	glUniform1i(uniforms[GBA_GL_BG_CHARBASE], GBARegisterDISPCNTIsFrameSelect(renderer->dispcnt) ? 0x5000 : 0);
1855	glUniform2i(uniforms[GBA_GL_BG_SIZE], 160, 128);
1856	glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
1857	glDrawBuffers(1, (GLenum[]) { GL_COLOR_ATTACHMENT0 });
1858}
1859
1860void GBAVideoGLRendererDrawWindow(struct GBAVideoGLRenderer* renderer, int y) {
1861	const struct GBAVideoGLShader* shader = &renderer->windowShader;
1862	const GLuint* uniforms = shader->uniforms;
1863	glBindFramebuffer(GL_FRAMEBUFFER, renderer->fbo[GBA_GL_FBO_WINDOW]);
1864	glViewport(0, 0, GBA_VIDEO_HORIZONTAL_PIXELS * renderer->scale, GBA_VIDEO_VERTICAL_PIXELS * renderer->scale);
1865	glScissor(0, renderer->firstY * renderer->scale, GBA_VIDEO_HORIZONTAL_PIXELS * renderer->scale, renderer->scale * (y - renderer->firstY + 1));
1866	glDrawBuffers(1, (GLenum[]) { GL_COLOR_ATTACHMENT0 });
1867	switch (renderer->dispcnt & 0xE000) {
1868	case 0x0000:
1869		// No windows are enabled
1870		glClearBufferiv(GL_COLOR, 0, (GLint[]) { ((renderer->dispcnt >> 8) & 0x1F) | 0x20, renderer->bldb, renderer->bldy, 0 });
1871		break;
1872	case 0x8000:
1873		// Only OBJWIN is enabled
1874		glClearBufferiv(GL_COLOR, 0, (GLint[]) { renderer->winout, renderer->bldb, renderer->bldy, 0 });
1875		break;
1876	default:
1877		glUseProgram(shader->program);
1878		glBindVertexArray(shader->vao);
1879		glUniform2i(uniforms[GBA_GL_VS_LOC], y - renderer->firstY + 1, renderer->firstY);
1880		glUniform2i(uniforms[GBA_GL_VS_MAXPOS], GBA_VIDEO_HORIZONTAL_PIXELS, GBA_VIDEO_VERTICAL_PIXELS);
1881		glUniform1i(uniforms[GBA_GL_WIN_DISPCNT], renderer->dispcnt >> 8);
1882		glUniform2i(uniforms[GBA_GL_WIN_BLEND], renderer->bldb, renderer->bldy);
1883		glUniform3i(uniforms[GBA_GL_WIN_FLAGS], renderer->winN[0].control, renderer->winN[1].control, renderer->winout);
1884		glUniform4iv(uniforms[GBA_GL_WIN_WIN0], GBA_VIDEO_VERTICAL_PIXELS, renderer->winNHistory[0]);
1885		glUniform4iv(uniforms[GBA_GL_WIN_WIN1], GBA_VIDEO_VERTICAL_PIXELS, renderer->winNHistory[1]);
1886		glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
1887		break;
1888	}
1889}
1890
1891void GBAVideoGLRendererSetScale(struct GBAVideoGLRenderer* renderer, int scale) {
1892	if (scale == renderer->scale) {
1893		return;
1894	}
1895	if (renderer->temporaryBuffer) {
1896		mappedMemoryFree(renderer->temporaryBuffer, GBA_VIDEO_HORIZONTAL_PIXELS * GBA_VIDEO_VERTICAL_PIXELS * renderer->scale * renderer->scale * BYTES_PER_PIXEL);
1897		renderer->temporaryBuffer = NULL;
1898	}
1899	renderer->scale = scale;
1900	_initFramebuffers(renderer);
1901	renderer->paletteDirty = true;
1902}
1903
1904#endif