all repos — mgba @ 505d63fab55ff83c7487a4162e7f932fae0e4df1

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