all repos — mgba @ c5ae273a3a786a00dbe470fac01885819e86e958

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