OpenTTD Source  13.2.1
opengl.cpp
1 /*
2  * This file is part of OpenTTD.
3  * OpenTTD 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, version 2.
4  * OpenTTD 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.
5  * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
6  */
7 
10 #include "../stdafx.h"
11 
12 /* Define to disable buffer syncing. Will increase max fast forward FPS but produces artifacts. Mainly useful for performance testing. */
13 // #define NO_GL_BUFFER_SYNC
14 /* Define to allow software rendering backends. */
15 // #define GL_ALLOW_SOFTWARE_RENDERER
16 
17 #if defined(_WIN32)
18 # include <windows.h>
19 #endif
20 
21 #define GL_GLEXT_PROTOTYPES
22 #if defined(__APPLE__)
23 # define GL_SILENCE_DEPRECATION
24 # include <OpenGL/gl3.h>
25 #else
26 # include <GL/gl.h>
27 #endif
28 #include "../3rdparty/opengl/glext.h"
29 
30 #include "opengl.h"
31 #include "../core/geometry_func.hpp"
32 #include "../core/mem_func.hpp"
33 #include "../core/math_func.hpp"
34 #include "../core/mem_func.hpp"
35 #include "../gfx_func.h"
36 #include "../debug.h"
37 #include "../blitter/factory.hpp"
38 #include "../zoom_func.h"
39 #include <array>
40 #include <numeric>
41 
42 #include "../table/opengl_shader.h"
43 #include "../table/sprites.h"
44 
45 
46 #include "../safeguards.h"
47 
48 
49 /* Define function pointers of all OpenGL functions that we load dynamically. */
50 
51 #define GL(function) static decltype(&function) _ ## function
52 
53 GL(glGetString);
54 GL(glGetIntegerv);
55 GL(glGetError);
56 GL(glDebugMessageControl);
57 GL(glDebugMessageCallback);
58 
59 GL(glDisable);
60 GL(glEnable);
61 GL(glViewport);
62 GL(glClear);
63 GL(glClearColor);
64 GL(glBlendFunc);
65 GL(glDrawArrays);
66 
67 GL(glTexImage1D);
68 GL(glTexImage2D);
69 GL(glTexParameteri);
70 GL(glTexSubImage1D);
71 GL(glTexSubImage2D);
72 GL(glBindTexture);
73 GL(glDeleteTextures);
74 GL(glGenTextures);
75 GL(glPixelStorei);
76 
77 GL(glActiveTexture);
78 
79 GL(glGenBuffers);
80 GL(glDeleteBuffers);
81 GL(glBindBuffer);
82 GL(glBufferData);
83 GL(glBufferSubData);
84 GL(glMapBuffer);
85 GL(glUnmapBuffer);
86 GL(glClearBufferSubData);
87 
88 GL(glBufferStorage);
89 GL(glMapBufferRange);
90 GL(glClientWaitSync);
91 GL(glFenceSync);
92 GL(glDeleteSync);
93 
94 GL(glGenVertexArrays);
95 GL(glDeleteVertexArrays);
96 GL(glBindVertexArray);
97 
98 GL(glCreateProgram);
99 GL(glDeleteProgram);
100 GL(glLinkProgram);
101 GL(glUseProgram);
102 GL(glGetProgramiv);
103 GL(glGetProgramInfoLog);
104 GL(glCreateShader);
105 GL(glDeleteShader);
106 GL(glShaderSource);
107 GL(glCompileShader);
108 GL(glAttachShader);
109 GL(glGetShaderiv);
110 GL(glGetShaderInfoLog);
111 GL(glGetUniformLocation);
112 GL(glUniform1i);
113 GL(glUniform1f);
114 GL(glUniform2f);
115 GL(glUniform4f);
116 
117 GL(glGetAttribLocation);
118 GL(glEnableVertexAttribArray);
119 GL(glDisableVertexAttribArray);
120 GL(glVertexAttribPointer);
121 GL(glBindFragDataLocation);
122 
123 #undef GL
124 
125 
128  float x, y;
129  float u, v;
130 };
131 
133 static const int MAX_CACHED_CURSORS = 48;
134 
135 /* static */ OpenGLBackend *OpenGLBackend::instance = nullptr;
136 
137 GetOGLProcAddressProc GetOGLProcAddress;
138 
146 const char *FindStringInExtensionList(const char *string, const char *substring)
147 {
148  while (true) {
149  /* Is the extension string present at all? */
150  const char *pos = strstr(string, substring);
151  if (pos == nullptr) break;
152 
153  /* Is this a real match, i.e. are the chars before and after the matched string
154  * indeed spaces (or the start or end of the string, respectively)? */
155  const char *end = pos + strlen(substring);
156  if ((pos == string || pos[-1] == ' ') && (*end == ' ' || *end == '\0')) return pos;
157 
158  /* False hit, try again for the remaining string. */
159  string = end;
160  }
161 
162  return nullptr;
163 }
164 
170 static bool IsOpenGLExtensionSupported(const char *extension)
171 {
172  static PFNGLGETSTRINGIPROC glGetStringi = nullptr;
173  static bool glGetStringi_loaded = false;
174 
175  /* Starting with OpenGL 3.0 the preferred API to get the extensions
176  * has changed. Try to load the required function once. */
177  if (!glGetStringi_loaded) {
178  if (IsOpenGLVersionAtLeast(3, 0)) glGetStringi = (PFNGLGETSTRINGIPROC)GetOGLProcAddress("glGetStringi");
179  glGetStringi_loaded = true;
180  }
181 
182  if (glGetStringi != nullptr) {
183  /* New style: Each supported extension can be queried and compared independently. */
184  GLint num_exts;
185  _glGetIntegerv(GL_NUM_EXTENSIONS, &num_exts);
186 
187  for (GLint i = 0; i < num_exts; i++) {
188  const char *entry = (const char *)glGetStringi(GL_EXTENSIONS, i);
189  if (strcmp(entry, extension) == 0) return true;
190  }
191  } else {
192  /* Old style: A single, space-delimited string for all extensions. */
193  return FindStringInExtensionList((const char *)_glGetString(GL_EXTENSIONS), extension) != nullptr;
194  }
195 
196  return false;
197 }
198 
199 static byte _gl_major_ver = 0;
200 static byte _gl_minor_ver = 0;
201 
209 bool IsOpenGLVersionAtLeast(byte major, byte minor)
210 {
211  return (_gl_major_ver > major) || (_gl_major_ver == major && _gl_minor_ver >= minor);
212 }
213 
221 template <typename F>
222 static bool BindGLProc(F &f, const char *name)
223 {
224  f = reinterpret_cast<F>(GetOGLProcAddress(name));
225  return f != nullptr;
226 }
227 
229 static bool BindBasicInfoProcs()
230 {
231  if (!BindGLProc(_glGetString, "glGetString")) return false;
232  if (!BindGLProc(_glGetIntegerv, "glGetIntegerv")) return false;
233  if (!BindGLProc(_glGetError, "glGetError")) return false;
234 
235  return true;
236 }
237 
239 static bool BindBasicOpenGLProcs()
240 {
241  if (!BindGLProc(_glDisable, "glDisable")) return false;
242  if (!BindGLProc(_glEnable, "glEnable")) return false;
243  if (!BindGLProc(_glViewport, "glViewport")) return false;
244  if (!BindGLProc(_glTexImage1D, "glTexImage1D")) return false;
245  if (!BindGLProc(_glTexImage2D, "glTexImage2D")) return false;
246  if (!BindGLProc(_glTexParameteri, "glTexParameteri")) return false;
247  if (!BindGLProc(_glTexSubImage1D, "glTexSubImage1D")) return false;
248  if (!BindGLProc(_glTexSubImage2D, "glTexSubImage2D")) return false;
249  if (!BindGLProc(_glBindTexture, "glBindTexture")) return false;
250  if (!BindGLProc(_glDeleteTextures, "glDeleteTextures")) return false;
251  if (!BindGLProc(_glGenTextures, "glGenTextures")) return false;
252  if (!BindGLProc(_glPixelStorei, "glPixelStorei")) return false;
253  if (!BindGLProc(_glClear, "glClear")) return false;
254  if (!BindGLProc(_glClearColor, "glClearColor")) return false;
255  if (!BindGLProc(_glBlendFunc, "glBlendFunc")) return false;
256  if (!BindGLProc(_glDrawArrays, "glDrawArrays")) return false;
257 
258  return true;
259 }
260 
262 static bool BindTextureExtensions()
263 {
264  if (IsOpenGLVersionAtLeast(1, 3)) {
265  if (!BindGLProc(_glActiveTexture, "glActiveTexture")) return false;
266  } else {
267  if (!BindGLProc(_glActiveTexture, "glActiveTextureARB")) return false;
268  }
269 
270  return true;
271 }
272 
274 static bool BindVBOExtension()
275 {
276  if (IsOpenGLVersionAtLeast(1, 5)) {
277  if (!BindGLProc(_glGenBuffers, "glGenBuffers")) return false;
278  if (!BindGLProc(_glDeleteBuffers, "glDeleteBuffers")) return false;
279  if (!BindGLProc(_glBindBuffer, "glBindBuffer")) return false;
280  if (!BindGLProc(_glBufferData, "glBufferData")) return false;
281  if (!BindGLProc(_glBufferSubData, "glBufferSubData")) return false;
282  if (!BindGLProc(_glMapBuffer, "glMapBuffer")) return false;
283  if (!BindGLProc(_glUnmapBuffer, "glUnmapBuffer")) return false;
284  } else {
285  if (!BindGLProc(_glGenBuffers, "glGenBuffersARB")) return false;
286  if (!BindGLProc(_glDeleteBuffers, "glDeleteBuffersARB")) return false;
287  if (!BindGLProc(_glBindBuffer, "glBindBufferARB")) return false;
288  if (!BindGLProc(_glBufferData, "glBufferDataARB")) return false;
289  if (!BindGLProc(_glBufferSubData, "glBufferSubDataARB")) return false;
290  if (!BindGLProc(_glMapBuffer, "glMapBufferARB")) return false;
291  if (!BindGLProc(_glUnmapBuffer, "glUnmapBufferARB")) return false;
292  }
293 
294  if (IsOpenGLVersionAtLeast(4, 3) || IsOpenGLExtensionSupported("GL_ARB_clear_buffer_object")) {
295  BindGLProc(_glClearBufferSubData, "glClearBufferSubData");
296  } else {
297  _glClearBufferSubData = nullptr;
298  }
299 
300  return true;
301 }
302 
304 static bool BindVBAExtension()
305 {
306  /* The APPLE and ARB variants have different semantics (that don't matter for us).
307  * Successfully getting pointers to one variant doesn't mean it is supported for
308  * the current context. Always check the extension strings as well. */
309  if (IsOpenGLVersionAtLeast(3, 0) || IsOpenGLExtensionSupported("GL_ARB_vertex_array_object")) {
310  if (!BindGLProc(_glGenVertexArrays, "glGenVertexArrays")) return false;
311  if (!BindGLProc(_glDeleteVertexArrays, "glDeleteVertexArrays")) return false;
312  if (!BindGLProc(_glBindVertexArray, "glBindVertexArray")) return false;
313  } else if (IsOpenGLExtensionSupported("GL_APPLE_vertex_array_object")) {
314  if (!BindGLProc(_glGenVertexArrays, "glGenVertexArraysAPPLE")) return false;
315  if (!BindGLProc(_glDeleteVertexArrays, "glDeleteVertexArraysAPPLE")) return false;
316  if (!BindGLProc(_glBindVertexArray, "glBindVertexArrayAPPLE")) return false;
317  }
318 
319  return true;
320 }
321 
323 static bool BindShaderExtensions()
324 {
325  if (IsOpenGLVersionAtLeast(2, 0)) {
326  if (!BindGLProc(_glCreateProgram, "glCreateProgram")) return false;
327  if (!BindGLProc(_glDeleteProgram, "glDeleteProgram")) return false;
328  if (!BindGLProc(_glLinkProgram, "glLinkProgram")) return false;
329  if (!BindGLProc(_glUseProgram, "glUseProgram")) return false;
330  if (!BindGLProc(_glGetProgramiv, "glGetProgramiv")) return false;
331  if (!BindGLProc(_glGetProgramInfoLog, "glGetProgramInfoLog")) return false;
332  if (!BindGLProc(_glCreateShader, "glCreateShader")) return false;
333  if (!BindGLProc(_glDeleteShader, "glDeleteShader")) return false;
334  if (!BindGLProc(_glShaderSource, "glShaderSource")) return false;
335  if (!BindGLProc(_glCompileShader, "glCompileShader")) return false;
336  if (!BindGLProc(_glAttachShader, "glAttachShader")) return false;
337  if (!BindGLProc(_glGetShaderiv, "glGetShaderiv")) return false;
338  if (!BindGLProc(_glGetShaderInfoLog, "glGetShaderInfoLog")) return false;
339  if (!BindGLProc(_glGetUniformLocation, "glGetUniformLocation")) return false;
340  if (!BindGLProc(_glUniform1i, "glUniform1i")) return false;
341  if (!BindGLProc(_glUniform1f, "glUniform1f")) return false;
342  if (!BindGLProc(_glUniform2f, "glUniform2f")) return false;
343  if (!BindGLProc(_glUniform4f, "glUniform4f")) return false;
344 
345  if (!BindGLProc(_glGetAttribLocation, "glGetAttribLocation")) return false;
346  if (!BindGLProc(_glEnableVertexAttribArray, "glEnableVertexAttribArray")) return false;
347  if (!BindGLProc(_glDisableVertexAttribArray, "glDisableVertexAttribArray")) return false;
348  if (!BindGLProc(_glVertexAttribPointer, "glVertexAttribPointer")) return false;
349  } else {
350  /* In the ARB extension programs and shaders are in the same object space. */
351  if (!BindGLProc(_glCreateProgram, "glCreateProgramObjectARB")) return false;
352  if (!BindGLProc(_glDeleteProgram, "glDeleteObjectARB")) return false;
353  if (!BindGLProc(_glLinkProgram, "glLinkProgramARB")) return false;
354  if (!BindGLProc(_glUseProgram, "glUseProgramObjectARB")) return false;
355  if (!BindGLProc(_glGetProgramiv, "glGetObjectParameterivARB")) return false;
356  if (!BindGLProc(_glGetProgramInfoLog, "glGetInfoLogARB")) return false;
357  if (!BindGLProc(_glCreateShader, "glCreateShaderObjectARB")) return false;
358  if (!BindGLProc(_glDeleteShader, "glDeleteObjectARB")) return false;
359  if (!BindGLProc(_glShaderSource, "glShaderSourceARB")) return false;
360  if (!BindGLProc(_glCompileShader, "glCompileShaderARB")) return false;
361  if (!BindGLProc(_glAttachShader, "glAttachObjectARB")) return false;
362  if (!BindGLProc(_glGetShaderiv, "glGetObjectParameterivARB")) return false;
363  if (!BindGLProc(_glGetShaderInfoLog, "glGetInfoLogARB")) return false;
364  if (!BindGLProc(_glGetUniformLocation, "glGetUniformLocationARB")) return false;
365  if (!BindGLProc(_glUniform1i, "glUniform1iARB")) return false;
366  if (!BindGLProc(_glUniform1f, "glUniform1fARB")) return false;
367  if (!BindGLProc(_glUniform2f, "glUniform2fARB")) return false;
368  if (!BindGLProc(_glUniform4f, "glUniform4fARB")) return false;
369 
370  if (!BindGLProc(_glGetAttribLocation, "glGetAttribLocationARB")) return false;
371  if (!BindGLProc(_glEnableVertexAttribArray, "glEnableVertexAttribArrayARB")) return false;
372  if (!BindGLProc(_glDisableVertexAttribArray, "glDisableVertexAttribArrayARB")) return false;
373  if (!BindGLProc(_glVertexAttribPointer, "glVertexAttribPointerARB")) return false;
374  }
375 
376  /* Bind functions only needed when using GLSL 1.50 shaders. */
377  if (IsOpenGLVersionAtLeast(3, 0)) {
378  BindGLProc(_glBindFragDataLocation, "glBindFragDataLocation");
379  } else if (IsOpenGLExtensionSupported("GL_EXT_gpu_shader4")) {
380  BindGLProc(_glBindFragDataLocation, "glBindFragDataLocationEXT");
381  } else {
382  _glBindFragDataLocation = nullptr;
383  }
384 
385  return true;
386 }
387 
389 static bool BindPersistentBufferExtensions()
390 {
391  /* Optional functions for persistent buffer mapping. */
392  if (IsOpenGLVersionAtLeast(3, 0)) {
393  if (!BindGLProc(_glMapBufferRange, "glMapBufferRange")) return false;
394  }
395  if (IsOpenGLVersionAtLeast(4, 4) || IsOpenGLExtensionSupported("GL_ARB_buffer_storage")) {
396  if (!BindGLProc(_glBufferStorage, "glBufferStorage")) return false;
397  }
398 #ifndef NO_GL_BUFFER_SYNC
399  if (IsOpenGLVersionAtLeast(3, 2) || IsOpenGLExtensionSupported("GL_ARB_sync")) {
400  if (!BindGLProc(_glClientWaitSync, "glClientWaitSync")) return false;
401  if (!BindGLProc(_glFenceSync, "glFenceSync")) return false;
402  if (!BindGLProc(_glDeleteSync, "glDeleteSync")) return false;
403  }
404 #endif
405 
406  return true;
407 }
408 
410 void APIENTRY DebugOutputCallback(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar *message, const void *userParam)
411 {
412  /* Make severity human readable. */
413  const char *severity_str = "";
414  switch (severity) {
415  case GL_DEBUG_SEVERITY_HIGH: severity_str = "high"; break;
416  case GL_DEBUG_SEVERITY_MEDIUM: severity_str = "medium"; break;
417  case GL_DEBUG_SEVERITY_LOW: severity_str = "low"; break;
418  }
419 
420  /* Make type human readable.*/
421  const char *type_str = "Other";
422  switch (type) {
423  case GL_DEBUG_TYPE_ERROR: type_str = "Error"; break;
424  case GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR: type_str = "Deprecated"; break;
425  case GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR: type_str = "Undefined behaviour"; break;
426  case GL_DEBUG_TYPE_PERFORMANCE: type_str = "Performance"; break;
427  case GL_DEBUG_TYPE_PORTABILITY: type_str = "Portability"; break;
428  }
429 
430  Debug(driver, 6, "OpenGL: {} ({}) - {}", type_str, severity_str, message);
431 }
432 
434 void SetupDebugOutput()
435 {
436 #ifndef NO_DEBUG_MESSAGES
437  if (_debug_driver_level < 6) return;
438 
439  if (IsOpenGLVersionAtLeast(4, 3)) {
440  BindGLProc(_glDebugMessageControl, "glDebugMessageControl");
441  BindGLProc(_glDebugMessageCallback, "glDebugMessageCallback");
442  } else if (IsOpenGLExtensionSupported("GL_ARB_debug_output")) {
443  BindGLProc(_glDebugMessageControl, "glDebugMessageControlARB");
444  BindGLProc(_glDebugMessageCallback, "glDebugMessageCallbackARB");
445  }
446 
447  if (_glDebugMessageControl != nullptr && _glDebugMessageCallback != nullptr) {
448  /* Enable debug output. As synchronous debug output costs performance, we only enable it with a high debug level. */
449  _glEnable(GL_DEBUG_OUTPUT);
450  if (_debug_driver_level >= 8) _glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS);
451 
452  _glDebugMessageCallback(&DebugOutputCallback, nullptr);
453  /* Enable all messages on highest debug level.*/
454  _glDebugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, nullptr, _debug_driver_level >= 9 ? GL_TRUE : GL_FALSE);
455  /* Get debug messages for errors and undefined/deprecated behaviour. */
456  _glDebugMessageControl(GL_DONT_CARE, GL_DEBUG_TYPE_ERROR, GL_DONT_CARE, 0, nullptr, GL_TRUE);
457  _glDebugMessageControl(GL_DONT_CARE, GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR, GL_DONT_CARE, 0, nullptr, GL_TRUE);
458  _glDebugMessageControl(GL_DONT_CARE, GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR, GL_DONT_CARE, 0, nullptr, GL_TRUE);
459  }
460 #endif
461 }
462 
469 /* static */ const char *OpenGLBackend::Create(GetOGLProcAddressProc get_proc, const Dimension &screen_res)
470 {
472 
473  GetOGLProcAddress = get_proc;
474 
476  return OpenGLBackend::instance->Init(screen_res);
477 }
478 
482 /* static */ void OpenGLBackend::Destroy()
483 {
485  OpenGLBackend::instance = nullptr;
486 }
487 
491 OpenGLBackend::OpenGLBackend() : cursor_cache(MAX_CACHED_CURSORS)
492 {
493 }
494 
499 {
500  if (_glDeleteProgram != nullptr) {
501  _glDeleteProgram(this->remap_program);
502  _glDeleteProgram(this->vid_program);
503  _glDeleteProgram(this->pal_program);
504  _glDeleteProgram(this->sprite_program);
505  }
506  if (_glDeleteVertexArrays != nullptr) _glDeleteVertexArrays(1, &this->vao_quad);
507  if (_glDeleteBuffers != nullptr) {
508  _glDeleteBuffers(1, &this->vbo_quad);
509  _glDeleteBuffers(1, &this->vid_pbo);
510  _glDeleteBuffers(1, &this->anim_pbo);
511  }
512  if (_glDeleteTextures != nullptr) {
513  this->InternalClearCursorCache();
515 
516  _glDeleteTextures(1, &this->vid_texture);
517  _glDeleteTextures(1, &this->anim_texture);
518  _glDeleteTextures(1, &this->pal_texture);
519  }
520 }
521 
527 const char *OpenGLBackend::Init(const Dimension &screen_res)
528 {
529  if (!BindBasicInfoProcs()) return "OpenGL not supported";
530 
531  /* Always query the supported OpenGL version as the current context might have changed. */
532  const char *ver = (const char *)_glGetString(GL_VERSION);
533  const char *vend = (const char *)_glGetString(GL_VENDOR);
534  const char *renderer = (const char *)_glGetString(GL_RENDERER);
535 
536  if (ver == nullptr || vend == nullptr || renderer == nullptr) return "OpenGL not supported";
537 
538  Debug(driver, 1, "OpenGL driver: {} - {} ({})", vend, renderer, ver);
539 
540 #ifndef GL_ALLOW_SOFTWARE_RENDERER
541  /* Don't use MESA software rendering backends as they are slower than
542  * just using a non-OpenGL video driver. */
543  if (strncmp(renderer, "llvmpipe", 8) == 0 || strncmp(renderer, "softpipe", 8) == 0) return "Software renderer detected, not using OpenGL";
544 #endif
545 
546  const char *minor = strchr(ver, '.');
547  _gl_major_ver = atoi(ver);
548  _gl_minor_ver = minor != nullptr ? atoi(minor + 1) : 0;
549 
550 #ifdef _WIN32
551  /* Old drivers on Windows (especially if made by Intel) seem to be
552  * unstable, so cull the oldest stuff here. */
553  if (!IsOpenGLVersionAtLeast(3, 2)) return "Need at least OpenGL version 3.2 on Windows";
554 #endif
555 
556  if (!BindBasicOpenGLProcs()) return "Failed to bind basic OpenGL functions.";
557 
558  SetupDebugOutput();
559 
560  /* OpenGL 1.3 is the absolute minimum. */
561  if (!IsOpenGLVersionAtLeast(1, 3)) return "OpenGL version >= 1.3 required";
562  /* Check for non-power-of-two texture support. */
563  if (!IsOpenGLVersionAtLeast(2, 0) && !IsOpenGLExtensionSupported("GL_ARB_texture_non_power_of_two")) return "Non-power-of-two textures not supported";
564  /* Check for single element texture formats. */
565  if (!IsOpenGLVersionAtLeast(3, 0) && !IsOpenGLExtensionSupported("GL_ARB_texture_rg")) return "Single element texture formats not supported";
566  if (!BindTextureExtensions()) return "Failed to bind texture extension functions";
567  /* Check for vertex buffer objects. */
568  if (!IsOpenGLVersionAtLeast(1, 5) && !IsOpenGLExtensionSupported("ARB_vertex_buffer_object")) return "Vertex buffer objects not supported";
569  if (!BindVBOExtension()) return "Failed to bind VBO extension functions";
570  /* Check for pixel buffer objects. */
571  if (!IsOpenGLVersionAtLeast(2, 1) && !IsOpenGLExtensionSupported("GL_ARB_pixel_buffer_object")) return "Pixel buffer objects not supported";
572  /* Check for vertex array objects. */
573  if (!IsOpenGLVersionAtLeast(3, 0) && (!IsOpenGLExtensionSupported("GL_ARB_vertex_array_object") || !IsOpenGLExtensionSupported("GL_APPLE_vertex_array_object"))) return "Vertex array objects not supported";
574  if (!BindVBAExtension()) return "Failed to bind VBA extension functions";
575  /* Check for shader objects. */
576  if (!IsOpenGLVersionAtLeast(2, 0) && (!IsOpenGLExtensionSupported("GL_ARB_shader_objects") || !IsOpenGLExtensionSupported("GL_ARB_fragment_shader") || !IsOpenGLExtensionSupported("GL_ARB_vertex_shader"))) return "No shader support";
577  if (!BindShaderExtensions()) return "Failed to bind shader extension functions";
578  if (IsOpenGLVersionAtLeast(3, 2) && _glBindFragDataLocation == nullptr) return "OpenGL claims to support version 3.2 but doesn't have glBindFragDataLocation";
579 
580  this->persistent_mapping_supported = IsOpenGLVersionAtLeast(3, 0) && (IsOpenGLVersionAtLeast(4, 4) || IsOpenGLExtensionSupported("GL_ARB_buffer_storage"));
581 #ifndef NO_GL_BUFFER_SYNC
582  this->persistent_mapping_supported = this->persistent_mapping_supported && (IsOpenGLVersionAtLeast(3, 2) || IsOpenGLExtensionSupported("GL_ARB_sync"));
583 #endif
584 
585  if (this->persistent_mapping_supported && !BindPersistentBufferExtensions()) {
586  Debug(driver, 1, "OpenGL claims to support persistent buffer mapping but doesn't export all functions, not using persistent mapping.");
587  this->persistent_mapping_supported = false;
588  }
589  if (this->persistent_mapping_supported) Debug(driver, 3, "OpenGL: Using persistent buffer mapping");
590 
591  /* Check maximum texture size against screen resolution. */
592  GLint max_tex_size = 0;
593  _glGetIntegerv(GL_MAX_TEXTURE_SIZE, &max_tex_size);
594  if (std::max(screen_res.width, screen_res.height) > (uint)max_tex_size) return "Max supported texture size is too small";
595 
596  /* Check available texture units. */
597  GLint max_tex_units = 0;
598  _glGetIntegerv(GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS, &max_tex_units);
599  if (max_tex_units < 4) return "Not enough simultaneous textures supported";
600 
601  Debug(driver, 2, "OpenGL shading language version: {}, texture units = {}", (const char *)_glGetString(GL_SHADING_LANGUAGE_VERSION), (int)max_tex_units);
602 
603  if (!this->InitShaders()) return "Failed to initialize shaders";
604 
605  /* Setup video buffer texture. */
606  _glGenTextures(1, &this->vid_texture);
607  _glBindTexture(GL_TEXTURE_2D, this->vid_texture);
608  _glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
609  _glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
610  _glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 0);
611  _glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
612  _glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
613  _glBindTexture(GL_TEXTURE_2D, 0);
614  if (_glGetError() != GL_NO_ERROR) return "Can't generate video buffer texture";
615 
616  /* Setup video buffer texture. */
617  _glGenTextures(1, &this->anim_texture);
618  _glBindTexture(GL_TEXTURE_2D, this->anim_texture);
619  _glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
620  _glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
621  _glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 0);
622  _glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
623  _glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
624  _glBindTexture(GL_TEXTURE_2D, 0);
625  if (_glGetError() != GL_NO_ERROR) return "Can't generate animation buffer texture";
626 
627  /* Setup palette texture. */
628  _glGenTextures(1, &this->pal_texture);
629  _glBindTexture(GL_TEXTURE_1D, this->pal_texture);
630  _glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
631  _glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
632  _glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MAX_LEVEL, 0);
633  _glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
634  _glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
635  _glTexImage1D(GL_TEXTURE_1D, 0, GL_RGBA8, 256, 0, GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV, nullptr);
636  _glBindTexture(GL_TEXTURE_1D, 0);
637  if (_glGetError() != GL_NO_ERROR) return "Can't generate palette lookup texture";
638 
639  /* Bind uniforms in rendering shader program. */
640  GLint tex_location = _glGetUniformLocation(this->vid_program, "colour_tex");
641  GLint palette_location = _glGetUniformLocation(this->vid_program, "palette");
642  GLint sprite_location = _glGetUniformLocation(this->vid_program, "sprite");
643  GLint screen_location = _glGetUniformLocation(this->vid_program, "screen");
644  _glUseProgram(this->vid_program);
645  _glUniform1i(tex_location, 0); // Texture unit 0.
646  _glUniform1i(palette_location, 1); // Texture unit 1.
647  /* Values that result in no transform. */
648  _glUniform4f(sprite_location, 0.0f, 0.0f, 1.0f, 1.0f);
649  _glUniform2f(screen_location, 1.0f, 1.0f);
650 
651  /* Bind uniforms in palette rendering shader program. */
652  tex_location = _glGetUniformLocation(this->pal_program, "colour_tex");
653  palette_location = _glGetUniformLocation(this->pal_program, "palette");
654  sprite_location = _glGetUniformLocation(this->pal_program, "sprite");
655  screen_location = _glGetUniformLocation(this->pal_program, "screen");
656  _glUseProgram(this->pal_program);
657  _glUniform1i(tex_location, 0); // Texture unit 0.
658  _glUniform1i(palette_location, 1); // Texture unit 1.
659  _glUniform4f(sprite_location, 0.0f, 0.0f, 1.0f, 1.0f);
660  _glUniform2f(screen_location, 1.0f, 1.0f);
661 
662  /* Bind uniforms in remap shader program. */
663  tex_location = _glGetUniformLocation(this->remap_program, "colour_tex");
664  palette_location = _glGetUniformLocation(this->remap_program, "palette");
665  GLint remap_location = _glGetUniformLocation(this->remap_program, "remap_tex");
666  this->remap_sprite_loc = _glGetUniformLocation(this->remap_program, "sprite");
667  this->remap_screen_loc = _glGetUniformLocation(this->remap_program, "screen");
668  this->remap_zoom_loc = _glGetUniformLocation(this->remap_program, "zoom");
669  this->remap_rgb_loc = _glGetUniformLocation(this->remap_program, "rgb");
670  _glUseProgram(this->remap_program);
671  _glUniform1i(tex_location, 0); // Texture unit 0.
672  _glUniform1i(palette_location, 1); // Texture unit 1.
673  _glUniform1i(remap_location, 2); // Texture unit 2.
674 
675  /* Bind uniforms in sprite shader program. */
676  tex_location = _glGetUniformLocation(this->sprite_program, "colour_tex");
677  palette_location = _glGetUniformLocation(this->sprite_program, "palette");
678  remap_location = _glGetUniformLocation(this->sprite_program, "remap_tex");
679  GLint pal_location = _glGetUniformLocation(this->sprite_program, "pal");
680  this->sprite_sprite_loc = _glGetUniformLocation(this->sprite_program, "sprite");
681  this->sprite_screen_loc = _glGetUniformLocation(this->sprite_program, "screen");
682  this->sprite_zoom_loc = _glGetUniformLocation(this->sprite_program, "zoom");
683  this->sprite_rgb_loc = _glGetUniformLocation(this->sprite_program, "rgb");
684  this->sprite_crash_loc = _glGetUniformLocation(this->sprite_program, "crash");
685  _glUseProgram(this->sprite_program);
686  _glUniform1i(tex_location, 0); // Texture unit 0.
687  _glUniform1i(palette_location, 1); // Texture unit 1.
688  _glUniform1i(remap_location, 2); // Texture unit 2.
689  _glUniform1i(pal_location, 3); // Texture unit 3.
690  (void)_glGetError(); // Clear errors.
691 
692  /* Create pixel buffer object as video buffer storage. */
693  _glGenBuffers(1, &this->vid_pbo);
694  _glBindBuffer(GL_PIXEL_UNPACK_BUFFER, this->vid_pbo);
695  _glGenBuffers(1, &this->anim_pbo);
696  _glBindBuffer(GL_PIXEL_UNPACK_BUFFER, this->anim_pbo);
697  if (_glGetError() != GL_NO_ERROR) return "Can't allocate pixel buffer for video buffer";
698 
699  /* Prime vertex buffer with a full-screen quad and store
700  * the corresponding state in a vertex array object. */
701  static const Simple2DVertex vert_array[] = {
702  // x y u v
703  { 1.f, -1.f, 1.f, 1.f },
704  { 1.f, 1.f, 1.f, 0.f },
705  { -1.f, -1.f, 0.f, 1.f },
706  { -1.f, 1.f, 0.f, 0.f },
707  };
708 
709  /* Create VAO. */
710  _glGenVertexArrays(1, &this->vao_quad);
711  _glBindVertexArray(this->vao_quad);
712 
713  /* Create and fill VBO. */
714  _glGenBuffers(1, &this->vbo_quad);
715  _glBindBuffer(GL_ARRAY_BUFFER, this->vbo_quad);
716  _glBufferData(GL_ARRAY_BUFFER, sizeof(vert_array), vert_array, GL_STATIC_DRAW);
717  if (_glGetError() != GL_NO_ERROR) return "Can't generate VBO for fullscreen quad";
718 
719  /* Set vertex state. */
720  GLint loc_position = _glGetAttribLocation(this->vid_program, "position");
721  GLint colour_position = _glGetAttribLocation(this->vid_program, "colour_uv");
722  _glEnableVertexAttribArray(loc_position);
723  _glEnableVertexAttribArray(colour_position);
724  _glVertexAttribPointer(loc_position, 2, GL_FLOAT, GL_FALSE, sizeof(Simple2DVertex), (GLvoid *)offsetof(Simple2DVertex, x));
725  _glVertexAttribPointer(colour_position, 2, GL_FLOAT, GL_FALSE, sizeof(Simple2DVertex), (GLvoid *)offsetof(Simple2DVertex, u));
726  _glBindVertexArray(0);
727 
728  /* Create resources for sprite rendering. */
729  if (!OpenGLSprite::Create()) return "Failed to create sprite rendering resources";
730 
731  this->PrepareContext();
732  (void)_glGetError(); // Clear errors.
733 
734  return nullptr;
735 }
736 
737 void OpenGLBackend::PrepareContext()
738 {
739  _glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
740  _glDisable(GL_DEPTH_TEST);
741  /* Enable alpha blending using the src alpha factor. */
742  _glEnable(GL_BLEND);
743  _glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
744 }
745 
746 std::string OpenGLBackend::GetDriverName()
747 {
748  std::string res{};
749  /* Skipping GL_VENDOR as it tends to be "obvious" from the renderer and version data, and just makes the string pointlessly longer */
750  res += reinterpret_cast<const char *>(_glGetString(GL_RENDERER));
751  res += ", ";
752  res += reinterpret_cast<const char *>(_glGetString(GL_VERSION));
753  return res;
754 }
755 
761 static bool VerifyShader(GLuint shader)
762 {
763  static ReusableBuffer<char> log_buf;
764 
765  GLint result = GL_FALSE;
766  _glGetShaderiv(shader, GL_COMPILE_STATUS, &result);
767 
768  /* Output log if there is one. */
769  GLint log_len = 0;
770  _glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &log_len);
771  if (log_len > 0) {
772  _glGetShaderInfoLog(shader, log_len, nullptr, log_buf.Allocate(log_len));
773  Debug(driver, result != GL_TRUE ? 0 : 2, "{}", log_buf.GetBuffer()); // Always print on failure.
774  }
775 
776  return result == GL_TRUE;
777 }
778 
784 static bool VerifyProgram(GLuint program)
785 {
786  static ReusableBuffer<char> log_buf;
787 
788  GLint result = GL_FALSE;
789  _glGetProgramiv(program, GL_LINK_STATUS, &result);
790 
791  /* Output log if there is one. */
792  GLint log_len = 0;
793  _glGetProgramiv(program, GL_INFO_LOG_LENGTH, &log_len);
794  if (log_len > 0) {
795  _glGetProgramInfoLog(program, log_len, nullptr, log_buf.Allocate(log_len));
796  Debug(driver, result != GL_TRUE ? 0 : 2, "{}", log_buf.GetBuffer()); // Always print on failure.
797  }
798 
799  return result == GL_TRUE;
800 }
801 
807 {
808  const char *ver = (const char *)_glGetString(GL_SHADING_LANGUAGE_VERSION);
809  if (ver == nullptr) return false;
810 
811  int glsl_major = ver[0] - '0';
812  int glsl_minor = ver[2] - '0';
813 
814  bool glsl_150 = (IsOpenGLVersionAtLeast(3, 2) || glsl_major > 1 || (glsl_major == 1 && glsl_minor >= 5)) && _glBindFragDataLocation != nullptr;
815 
816  /* Create vertex shader. */
817  GLuint vert_shader = _glCreateShader(GL_VERTEX_SHADER);
818  _glShaderSource(vert_shader, glsl_150 ? lengthof(_vertex_shader_sprite_150) : lengthof(_vertex_shader_sprite), glsl_150 ? _vertex_shader_sprite_150 : _vertex_shader_sprite, nullptr);
819  _glCompileShader(vert_shader);
820  if (!VerifyShader(vert_shader)) return false;
821 
822  /* Create fragment shader for plain RGBA. */
823  GLuint frag_shader_rgb = _glCreateShader(GL_FRAGMENT_SHADER);
824  _glShaderSource(frag_shader_rgb, glsl_150 ? lengthof(_frag_shader_direct_150) : lengthof(_frag_shader_direct), glsl_150 ? _frag_shader_direct_150 : _frag_shader_direct, nullptr);
825  _glCompileShader(frag_shader_rgb);
826  if (!VerifyShader(frag_shader_rgb)) return false;
827 
828  /* Create fragment shader for paletted only. */
829  GLuint frag_shader_pal = _glCreateShader(GL_FRAGMENT_SHADER);
830  _glShaderSource(frag_shader_pal, glsl_150 ? lengthof(_frag_shader_palette_150) : lengthof(_frag_shader_palette), glsl_150 ? _frag_shader_palette_150 : _frag_shader_palette, nullptr);
831  _glCompileShader(frag_shader_pal);
832  if (!VerifyShader(frag_shader_pal)) return false;
833 
834  /* Sprite remap fragment shader. */
835  GLuint remap_shader = _glCreateShader(GL_FRAGMENT_SHADER);
837  _glCompileShader(remap_shader);
838  if (!VerifyShader(remap_shader)) return false;
839 
840  /* Sprite fragment shader. */
841  GLuint sprite_shader = _glCreateShader(GL_FRAGMENT_SHADER);
842  _glShaderSource(sprite_shader, glsl_150 ? lengthof(_frag_shader_sprite_blend_150) : lengthof(_frag_shader_sprite_blend), glsl_150 ? _frag_shader_sprite_blend_150 : _frag_shader_sprite_blend, nullptr);
843  _glCompileShader(sprite_shader);
844  if (!VerifyShader(sprite_shader)) return false;
845 
846  /* Link shaders to program. */
847  this->vid_program = _glCreateProgram();
848  _glAttachShader(this->vid_program, vert_shader);
849  _glAttachShader(this->vid_program, frag_shader_rgb);
850 
851  this->pal_program = _glCreateProgram();
852  _glAttachShader(this->pal_program, vert_shader);
853  _glAttachShader(this->pal_program, frag_shader_pal);
854 
855  this->remap_program = _glCreateProgram();
856  _glAttachShader(this->remap_program, vert_shader);
857  _glAttachShader(this->remap_program, remap_shader);
858 
859  this->sprite_program = _glCreateProgram();
860  _glAttachShader(this->sprite_program, vert_shader);
861  _glAttachShader(this->sprite_program, sprite_shader);
862 
863  if (glsl_150) {
864  /* Bind fragment shader outputs. */
865  _glBindFragDataLocation(this->vid_program, 0, "colour");
866  _glBindFragDataLocation(this->pal_program, 0, "colour");
867  _glBindFragDataLocation(this->remap_program, 0, "colour");
868  _glBindFragDataLocation(this->sprite_program, 0, "colour");
869  }
870 
871  _glLinkProgram(this->vid_program);
872  if (!VerifyProgram(this->vid_program)) return false;
873 
874  _glLinkProgram(this->pal_program);
875  if (!VerifyProgram(this->pal_program)) return false;
876 
877  _glLinkProgram(this->remap_program);
878  if (!VerifyProgram(this->remap_program)) return false;
879 
880  _glLinkProgram(this->sprite_program);
881  if (!VerifyProgram(this->sprite_program)) return false;
882 
883  _glDeleteShader(vert_shader);
884  _glDeleteShader(frag_shader_rgb);
885  _glDeleteShader(frag_shader_pal);
886  _glDeleteShader(remap_shader);
887  _glDeleteShader(sprite_shader);
888 
889  return true;
890 }
891 
898 template <class T>
899 static void ClearPixelBuffer(size_t len, T data)
900 {
901  T *buf = reinterpret_cast<T *>(_glMapBuffer(GL_PIXEL_UNPACK_BUFFER, GL_READ_WRITE));
902  for (size_t i = 0; i < len; i++) {
903  *buf++ = data;
904  }
905  _glUnmapBuffer(GL_PIXEL_UNPACK_BUFFER);
906 }
907 
915 bool OpenGLBackend::Resize(int w, int h, bool force)
916 {
917  if (!force && _screen.width == w && _screen.height == h) return false;
918 
920  int pitch = Align(w, 4);
921 
922  _glViewport(0, 0, w, h);
923 
924  _glPixelStorei(GL_UNPACK_ROW_LENGTH, pitch);
925 
926  this->vid_buffer = nullptr;
927  if (this->persistent_mapping_supported) {
928  _glDeleteBuffers(1, &this->vid_pbo);
929  _glGenBuffers(1, &this->vid_pbo);
930  _glBindBuffer(GL_PIXEL_UNPACK_BUFFER, this->vid_pbo);
931  _glBufferStorage(GL_PIXEL_UNPACK_BUFFER, pitch * h * bpp / 8, nullptr, GL_MAP_READ_BIT | GL_MAP_WRITE_BIT | GL_MAP_PERSISTENT_BIT | GL_MAP_COHERENT_BIT | GL_CLIENT_STORAGE_BIT);
932  } else {
933  /* Re-allocate video buffer texture and backing store. */
934  _glBindBuffer(GL_PIXEL_UNPACK_BUFFER, this->vid_pbo);
935  _glBufferData(GL_PIXEL_UNPACK_BUFFER, pitch * h * bpp / 8, nullptr, GL_DYNAMIC_DRAW);
936  }
937 
938  if (bpp == 32) {
939  /* Initialize backing store alpha to opaque for 32bpp modes. */
940  Colour black(0, 0, 0);
941  if (_glClearBufferSubData != nullptr) {
942  _glClearBufferSubData(GL_PIXEL_UNPACK_BUFFER, GL_RGBA8, 0, pitch * h * bpp / 8, GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV, &black.data);
943  } else {
944  ClearPixelBuffer<uint32>(pitch * h, black.data);
945  }
946  } else if (bpp == 8) {
947  if (_glClearBufferSubData != nullptr) {
948  byte b = 0;
949  _glClearBufferSubData(GL_PIXEL_UNPACK_BUFFER, GL_R8, 0, pitch * h, GL_RED, GL_UNSIGNED_BYTE, &b);
950  } else {
951  ClearPixelBuffer<byte>(pitch * h, 0);
952  }
953  }
954 
955  _glActiveTexture(GL_TEXTURE0);
956  _glBindTexture(GL_TEXTURE_2D, this->vid_texture);
957  switch (bpp) {
958  case 8:
959  _glTexImage2D(GL_TEXTURE_2D, 0, GL_R8, w, h, 0, GL_RED, GL_UNSIGNED_BYTE, nullptr);
960  break;
961 
962  default:
963  _glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, w, h, 0, GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV, nullptr);
964  break;
965  }
966  _glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0);
967 
968  /* Does this blitter need a separate animation buffer? */
969  if (BlitterFactory::GetCurrentBlitter()->NeedsAnimationBuffer()) {
970  this->anim_buffer = nullptr;
971  if (this->persistent_mapping_supported) {
972  _glDeleteBuffers(1, &this->anim_pbo);
973  _glGenBuffers(1, &this->anim_pbo);
974  _glBindBuffer(GL_PIXEL_UNPACK_BUFFER, this->anim_pbo);
975  _glBufferStorage(GL_PIXEL_UNPACK_BUFFER, pitch * h, nullptr, GL_MAP_READ_BIT | GL_MAP_WRITE_BIT | GL_MAP_PERSISTENT_BIT | GL_MAP_COHERENT_BIT | GL_CLIENT_STORAGE_BIT);
976  } else {
977  _glBindBuffer(GL_PIXEL_UNPACK_BUFFER, this->anim_pbo);
978  _glBufferData(GL_PIXEL_UNPACK_BUFFER, pitch * h, nullptr, GL_DYNAMIC_DRAW);
979  }
980 
981  /* Initialize buffer as 0 == no remap. */
982  if (_glClearBufferSubData != nullptr) {
983  byte b = 0;
984  _glClearBufferSubData(GL_PIXEL_UNPACK_BUFFER, GL_R8, 0, pitch * h, GL_RED, GL_UNSIGNED_BYTE, &b);
985  } else {
986  ClearPixelBuffer<byte>(pitch * h, 0);
987  }
988 
989  _glBindTexture(GL_TEXTURE_2D, this->anim_texture);
990  _glTexImage2D(GL_TEXTURE_2D, 0, GL_R8, w, h, 0, GL_RED, GL_UNSIGNED_BYTE, nullptr);
991  _glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0);
992  } else {
993  if (this->anim_buffer != nullptr) {
994  _glBindBuffer(GL_PIXEL_UNPACK_BUFFER, this->anim_pbo);
995  _glUnmapBuffer(GL_PIXEL_UNPACK_BUFFER);
996  _glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0);
997  this->anim_buffer = nullptr;
998  }
999 
1000  /* Allocate dummy texture that always reads as 0 == no remap. */
1001  uint dummy = 0;
1002  _glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
1003  _glBindTexture(GL_TEXTURE_2D, this->anim_texture);
1004  _glTexImage2D(GL_TEXTURE_2D, 0, GL_R8, 1, 1, 0, GL_RED, GL_UNSIGNED_BYTE, &dummy);
1005  }
1006 
1007  _glBindTexture(GL_TEXTURE_2D, 0);
1008 
1009  /* Set new viewport. */
1010  _screen.height = h;
1011  _screen.width = w;
1012  _screen.pitch = pitch;
1013  _screen.dst_ptr = nullptr;
1014 
1015  /* Update screen size in remap shader program. */
1016  _glUseProgram(this->remap_program);
1017  _glUniform2f(this->remap_screen_loc, (float)_screen.width, (float)_screen.height);
1018 
1019  _glClear(GL_COLOR_BUFFER_BIT);
1020 
1021  return true;
1022 }
1023 
1030 void OpenGLBackend::UpdatePalette(const Colour *pal, uint first, uint length)
1031 {
1032  assert(first + length <= 256);
1033 
1034  _glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
1035  _glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0);
1036  _glActiveTexture(GL_TEXTURE1);
1037  _glBindTexture(GL_TEXTURE_1D, this->pal_texture);
1038  _glTexSubImage1D(GL_TEXTURE_1D, 0, first, length, GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV, pal + first);
1039 }
1040 
1045 {
1046  _glClear(GL_COLOR_BUFFER_BIT);
1047 
1048  _glDisable(GL_BLEND);
1049 
1050  /* Blit video buffer to screen. */
1051  _glActiveTexture(GL_TEXTURE0);
1052  _glBindTexture(GL_TEXTURE_2D, this->vid_texture);
1053  _glActiveTexture(GL_TEXTURE1);
1054  _glBindTexture(GL_TEXTURE_1D, this->pal_texture);
1055  /* Is the blitter relying on a separate animation buffer? */
1056  if (BlitterFactory::GetCurrentBlitter()->NeedsAnimationBuffer()) {
1057  _glActiveTexture(GL_TEXTURE2);
1058  _glBindTexture(GL_TEXTURE_2D, this->anim_texture);
1059  _glUseProgram(this->remap_program);
1060  _glUniform4f(this->remap_sprite_loc, 0.0f, 0.0f, 1.0f, 1.0f);
1061  _glUniform2f(this->remap_screen_loc, 1.0f, 1.0f);
1062  _glUniform1f(this->remap_zoom_loc, 0);
1063  _glUniform1i(this->remap_rgb_loc, 1);
1064  } else {
1065  _glUseProgram(BlitterFactory::GetCurrentBlitter()->GetScreenDepth() == 8 ? this->pal_program : this->vid_program);
1066  }
1067  _glBindVertexArray(this->vao_quad);
1068  _glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
1069 
1070  _glEnable(GL_BLEND);
1071 }
1072 
1077 {
1078  if (!this->cursor_in_window) return;
1079 
1080  /* Draw cursor on screen */
1081  _cur_dpi = &_screen;
1082  for (uint i = 0; i < this->cursor_sprite_count; ++i) {
1083  SpriteID sprite = this->cursor_sprite_seq[i].sprite;
1084 
1085  /* Sprites are cached by PopulateCursorCache(). */
1086  if (this->cursor_cache.Contains(sprite)) {
1087  Sprite *spr = this->cursor_cache.Get(sprite);
1088 
1089  this->RenderOglSprite((OpenGLSprite *)spr->data, this->cursor_sprite_seq[i].pal,
1090  this->cursor_pos.x + this->cursor_sprite_pos[i].x + UnScaleByZoom(spr->x_offs, ZOOM_LVL_GUI),
1091  this->cursor_pos.y + this->cursor_sprite_pos[i].y + UnScaleByZoom(spr->y_offs, ZOOM_LVL_GUI),
1092  ZOOM_LVL_GUI);
1093  }
1094  }
1095 }
1096 
1097 void OpenGLBackend::PopulateCursorCache()
1098 {
1099  static_assert(lengthof(_cursor.sprite_seq) == lengthof(this->cursor_sprite_seq));
1100  static_assert(lengthof(_cursor.sprite_pos) == lengthof(this->cursor_sprite_pos));
1101 
1102  if (this->clear_cursor_cache) {
1103  /* We have a pending cursor cache clear to do first. */
1104  this->clear_cursor_cache = false;
1105  this->last_sprite_pal = (PaletteID)-1;
1106 
1107  this->InternalClearCursorCache();
1108  }
1109 
1110  this->cursor_pos = _cursor.pos;
1111  this->cursor_sprite_count = _cursor.sprite_count;
1112  this->cursor_in_window = _cursor.in_window;
1113 
1114  for (uint i = 0; i < _cursor.sprite_count; ++i) {
1115  this->cursor_sprite_seq[i] = _cursor.sprite_seq[i];
1116  this->cursor_sprite_pos[i] = _cursor.sprite_pos[i];
1117  SpriteID sprite = _cursor.sprite_seq[i].sprite;
1118 
1119  if (!this->cursor_cache.Contains(sprite)) {
1120  Sprite *old = this->cursor_cache.Insert(sprite, (Sprite *)GetRawSprite(sprite, ST_NORMAL, &SimpleSpriteAlloc, this));
1121  if (old != nullptr) {
1122  OpenGLSprite *sprite = (OpenGLSprite *)old->data;
1123  sprite->~OpenGLSprite();
1124  free(old);
1125  }
1126  }
1127  }
1128 }
1129 
1134 {
1135  Sprite *sp;
1136  while ((sp = this->cursor_cache.Pop()) != nullptr) {
1137  OpenGLSprite *sprite = (OpenGLSprite *)sp->data;
1138  sprite->~OpenGLSprite();
1139  free(sp);
1140  }
1141 }
1142 
1147 {
1148  /* If the game loop is threaded, this function might be called
1149  * from the game thread. As we can call OpenGL functions only
1150  * on the main thread, just set a flag that is handled the next
1151  * time we prepare the cursor cache for drawing. */
1152  this->clear_cursor_cache = true;
1153 }
1154 
1160 {
1161 #ifndef NO_GL_BUFFER_SYNC
1162  if (this->sync_vid_mapping != nullptr) _glClientWaitSync(this->sync_vid_mapping, GL_SYNC_FLUSH_COMMANDS_BIT, 100000000); // 100ms timeout.
1163 #endif
1164 
1165  if (!this->persistent_mapping_supported) {
1166  assert(this->vid_buffer == nullptr);
1167  _glBindBuffer(GL_PIXEL_UNPACK_BUFFER, this->vid_pbo);
1168  this->vid_buffer = _glMapBuffer(GL_PIXEL_UNPACK_BUFFER, GL_READ_WRITE);
1169  } else if (this->vid_buffer == nullptr) {
1170  _glBindBuffer(GL_PIXEL_UNPACK_BUFFER, this->vid_pbo);
1171  this->vid_buffer = _glMapBufferRange(GL_PIXEL_UNPACK_BUFFER, 0, _screen.pitch * _screen.height * BlitterFactory::GetCurrentBlitter()->GetScreenDepth() / 8, GL_MAP_READ_BIT | GL_MAP_WRITE_BIT | GL_MAP_PERSISTENT_BIT | GL_MAP_COHERENT_BIT);
1172  }
1173 
1174  return this->vid_buffer;
1175 }
1176 
1182 {
1183  if (this->anim_pbo == 0) return nullptr;
1184 
1185 #ifndef NO_GL_BUFFER_SYNC
1186  if (this->sync_anim_mapping != nullptr) _glClientWaitSync(this->sync_anim_mapping, GL_SYNC_FLUSH_COMMANDS_BIT, 100000000); // 100ms timeout.
1187 #endif
1188 
1189  if (!this->persistent_mapping_supported) {
1190  _glBindBuffer(GL_PIXEL_UNPACK_BUFFER, this->anim_pbo);
1191  this->anim_buffer = _glMapBuffer(GL_PIXEL_UNPACK_BUFFER, GL_READ_WRITE);
1192  } else if (this->anim_buffer == nullptr) {
1193  _glBindBuffer(GL_PIXEL_UNPACK_BUFFER, this->anim_pbo);
1194  this->anim_buffer = _glMapBufferRange(GL_PIXEL_UNPACK_BUFFER, 0, _screen.pitch * _screen.height, GL_MAP_READ_BIT | GL_MAP_WRITE_BIT | GL_MAP_PERSISTENT_BIT | GL_MAP_COHERENT_BIT);
1195  }
1196 
1197  return (uint8 *)this->anim_buffer;
1198 }
1199 
1204 void OpenGLBackend::ReleaseVideoBuffer(const Rect &update_rect)
1205 {
1206  assert(this->vid_pbo != 0);
1207 
1208  _glBindBuffer(GL_PIXEL_UNPACK_BUFFER, this->vid_pbo);
1209  if (!this->persistent_mapping_supported) {
1210  _glUnmapBuffer(GL_PIXEL_UNPACK_BUFFER);
1211  this->vid_buffer = nullptr;
1212  }
1213 
1214 #ifndef NO_GL_BUFFER_SYNC
1215  if (this->persistent_mapping_supported) {
1216  _glDeleteSync(this->sync_vid_mapping);
1217  this->sync_vid_mapping = nullptr;
1218  }
1219 #endif
1220 
1221  /* Update changed rect of the video buffer texture. */
1222  if (!IsEmptyRect(update_rect)) {
1223  _glActiveTexture(GL_TEXTURE0);
1224  _glBindTexture(GL_TEXTURE_2D, this->vid_texture);
1225  _glPixelStorei(GL_UNPACK_ROW_LENGTH, _screen.pitch);
1226  switch (BlitterFactory::GetCurrentBlitter()->GetScreenDepth()) {
1227  case 8:
1228  _glTexSubImage2D(GL_TEXTURE_2D, 0, update_rect.left, update_rect.top, update_rect.right - update_rect.left, update_rect.bottom - update_rect.top, GL_RED, GL_UNSIGNED_BYTE, (GLvoid *)(size_t)(update_rect.top * _screen.pitch + update_rect.left));
1229  break;
1230 
1231  default:
1232  _glTexSubImage2D(GL_TEXTURE_2D, 0, update_rect.left, update_rect.top, update_rect.right - update_rect.left, update_rect.bottom - update_rect.top, GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV, (GLvoid *)(size_t)(update_rect.top * _screen.pitch * 4 + update_rect.left * 4));
1233  break;
1234  }
1235 
1236 #ifndef NO_GL_BUFFER_SYNC
1237  if (this->persistent_mapping_supported) this->sync_vid_mapping = _glFenceSync(GL_SYNC_GPU_COMMANDS_COMPLETE, 0);
1238 #endif
1239  }
1240 }
1241 
1246 void OpenGLBackend::ReleaseAnimBuffer(const Rect &update_rect)
1247 {
1248  if (this->anim_pbo == 0) return;
1249 
1250  _glBindBuffer(GL_PIXEL_UNPACK_BUFFER, this->anim_pbo);
1251  if (!this->persistent_mapping_supported) {
1252  _glUnmapBuffer(GL_PIXEL_UNPACK_BUFFER);
1253  this->anim_buffer = nullptr;
1254  }
1255 
1256 #ifndef NO_GL_BUFFER_SYNC
1257  if (this->persistent_mapping_supported) {
1258  _glDeleteSync(this->sync_anim_mapping);
1259  this->sync_anim_mapping = nullptr;
1260  }
1261 #endif
1262 
1263  /* Update changed rect of the video buffer texture. */
1264  if (update_rect.left != update_rect.right) {
1265  _glActiveTexture(GL_TEXTURE0);
1266  _glBindTexture(GL_TEXTURE_2D, this->anim_texture);
1267  _glPixelStorei(GL_UNPACK_ROW_LENGTH, _screen.pitch);
1268  _glTexSubImage2D(GL_TEXTURE_2D, 0, update_rect.left, update_rect.top, update_rect.right - update_rect.left, update_rect.bottom - update_rect.top, GL_RED, GL_UNSIGNED_BYTE, (GLvoid *)(size_t)(update_rect.top * _screen.pitch + update_rect.left));
1269 
1270 #ifndef NO_GL_BUFFER_SYNC
1271  if (this->persistent_mapping_supported) this->sync_anim_mapping = _glFenceSync(GL_SYNC_GPU_COMMANDS_COMPLETE, 0);
1272 #endif
1273  }
1274 }
1275 
1276 /* virtual */ Sprite *OpenGLBackend::Encode(const SpriteLoader::Sprite *sprite, AllocatorProc *allocator)
1277 {
1278  /* Allocate and construct sprite data. */
1279  Sprite *dest_sprite = (Sprite *)allocator(sizeof(*dest_sprite) + sizeof(OpenGLSprite));
1280 
1281  OpenGLSprite *gl_sprite = (OpenGLSprite *)dest_sprite->data;
1282  new (gl_sprite) OpenGLSprite(sprite->width, sprite->height, sprite->type == ST_FONT ? 1 : ZOOM_LVL_COUNT, sprite->colours);
1283 
1284  /* Upload texture data. */
1285  for (int i = 0; i < (sprite->type == ST_FONT ? 1 : ZOOM_LVL_COUNT); i++) {
1286  gl_sprite->Update(sprite[i].width, sprite[i].height, i, sprite[i].data);
1287  }
1288 
1289  dest_sprite->height = sprite->height;
1290  dest_sprite->width = sprite->width;
1291  dest_sprite->x_offs = sprite->x_offs;
1292  dest_sprite->y_offs = sprite->y_offs;
1293 
1294  return dest_sprite;
1295 }
1296 
1304 void OpenGLBackend::RenderOglSprite(OpenGLSprite *gl_sprite, PaletteID pal, int x, int y, ZoomLevel zoom)
1305 {
1306  /* Set textures. */
1307  bool rgb = gl_sprite->BindTextures();
1308  _glActiveTexture(GL_TEXTURE0 + 1);
1309  _glBindTexture(GL_TEXTURE_1D, this->pal_texture);
1310 
1311  /* Set palette remap. */
1312  _glActiveTexture(GL_TEXTURE0 + 3);
1313  if (pal != PAL_NONE) {
1314  _glBindTexture(GL_TEXTURE_1D, OpenGLSprite::pal_tex);
1315  if (pal != this->last_sprite_pal) {
1316  /* Different remap palette in use, update texture. */
1317  _glBindBuffer(GL_PIXEL_UNPACK_BUFFER, OpenGLSprite::pal_pbo);
1318  _glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
1319 
1320  _glBufferSubData(GL_PIXEL_UNPACK_BUFFER, 0, 256, GetNonSprite(GB(pal, 0, PALETTE_WIDTH), ST_RECOLOUR) + 1);
1321  _glTexSubImage1D(GL_TEXTURE_1D, 0, 0, 256, GL_RED, GL_UNSIGNED_BYTE, nullptr);
1322 
1323  _glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0);
1324 
1325  this->last_sprite_pal = pal;
1326  }
1327  } else {
1328  _glBindTexture(GL_TEXTURE_1D, OpenGLSprite::pal_identity);
1329  }
1330 
1331  /* Set up shader program. */
1332  Dimension dim = gl_sprite->GetSize(zoom);
1333  _glUseProgram(this->sprite_program);
1334  _glUniform4f(this->sprite_sprite_loc, (float)x, (float)y, (float)dim.width, (float)dim.height);
1335  _glUniform1f(this->sprite_zoom_loc, (float)(zoom - ZOOM_LVL_BEGIN));
1336  _glUniform2f(this->sprite_screen_loc, (float)_screen.width, (float)_screen.height);
1337  _glUniform1i(this->sprite_rgb_loc, rgb ? 1 : 0);
1338  _glUniform1i(this->sprite_crash_loc, pal == PALETTE_CRASH ? 1 : 0);
1339 
1340  _glBindVertexArray(this->vao_quad);
1341  _glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
1342 }
1343 
1344 
1345 /* static */ GLuint OpenGLSprite::dummy_tex[] = { 0, 0 };
1346 /* static */ GLuint OpenGLSprite::pal_identity = 0;
1347 /* static */ GLuint OpenGLSprite::pal_tex = 0;
1348 /* static */ GLuint OpenGLSprite::pal_pbo = 0;
1349 
1354 /* static */ bool OpenGLSprite::Create()
1355 {
1356  _glGenTextures(NUM_TEX, OpenGLSprite::dummy_tex);
1357 
1358  for (int t = TEX_RGBA; t < NUM_TEX; t++) {
1359  _glBindTexture(GL_TEXTURE_2D, OpenGLSprite::dummy_tex[t]);
1360 
1361  _glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST_MIPMAP_NEAREST);
1362  _glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
1363  _glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 0);
1364  _glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
1365  _glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
1366  }
1367 
1368  _glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0);
1369  _glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
1370 
1371  /* Load dummy RGBA texture. */
1372  const Colour rgb_pixel(0, 0, 0);
1373  _glBindTexture(GL_TEXTURE_2D, OpenGLSprite::dummy_tex[TEX_RGBA]);
1374  _glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, 1, 1, 0, GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV, &rgb_pixel);
1375 
1376  /* Load dummy remap texture. */
1377  const uint pal = 0;
1378  _glBindTexture(GL_TEXTURE_2D, OpenGLSprite::dummy_tex[TEX_REMAP]);
1379  _glTexImage2D(GL_TEXTURE_2D, 0, GL_R8, 1, 1, 0, GL_RED, GL_UNSIGNED_BYTE, &pal);
1380 
1381  /* Create palette remap textures. */
1382  std::array<uint8, 256> identity_pal;
1383  std::iota(std::begin(identity_pal), std::end(identity_pal), 0);
1384 
1385  /* Permanent texture for identity remap. */
1386  _glGenTextures(1, &OpenGLSprite::pal_identity);
1387  _glBindTexture(GL_TEXTURE_1D, OpenGLSprite::pal_identity);
1388  _glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
1389  _glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
1390  _glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MAX_LEVEL, 0);
1391  _glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
1392  _glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
1393  _glTexImage1D(GL_TEXTURE_1D, 0, GL_R8, 256, 0, GL_RED, GL_UNSIGNED_BYTE, identity_pal.data());
1394 
1395  /* Dynamically updated texture for remaps. */
1396  _glGenTextures(1, &OpenGLSprite::pal_tex);
1397  _glBindTexture(GL_TEXTURE_1D, OpenGLSprite::pal_tex);
1398  _glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
1399  _glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
1400  _glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MAX_LEVEL, 0);
1401  _glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
1402  _glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
1403  _glTexImage1D(GL_TEXTURE_1D, 0, GL_R8, 256, 0, GL_RED, GL_UNSIGNED_BYTE, identity_pal.data());
1404 
1405  /* Pixel buffer for remap updates. */
1406  _glGenBuffers(1, &OpenGLSprite::pal_pbo);
1407  _glBindBuffer(GL_PIXEL_UNPACK_BUFFER, OpenGLSprite::pal_pbo);
1408  _glBufferData(GL_PIXEL_UNPACK_BUFFER, 256, identity_pal.data(), GL_DYNAMIC_DRAW);
1409  _glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0);
1410 
1411  return _glGetError() == GL_NO_ERROR;
1412 }
1413 
1415 /* static */ void OpenGLSprite::Destroy()
1416 {
1417  _glDeleteTextures(NUM_TEX, OpenGLSprite::dummy_tex);
1418  _glDeleteTextures(1, &OpenGLSprite::pal_identity);
1419  _glDeleteTextures(1, &OpenGLSprite::pal_tex);
1420  if (_glDeleteBuffers != nullptr) _glDeleteBuffers(1, &OpenGLSprite::pal_pbo);
1421 }
1422 
1430 OpenGLSprite::OpenGLSprite(uint width, uint height, uint levels, SpriteColourComponent components)
1431 {
1432  assert(levels > 0);
1433  (void)_glGetError();
1434 
1435  this->dim.width = width;
1436  this->dim.height = height;
1437 
1438  MemSetT(this->tex, 0, NUM_TEX);
1439  _glActiveTexture(GL_TEXTURE0);
1440  _glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0);
1441 
1442  for (int t = TEX_RGBA; t < NUM_TEX; t++) {
1443  /* Sprite component present? */
1444  if (t == TEX_RGBA && components == SCC_PAL) continue;
1445  if (t == TEX_REMAP && (components & SCC_PAL) != SCC_PAL) continue;
1446 
1447  /* Allocate texture. */
1448  _glGenTextures(1, &this->tex[t]);
1449  _glBindTexture(GL_TEXTURE_2D, this->tex[t]);
1450 
1451  _glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST_MIPMAP_NEAREST);
1452  _glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
1453  _glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, levels - 1);
1454  _glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
1455  _glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
1456 
1457  /* Set size. */
1458  for (uint i = 0, w = width, h = height; i < levels; i++, w /= 2, h /= 2) {
1459  assert(w * h != 0);
1460  if (t == TEX_REMAP) {
1461  _glTexImage2D(GL_TEXTURE_2D, i, GL_R8, w, h, 0, GL_RED, GL_UNSIGNED_BYTE, nullptr);
1462  } else {
1463  _glTexImage2D(GL_TEXTURE_2D, i, GL_RGBA8, w, h, 0, GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV, nullptr);
1464  }
1465  }
1466  }
1467 
1468  assert(_glGetError() == GL_NO_ERROR);
1469 }
1470 
1471 OpenGLSprite::~OpenGLSprite()
1472 {
1473  _glDeleteTextures(NUM_TEX, this->tex);
1474 }
1475 
1483 void OpenGLSprite::Update(uint width, uint height, uint level, const SpriteLoader::CommonPixel * data)
1484 {
1485  static ReusableBuffer<Colour> buf_rgba;
1486  static ReusableBuffer<uint8> buf_pal;
1487 
1488  _glActiveTexture(GL_TEXTURE0);
1489  _glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0);
1490  _glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
1491 
1492  if (this->tex[TEX_RGBA] != 0) {
1493  /* Unpack pixel data */
1494  Colour *rgba = buf_rgba.Allocate(width * height);
1495  for (size_t i = 0; i < width * height; i++) {
1496  rgba[i].r = data[i].r;
1497  rgba[i].g = data[i].g;
1498  rgba[i].b = data[i].b;
1499  rgba[i].a = data[i].a;
1500  }
1501 
1502  _glBindTexture(GL_TEXTURE_2D, this->tex[TEX_RGBA]);
1503  _glTexSubImage2D(GL_TEXTURE_2D, level, 0, 0, width, height, GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV, rgba);
1504  }
1505 
1506  if (this->tex[TEX_REMAP] != 0) {
1507  /* Unpack and align pixel data. */
1508  int pitch = Align(width, 4);
1509 
1510  uint8 *pal = buf_pal.Allocate(pitch * height);
1511  const SpriteLoader::CommonPixel *row = data;
1512  for (uint y = 0; y < height; y++, pal += pitch, row += width) {
1513  for (uint x = 0; x < width; x++) {
1514  pal[x] = row[x].m;
1515  }
1516  }
1517 
1518  _glBindTexture(GL_TEXTURE_2D, this->tex[TEX_REMAP]);
1519  _glTexSubImage2D(GL_TEXTURE_2D, level, 0, 0, width, height, GL_RED, GL_UNSIGNED_BYTE, buf_pal.GetBuffer());
1520  }
1521 
1522  assert(_glGetError() == GL_NO_ERROR);
1523 }
1524 
1531 {
1532  Dimension sd = { (uint)UnScaleByZoomLower(this->dim.width, level), (uint)UnScaleByZoomLower(this->dim.height, level) };
1533  return sd;
1534 }
1535 
1541 {
1542  _glActiveTexture(GL_TEXTURE0);
1543  _glBindTexture(GL_TEXTURE_2D, this->tex[TEX_RGBA] != 0 ? this->tex[TEX_RGBA] : OpenGLSprite::dummy_tex[TEX_RGBA]);
1544  _glActiveTexture(GL_TEXTURE0 + 2);
1545  _glBindTexture(GL_TEXTURE_2D, this->tex[TEX_REMAP] != 0 ? this->tex[TEX_REMAP] : OpenGLSprite::dummy_tex[TEX_REMAP]);
1546 
1547  return this->tex[TEX_RGBA] != 0;
1548 }
SpriteLoader::CommonPixel::m
uint8 m
Remap-channel.
Definition: spriteloader.hpp:39
OpenGLBackend::cursor_pos
Point cursor_pos
Cursor position.
Definition: opengl.h:66
SCC_PAL
@ SCC_PAL
Sprite has palette data.
Definition: spriteloader.hpp:25
OpenGLBackend::sync_vid_mapping
GLsync sync_vid_mapping
Sync object for the persistently mapped video buffer.
Definition: opengl.h:33
_frag_shader_palette
static const char * _frag_shader_palette[]
Fragment shader that performs a palette lookup to read the colour from an 8bpp texture.
Definition: opengl_shader.h:62
SpriteLoader::CommonPixel::r
uint8 r
Red-channel.
Definition: spriteloader.hpp:35
LRUCache::Get
Tdata * Get(const Tkey key)
Get an item from the cache.
Definition: lrucache.hpp:104
OpenGLBackend::RenderOglSprite
void RenderOglSprite(OpenGLSprite *gl_sprite, PaletteID pal, int x, int y, ZoomLevel zoom)
Render a sprite to the back buffer.
Definition: opengl.cpp:1304
OpenGLSprite::pal_tex
static GLuint pal_tex
Texture for palette remap.
Definition: opengl.h:132
Colour::data
uint32 data
Conversion of the channel information to a 32 bit number.
Definition: gfx_type.h:160
OpenGLBackend::pal_program
GLuint pal_program
Shader program for rendering a paletted video buffer.
Definition: opengl.h:40
OpenGLSprite::TEX_RGBA
@ TEX_RGBA
RGBA texture part.
Definition: opengl.h:121
UnScaleByZoomLower
static int UnScaleByZoomLower(int value, ZoomLevel zoom)
Scale by zoom level, usually shift right (when zoom > ZOOM_LVL_NORMAL)
Definition: zoom_func.h:67
GB
static uint GB(const T x, const uint8 s, const uint8 n)
Fetch n bits from x, started at bit s.
Definition: bitmath_func.hpp:32
ST_FONT
@ ST_FONT
A sprite used for fonts.
Definition: gfx_type.h:310
ReusableBuffer
A reusable buffer that can be used for places that temporary allocate a bit of memory and do that ver...
Definition: alloc_type.hpp:24
Dimension
Dimensions (a width and height) of a rectangle in 2D.
Definition: geometry_type.hpp:27
_frag_shader_sprite_blend_150
static const char * _frag_shader_sprite_blend_150[]
GLSL 1.50 fragment shader that performs a palette lookup to read the colour from a sprite texture.
Definition: opengl_shader.h:177
OpenGLSprite::GetSize
Dimension GetSize(ZoomLevel level) const
Query the sprite size at a certain zoom level.
Definition: opengl.cpp:1530
CursorVars::sprite_count
uint sprite_count
number of sprites to draw
Definition: gfx_type.h:130
LRUCache::Pop
Tdata * Pop()
Pop the least recently used item.
Definition: lrucache.hpp:88
OpenGLSprite::pal_identity
static GLuint pal_identity
Identity texture mapping.
Definition: opengl.h:131
_frag_shader_direct_150
static const char * _frag_shader_direct_150[]
GLSL 1.50 fragment shader that reads the fragment colour from a 32bpp texture.
Definition: opengl_shader.h:51
_vertex_shader_sprite
static const char * _vertex_shader_sprite[]
Vertex shader that positions a sprite on screen.
Definition: opengl_shader.h:11
OpenGLSprite::Destroy
static void Destroy()
Free all common resources for sprite rendering.
Definition: opengl.cpp:1415
Sprite::data
byte data[]
Sprite data.
Definition: spritecache.h:22
OpenGLSprite::tex
GLuint tex[NUM_TEX]
The texture objects.
Definition: opengl.h:127
OpenGLSprite::OpenGLSprite
OpenGLSprite(uint width, uint height, uint levels, SpriteColourComponent components)
Create an OpenGL sprite with a palette remap part.
Definition: opengl.cpp:1430
OpenGLSprite::TEX_REMAP
@ TEX_REMAP
Remap texture part.
Definition: opengl.h:122
Blitter::GetScreenDepth
virtual uint8 GetScreenDepth()=0
Get the screen depth this blitter works for.
PalSpriteID::sprite
SpriteID sprite
The 'real' sprite.
Definition: gfx_type.h:23
ZOOM_LVL_COUNT
@ ZOOM_LVL_COUNT
Number of zoom levels.
Definition: zoom_type.h:30
Sprite::height
uint16 height
Height of the sprite.
Definition: spritecache.h:18
Sprite::x_offs
int16 x_offs
Number of pixels to shift the sprite to the right.
Definition: spritecache.h:20
OpenGLBackend::vid_buffer
void * vid_buffer
Pointer to the mapped video buffer.
Definition: opengl.h:36
ZoomLevel
ZoomLevel
All zoom levels we know.
Definition: zoom_type.h:19
ReusableBuffer::Allocate
T * Allocate(size_t count)
Get buffer of at least count times T.
Definition: alloc_type.hpp:42
ST_NORMAL
@ ST_NORMAL
The most basic (normal) sprite.
Definition: gfx_type.h:308
OpenGLSprite::pal_pbo
static GLuint pal_pbo
Pixel buffer object for remap upload.
Definition: opengl.h:133
OpenGLBackend::~OpenGLBackend
~OpenGLBackend()
Free allocated resources.
Definition: opengl.cpp:498
OpenGLBackend::sprite_zoom_loc
GLint sprite_zoom_loc
Uniform location for sprite zoom;.
Definition: opengl.h:58
CursorVars::sprite_pos
Point sprite_pos[16]
relative position of individual sprites
Definition: gfx_type.h:129
ZOOM_LVL_BEGIN
@ ZOOM_LVL_BEGIN
Begin for iteration.
Definition: zoom_type.h:21
OpenGLBackend::anim_pbo
GLuint anim_pbo
Pixel buffer object storing the memory used for the animation buffer.
Definition: opengl.h:46
SpriteID
uint32 SpriteID
The number of a sprite, without mapping bits and colourtables.
Definition: gfx_type.h:17
OpenGLBackend
Platform-independent back-end class for OpenGL video drivers.
Definition: opengl.h:28
OpenGLBackend::vid_texture
GLuint vid_texture
Texture handle for the video buffer texture.
Definition: opengl.h:38
OpenGLBackend::remap_rgb_loc
GLint remap_rgb_loc
Uniform location for RGB mode flag;.
Definition: opengl.h:53
_frag_shader_palette_150
static const char * _frag_shader_palette_150[]
GLSL 1.50 fragment shader that performs a palette lookup to read the colour from an 8bpp texture.
Definition: opengl_shader.h:74
OpenGLBackend::DrawMouseCursor
void DrawMouseCursor()
Draw mouse cursor on screen.
Definition: opengl.cpp:1076
OpenGLBackend::last_sprite_pal
PaletteID last_sprite_pal
Last uploaded remap palette.
Definition: opengl.h:63
Align
static T Align(const T x, uint n)
Return the smallest multiple of n equal or greater than x.
Definition: math_func.hpp:35
Simple2DVertex
A simple 2D vertex with just position and texture.
Definition: opengl.cpp:127
PALETTE_WIDTH
@ PALETTE_WIDTH
number of bits of the sprite containing the recolour palette
Definition: sprites.h:1522
SpriteLoader::Sprite::type
SpriteType type
The sprite type.
Definition: spriteloader.hpp:53
OpenGLBackend::anim_buffer
void * anim_buffer
Pointer to the mapped animation buffer.
Definition: opengl.h:45
OpenGLBackend::ReleaseVideoBuffer
void ReleaseVideoBuffer(const Rect &update_rect)
Update video buffer texture after the video buffer was filled.
Definition: opengl.cpp:1204
OpenGLBackend::vbo_quad
GLuint vbo_quad
Vertex buffer with a fullscreen quad.
Definition: opengl.h:42
OpenGLSprite::Create
static bool Create()
Create all common resources for sprite rendering.
Definition: opengl.cpp:1354
SpriteLoader::CommonPixel
Definition of a common pixel in OpenTTD's realm.
Definition: spriteloader.hpp:34
LRUCache::Contains
bool Contains(const Tkey key)
Test if a key is already contained in the cache.
Definition: lrucache.hpp:47
BlitterFactory::GetCurrentBlitter
static Blitter * GetCurrentBlitter()
Get the current active blitter (always set by calling SelectBlitter).
Definition: factory.hpp:141
OpenGLBackend::GetVideoBuffer
void * GetVideoBuffer()
Get a pointer to the memory for the video driver to draw to.
Definition: opengl.cpp:1159
OpenGLBackend::instance
static OpenGLBackend * instance
Singleton instance pointer.
Definition: opengl.h:30
Sprite::width
uint16 width
Width of the sprite.
Definition: spritecache.h:19
SpriteLoader::Sprite::x_offs
int16 x_offs
The x-offset of where the sprite will be drawn.
Definition: spriteloader.hpp:51
OpenGLBackend::cursor_in_window
bool cursor_in_window
Cursor inside this window.
Definition: opengl.h:67
OpenGLBackend::anim_texture
GLuint anim_texture
Texture handle for the animation buffer texture.
Definition: opengl.h:47
OpenGLBackend::sprite_screen_loc
GLint sprite_screen_loc
Uniform location for screen size;.
Definition: opengl.h:57
OpenGLBackend::Create
static const char * Create(GetOGLProcAddressProc get_proc, const Dimension &screen_res)
Create and initialize the singleton back-end class.
Definition: opengl.cpp:469
_vertex_shader_sprite_150
static const char * _vertex_shader_sprite_150[]
GLSL 1.50 vertex shader that positions a sprite on screen.
Definition: opengl_shader.h:26
OpenGLBackend::sync_anim_mapping
GLsync sync_anim_mapping
Sync object for the persistently mapped animation buffer.
Definition: opengl.h:34
OpenGLBackend::Destroy
static void Destroy()
Free resources and destroy singleton back-end class.
Definition: opengl.cpp:482
UnScaleByZoom
static int UnScaleByZoom(int value, ZoomLevel zoom)
Scale by zoom level, usually shift right (when zoom > ZOOM_LVL_NORMAL) When shifting right,...
Definition: zoom_func.h:34
OpenGLBackend::persistent_mapping_supported
bool persistent_mapping_supported
Persistent pixel buffer mapping supported.
Definition: opengl.h:32
OpenGLBackend::cursor_cache
LRUCache< SpriteID, Sprite > cursor_cache
Cache of encoded cursor sprites.
Definition: opengl.h:62
LRUCache::Insert
Tdata * Insert(const Tkey key, Tdata *item)
Insert a new data item with a specified key.
Definition: lrucache.hpp:58
SpriteLoader::Sprite::colours
SpriteColourComponent colours
The colour components of the sprite with useful information.
Definition: spriteloader.hpp:54
OpenGLBackend::cursor_sprite_seq
PalSpriteID cursor_sprite_seq[16]
Current image of cursor.
Definition: opengl.h:68
_frag_shader_rgb_mask_blend_150
static const char * _frag_shader_rgb_mask_blend_150[]
GLSL 1.50 fragment shader that performs a palette lookup to read the colour from an 8bpp texture.
Definition: opengl_shader.h:126
Colour
Structure to access the alpha, red, green, and blue channels from a 32 bit number.
Definition: gfx_type.h:159
OpenGLBackend::vao_quad
GLuint vao_quad
Vertex array object storing the rendering state for the fullscreen quad.
Definition: opengl.h:41
OpenGLSprite::dummy_tex
static GLuint dummy_tex[NUM_TEX]
1x1 dummy textures to substitute for unused sprite components.
Definition: opengl.h:129
OpenGLBackend::ClearCursorCache
void ClearCursorCache()
Queue a request for cursor cache clear.
Definition: opengl.cpp:1146
SpriteLoader::CommonPixel::b
uint8 b
Blue-channel.
Definition: spriteloader.hpp:37
SpriteLoader::Sprite::width
uint16 width
Width of the sprite.
Definition: spriteloader.hpp:50
PALETTE_CRASH
static const PaletteID PALETTE_CRASH
Recolour sprite greying of crashed vehicles.
Definition: sprites.h:1598
OpenGLSprite::Update
void Update(uint width, uint height, uint level, const SpriteLoader::CommonPixel *data)
Update a single mip-map level with new pixel data.
Definition: opengl.cpp:1483
IsEmptyRect
static bool IsEmptyRect(const Rect &r)
Check if a rectangle is empty.
Definition: geometry_func.hpp:22
_frag_shader_sprite_blend
static const char * _frag_shader_sprite_blend[]
Fragment shader that performs a palette lookup to read the colour from a sprite texture.
Definition: opengl_shader.h:149
OpenGLBackend::pal_texture
GLuint pal_texture
Palette lookup texture.
Definition: opengl.h:43
Colour::a
uint8 a
colour channels in LE order
Definition: gfx_type.h:167
FindStringInExtensionList
const char * FindStringInExtensionList(const char *string, const char *substring)
Find a substring in a string made of space delimited elements.
Definition: opengl.cpp:146
GetRawSprite
void * GetRawSprite(SpriteID sprite, SpriteType type, AllocatorProc *allocator, SpriteEncoder *encoder)
Reads a sprite (from disk or sprite cache).
Definition: spritecache.cpp:941
ReusableBuffer::GetBuffer
const T * GetBuffer() const
Get the currently allocated buffer.
Definition: alloc_type.hpp:75
OpenGLBackend::cursor_sprite_count
uint cursor_sprite_count
Number of cursor sprites to draw.
Definition: opengl.h:70
PaletteID
uint32 PaletteID
The number of the palette.
Definition: gfx_type.h:18
OpenGLBackend::InternalClearCursorCache
void InternalClearCursorCache()
Clear all cached cursor sprites.
Definition: opengl.cpp:1133
OpenGLBackend::sprite_sprite_loc
GLint sprite_sprite_loc
Uniform location for sprite parameters.
Definition: opengl.h:56
Sprite::y_offs
int16 y_offs
Number of pixels to shift the sprite downwards.
Definition: spritecache.h:21
opengl.h
SpriteLoader::Sprite
Structure for passing information from the sprite loader to the blitter.
Definition: spriteloader.hpp:48
OpenGLSprite::BindTextures
bool BindTextures()
Bind textures for rendering this sprite.
Definition: opengl.cpp:1540
OpenGLBackend::Paint
void Paint()
Render video buffer to the screen.
Definition: opengl.cpp:1044
OpenGLBackend::remap_sprite_loc
GLint remap_sprite_loc
Uniform location for sprite parameters.
Definition: opengl.h:50
Debug
#define Debug(name, level, format_string,...)
Ouptut a line of debugging information.
Definition: debug.h:37
CursorVars::sprite_seq
PalSpriteID sprite_seq[16]
current image of cursor
Definition: gfx_type.h:128
lengthof
#define lengthof(x)
Return the length of an fixed size array.
Definition: stdafx.h:386
OpenGLBackend::UpdatePalette
void UpdatePalette(const Colour *pal, uint first, uint length)
Update the stored palette.
Definition: opengl.cpp:1030
OpenGLBackend::sprite_program
GLuint sprite_program
Shader program for blending and rendering a sprite to the video buffer.
Definition: opengl.h:55
OpenGLBackend::sprite_crash_loc
GLint sprite_crash_loc
Uniform location for crash remap mode flag;.
Definition: opengl.h:60
MemSetT
static void MemSetT(T *ptr, byte value, size_t num=1)
Type-safe version of memset().
Definition: mem_func.hpp:49
OpenGLSprite
Class that encapsulates a RGBA texture together with a paletted remap texture.
Definition: opengl.h:117
SpriteLoader::CommonPixel::g
uint8 g
Green-channel.
Definition: spriteloader.hpp:36
SpriteLoader::CommonPixel::a
uint8 a
Alpha-channel.
Definition: spriteloader.hpp:38
OpenGLBackend::clear_cursor_cache
bool clear_cursor_cache
A clear of the cursor cache is pending.
Definition: opengl.h:64
OpenGLBackend::OpenGLBackend
OpenGLBackend()
Construct OpenGL back-end class.
Definition: opengl.cpp:491
_frag_shader_rgb_mask_blend
static const char * _frag_shader_rgb_mask_blend[]
Fragment shader that performs a palette lookup to read the colour from an 8bpp texture.
Definition: opengl_shader.h:102
ST_RECOLOUR
@ ST_RECOLOUR
Recolour sprite.
Definition: gfx_type.h:311
SpriteLoader::Sprite::y_offs
int16 y_offs
The y-offset of where the sprite will be drawn.
Definition: spriteloader.hpp:52
SpriteLoader::Sprite::height
uint16 height
Height of the sprite.
Definition: spriteloader.hpp:49
OpenGLBackend::sprite_rgb_loc
GLint sprite_rgb_loc
Uniform location for RGB mode flag;.
Definition: opengl.h:59
free
static void free(const void *ptr)
Version of the standard free that accepts const pointers.
Definition: stdafx.h:470
_frag_shader_direct
static const char * _frag_shader_direct[]
Fragment shader that reads the fragment colour from a 32bpp texture.
Definition: opengl_shader.h:41
SimpleSpriteAlloc
void * SimpleSpriteAlloc(size_t size)
Sprite allocator simply using malloc.
Definition: spritecache.cpp:882
OpenGLBackend::remap_zoom_loc
GLint remap_zoom_loc
Uniform location for sprite zoom;.
Definition: opengl.h:52
OpenGLBackend::remap_screen_loc
GLint remap_screen_loc
Uniform location for screen size;.
Definition: opengl.h:51
Rect
Specification of a rectangle with absolute coordinates of all edges.
Definition: geometry_type.hpp:69
CursorVars::pos
Point pos
logical mouse position
Definition: gfx_type.h:117
OpenGLBackend::vid_pbo
GLuint vid_pbo
Pixel buffer object storing the memory used for the video driver to draw to.
Definition: opengl.h:37
Sprite
Data structure describing a sprite.
Definition: spritecache.h:17
CursorVars::in_window
bool in_window
mouse inside this window, determines drawing logic
Definition: gfx_type.h:141
OpenGLBackend::ReleaseAnimBuffer
void ReleaseAnimBuffer(const Rect &update_rect)
Update animation buffer texture after the animation buffer was filled.
Definition: opengl.cpp:1246
OpenGLBackend::remap_program
GLuint remap_program
Shader program for blending and rendering a RGBA + remap texture.
Definition: opengl.h:49
OpenGLBackend::Init
const char * Init(const Dimension &screen_res)
Check for the needed OpenGL functionality and allocate all resources.
Definition: opengl.cpp:527
OpenGLBackend::vid_program
GLuint vid_program
Shader program for rendering a RGBA video buffer.
Definition: opengl.h:39
OpenGLBackend::Resize
bool Resize(int w, int h, bool force=false)
Change the size of the drawing window and allocate matching resources.
Definition: opengl.cpp:915
OpenGLBackend::GetAnimBuffer
uint8 * GetAnimBuffer()
Get a pointer to the memory for the separate animation buffer.
Definition: opengl.cpp:1181
OpenGLBackend::Encode
Sprite * Encode(const SpriteLoader::Sprite *sprite, AllocatorProc *allocator) override
Convert a sprite from the loader to our own format.
Definition: opengl.cpp:1276
IsOpenGLVersionAtLeast
bool IsOpenGLVersionAtLeast(byte major, byte minor)
Check if the current OpenGL version is equal or higher than a given one.
Definition: opengl.cpp:209
OpenGLBackend::cursor_sprite_pos
Point cursor_sprite_pos[16]
Relative position of individual cursor sprites.
Definition: opengl.h:69
OpenGLBackend::InitShaders
bool InitShaders()
Create all needed shader programs.
Definition: opengl.cpp:806
SpriteColourComponent
SpriteColourComponent
The different colour components a sprite can have.
Definition: spriteloader.hpp:22