all repos — mgba @ 71b6066d4f6aecc85dc1dafc92cecaf6154f8f4a

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 _finalizeLayers(struct GBAVideoGLRenderer* renderer);
  45
  46#define TEST_LAYER_ENABLED(X) !renderer->disableBG[X] && glRenderer->bg[X].enabled == 4
  47
  48struct GBAVideoGLUniform {
  49	const char* name;
  50	int type;
  51};
  52
  53static const GLchar* const _gl3Header =
  54	"#version 130\n";
  55
  56static const char* const _vertexShader =
  57	"in vec2 position;\n"
  58	"uniform ivec2 loc;\n"
  59	"uniform ivec2 maxPos;\n"
  60	"out vec2 texCoord;\n"
  61
  62	"void main() {\n"
  63	"	vec2 local = vec2(position.x, float(position.y * loc.x + loc.y) / abs(maxPos.y));\n"
  64	"	gl_Position = vec4((local * 2. - 1.) * sign(maxPos), 0., 1.);\n"
  65	"	texCoord = local * abs(maxPos);\n"
  66	"}";
  67
  68static const char* const _renderTile16 =
  69	"vec4 renderTile(int tile, int paletteId, ivec2 localCoord) {\n"
  70	"	int address = charBase + tile * 16 + (localCoord.x >> 2) + (localCoord.y << 1);\n"
  71	"	vec4 halfrow = texelFetch(vram, ivec2(address & 255, address >> 8), 0);\n"
  72	"	int entry = int(halfrow[3 - (localCoord.x & 3)] * 15.9);\n"
  73	"	vec4 color = texelFetch(palette, ivec2(entry, paletteId), 0);\n"
  74	"	if (entry == 0) {\n"
  75	"		discard;\n"
  76	"	}\n"
  77	"	color.a = 1;\n"
  78	"	return color;\n"
  79	"}";
  80
  81static const char* const _renderTile256 =
  82	"vec4 renderTile(int tile, int paletteId, ivec2 localCoord) {\n"
  83	"	int address = charBase + tile * 32 + (localCoord.x >> 1) + (localCoord.y << 2);\n"
  84	"	vec4 halfrow = texelFetch(vram, ivec2(address & 255, address >> 8), 0);\n"
  85	"	int entry = int(halfrow[3 - 2 * (localCoord.x & 1)] * 15.9);\n"
  86	"	int pal2 = int(halfrow[2 - 2 * (localCoord.x & 1)] * 15.9);\n"
  87	"	vec4 color = texelFetch(palette, ivec2(entry, pal2 + (paletteId & 16)), 0);\n"
  88	"	if ((pal2 | entry) == 0) {\n"
  89	"		discard;\n"
  90	"	}\n"
  91	"	color.a = 1.;\n"
  92	"	return color;\n"
  93	"}";
  94
  95static const struct GBAVideoGLUniform _uniformsMode0[] = {
  96	{ "loc", GBA_GL_VS_LOC, },
  97	{ "maxPos", GBA_GL_VS_MAXPOS, },
  98	{ "vram", GBA_GL_BG_VRAM, },
  99	{ "palette", GBA_GL_BG_PALETTE, },
 100	{ "screenBase", GBA_GL_BG_SCREENBASE, },
 101	{ "charBase", GBA_GL_BG_CHARBASE, },
 102	{ "size", GBA_GL_BG_SIZE, },
 103	{ "offset", GBA_GL_BG_OFFSET, },
 104	{ "inflags", GBA_GL_BG_INFLAGS, },
 105	{ 0 }
 106};
 107
 108static const char* const _renderMode0 =
 109	"in vec2 texCoord;\n"
 110	"uniform sampler2D vram;\n"
 111	"uniform sampler2D palette;\n"
 112	"uniform int screenBase;\n"
 113	"uniform int charBase;\n"
 114	"uniform int size;\n"
 115	"uniform ivec2 offset;\n"
 116	"uniform ivec4 inflags;\n"
 117	"out vec4 color;\n"
 118	"out vec4 flags;\n"
 119	"const vec4 flagCoeff = vec4(32., 32., 16., 16.);\n"
 120
 121	"vec4 renderTile(int tile, int paletteId, ivec2 localCoord);\n"
 122
 123	"void main() {\n"
 124	"	ivec2 coord = ivec2(texCoord) + offset;\n"
 125	"	if ((size & 1) == 1) {\n"
 126	"		coord.y += coord.x & 256;\n"
 127	"	}\n"
 128	"	coord.x &= 255;\n"
 129	"	int mapAddress = screenBase + (coord.x >> 3) + (coord.y >> 3) * 32;\n"
 130	"	vec4 map = texelFetch(vram, ivec2(mapAddress & 255, mapAddress >> 8), 0);\n"
 131	"	int tileFlags = int(map.g * 15.9);\n"
 132	"	if ((tileFlags & 4) == 4) {\n"
 133	"		coord.x ^= 7;\n"
 134	"	}\n"
 135	"	if ((tileFlags & 8) == 8) {\n"
 136	"		coord.y ^= 7;\n"
 137	"	}\n"
 138	"	int tile = int(map.a * 15.9) + int(map.b * 15.9) * 16 + (tileFlags & 0x3) * 256;\n"
 139	"	color = renderTile(tile, int(map.r * 15.9), coord & 7);\n"
 140	"	flags = inflags / flagCoeff;\n"
 141	"}";
 142
 143static const char* const _fetchTileOverflow =
 144	"vec4 fetchTile(ivec2 coord) {\n"
 145	"	int sizeAdjusted = (0x8000 << size) - 1;\n"
 146	"	coord &= sizeAdjusted;\n"
 147	"	return renderTile(coord);\n"
 148	"}";
 149
 150static const char* const _fetchTileNoOverflow =
 151	"vec4 fetchTile(ivec2 coord) {\n"
 152	"	int sizeAdjusted = (0x8000 << size) - 1;\n"
 153	"	ivec2 outerCoord = coord & ~sizeAdjusted;\n"
 154	"	if ((outerCoord.x | outerCoord.y) != 0) {\n"
 155	"		discard;\n"
 156	"	}\n"
 157	"	return renderTile(coord);\n"
 158	"}";
 159
 160static const struct GBAVideoGLUniform _uniformsMode2[] = {
 161	{ "loc", GBA_GL_VS_LOC, },
 162	{ "maxPos", GBA_GL_VS_MAXPOS, },
 163	{ "vram", GBA_GL_BG_VRAM, },
 164	{ "palette", GBA_GL_BG_PALETTE, },
 165	{ "screenBase", GBA_GL_BG_SCREENBASE, },
 166	{ "charBase", GBA_GL_BG_CHARBASE, },
 167	{ "size", GBA_GL_BG_SIZE, },
 168	{ "inflags", GBA_GL_BG_INFLAGS, },
 169	{ "offset", GBA_GL_BG_OFFSET, },
 170	{ "transform", GBA_GL_BG_TRANSFORM, },
 171	{ "range", GBA_GL_BG_RANGE, },
 172	{ 0 }
 173};
 174
 175static const char* const _renderMode2 =
 176	"in vec2 texCoord;\n"
 177	"uniform sampler2D vram;\n"
 178	"uniform sampler2D palette;\n"
 179	"uniform int screenBase;\n"
 180	"uniform int charBase;\n"
 181	"uniform int size;\n"
 182	"uniform ivec4 inflags;\n"
 183	"uniform ivec2[4] offset;\n"
 184	"uniform ivec2[4] transform;\n"
 185	"uniform vec2 range;\n"
 186	"out vec4 color;\n"
 187	"out vec4 flags;\n"
 188	"const vec4 flagCoeff = vec4(32., 32., 16., 16.);\n"
 189	"precision highp float;\n"
 190	"precision highp int;\n"
 191
 192	"vec4 fetchTile(ivec2 coord);\n"
 193
 194	"vec4 renderTile(ivec2 coord) {\n"
 195	"	int map = (coord.x >> 11) + (((coord.y >> 7) & 0x7F0) << size);\n"
 196	"	int mapAddress = screenBase + (map >> 1);\n"
 197	"	vec4 twomaps = texelFetch(vram, ivec2(mapAddress & 255, mapAddress >> 8), 0);\n"
 198	"	int tile = int(twomaps[3 - 2 * (map & 1)] * 15.9) + int(twomaps[2 - 2 * (map & 1)] * 15.9) * 16;\n"
 199	"	int address = charBase + tile * 32 + ((coord.x >> 9) & 3) + ((coord.y >> 6) & 0x1C);\n"
 200	"	vec4 halfrow = texelFetch(vram, ivec2(address & 255, address >> 8), 0);\n"
 201	"	int entry = int(halfrow[3 - ((coord.x >> 7) & 2)] * 15.9);\n"
 202	"	int pal2 = int(halfrow[2 - ((coord.x >> 7) & 2)] * 15.9);\n"
 203	"	vec4 color = texelFetch(palette, ivec2(entry, pal2), 0);\n"
 204	"	if ((pal2 | entry) == 0) {\n"
 205	"		discard;\n"
 206	"	}\n"
 207	"	color.a = 1.;\n"
 208	"	return color;\n"
 209	"}\n"
 210
 211	"vec2 interpolate(ivec2 arr[4], float x) {\n"
 212	"	float x1m = 1. - x;\n"
 213	"	return x1m * x1m * x1m * arr[0] +"
 214		"  3 * x1m * x1m * x   * arr[1] +"
 215		"  3 * x1m * x   * x   * arr[2] +"
 216		"      x   * x   * x   * arr[3];\n"
 217	"}\n"
 218
 219	"void main() {\n"
 220	"	float y = texCoord.y - range.x;\n"
 221	"	float lin = 0.5 - y / range.y * 0.25;\n"
 222	"	vec2 mixedTransform = interpolate(transform, lin);\n"
 223	"	vec2 mixedOffset = interpolate(offset, lin);\n"
 224	"	color = fetchTile(ivec2(mixedTransform * texCoord.x + mixedOffset));\n"
 225	"	flags = inflags / flagCoeff;\n"
 226	"}";
 227
 228static const struct GBAVideoGLUniform _uniformsObj[] = {
 229	{ "loc", GBA_GL_VS_LOC, },
 230	{ "maxPos", GBA_GL_VS_MAXPOS, },
 231	{ "vram", GBA_GL_OBJ_VRAM, },
 232	{ "palette", GBA_GL_OBJ_PALETTE, },
 233	{ "charBase", GBA_GL_OBJ_CHARBASE, },
 234	{ "stride", GBA_GL_OBJ_STRIDE, },
 235	{ "localPalette", GBA_GL_OBJ_LOCALPALETTE, },
 236	{ "inflags", GBA_GL_OBJ_INFLAGS, },
 237	{ "transform", GBA_GL_OBJ_TRANSFORM, },
 238	{ "dims", GBA_GL_OBJ_DIMS, },
 239	{ "objwin", GBA_GL_OBJ_OBJWIN, },
 240	{ 0 }
 241};
 242
 243static const char* const _renderObj =
 244	"in vec2 texCoord;\n"
 245	"uniform sampler2D vram;\n"
 246	"uniform sampler2D palette;\n"
 247	"uniform int charBase;\n"
 248	"uniform int stride;\n"
 249	"uniform int localPalette;\n"
 250	"uniform ivec4 inflags;\n"
 251	"uniform mat2x2 transform;\n"
 252	"uniform ivec4 dims;\n"
 253	"uniform vec3 objwin;\n"
 254	"out vec4 color;\n"
 255	"out vec4 flags;\n"
 256	"out vec2 window;\n"
 257	"const vec4 flagCoeff = vec4(32., 32., 16., 16.);\n"
 258
 259	"vec4 renderTile(int tile, int paletteId, ivec2 localCoord);\n"
 260
 261	"void main() {\n"
 262	"	ivec2 coord = ivec2(transform * (texCoord - dims.zw / 2) + dims.xy / 2);\n"
 263	"	if ((coord & ~(dims.xy - 1)) != ivec2(0, 0)) {\n"
 264	"		discard;\n"
 265	"	}\n"
 266	"	vec4 pix = renderTile((coord.x >> 3) + (coord.y >> 3) * stride, 16 + localPalette, coord & 7);\n"
 267	"	if (objwin.x > 0) {\n"
 268	"		pix.a = 0;\n"
 269	"	}\n"
 270	"	color = pix;\n"
 271	"	flags = inflags / flagCoeff;\n"
 272	"	window = objwin.yz;\n"
 273	"}";
 274
 275static const struct GBAVideoGLUniform _uniformsFinalize[] = {
 276	{ "loc", GBA_GL_VS_LOC, },
 277	{ "maxPos", GBA_GL_VS_MAXPOS, },
 278	{ "scale", GBA_GL_FINALIZE_SCALE, },
 279	{ "layers", GBA_GL_FINALIZE_LAYERS, },
 280	{ "flags", GBA_GL_FINALIZE_FLAGS, },
 281	{ "window", GBA_GL_FINALIZE_WINDOW, },
 282	{ "backdrop", GBA_GL_FINALIZE_BACKDROP, },
 283	{ "backdropFlags", GBA_GL_FINALIZE_BACKDROPFLAGS, },
 284	{ 0 }
 285};
 286
 287static const char* const _finalize =
 288	"in vec2 texCoord;\n"
 289	"uniform int scale;\n"
 290	"uniform sampler2D layers[5];\n"
 291	"uniform sampler2D flags[5];\n"
 292	"uniform sampler2D window;\n"
 293	"uniform vec4 backdrop;\n"
 294	"uniform vec4 backdropFlags;\n"
 295	"const vec4 flagCoeff = vec4(32., 32., 16., 16.);\n"
 296	"out vec4 color;\n"
 297
 298	"void composite(vec4 pixel, ivec4 flags, inout vec4 topPixel, inout ivec4 topFlags, inout vec4 bottomPixel, inout ivec4 bottomFlags) {\n"
 299	"	if (pixel.a == 0) {\n"
 300	"		return;\n"
 301	"	}\n"
 302	"	if (flags.x >= topFlags.x) {\n"
 303	"		if (flags.x >= bottomFlags.x) {\n"
 304	"			return;\n"
 305	"		}\n"
 306	"		bottomFlags = flags;\n"
 307	"		bottomPixel = pixel;\n"
 308	"	} else {\n"
 309	"		bottomFlags = topFlags;\n"
 310	"		topFlags = flags;\n"
 311	"		bottomPixel = topPixel;\n"
 312	"		topPixel = pixel;\n"
 313	"	}\n"
 314	"}\n"
 315
 316	"void main() {\n"
 317	"	vec4 windowFlags = texelFetch(window, ivec2(texCoord * scale), 0);\n"
 318	"	int layerWindow = int(windowFlags.x * 32) | int(windowFlags.y * 512);\n"
 319	"	vec4 topPixel = backdrop;\n"
 320	"	vec4 bottomPixel = backdrop;\n"
 321	"	ivec4 topFlags = ivec4(backdropFlags * flagCoeff);\n"
 322	"	ivec4 bottomFlags = ivec4(backdropFlags * flagCoeff);\n"
 323	"	if ((layerWindow & 1) == 0) {\n"
 324	"		vec4 pix = texelFetch(layers[0], ivec2(texCoord * scale), 0);\n"
 325	"		ivec4 inflags = ivec4(texelFetch(flags[0], ivec2(texCoord * scale), 0) * flagCoeff);\n"
 326	"		composite(pix, inflags, topPixel, topFlags, bottomPixel, bottomFlags);\n"
 327	"	}\n"
 328	"	if ((layerWindow & 2) == 0) {\n"
 329	"		vec4 pix = texelFetch(layers[1], ivec2(texCoord * scale), 0);\n"
 330	"		ivec4 inflags = ivec4(texelFetch(flags[1], ivec2(texCoord * scale), 0) * flagCoeff);\n"
 331	"		composite(pix, inflags, topPixel, topFlags, bottomPixel, bottomFlags);\n"
 332	"	}\n"
 333	"	if ((layerWindow & 4) == 0) {\n"
 334	"		vec4 pix = texelFetch(layers[2], ivec2(texCoord * scale), 0);\n"
 335	"		ivec4 inflags = ivec4(texelFetch(flags[2], ivec2(texCoord * scale), 0) * flagCoeff);\n"
 336	"		composite(pix, inflags, topPixel, topFlags, bottomPixel, bottomFlags);\n"
 337	"	}\n"
 338	"	if ((layerWindow & 8) == 0) {\n"
 339	"		vec4 pix = texelFetch(layers[3], ivec2(texCoord * scale), 0);\n"
 340	"		ivec4 inflags = ivec4(texelFetch(flags[3], ivec2(texCoord * scale), 0) * flagCoeff);\n"
 341	"		composite(pix, inflags, topPixel, topFlags, bottomPixel, bottomFlags);\n"
 342	"	}\n"
 343	"	if ((layerWindow & 32) != 0) {\n"
 344	"		topFlags.y &= ~1;\n"
 345	"	}\n"
 346	"	if ((layerWindow & 16) == 0) {\n"
 347	"		vec4 pix = texelFetch(layers[4], ivec2(texCoord * scale), 0);\n"
 348	"		ivec4 inflags = ivec4(texelFetch(flags[4], ivec2(texCoord * scale), 0) * flagCoeff);\n"
 349	"		composite(pix, inflags, topPixel, topFlags, bottomPixel, bottomFlags);\n"
 350	"	}\n"
 351	"	if ((topFlags.y & 13) == 5) {\n"
 352	"		if ((bottomFlags.y & 2) == 2) {\n"
 353	"			topPixel *= topFlags.z / 16.;\n"
 354	"			topPixel += bottomPixel * bottomFlags.w / 16.;\n"
 355	"		}\n"
 356	"	} else if ((topFlags.y & 13) == 9) {\n"
 357	"		topPixel += (1. - topPixel) * windowFlags.z;\n"
 358	"	} else if ((topFlags.y & 13) == 13) {\n"
 359	"		topPixel -= topPixel * windowFlags.z;\n"
 360	"	}\n"
 361	"	color = topPixel;\n"
 362	"}";
 363
 364static const GLint _vertices[] = {
 365	0, 0,
 366	0, 1,
 367	1, 1,
 368	1, 0,
 369};
 370
 371void GBAVideoGLRendererCreate(struct GBAVideoGLRenderer* renderer) {
 372	renderer->d.init = GBAVideoGLRendererInit;
 373	renderer->d.reset = GBAVideoGLRendererReset;
 374	renderer->d.deinit = GBAVideoGLRendererDeinit;
 375	renderer->d.writeVideoRegister = GBAVideoGLRendererWriteVideoRegister;
 376	renderer->d.writeVRAM = GBAVideoGLRendererWriteVRAM;
 377	renderer->d.writeOAM = GBAVideoGLRendererWriteOAM;
 378	renderer->d.writePalette = GBAVideoGLRendererWritePalette;
 379	renderer->d.drawScanline = GBAVideoGLRendererDrawScanline;
 380	renderer->d.finishFrame = GBAVideoGLRendererFinishFrame;
 381	renderer->d.getPixels = GBAVideoGLRendererGetPixels;
 382	renderer->d.putPixels = GBAVideoGLRendererPutPixels;
 383
 384	renderer->d.disableBG[0] = false;
 385	renderer->d.disableBG[1] = false;
 386	renderer->d.disableBG[2] = false;
 387	renderer->d.disableBG[3] = false;
 388	renderer->d.disableOBJ = false;
 389
 390	renderer->scale = 1;
 391}
 392
 393static void _compileShader(struct GBAVideoGLRenderer* glRenderer, struct GBAVideoGLShader* shader, const char** shaderBuffer, int shaderBufferLines, GLuint vs, const struct GBAVideoGLUniform* uniforms, char* log) {
 394	GLuint program = glCreateProgram();
 395	shader->program = program;
 396
 397	GLuint fs = glCreateShader(GL_FRAGMENT_SHADER);
 398	glAttachShader(program, vs);
 399	glAttachShader(program, fs);
 400	glShaderSource(fs, shaderBufferLines, shaderBuffer, 0);
 401	glCompileShader(fs);
 402	glGetShaderInfoLog(fs, 1024, 0, log);
 403	if (log[0]) {
 404		mLOG(GBA_VIDEO, ERROR, "Fragment shader compilation failure: %s", log);
 405	}
 406	glLinkProgram(program);
 407	glGetProgramInfoLog(program, 1024, 0, log);
 408	if (log[0]) {
 409		mLOG(GBA_VIDEO, ERROR, "Program link failure: %s", log);
 410	}
 411	glDeleteShader(fs);
 412#ifndef BUILD_GLES3
 413	glBindFragDataLocation(program, 0, "color");
 414	glBindFragDataLocation(program, 1, "flags");
 415#endif
 416
 417	glGenVertexArrays(1, &shader->vao);
 418	glBindVertexArray(shader->vao);
 419	glBindBuffer(GL_ARRAY_BUFFER, glRenderer->vbo);
 420	GLuint positionLocation = glGetAttribLocation(program, "position");
 421	glVertexAttribPointer(positionLocation, 2, GL_INT, GL_FALSE, 0, NULL);
 422
 423	size_t i;
 424	for (i = 0; uniforms[i].name; ++i) {
 425		shader->uniforms[uniforms[i].type] = glGetUniformLocation(program, uniforms[i].name);
 426	}
 427}
 428
 429static void _deleteShader(struct GBAVideoGLShader* shader) {
 430	glDeleteProgram(shader->program);
 431	glDeleteVertexArrays(1, &shader->vao);
 432}
 433
 434static void _initFramebufferTexture(GLuint tex, GLenum format, GLenum attachment, int scale) {
 435	glBindTexture(GL_TEXTURE_2D, tex);
 436	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
 437	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
 438	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
 439	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
 440	glTexImage2D(GL_TEXTURE_2D, 0, format, GBA_VIDEO_HORIZONTAL_PIXELS * scale, GBA_VIDEO_VERTICAL_PIXELS * scale, 0, format, GL_UNSIGNED_BYTE, 0);
 441	glFramebufferTexture2D(GL_FRAMEBUFFER, attachment, GL_TEXTURE_2D, tex, 0);	
 442}
 443
 444void GBAVideoGLRendererInit(struct GBAVideoRenderer* renderer) {
 445	struct GBAVideoGLRenderer* glRenderer = (struct GBAVideoGLRenderer*) renderer;
 446	glRenderer->temporaryBuffer = NULL;
 447
 448	glGenFramebuffers(GBA_GL_FBO_MAX, glRenderer->fbo);
 449	glGenTextures(GBA_GL_TEX_MAX, glRenderer->layers);
 450
 451	glGenTextures(1, &glRenderer->paletteTex);
 452	glBindTexture(GL_TEXTURE_2D, glRenderer->paletteTex);
 453	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
 454	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
 455
 456	glGenTextures(1, &glRenderer->vramTex);
 457	glBindTexture(GL_TEXTURE_2D, glRenderer->vramTex);
 458	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
 459	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
 460	glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA4, 256, 192, 0, GL_RGBA, GL_UNSIGNED_SHORT_4_4_4_4, 0);
 461
 462	glBindFramebuffer(GL_FRAMEBUFFER, glRenderer->fbo[GBA_GL_FBO_OBJ]);
 463	_initFramebufferTexture(glRenderer->layers[GBA_GL_TEX_OBJ_COLOR], GL_RGBA, GL_COLOR_ATTACHMENT0, glRenderer->scale);
 464	_initFramebufferTexture(glRenderer->layers[GBA_GL_TEX_OBJ_FLAGS], GL_RGBA, GL_COLOR_ATTACHMENT1, glRenderer->scale);
 465
 466	glBindFramebuffer(GL_FRAMEBUFFER, glRenderer->fbo[GBA_GL_FBO_WINDOW]);
 467	_initFramebufferTexture(glRenderer->layers[GBA_GL_TEX_WINDOW], GL_RGB, GL_COLOR_ATTACHMENT0, glRenderer->scale);
 468
 469	glBindFramebuffer(GL_FRAMEBUFFER, glRenderer->fbo[GBA_GL_FBO_OUTPUT]);
 470	_initFramebufferTexture(glRenderer->outputTex, GL_RGB, GL_COLOR_ATTACHMENT0, glRenderer->scale);
 471
 472	glBindFramebuffer(GL_FRAMEBUFFER, 0);
 473
 474	glGenBuffers(1, &glRenderer->vbo);
 475	glBindBuffer(GL_ARRAY_BUFFER, glRenderer->vbo);
 476	glBufferData(GL_ARRAY_BUFFER, sizeof(_vertices), _vertices, GL_STATIC_DRAW);
 477
 478	int i;
 479	for (i = 0; i < 4; ++i) {
 480		struct GBAVideoGLBackground* bg = &glRenderer->bg[i];
 481		bg->index = i;
 482		bg->enabled = 0;
 483		bg->priority = 0;
 484		bg->charBase = 0;
 485		bg->mosaic = 0;
 486		bg->multipalette = 0;
 487		bg->screenBase = 0;
 488		bg->overflow = 0;
 489		bg->size = 0;
 490		bg->target1 = 0;
 491		bg->target2 = 0;
 492		bg->x = 0;
 493		bg->y = 0;
 494		bg->refx = 0;
 495		bg->refy = 0;
 496		bg->affine[0].dx = 256;
 497		bg->affine[0].dmx = 0;
 498		bg->affine[0].dy = 0;
 499		bg->affine[0].dmy = 256;
 500		bg->affine[0].sx = 0;
 501		bg->affine[0].sy = 0;
 502		glGenFramebuffers(1, &bg->fbo);
 503		glGenTextures(1, &bg->tex);
 504		glGenTextures(1, &bg->flags);
 505		glBindFramebuffer(GL_FRAMEBUFFER, bg->fbo);
 506		_initFramebufferTexture(bg->tex, GL_RGBA, GL_COLOR_ATTACHMENT0, glRenderer->scale);
 507		_initFramebufferTexture(bg->flags, GL_RGBA, GL_COLOR_ATTACHMENT1, glRenderer->scale);
 508		glBindFramebuffer(GL_FRAMEBUFFER, 0);
 509	}
 510
 511	char log[1024];
 512	const GLchar* shaderBuffer[8];
 513	shaderBuffer[0] = _gl3Header;
 514
 515	GLuint vs = glCreateShader(GL_VERTEX_SHADER);
 516	shaderBuffer[1] = _vertexShader;
 517	glShaderSource(vs, 2, shaderBuffer, 0);
 518	glCompileShader(vs);
 519	glGetShaderInfoLog(vs, 1024, 0, log);
 520	if (log[0]) {
 521		mLOG(GBA_VIDEO, ERROR, "Vertex shader compilation failure: %s", log);
 522	}
 523
 524	shaderBuffer[1] = _renderMode0;
 525
 526	shaderBuffer[2] = _renderTile16;
 527	_compileShader(glRenderer, &glRenderer->bgShader[0], shaderBuffer, 3, vs, _uniformsMode0, log);
 528
 529	shaderBuffer[2] = _renderTile256;
 530	_compileShader(glRenderer, &glRenderer->bgShader[1], shaderBuffer, 3, vs, _uniformsMode0, log);
 531
 532	shaderBuffer[1] = _renderMode2;
 533
 534	shaderBuffer[2] = _fetchTileOverflow;
 535	_compileShader(glRenderer, &glRenderer->bgShader[2], shaderBuffer, 3, vs, _uniformsMode2, log);
 536
 537	shaderBuffer[2] = _fetchTileNoOverflow;
 538	_compileShader(glRenderer, &glRenderer->bgShader[3], shaderBuffer, 3, vs, _uniformsMode2, log);
 539
 540	shaderBuffer[1] = _renderObj;
 541
 542	shaderBuffer[2] = _renderTile16;
 543	_compileShader(glRenderer, &glRenderer->objShader[0], shaderBuffer, 3, vs, _uniformsObj, log);
 544#ifndef BUILD_GLES3
 545	glBindFragDataLocation(glRenderer->objShader[0].program, 2, "window");
 546#endif
 547
 548	shaderBuffer[2] = _renderTile256;
 549	_compileShader(glRenderer, &glRenderer->objShader[1], shaderBuffer, 3, vs, _uniformsObj, log);
 550#ifndef BUILD_GLES3
 551	glBindFragDataLocation(glRenderer->objShader[1].program, 2, "window");
 552#endif
 553
 554	shaderBuffer[1] = _finalize;
 555	_compileShader(glRenderer, &glRenderer->finalizeShader, shaderBuffer, 2, vs, _uniformsFinalize, log);
 556
 557	glBindVertexArray(0);
 558	glDeleteShader(vs);
 559
 560	GBAVideoGLRendererReset(renderer);
 561}
 562
 563void GBAVideoGLRendererDeinit(struct GBAVideoRenderer* renderer) {
 564	struct GBAVideoGLRenderer* glRenderer = (struct GBAVideoGLRenderer*) renderer;
 565	if (glRenderer->temporaryBuffer) {
 566		mappedMemoryFree(glRenderer->temporaryBuffer, GBA_VIDEO_HORIZONTAL_PIXELS * GBA_VIDEO_VERTICAL_PIXELS * glRenderer->scale * glRenderer->scale);
 567	}
 568	glDeleteFramebuffers(GBA_GL_FBO_MAX, glRenderer->fbo);
 569	glDeleteTextures(GBA_GL_TEX_MAX, glRenderer->layers);
 570	glDeleteTextures(1, &glRenderer->paletteTex);
 571	glDeleteTextures(1, &glRenderer->vramTex);
 572
 573	_deleteShader(&glRenderer->bgShader[0]);
 574	_deleteShader(&glRenderer->bgShader[1]);
 575	_deleteShader(&glRenderer->bgShader[2]);
 576	_deleteShader(&glRenderer->bgShader[3]);
 577	_deleteShader(&glRenderer->objShader[0]);
 578	_deleteShader(&glRenderer->objShader[1]);
 579	_deleteShader(&glRenderer->finalizeShader);
 580
 581	int i;
 582	for (i = 0; i < 4; ++i) {
 583		struct GBAVideoGLBackground* bg = &glRenderer->bg[i];
 584		glDeleteFramebuffers(1, &bg->fbo);
 585		glDeleteTextures(1, &bg->tex);
 586		glDeleteTextures(1, &bg->flags);
 587	}
 588}
 589
 590void GBAVideoGLRendererReset(struct GBAVideoRenderer* renderer) {
 591	struct GBAVideoGLRenderer* glRenderer = (struct GBAVideoGLRenderer*) renderer;
 592
 593	glRenderer->paletteDirty = true;
 594	glRenderer->vramDirty = 0xFFFFFF;
 595	glRenderer->firstAffine = -1;
 596}
 597
 598void GBAVideoGLRendererWriteVRAM(struct GBAVideoRenderer* renderer, uint32_t address) {
 599	struct GBAVideoGLRenderer* glRenderer = (struct GBAVideoGLRenderer*) renderer;
 600	glRenderer->vramDirty |= 1 << (address >> 12);
 601}
 602
 603void GBAVideoGLRendererWriteOAM(struct GBAVideoRenderer* renderer, uint32_t oam) {
 604	UNUSED(oam);
 605	struct GBAVideoGLRenderer* glRenderer = (struct GBAVideoGLRenderer*) renderer;
 606	glRenderer->oamDirty = true;
 607}
 608
 609void GBAVideoGLRendererWritePalette(struct GBAVideoRenderer* renderer, uint32_t address, uint16_t value) {
 610	struct GBAVideoGLRenderer* glRenderer = (struct GBAVideoGLRenderer*) renderer;
 611#ifdef BUILD_GLES3
 612	glRenderer->shadowPalette[address >> 1] = (value & 0x3F) | ((value & 0x7FE0) << 1);
 613#else
 614	UNUSED(address);
 615	UNUSED(value);
 616#endif
 617	glRenderer->paletteDirty = true;
 618}
 619
 620uint16_t GBAVideoGLRendererWriteVideoRegister(struct GBAVideoRenderer* renderer, uint32_t address, uint16_t value) {
 621	struct GBAVideoGLRenderer* glRenderer = (struct GBAVideoGLRenderer*) renderer;
 622	if (renderer->cache) {
 623		GBAVideoCacheWriteVideoRegister(renderer->cache, address, value);
 624	}
 625
 626	switch (address) {
 627	case REG_DISPCNT:
 628		value &= 0xFFF7;
 629		glRenderer->dispcnt = value;
 630		GBAVideoGLRendererUpdateDISPCNT(glRenderer);
 631		break;
 632	case REG_BG0CNT:
 633		value &= 0xDFFF;
 634		GBAVideoGLRendererWriteBGCNT(&glRenderer->bg[0], value);
 635		break;
 636	case REG_BG1CNT:
 637		value &= 0xDFFF;
 638		GBAVideoGLRendererWriteBGCNT(&glRenderer->bg[1], value);
 639		break;
 640	case REG_BG2CNT:
 641		value &= 0xFFFF;
 642		GBAVideoGLRendererWriteBGCNT(&glRenderer->bg[2], value);
 643		break;
 644	case REG_BG3CNT:
 645		value &= 0xFFFF;
 646		GBAVideoGLRendererWriteBGCNT(&glRenderer->bg[3], value);
 647		break;
 648	case REG_BG0HOFS:
 649		value &= 0x01FF;
 650		glRenderer->bg[0].x = value;
 651		break;
 652	case REG_BG0VOFS:
 653		value &= 0x01FF;
 654		glRenderer->bg[0].y = value;
 655		break;
 656	case REG_BG1HOFS:
 657		value &= 0x01FF;
 658		glRenderer->bg[1].x = value;
 659		break;
 660	case REG_BG1VOFS:
 661		value &= 0x01FF;
 662		glRenderer->bg[1].y = value;
 663		break;
 664	case REG_BG2HOFS:
 665		value &= 0x01FF;
 666		glRenderer->bg[2].x = value;
 667		break;
 668	case REG_BG2VOFS:
 669		value &= 0x01FF;
 670		glRenderer->bg[2].y = value;
 671		break;
 672	case REG_BG3HOFS:
 673		value &= 0x01FF;
 674		glRenderer->bg[3].x = value;
 675		break;
 676	case REG_BG3VOFS:
 677		value &= 0x01FF;
 678		glRenderer->bg[3].y = value;
 679		break;
 680	case REG_BG2PA:
 681		glRenderer->bg[2].affine[0].dx = value;
 682		break;
 683	case REG_BG2PB:
 684		glRenderer->bg[2].affine[0].dmx = value;
 685		break;
 686	case REG_BG2PC:
 687		glRenderer->bg[2].affine[0].dy = value;
 688		break;
 689	case REG_BG2PD:
 690		glRenderer->bg[2].affine[0].dmy = value;
 691		break;
 692	case REG_BG2X_LO:
 693		GBAVideoGLRendererWriteBGX_LO(&glRenderer->bg[2], value);
 694		break;
 695	case REG_BG2X_HI:
 696		GBAVideoGLRendererWriteBGX_HI(&glRenderer->bg[2], value);
 697		break;
 698	case REG_BG2Y_LO:
 699		GBAVideoGLRendererWriteBGY_LO(&glRenderer->bg[2], value);
 700		break;
 701	case REG_BG2Y_HI:
 702		GBAVideoGLRendererWriteBGY_HI(&glRenderer->bg[2], value);
 703		break;
 704	case REG_BG3PA:
 705		glRenderer->bg[3].affine[0].dx = value;
 706		break;
 707	case REG_BG3PB:
 708		glRenderer->bg[3].affine[0].dmx = value;
 709		break;
 710	case REG_BG3PC:
 711		glRenderer->bg[3].affine[0].dy = value;
 712		break;
 713	case REG_BG3PD:
 714		glRenderer->bg[3].affine[0].dmy = value;
 715		break;
 716	case REG_BG3X_LO:
 717		GBAVideoGLRendererWriteBGX_LO(&glRenderer->bg[3], value);
 718		break;
 719	case REG_BG3X_HI:
 720		GBAVideoGLRendererWriteBGX_HI(&glRenderer->bg[3], value);
 721		break;
 722	case REG_BG3Y_LO:
 723		GBAVideoGLRendererWriteBGY_LO(&glRenderer->bg[3], value);
 724		break;
 725	case REG_BG3Y_HI:
 726		GBAVideoGLRendererWriteBGY_HI(&glRenderer->bg[3], value);
 727		break;
 728	case REG_BLDCNT:
 729		GBAVideoGLRendererWriteBLDCNT(glRenderer, value);
 730		value &= 0x3FFF;
 731		break;
 732	case REG_BLDALPHA:
 733		glRenderer->blda = value & 0x1F;
 734		if (glRenderer->blda > 0x10) {
 735			glRenderer->blda = 0x10;
 736		}
 737		glRenderer->bldb = (value >> 8) & 0x1F;
 738		if (glRenderer->bldb > 0x10) {
 739			glRenderer->bldb = 0x10;
 740		}
 741		value &= 0x1F1F;
 742		break;
 743	case REG_BLDY:
 744		value &= 0x1F;
 745		if (value > 0x10) {
 746			value = 0x10;
 747		}
 748		glRenderer->bldy = value;
 749		break;
 750	case REG_WIN0H:
 751		glRenderer->winN[0].h[0].end = value;
 752		glRenderer->winN[0].h[0].start = value >> 8;
 753		if (glRenderer->winN[0].h[0].start > GBA_VIDEO_HORIZONTAL_PIXELS && glRenderer->winN[0].h[0].start > glRenderer->winN[0].h[0].end) {
 754			glRenderer->winN[0].h[0].start = 0;
 755		}
 756		if (glRenderer->winN[0].h[0].end > GBA_VIDEO_HORIZONTAL_PIXELS) {
 757			glRenderer->winN[0].h[0].end = GBA_VIDEO_HORIZONTAL_PIXELS;
 758			if (glRenderer->winN[0].h[0].start > GBA_VIDEO_HORIZONTAL_PIXELS) {
 759				glRenderer->winN[0].h[0].start = GBA_VIDEO_HORIZONTAL_PIXELS;
 760			}
 761		}
 762		break;
 763	case REG_WIN1H:
 764		glRenderer->winN[1].h[0].end = value;
 765		glRenderer->winN[1].h[0].start = value >> 8;
 766		if (glRenderer->winN[1].h[0].start > GBA_VIDEO_HORIZONTAL_PIXELS && glRenderer->winN[1].h[0].start > glRenderer->winN[1].h[0].end) {
 767			glRenderer->winN[1].h[0].start = 0;
 768		}
 769		if (glRenderer->winN[1].h[0].end > GBA_VIDEO_HORIZONTAL_PIXELS) {
 770			glRenderer->winN[1].h[0].end = GBA_VIDEO_HORIZONTAL_PIXELS;
 771			if (glRenderer->winN[1].h[0].start > GBA_VIDEO_HORIZONTAL_PIXELS) {
 772				glRenderer->winN[1].h[0].start = GBA_VIDEO_HORIZONTAL_PIXELS;
 773			}
 774		}
 775		break;
 776	case REG_WIN0V:
 777		glRenderer->winN[0].v.end = value;
 778		glRenderer->winN[0].v.start = value >> 8;
 779		if (glRenderer->winN[0].v.start > GBA_VIDEO_VERTICAL_PIXELS && glRenderer->winN[0].v.start > glRenderer->winN[0].v.end) {
 780			glRenderer->winN[0].v.start = 0;
 781		}
 782		if (glRenderer->winN[0].v.end > GBA_VIDEO_VERTICAL_PIXELS) {
 783			glRenderer->winN[0].v.end = GBA_VIDEO_VERTICAL_PIXELS;
 784			if (glRenderer->winN[0].v.start > GBA_VIDEO_VERTICAL_PIXELS) {
 785				glRenderer->winN[0].v.start = GBA_VIDEO_VERTICAL_PIXELS;
 786			}
 787		}
 788		break;
 789	case REG_WIN1V:
 790		glRenderer->winN[1].v.end = value;
 791		glRenderer->winN[1].v.start = value >> 8;
 792		if (glRenderer->winN[1].v.start > GBA_VIDEO_VERTICAL_PIXELS && glRenderer->winN[1].v.start > glRenderer->winN[1].v.end) {
 793			glRenderer->winN[1].v.start = 0;
 794		}
 795		if (glRenderer->winN[1].v.end > GBA_VIDEO_VERTICAL_PIXELS) {
 796			glRenderer->winN[1].v.end = GBA_VIDEO_VERTICAL_PIXELS;
 797			if (glRenderer->winN[1].v.start > GBA_VIDEO_VERTICAL_PIXELS) {
 798				glRenderer->winN[1].v.start = GBA_VIDEO_VERTICAL_PIXELS;
 799			}
 800		}
 801		break;
 802	case REG_WININ:
 803		value &= 0x3F3F;
 804		glRenderer->winN[0].control = value;
 805		glRenderer->winN[1].control = value >> 8;
 806		break;
 807	case REG_WINOUT:
 808		value &= 0x3F3F;
 809		glRenderer->winout = value;
 810		glRenderer->objwin = value >> 8;
 811		break;
 812	case REG_MOSAIC:
 813		glRenderer->mosaic = value;
 814		break;
 815	default:
 816		break;
 817	}
 818	return value;
 819}
 820
 821void GBAVideoGLRendererDrawScanline(struct GBAVideoRenderer* renderer, int y) {
 822	struct GBAVideoGLRenderer* glRenderer = (struct GBAVideoGLRenderer*) renderer;
 823	if (glRenderer->paletteDirty) {
 824		glBindTexture(GL_TEXTURE_2D, glRenderer->paletteTex);
 825#ifdef BUILD_GLES3
 826		glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB565, 16, 32, 0, GL_RGBA, GL_UNSIGNED_SHORT_5_6_5, glRenderer->shadowPalette);
 827#else
 828		glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB5_A1, 16, 32, 0, GL_RGBA, GL_UNSIGNED_SHORT_1_5_5_5_REV, glRenderer->d.palette);
 829#endif
 830		glRenderer->paletteDirty = false;
 831	}
 832	int i;
 833	for (i = 0; i < 24; ++i) {
 834		if (!(glRenderer->vramDirty & (1 << i))) {
 835			continue;
 836		}
 837		// TODO: PBOs
 838		glBindTexture(GL_TEXTURE_2D, glRenderer->vramTex);
 839		glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 8 * i, 256, 8, GL_RGBA, GL_UNSIGNED_SHORT_4_4_4_4, &glRenderer->d.vram[2048 * i]);
 840	}
 841	glRenderer->vramDirty = 0;
 842
 843	if (y == 0) {
 844		memcpy(&glRenderer->winN[0].h[1], &glRenderer->winN[0].h[0], sizeof(struct GBAVideoWindowRegion));
 845		memcpy(&glRenderer->winN[1].h[1], &glRenderer->winN[1].h[0], sizeof(struct GBAVideoWindowRegion));
 846
 847		glDisable(GL_SCISSOR_TEST);		
 848		glClearColor(0, 0, 0, 0);
 849		glBindFramebuffer(GL_FRAMEBUFFER, glRenderer->fbo[GBA_GL_FBO_OBJ]);
 850		glDrawBuffers(2, (GLenum[]) { GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1 });
 851		glClear(GL_COLOR_BUFFER_BIT);
 852
 853		for (i = 0; i < 4; ++i) {
 854			glBindFramebuffer(GL_FRAMEBUFFER, glRenderer->bg[i].fbo);
 855			glDrawBuffers(2, (GLenum[]) { GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1 });
 856			glClear(GL_COLOR_BUFFER_BIT);
 857		}
 858		glDrawBuffers(1, (GLenum[]) { GL_COLOR_ATTACHMENT0 });
 859	}
 860	glEnable(GL_SCISSOR_TEST);
 861
 862	if (GBARegisterDISPCNTGetMode(glRenderer->dispcnt) != 0) {
 863		if (glRenderer->firstAffine < 0) {
 864			memcpy(&glRenderer->bg[2].affine[3], &glRenderer->bg[2].affine[0], sizeof(struct GBAVideoGLAffine));
 865			memcpy(&glRenderer->bg[3].affine[3], &glRenderer->bg[3].affine[0], sizeof(struct GBAVideoGLAffine));
 866			memcpy(&glRenderer->bg[2].affine[2], &glRenderer->bg[2].affine[0], sizeof(struct GBAVideoGLAffine));
 867			memcpy(&glRenderer->bg[3].affine[2], &glRenderer->bg[3].affine[0], sizeof(struct GBAVideoGLAffine));
 868			memcpy(&glRenderer->bg[2].affine[1], &glRenderer->bg[2].affine[0], sizeof(struct GBAVideoGLAffine));
 869			memcpy(&glRenderer->bg[3].affine[1], &glRenderer->bg[3].affine[0], sizeof(struct GBAVideoGLAffine));
 870			glRenderer->firstAffine = y;
 871		}
 872	} else {
 873		glRenderer->firstAffine = -1;
 874	}
 875
 876	GBAVideoGLRendererDrawWindow(glRenderer, y);
 877	if (GBARegisterDISPCNTIsObjEnable(glRenderer->dispcnt) && !glRenderer->d.disableOBJ) {
 878		if (glRenderer->oamDirty) {
 879			glRenderer->oamMax = GBAVideoRendererCleanOAM(glRenderer->d.oam->obj, glRenderer->sprites, 0);
 880			glRenderer->oamDirty = false;
 881		}
 882		int i;
 883		for (i = glRenderer->oamMax; i--;) {
 884			struct GBAVideoRendererSprite* sprite = &glRenderer->sprites[i];
 885			if ((y < sprite->y && (sprite->endY - 256 < 0 || y >= sprite->endY - 256)) || y >= sprite->endY) {
 886				continue;
 887			}
 888
 889			GBAVideoGLRendererDrawSprite(glRenderer, &sprite->obj, y, sprite->y);
 890		}
 891	}
 892
 893	if (TEST_LAYER_ENABLED(0) && GBARegisterDISPCNTGetMode(glRenderer->dispcnt) < 2) {
 894		GBAVideoGLRendererDrawBackgroundMode0(glRenderer, &glRenderer->bg[0], y);
 895	}
 896	if (TEST_LAYER_ENABLED(1) && GBARegisterDISPCNTGetMode(glRenderer->dispcnt) < 2) {
 897		GBAVideoGLRendererDrawBackgroundMode0(glRenderer, &glRenderer->bg[1], y);
 898	}
 899	if (TEST_LAYER_ENABLED(2)) {
 900		switch (GBARegisterDISPCNTGetMode(glRenderer->dispcnt)) {
 901		case 0:
 902			GBAVideoGLRendererDrawBackgroundMode0(glRenderer, &glRenderer->bg[2], y);
 903			break;
 904		case 1:
 905		case 2:
 906			GBAVideoGLRendererDrawBackgroundMode2(glRenderer, &glRenderer->bg[2], y);
 907			break;
 908		case 3:
 909			//GBAVideoGLRendererDrawBackgroundMode3(glRenderer, &glRenderer->bg[2], y);
 910			break;
 911		case 4:
 912			//GBAVideoGLRendererDrawBackgroundMode4(glRenderer, &glRenderer->bg[2], y);
 913			break;
 914		case 5:
 915			//GBAVideoGLRendererDrawBackgroundMode5(glRenderer, &glRenderer->bg[2], y);
 916			break;
 917		}
 918	}
 919	if (TEST_LAYER_ENABLED(3)) {
 920		switch (GBARegisterDISPCNTGetMode(glRenderer->dispcnt)) {
 921		case 0:
 922			GBAVideoGLRendererDrawBackgroundMode0(glRenderer, &glRenderer->bg[3], y);
 923			break;
 924		case 2:
 925			GBAVideoGLRendererDrawBackgroundMode2(glRenderer, &glRenderer->bg[3], y);
 926			break;
 927		}
 928	}
 929
 930	if (GBARegisterDISPCNTGetMode(glRenderer->dispcnt) != 0) {
 931		memcpy(&glRenderer->bg[2].affine[3], &glRenderer->bg[2].affine[2], sizeof(struct GBAVideoGLAffine));
 932		memcpy(&glRenderer->bg[3].affine[3], &glRenderer->bg[3].affine[2], sizeof(struct GBAVideoGLAffine));
 933		memcpy(&glRenderer->bg[2].affine[2], &glRenderer->bg[2].affine[1], sizeof(struct GBAVideoGLAffine));
 934		memcpy(&glRenderer->bg[3].affine[2], &glRenderer->bg[3].affine[1], sizeof(struct GBAVideoGLAffine));
 935		memcpy(&glRenderer->bg[2].affine[1], &glRenderer->bg[2].affine[0], sizeof(struct GBAVideoGLAffine));
 936		memcpy(&glRenderer->bg[3].affine[1], &glRenderer->bg[3].affine[0], sizeof(struct GBAVideoGLAffine));
 937
 938		glRenderer->bg[2].affine[0].sx += glRenderer->bg[2].affine[0].dmx;
 939		glRenderer->bg[2].affine[0].sy += glRenderer->bg[2].affine[0].dmy;
 940		glRenderer->bg[3].affine[0].sx += glRenderer->bg[3].affine[0].dmx;
 941		glRenderer->bg[3].affine[0].sy += glRenderer->bg[3].affine[0].dmy;
 942	}
 943	memcpy(&glRenderer->winN[0].h[1], &glRenderer->winN[0].h[0], sizeof(struct GBAVideoWindowRegion));
 944	memcpy(&glRenderer->winN[1].h[1], &glRenderer->winN[1].h[0], sizeof(struct GBAVideoWindowRegion));
 945}
 946
 947void GBAVideoGLRendererFinishFrame(struct GBAVideoRenderer* renderer) {
 948	struct GBAVideoGLRenderer* glRenderer = (struct GBAVideoGLRenderer*) renderer;
 949	_finalizeLayers(glRenderer);
 950	glRenderer->firstAffine = -1;
 951	glRenderer->bg[2].affine[0].sx = glRenderer->bg[2].refx;
 952	glRenderer->bg[2].affine[0].sy = glRenderer->bg[2].refy;
 953	glRenderer->bg[3].affine[0].sx = glRenderer->bg[3].refx;
 954	glRenderer->bg[3].affine[0].sy = glRenderer->bg[3].refy;
 955	glFlush();
 956}
 957
 958void GBAVideoGLRendererGetPixels(struct GBAVideoRenderer* renderer, size_t* stride, const void** pixels) {
 959	struct GBAVideoGLRenderer* glRenderer = (struct GBAVideoGLRenderer*) renderer;
 960	*stride = GBA_VIDEO_HORIZONTAL_PIXELS * glRenderer->scale;
 961	if (!glRenderer->temporaryBuffer) {
 962		glRenderer->temporaryBuffer = anonymousMemoryMap(GBA_VIDEO_HORIZONTAL_PIXELS * GBA_VIDEO_VERTICAL_PIXELS * glRenderer->scale * glRenderer->scale * BYTES_PER_PIXEL);
 963	}
 964	glFinish();
 965	glBindFramebuffer(GL_FRAMEBUFFER, glRenderer->fbo[GBA_GL_FBO_OUTPUT]);
 966	glPixelStorei(GL_PACK_ROW_LENGTH, GBA_VIDEO_HORIZONTAL_PIXELS * glRenderer->scale);
 967	glPixelStorei(GL_PACK_ALIGNMENT, 1);
 968	glReadPixels(0, 0, GBA_VIDEO_HORIZONTAL_PIXELS * glRenderer->scale, GBA_VIDEO_VERTICAL_PIXELS * glRenderer->scale, GL_RGBA, GL_UNSIGNED_BYTE, (void*) glRenderer->temporaryBuffer);
 969	*pixels = glRenderer->temporaryBuffer;
 970}
 971
 972void GBAVideoGLRendererPutPixels(struct GBAVideoRenderer* renderer, size_t stride, const void* pixels) {
 973
 974}
 975
 976static void _enableBg(struct GBAVideoGLRenderer* renderer, int bg, bool active) {
 977	int wasActive = renderer->bg[bg].enabled;
 978	if (!active) {
 979		renderer->bg[bg].enabled = 0;
 980	} else if (!wasActive && active) {
 981		/*if (renderer->nextY == 0 || GBARegisterDISPCNTGetMode(renderer->dispcnt) > 2) {
 982			// TODO: Investigate in more depth how switching background works in different modes
 983			renderer->bg[bg].enabled = 4;
 984		} else {
 985			renderer->bg[bg].enabled = 1;
 986		}*/
 987		renderer->bg[bg].enabled = 4;
 988	}
 989}
 990
 991static void GBAVideoGLRendererUpdateDISPCNT(struct GBAVideoGLRenderer* renderer) {
 992	_enableBg(renderer, 0, GBARegisterDISPCNTGetBg0Enable(renderer->dispcnt));
 993	_enableBg(renderer, 1, GBARegisterDISPCNTGetBg1Enable(renderer->dispcnt));
 994	_enableBg(renderer, 2, GBARegisterDISPCNTGetBg2Enable(renderer->dispcnt));
 995	_enableBg(renderer, 3, GBARegisterDISPCNTGetBg3Enable(renderer->dispcnt));
 996}
 997
 998static void GBAVideoGLRendererWriteBGCNT(struct GBAVideoGLBackground* bg, uint16_t value) {
 999	bg->priority = GBARegisterBGCNTGetPriority(value);
1000	bg->charBase = GBARegisterBGCNTGetCharBase(value) << 13;
1001	bg->mosaic = GBARegisterBGCNTGetMosaic(value);
1002	bg->multipalette = GBARegisterBGCNTGet256Color(value);
1003	bg->screenBase = GBARegisterBGCNTGetScreenBase(value) << 10;
1004	bg->overflow = GBARegisterBGCNTGetOverflow(value);
1005	bg->size = GBARegisterBGCNTGetSize(value);
1006}
1007
1008static void GBAVideoGLRendererWriteBGX_LO(struct GBAVideoGLBackground* bg, uint16_t value) {
1009	bg->refx = (bg->refx & 0xFFFF0000) | value;
1010	bg->affine[0].sx = bg->refx;
1011}
1012
1013static void GBAVideoGLRendererWriteBGX_HI(struct GBAVideoGLBackground* bg, uint16_t value) {
1014	bg->refx = (bg->refx & 0x0000FFFF) | (value << 16);
1015	bg->refx <<= 4;
1016	bg->refx >>= 4;
1017	bg->affine[0].sx = bg->refx;
1018}
1019
1020static void GBAVideoGLRendererWriteBGY_LO(struct GBAVideoGLBackground* bg, uint16_t value) {
1021	bg->refy = (bg->refy & 0xFFFF0000) | value;
1022	bg->affine[0].sy = bg->refy;
1023}
1024
1025static void GBAVideoGLRendererWriteBGY_HI(struct GBAVideoGLBackground* bg, uint16_t value) {
1026	bg->refy = (bg->refy & 0x0000FFFF) | (value << 16);
1027	bg->refy <<= 4;
1028	bg->refy >>= 4;
1029	bg->affine[0].sy = bg->refy;
1030}
1031
1032static void GBAVideoGLRendererWriteBLDCNT(struct GBAVideoGLRenderer* renderer, uint16_t value) {
1033	renderer->bg[0].target1 = GBARegisterBLDCNTGetTarget1Bg0(value);
1034	renderer->bg[1].target1 = GBARegisterBLDCNTGetTarget1Bg1(value);
1035	renderer->bg[2].target1 = GBARegisterBLDCNTGetTarget1Bg2(value);
1036	renderer->bg[3].target1 = GBARegisterBLDCNTGetTarget1Bg3(value);
1037	renderer->bg[0].target2 = GBARegisterBLDCNTGetTarget2Bg0(value);
1038	renderer->bg[1].target2 = GBARegisterBLDCNTGetTarget2Bg1(value);
1039	renderer->bg[2].target2 = GBARegisterBLDCNTGetTarget2Bg2(value);
1040	renderer->bg[3].target2 = GBARegisterBLDCNTGetTarget2Bg3(value);
1041
1042	renderer->blendEffect = GBARegisterBLDCNTGetEffect(value);
1043	renderer->target1Obj = GBARegisterBLDCNTGetTarget1Obj(value);
1044	renderer->target1Bd = GBARegisterBLDCNTGetTarget1Bd(value);
1045	renderer->target2Obj = GBARegisterBLDCNTGetTarget2Obj(value);
1046	renderer->target2Bd = GBARegisterBLDCNTGetTarget2Bd(value);
1047}
1048
1049void _finalizeLayers(struct GBAVideoGLRenderer* renderer) {
1050	const GLuint* uniforms = renderer->finalizeShader.uniforms;
1051	glBindFramebuffer(GL_FRAMEBUFFER, renderer->fbo[GBA_GL_FBO_OUTPUT]);
1052	glViewport(0, 0, GBA_VIDEO_HORIZONTAL_PIXELS * renderer->scale, GBA_VIDEO_VERTICAL_PIXELS * renderer->scale);
1053	glScissor(0, 0, GBA_VIDEO_HORIZONTAL_PIXELS * renderer->scale, GBA_VIDEO_VERTICAL_PIXELS * renderer->scale);
1054	glUseProgram(renderer->finalizeShader.program);
1055	glBindVertexArray(renderer->finalizeShader.vao);
1056	glActiveTexture(GL_TEXTURE0);
1057	glBindTexture(GL_TEXTURE_2D, renderer->layers[GBA_GL_TEX_WINDOW]);
1058	glActiveTexture(GL_TEXTURE0 + 1);
1059	glBindTexture(GL_TEXTURE_2D, renderer->layers[GBA_GL_TEX_OBJ_COLOR]);
1060	glActiveTexture(GL_TEXTURE0 + 2);
1061	glBindTexture(GL_TEXTURE_2D, renderer->layers[GBA_GL_TEX_OBJ_FLAGS]);
1062	glActiveTexture(GL_TEXTURE0 + 3);
1063	glBindTexture(GL_TEXTURE_2D, renderer->bg[0].tex);
1064	glActiveTexture(GL_TEXTURE0 + 4);
1065	glBindTexture(GL_TEXTURE_2D, renderer->bg[0].flags);
1066	glActiveTexture(GL_TEXTURE0 + 5);
1067	glBindTexture(GL_TEXTURE_2D, renderer->bg[1].tex);
1068	glActiveTexture(GL_TEXTURE0 + 6);
1069	glBindTexture(GL_TEXTURE_2D, renderer->bg[1].flags);
1070	glActiveTexture(GL_TEXTURE0 + 7);
1071	glBindTexture(GL_TEXTURE_2D, renderer->bg[2].tex);
1072	glActiveTexture(GL_TEXTURE0 + 8);
1073	glBindTexture(GL_TEXTURE_2D, renderer->bg[2].flags);
1074	glActiveTexture(GL_TEXTURE0 + 9);
1075	glBindTexture(GL_TEXTURE_2D, renderer->bg[3].tex);
1076	glActiveTexture(GL_TEXTURE0 + 10);
1077	glBindTexture(GL_TEXTURE_2D, renderer->bg[3].flags);
1078
1079	uint32_t backdrop = M_RGB5_TO_RGB8(renderer->d.palette[0]);
1080	glUniform2i(uniforms[GBA_GL_VS_LOC], GBA_VIDEO_VERTICAL_PIXELS, 0);
1081	glUniform2i(uniforms[GBA_GL_VS_MAXPOS], GBA_VIDEO_HORIZONTAL_PIXELS, GBA_VIDEO_VERTICAL_PIXELS);
1082	glUniform1i(uniforms[GBA_GL_FINALIZE_SCALE], renderer->scale);
1083	glUniform1iv(uniforms[GBA_GL_FINALIZE_LAYERS], 5, (GLint[]) { 3, 5, 7, 9, 1 });
1084	glUniform1iv(uniforms[GBA_GL_FINALIZE_FLAGS], 5, (GLint[]) { 4, 6, 8, 10, 2 });
1085	glUniform1i(uniforms[GBA_GL_FINALIZE_WINDOW], 0);
1086	glUniform4f(uniforms[GBA_GL_FINALIZE_BACKDROP], ((backdrop >> 16) & 0xFF) / 256., ((backdrop >> 8) & 0xFF) / 256., (backdrop & 0xFF) / 256., 0.f);
1087	glUniform4f(uniforms[GBA_GL_FINALIZE_BACKDROPFLAGS], 1, (renderer->target1Bd | (renderer->target2Bd * 2) | (renderer->blendEffect * 4)) / 32.f, renderer->blda / 16.f, renderer->bldb / 16.f);
1088	glEnableVertexAttribArray(0);
1089	glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
1090	glBindFramebuffer(GL_FRAMEBUFFER, 0);
1091}
1092
1093void GBAVideoGLRendererDrawSprite(struct GBAVideoGLRenderer* renderer, struct GBAObj* sprite, int y, int spriteY) {
1094	int width = GBAVideoObjSizes[GBAObjAttributesAGetShape(sprite->a) * 4 + GBAObjAttributesBGetSize(sprite->b)][0];
1095	int height = GBAVideoObjSizes[GBAObjAttributesAGetShape(sprite->a) * 4 + GBAObjAttributesBGetSize(sprite->b)][1];
1096	int32_t x = (uint32_t) GBAObjAttributesBGetX(sprite->b) << 23;
1097	x >>= 23;
1098
1099	int align = GBAObjAttributesAIs256Color(sprite->a) && !GBARegisterDISPCNTIsObjCharacterMapping(renderer->dispcnt);
1100	unsigned charBase = (BASE_TILE >> 1) + (GBAObjAttributesCGetTile(sprite->c) & ~align) * 0x10;
1101	int stride = GBARegisterDISPCNTIsObjCharacterMapping(renderer->dispcnt) ? (width >> 3) : (0x20 >> GBAObjAttributesAGet256Color(sprite->a));
1102
1103	if (spriteY + height >= 256) {
1104		spriteY -= 256;
1105	}
1106
1107	if (!GBAObjAttributesAIsTransformed(sprite->a) && GBAObjAttributesBIsVFlip(sprite->b)) {
1108		spriteY = (y - height) + (y - spriteY) + 1;
1109	}
1110
1111	int totalWidth = width;
1112	int totalHeight = height;
1113	if (GBAObjAttributesAIsTransformed(sprite->a) && GBAObjAttributesAIsDoubleSize(sprite->a)) {
1114		totalWidth <<= 1;
1115		totalHeight <<= 1;
1116	}
1117
1118	enum GBAVideoBlendEffect blendEffect = GBAObjAttributesAGetMode(sprite->a) == OBJ_MODE_SEMITRANSPARENT ? BLEND_ALPHA : renderer->blendEffect;
1119
1120	const struct GBAVideoGLShader* shader = &renderer->objShader[GBAObjAttributesAGet256Color(sprite->a)];
1121	const GLuint* uniforms = shader->uniforms;
1122	glBindFramebuffer(GL_FRAMEBUFFER, renderer->fbo[GBA_GL_FBO_OBJ]);
1123	glViewport(x * renderer->scale, spriteY * renderer->scale, totalWidth * renderer->scale, totalHeight * renderer->scale);
1124	glScissor(x * renderer->scale, y * renderer->scale, totalWidth * renderer->scale, renderer->scale);
1125	glUseProgram(shader->program);
1126	glBindVertexArray(shader->vao);
1127	glActiveTexture(GL_TEXTURE0);
1128	glBindTexture(GL_TEXTURE_2D, renderer->vramTex);
1129	glActiveTexture(GL_TEXTURE0 + 1);
1130	glBindTexture(GL_TEXTURE_2D, renderer->paletteTex);
1131	glUniform2i(uniforms[GBA_GL_VS_LOC], 1, y - spriteY);
1132	glUniform2i(uniforms[GBA_GL_VS_MAXPOS], (GBAObjAttributesBIsHFlip(sprite->b) && !GBAObjAttributesAIsTransformed(sprite->a)) ? -totalWidth : totalWidth, totalHeight);
1133	glUniform1i(uniforms[GBA_GL_OBJ_VRAM], 0);
1134	glUniform1i(uniforms[GBA_GL_OBJ_PALETTE], 1);
1135	glUniform1i(uniforms[GBA_GL_OBJ_CHARBASE], charBase);
1136	glUniform1i(uniforms[GBA_GL_OBJ_STRIDE], stride);
1137	glUniform1i(uniforms[GBA_GL_OBJ_LOCALPALETTE], GBAObjAttributesCGetPalette(sprite->c));
1138	glUniform4i(uniforms[GBA_GL_OBJ_INFLAGS], GBAObjAttributesCGetPriority(sprite->c) << 3,
1139	                                          (renderer->target1Obj || GBAObjAttributesAGetMode(sprite->a) == OBJ_MODE_SEMITRANSPARENT) | (renderer->target2Obj * 2) | (blendEffect * 4),
1140	                                          renderer->blda, renderer->bldb);
1141	if (GBAObjAttributesAIsTransformed(sprite->a)) {
1142		struct GBAOAMMatrix mat;
1143		LOAD_16(mat.a, 0, &renderer->d.oam->mat[GBAObjAttributesBGetMatIndex(sprite->b)].a);
1144		LOAD_16(mat.b, 0, &renderer->d.oam->mat[GBAObjAttributesBGetMatIndex(sprite->b)].b);
1145		LOAD_16(mat.c, 0, &renderer->d.oam->mat[GBAObjAttributesBGetMatIndex(sprite->b)].c);
1146		LOAD_16(mat.d, 0, &renderer->d.oam->mat[GBAObjAttributesBGetMatIndex(sprite->b)].d);
1147
1148		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 });
1149	} else {
1150		glUniformMatrix2fv(uniforms[GBA_GL_OBJ_TRANSFORM], 1, GL_FALSE, (GLfloat[]) { 1.f, 0, 0, 1.f });
1151	}
1152	glUniform4i(uniforms[GBA_GL_OBJ_DIMS], width, height, totalWidth, totalHeight);
1153	if (GBAObjAttributesAGetMode(sprite->a) == OBJ_MODE_OBJWIN) {
1154		int window = ~renderer->objwin & 0xFF;
1155		glUniform3f(uniforms[GBA_GL_OBJ_OBJWIN], 1, (window & 0xF) / 32.f, (window >> 4) / 32.f);
1156		glDrawBuffers(3, (GLenum[]) { GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1, GL_COLOR_ATTACHMENT2 });
1157	} else {
1158		glUniform3f(uniforms[GBA_GL_OBJ_OBJWIN], 0, 0, 0);
1159		glDrawBuffers(2, (GLenum[]) { GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1 });
1160	}
1161	glEnableVertexAttribArray(0);
1162	glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
1163	glDrawBuffers(1, (GLenum[]) { GL_COLOR_ATTACHMENT0 });
1164}
1165
1166void GBAVideoGLRendererDrawBackgroundMode0(struct GBAVideoGLRenderer* renderer, struct GBAVideoGLBackground* background, int y) {
1167	int inY = y + background->y;
1168	int yBase = inY & 0xFF;
1169	if (background->size == 2) {
1170		yBase += inY & 0x100;
1171	} else if (background->size == 3) {
1172		yBase += (inY & 0x100) << 1;
1173	}
1174
1175	const struct GBAVideoGLShader* shader = &renderer->bgShader[background->multipalette ? 1 : 0];
1176	const GLuint* uniforms = shader->uniforms;
1177	glBindFramebuffer(GL_FRAMEBUFFER, background->fbo);
1178	glViewport(0, 0, GBA_VIDEO_HORIZONTAL_PIXELS * renderer->scale, GBA_VIDEO_VERTICAL_PIXELS * renderer->scale);
1179	glScissor(0, y * renderer->scale, GBA_VIDEO_HORIZONTAL_PIXELS * renderer->scale, renderer->scale);
1180	glUseProgram(shader->program);
1181	glBindVertexArray(shader->vao);
1182	glActiveTexture(GL_TEXTURE0);
1183	glBindTexture(GL_TEXTURE_2D, renderer->vramTex);
1184	glActiveTexture(GL_TEXTURE0 + 1);
1185	glBindTexture(GL_TEXTURE_2D, renderer->paletteTex);
1186	glUniform2i(uniforms[GBA_GL_VS_LOC], 1, y);
1187	glUniform2i(uniforms[GBA_GL_VS_MAXPOS], GBA_VIDEO_HORIZONTAL_PIXELS, GBA_VIDEO_VERTICAL_PIXELS);
1188	glUniform1i(uniforms[GBA_GL_BG_VRAM], 0);
1189	glUniform1i(uniforms[GBA_GL_BG_PALETTE], 1);
1190	glUniform1i(uniforms[GBA_GL_BG_SCREENBASE], background->screenBase);
1191	glUniform1i(uniforms[GBA_GL_BG_CHARBASE], background->charBase);
1192	glUniform1i(uniforms[GBA_GL_BG_SIZE], background->size);
1193	glUniform2i(uniforms[GBA_GL_BG_OFFSET], background->x, yBase - y);
1194	glUniform4i(uniforms[GBA_GL_BG_INFLAGS], (background->priority << 3) + (background->index << 1) + 1,
1195		                                     background->target1 | (background->target2 * 2) | (renderer->blendEffect * 4),
1196		                                     renderer->blda, renderer->bldb);
1197	glDrawBuffers(2, (GLenum[]) { GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1 });
1198	glEnableVertexAttribArray(0);
1199	glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
1200	glDrawBuffers(1, (GLenum[]) { GL_COLOR_ATTACHMENT0 });
1201}
1202
1203void GBAVideoGLRendererDrawBackgroundMode2(struct GBAVideoGLRenderer* renderer, struct GBAVideoGLBackground* background, int y) {
1204	int reverse;
1205	int forward;
1206	switch (y - renderer->firstAffine) {
1207	case 0:
1208	case 1:
1209	case 2:
1210	case 3:
1211		return;
1212	case 4:
1213		forward = 2;
1214		reverse = 4;
1215		break;
1216	case 5:
1217		forward = 2;
1218		reverse = 3;
1219		break;
1220	case 6:
1221		forward = 2;
1222		reverse = 2;
1223		break;
1224	default:
1225		forward = 1;
1226		reverse = 1;
1227	}
1228
1229	const struct GBAVideoGLShader* shader = &renderer->bgShader[background->overflow ? 2 : 3];
1230	const GLuint* uniforms = shader->uniforms;
1231	glBindFramebuffer(GL_FRAMEBUFFER, background->fbo);
1232	glViewport(0, 0, GBA_VIDEO_HORIZONTAL_PIXELS * renderer->scale, GBA_VIDEO_VERTICAL_PIXELS * renderer->scale);
1233	glScissor(0, (y - reverse) * renderer->scale, GBA_VIDEO_HORIZONTAL_PIXELS * renderer->scale, renderer->scale * forward);
1234	glUseProgram(shader->program);
1235	glBindVertexArray(shader->vao);
1236	glActiveTexture(GL_TEXTURE0);
1237	glBindTexture(GL_TEXTURE_2D, renderer->vramTex);
1238	glActiveTexture(GL_TEXTURE0 + 1);
1239	glBindTexture(GL_TEXTURE_2D, renderer->paletteTex);
1240	glUniform2i(uniforms[GBA_GL_VS_LOC], forward, y - reverse);
1241	glUniform2i(uniforms[GBA_GL_VS_MAXPOS], GBA_VIDEO_HORIZONTAL_PIXELS, GBA_VIDEO_VERTICAL_PIXELS);
1242	glUniform1i(uniforms[GBA_GL_BG_VRAM], 0);
1243	glUniform1i(uniforms[GBA_GL_BG_PALETTE], 1);
1244	glUniform1i(uniforms[GBA_GL_BG_SCREENBASE], background->screenBase);
1245	glUniform1i(uniforms[GBA_GL_BG_CHARBASE], background->charBase);
1246	glUniform1i(uniforms[GBA_GL_BG_SIZE], background->size);
1247	glUniform2f(uniforms[GBA_GL_BG_RANGE], y, 1);
1248	glUniform4i(uniforms[GBA_GL_BG_INFLAGS], (background->priority << 3) + (background->index << 1) + 1,
1249		                                     background->target1 | (background->target2 * 2) | (renderer->blendEffect * 4),
1250		                                     renderer->blda, renderer->bldb);
1251	if (renderer->scale > 1) {
1252		glUniform2iv(uniforms[GBA_GL_BG_OFFSET], 4, (GLint[]) {
1253			background->affine[0].sx, background->affine[0].sy,
1254			background->affine[1].sx, background->affine[1].sy,
1255			background->affine[2].sx, background->affine[2].sy,
1256			background->affine[3].sx, background->affine[3].sy,
1257		});
1258		glUniform2iv(uniforms[GBA_GL_BG_TRANSFORM], 4, (GLint[]) {
1259			background->affine[0].dx, background->affine[0].dy,
1260			background->affine[1].dx, background->affine[1].dy,
1261			background->affine[2].dx, background->affine[2].dy,
1262			background->affine[3].dx, background->affine[3].dy,
1263		});
1264	} else {
1265		glUniform2iv(uniforms[GBA_GL_BG_OFFSET], 4, (GLint[]) {
1266			background->affine[0].sx, background->affine[0].sy,
1267			background->affine[0].sx, background->affine[0].sy,
1268			background->affine[0].sx, background->affine[0].sy,
1269			background->affine[0].sx, background->affine[0].sy,
1270		});
1271		glUniform2iv(uniforms[GBA_GL_BG_TRANSFORM], 4, (GLint[]) {
1272			background->affine[0].dx, background->affine[0].dy,
1273			background->affine[0].dx, background->affine[0].dy,
1274			background->affine[0].dx, background->affine[0].dy,
1275			background->affine[0].dx, background->affine[0].dy,
1276		});
1277	}
1278	glDrawBuffers(2, (GLenum[]) { GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1 });
1279	glEnableVertexAttribArray(0);
1280	glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
1281	glDrawBuffers(1, (GLenum[]) { GL_COLOR_ATTACHMENT0 });
1282}
1283
1284static void _scissorWindow(int start, int end, int y, int lines, int scale) {
1285	if (start > end) {
1286		_scissorWindow(start, GBA_VIDEO_HORIZONTAL_PIXELS * scale, y, lines, scale);
1287		_scissorWindow(0, end, y, lines, scale);
1288		return;
1289	}
1290	glScissor(start, y, end - start, lines);
1291	glClear(GL_COLOR_BUFFER_BIT);	
1292}
1293
1294static void _scissorWindowN(struct GBAVideoWindowRegion* region, int y, int scale) {
1295	int sdelta = region[0].start - region[1].start;
1296	int edelta = region[0].end - region[1].end;
1297	int maxDelta = 0;
1298	if (sdelta > maxDelta) {
1299		maxDelta = sdelta;
1300	} else if (-sdelta > maxDelta) {
1301		maxDelta = -sdelta;
1302	}
1303	if (edelta > maxDelta) {
1304		maxDelta = edelta;
1305	} else if (-edelta > maxDelta) {
1306		maxDelta = -edelta;
1307	}
1308	if (!(sdelta | edelta) || maxDelta >= GBA_VIDEO_VERTICAL_PIXELS / 2) {
1309		_scissorWindow(region[0].start * scale, region[0].end * scale, y, scale, scale);
1310	} else {
1311		int i;
1312		for (i = 0; i < scale; ++i) {
1313			int start = region[1].start * scale + sdelta * i;
1314			int end = region[1].end * scale + edelta * i;
1315			_scissorWindow(start, end, y + i, 1, scale);
1316		}
1317	}
1318}
1319
1320static void _clearWindow(GBAWindowControl window, int bldy) {
1321	window = ~window & 0xFF;
1322	glClearColor((window & 0xF) / 32.f, (window >> 4) / 32.f, bldy / 16.f, 0);
1323}
1324
1325void GBAVideoGLRendererDrawWindow(struct GBAVideoGLRenderer* renderer, int y) {
1326	glBindFramebuffer(GL_FRAMEBUFFER, renderer->fbo[GBA_GL_FBO_WINDOW]);
1327	int dispcnt = ((renderer->dispcnt >> 8) & 0x1F) | 0x20;
1328	if (!(renderer->dispcnt & 0xE000)) {
1329		_clearWindow(dispcnt, renderer->bldy);
1330		_scissorWindow(0, GBA_VIDEO_HORIZONTAL_PIXELS * renderer->scale, y * renderer->scale, renderer->scale, renderer->scale);
1331	} else {
1332		_clearWindow(renderer->winout & dispcnt, renderer->bldy);
1333		_scissorWindow(0, GBA_VIDEO_HORIZONTAL_PIXELS * renderer->scale, y * renderer->scale, renderer->scale, renderer->scale);
1334		if (GBARegisterDISPCNTIsWin1Enable(renderer->dispcnt) && y >= renderer->winN[1].v.start && y < renderer->winN[1].v.end) {
1335			_clearWindow(renderer->winN[1].control & dispcnt, renderer->bldy);
1336			_scissorWindowN(renderer->winN[1].h, y * renderer->scale, renderer->scale);
1337		}
1338		if (GBARegisterDISPCNTIsWin0Enable(renderer->dispcnt) && y >= renderer->winN[0].v.start && y < renderer->winN[0].v.end) {
1339			_clearWindow(renderer->winN[0].control & dispcnt, renderer->bldy);
1340			_scissorWindowN(renderer->winN[0].h, y * renderer->scale, renderer->scale);
1341		}
1342	}
1343}
1344
1345#endif