Source

gb_emulator / gb_emulator / src / gb_video_opengl_es2.cpp

Full commit
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
/*  Copyright © 2012, 2013 Chris Spencer <spencercw@gmail.com>

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */

#include <gb_emulator/gb_video_opengl_es2.h>

#include <limits>
#include <stdexcept>
#include <string>
#include <system_error>

#include <boost/filesystem/fstream.hpp>
#include <boost/filesystem/operations.hpp>

#include <GLES2/gl2ext.h>

#include <gb_emulator/gb.h>
#include <gb_emulator/glew_error.h>

namespace fs = boost::filesystem;
using std::ios_base;
using std::numeric_limits;
using std::runtime_error;
using std::string;
using std::system_category;
using std::system_error;

GbVideoOpenGLES2::GbVideoOpenGLES2(Gb &gb, const fs::path &installDir):
GbVideo(gb),
window_(nullptr),
windowClass_(0),
deviceContext_(nullptr),
program_(0),
vertexShader_(0),
fragmentShader_(0),
vertexBuffer_(0),
texture_(0),
installDir_(installDir),
unscaledPixelBuffer_(new uint32_t[WIDTH * HEIGHT]),
scaledPixelBuffer_(new uint32_t[SCALED_WIDTH * SCALED_HEIGHT]),
textureBuffer_(new uint32_t[TEXTURE_WIDTH * TEXTURE_HEIGHT])
{
}

GbVideoOpenGLES2::~GbVideoOpenGLES2()
{
	// Destroy the window if it has been created
	if (window_)
	{
		DestroyWindow(window_);
	}
	if (windowClass_)
	{
		UnregisterClassW(reinterpret_cast<wchar_t *>(windowClass_), GetModuleHandle(nullptr));
	}
}

void GbVideoOpenGLES2::draw(uint16_t *pixelBuffer, bool gbc)
{
	// Perform post-processing in software
	postProcess(pixelBuffer, gbc, unscaledPixelBuffer_.get(), scaledPixelBuffer_.get());

	// Upload the texture into video memory
	glBindTexture(GL_TEXTURE_2D, texture_);
	glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, SCALED_WIDTH, SCALED_HEIGHT, GL_BGRA_EXT,
		GL_UNSIGNED_BYTE, scaledPixelBuffer_.get());

	// Update the display
	glClearColor(0.f, 0.f, 0.f, 0.f);
	glClear(GL_COLOR_BUFFER_BIT);

	glDrawArrays(GL_TRIANGLE_STRIP, 0, 5);

	if (!eglSwapBuffers(display_, surface_))
	{
		throw system_error(GetLastError(), system_category(), "Failed to swap buffers");
	}
}

void GbVideoOpenGLES2::resize(GLsizei width, GLsizei height)
{
	glViewport(0, 0, width, height);
}

////////////////////////////////////////////////////////////////////////////////////////////////////
// Initialisation

void GbVideoOpenGLES2::initialise()
{
	// Register the window class
	WNDCLASSEXW windowClassData;
	memset(&windowClassData, 0, sizeof(windowClassData));
	windowClassData.cbSize = sizeof(windowClassData);
	windowClassData.style = 0;
	windowClassData.lpfnWndProc = &GbVideoOpenGLES2::initialWindowProc;
	windowClassData.cbClsExtra = 0;
	windowClassData.cbWndExtra = 0;
	windowClassData.hInstance = GetModuleHandle(nullptr);
	windowClassData.hIcon = nullptr;
	windowClassData.hCursor = LoadCursor(nullptr, IDC_ARROW);
	windowClassData.hbrBackground = nullptr;
	windowClassData.lpszClassName = L"WindowClass";
	windowClassData.hIconSm = nullptr;

	windowClass_ = RegisterClassExW(&windowClassData);
	if (!windowClass_)
	{
		throw system_error(GetLastError(), system_category(), "Failed to register window class");
	}

	RECT windowRect = { 0, 0, SCALED_WIDTH, SCALED_HEIGHT };
	if (!AdjustWindowRect(&windowRect, WS_OVERLAPPEDWINDOW, FALSE))
	{
		throw system_error(GetLastError(), system_category(), "Failed to set the main window size");
	}

	// Create the main window
	window_ = CreateWindowExW(0, reinterpret_cast<const wchar_t *>(windowClass_), L"GbVideoOpenGLES2",
		WS_OVERLAPPEDWINDOW | WS_VISIBLE, CW_USEDEFAULT, CW_USEDEFAULT,
		windowRect.right - windowRect.left, windowRect.bottom - windowRect.top, nullptr, nullptr,
		windowClassData.hInstance, this);
	if (!window_)
	{
		throw system_error(GetLastError(), system_category(), "Failed to create the main window");
	}

	// Show the window; OpenGL is initialised in the window procedure
	ShowWindow(window_, SW_SHOWNORMAL);
	UpdateWindow(window_);
}

void GbVideoOpenGLES2::initialiseGL(GLsizei width, GLsizei height)
{
	// Initialise OpenGL ES
	// Bind the display
	display_ = eglGetDisplay(deviceContext_);
	if (!display_)
	{
		throw runtime_error("Failed to get EGL display");
	}

	// Initialise EGL
	if (!eglInitialize(display_, nullptr, nullptr))
	{
		throw runtime_error("Failed to initialise EGL");
	}

	// Create the context
	static const EGLint configAttributes[] = {
		EGL_RED_SIZE, 8,
		EGL_GREEN_SIZE, 8,
		EGL_BLUE_SIZE, 8,
		EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT,
		EGL_NONE };
	EGLConfig config;
	EGLint configCount;
	if (!eglChooseConfig(display_, configAttributes, &config, 1, &configCount))
	{
		throw runtime_error("Failed to get EGL configuration");
	}

	static const EGLint contextAttributes[] = {
		EGL_CONTEXT_CLIENT_VERSION, 2,
		EGL_NONE };
	eglContext_ = eglCreateContext(display_, config, EGL_NO_CONTEXT, contextAttributes);
	if (!eglContext_)
	{
		throw runtime_error("Failed to create EGL context");
	}

	// Bind the window
	static const EGLint windowAttributes[] = {
		EGL_NONE };
	surface_ = eglCreateWindowSurface(display_, config, window_, windowAttributes);
	if (!surface_)
	{
		throw runtime_error("Failed to create EGL surface");
	}

	if (!eglMakeCurrent(display_, surface_, surface_, eglContext_))
	{
		throw runtime_error("Failed to attach EGL context to surface");
	}

	// Disable vsync
	eglSwapInterval(display_, 0);

	// Set the viewport
	glViewport(0, 0, width, height);

	// Initialise the shaders
	initialiseShaders();
	
	// Create the data buffers
	// Vertices
	static const GLfloat VERTICES[] = {
		 1.f, -1.f,    // Bottom right
		-1.f, -1.f,    // Bottom left
		-1.f,  1.f,    // Top left
		 1.f,  1.f,    // Top right
		 1.f, -1.f };  // Bottom right

	int positionParameter = glGetAttribLocation(program_, "a_position");
	if (positionParameter == -1)
	{
		throw runtime_error("Failed to get 'a_position' parameter from shader");
	}
	glEnableVertexAttribArray(positionParameter);
	glVertexAttribPointer(positionParameter, 2, GL_FLOAT, GL_FALSE, 0, VERTICES);

	// Texture coordinates
	static const GLfloat TEXTURE_X = static_cast<GLfloat>(SCALED_WIDTH)  / TEXTURE_WIDTH;
	static const GLfloat TEXTURE_Y = static_cast<GLfloat>(SCALED_HEIGHT) / TEXTURE_HEIGHT;
	static const GLfloat TEX_COORDS[] = {
		TEXTURE_X, TEXTURE_Y,
		0.f, TEXTURE_Y,
		0.f, 0.f,
		TEXTURE_X, 0.f,
		TEXTURE_X, TEXTURE_Y };

	int texCoordParameter = glGetAttribLocation(program_, "a_texCoord");
	if (texCoordParameter == -1)
	{
		throw runtime_error("Failed to get 'a_texCoord parameter from shader");
	}
	glEnableVertexAttribArray(texCoordParameter);
	glVertexAttribPointer(texCoordParameter, 2, GL_FLOAT, GL_FALSE, 0, TEX_COORDS);

	// Create the texture
	glGenTextures(1, &texture_);
	glBindTexture(GL_TEXTURE_2D, texture_);
	glTexImage2D(GL_TEXTURE_2D, 0, GL_BGRA_EXT, TEXTURE_WIDTH, TEXTURE_HEIGHT, 0, GL_BGRA_EXT,
		GL_UNSIGNED_BYTE, textureBuffer_.get());
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
	glBindTexture(GL_TEXTURE_2D, 0);

	// Bind the texture to the shader
	int samplerParam = glGetUniformLocation(program_, "s_texture");
	if (samplerParam == -1)
	{
		throw runtime_error("Failed to get 's_texture' parameter from shader");
	}
	glUniform1i(samplerParam, 0);
}

void GbVideoOpenGLES2::initialiseShaders()
{
	// Compile the shaders
	vertexShader_ = compileShader(GL_VERTEX_SHADER,
		installDir_ / "shaders/gles2/vertex_shader.glsl");
	fragmentShader_ = compileShader(GL_FRAGMENT_SHADER,
		installDir_ / "shaders/gles2/fragment_shader.glsl");

	// Link the shaders
	program_ = glCreateProgram();
	if (!program_)
	{
		throw runtime_error("Failed to create shader program");
	}

	glAttachShader(program_, vertexShader_);
	glAttachShader(program_, fragmentShader_);
	glLinkProgram(program_);

	// Check it was linked ok
	GLint linked = GL_FALSE;
	glGetProgramiv(program_, GL_LINK_STATUS, &linked);
	if (!linked)
	{
		string info;
		GLint infoLen = 0;
		glGetProgramiv(program_, GL_INFO_LOG_LENGTH, &infoLen);
		if (infoLen)
		{
			string info(infoLen, '\0');
			glGetProgramInfoLog(program_, infoLen, nullptr, &*info.begin());
		}

		string message = "Failed to link shaders";
		if (!info.empty())
		{
			message += ": " + info;
		}
		throw runtime_error(message);
	}

	// Bind the shaders
	glUseProgram(program_);
}

GLuint GbVideoOpenGLES2::compileShader(GLenum type, const fs::path &source)
{
	// Read in the shader file
	fs::ifstream f(source, ios_base::in | ios_base::binary);
	if (!f)
	{
		throw runtime_error("Failed to open shader file '" + source.string() + "' for reading");
	}

	uintmax_t sourceLen = fs::file_size(source);
	assert(sourceLen <= (numeric_limits<size_t>::max)());
	string sourceCode(static_cast<size_t>(sourceLen), '\0');
	f.read(&*sourceCode.begin(), sourceLen);
	if (f.gcount() < 0 || static_cast<uintmax_t>(f.gcount()) != sourceLen)
	{
		throw runtime_error("Failed to read from shader file '" + source.string() + "'");
	}

	// Compile the shader
	GLuint shader = glCreateShader(type);
	if (!shader)
	{
		throw runtime_error("Failed to create vertex shader");
	}

	const GLchar *glSourceCode = sourceCode.data();
	assert(sourceLen <= (numeric_limits<GLint>::max)());
	GLint glSourceLen = static_cast<GLint>(sourceLen);
	glShaderSource(shader, 1, &glSourceCode, &glSourceLen);
	glCompileShader(shader);

	// Check it was copmiled ok
	GLint compiled = 0;
	glGetShaderiv(shader, GL_COMPILE_STATUS, &compiled);
	if (!compiled)
	{
		string info;
		GLint infoLen = 0;
		glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &infoLen);
		if (infoLen)
		{
			string info(infoLen, '\0');
			glGetShaderInfoLog(shader, infoLen, nullptr, &*info.begin());
		}

		string message = "Failed to compile shader";
		if (!info.empty())
		{
			message += ": " + info;
		}
		throw runtime_error(message);
	}

	return shader;
}

////////////////////////////////////////////////////////////////////////////////////////////////////
// Window message operations

LRESULT CALLBACK GbVideoOpenGLES2::initialWindowProc(HWND window, unsigned message, WPARAM wParam,
	LPARAM lParam)
{
	// Wait for the creation message so we can get the parent pointer and apply it to the window
	if (message == WM_NCCREATE)
	{
		CREATESTRUCTW *cs = reinterpret_cast<CREATESTRUCTW *>(lParam);
		GbVideoOpenGLES2 *parent = reinterpret_cast<GbVideoOpenGLES2 *>(cs->lpCreateParams);

		SetWindowLongPtrW(window, GWLP_USERDATA, reinterpret_cast<LONG_PTR>(parent));
		SetWindowLongPtrW(window, GWLP_WNDPROC,
			reinterpret_cast<LONG_PTR>(&GbVideoOpenGLES2::windowProc));

		// Defer
		return parent->doWindowProc(window, message, wParam, lParam);
	}
	return DefWindowProcW(window, message, wParam, lParam);
}

LRESULT CALLBACK GbVideoOpenGLES2::windowProc(HWND window, unsigned message, WPARAM wParam, LPARAM lParam)
{
	// Get the pointer to the parent object
	GbVideoOpenGLES2 *parent = reinterpret_cast<GbVideoOpenGLES2 *>(GetWindowLongPtrW(window, GWLP_USERDATA));
	if (parent)
	{
		return parent->doWindowProc(window, message, wParam, lParam);
	}
	return DefWindowProcW(window, message, wParam, lParam);
}

LRESULT GbVideoOpenGLES2::doWindowProc(HWND window, unsigned message, WPARAM wParam, LPARAM lParam)
{
	switch (message)
	{
	case WM_CREATE:
		window_ = window;

		// Initialise OpenGL
		deviceContext_ = GetDC(window);
		if (!deviceContext_)
		{
			throw system_error(GetLastError(), system_category(), "Failed to get device context");
		}

		{
			RECT rect;
			if (!GetClientRect(window, &rect))
			{
				throw system_error(GetLastError(), system_category(), "Failed to get window area");
			}
			initialiseGL(rect.right, rect.bottom);
		}
		break;

	case WM_SIZE:
		{
			RECT rect;
			if (!GetClientRect(window, &rect))
			{
				throw system_error(GetLastError(), system_category(), "Failed to get window area");
			}
			resize(rect.right, rect.bottom);
		}
		break;

	case WM_CLOSE:
		// Close the window
		if (!DestroyWindow(window))
		{
			throw system_error(GetLastError(), system_category(), "Failed to destroy window");
		}
		window_ = nullptr;
		break;

	case WM_DESTROY:
		// Clean up
		if (surface_ && !eglDestroySurface(display_, surface_))
		{
			throw runtime_error("Failed to release EGL surface");
		}
		surface_ = nullptr;

		if (display_ && !eglDestroyContext(display_, eglContext_))
		{
			throw runtime_error("Failed to release EGL context");
		}
		eglContext_ = nullptr;

		if (deviceContext_ && !ReleaseDC(window, deviceContext_))
		{
			throw system_error(GetLastError(), system_category(),
				"Failed to release device context");
		}
		deviceContext_ = nullptr;

		// Quit
		PostQuitMessage(0);
		break;

	default:
		return DefWindowProcW(window, message, wParam, lParam);
	}

	return 0;
}