ecere/gfx3D/OpenGL: Also checking flags in addition to normal pointers
[sdk] / ecere / src / gfx / drivers / OpenGLDisplayDriver.ec
1 // We were using PBUFFER for alpha compositing on Linux before, but it does not seem to work, nor be required anymore.
2 // #define USEPBUFFER
3
4 namespace gfx::drivers;
5
6 // OpenGL Extensions
7 #if defined(__unix__) || defined(__APPLE__)
8
9 #if !defined(__MINGW32__)
10 #define GL_GLEXT_PROTOTYPES
11 #endif
12
13 #ifdef ECERE_MINIGLX
14
15 //#include <GL/miniglx.h>
16
17 #else
18
19 #if defined(__ANDROID__)
20
21 #else
22
23 #define property _property
24 #define new _new
25 #define class _class
26
27 #define Window    X11Window
28 #define Cursor    X11Cursor
29 #define Font      X11Font
30 #define Display   X11Display
31 #define Time      X11Time
32 #define KeyCode   X11KeyCode
33 #define Picture   X11Picture
34 #define uint _uint
35
36 #include <X11/Xlib.h>
37 #include <X11/Xutil.h>
38 #include <GL/glx.h>
39 #include <X11/extensions/XShm.h>
40 #include <sys/ipc.h>
41 #include <sys/shm.h>
42 #include <X11/extensions/Xrender.h>
43 #include <X11/extensions/shape.h>
44
45 #undef Window
46 #undef Cursor
47 #undef Font
48 #undef Display
49 #undef Time
50 #undef KeyCode
51 #undef Picture
52 #undef uint
53 #undef new
54 #undef property
55 #undef class
56
57 #endif
58
59 #endif
60
61 #endif
62
63 #if defined(__APPLE__)
64 #include <OpenGl/gl.h>
65 #endif
66
67 #if defined(__WIN32__) || defined(__unix__) || defined(__APPLE__)
68
69 #if defined(__WIN32__)
70 #define WIN32_LEAN_AND_MEAN
71 #undef _WIN32_WINNT
72 #define _WIN32_WINNT 0x0502
73 #define String Sting_
74 #include <windows.h>
75 #undef String
76 #endif
77
78 #if defined(__ANDROID__)
79
80 #include <GLES/gl.h>
81 #include <EGL/egl.h>
82
83 #else
84
85 #include <GL/gl.h>
86 #include <GL/glext.h>
87
88 #endif
89
90 import "Display"
91
92 #if defined(__unix__) || defined(__APPLE__)
93
94 #ifndef __ANDROID__
95 import "XInterface"
96 #endif
97
98 #endif
99
100 static double nearPlane = 1;
101
102 #define glLoadMatrix glLoadMatrixd
103 #define glMultMatrix glMultMatrixd
104 #define glGetMatrix  glGetDoublev
105 #define glTranslate glTranslated
106 #define glScale glScaled
107
108 /*
109 #define glVertex3v glVertex3dv
110 #define glNormal3v glNormal3dv
111 */
112
113 /*
114 //#ifdef VERTEX_FORMAT_DOUBLE
115
116 #define glLoadMatrix glLoadMatrixd
117 #define glMultMatrix glMultMatrixd
118 #define glGetMatrix  glGetDoublev
119 #define glVertex3v glVertex3dv
120 #define glNormal3v glNormal3dv
121 #define glTranslate glTranslated
122 #define glScale glScaled
123 //#define GL_VERTEX_FORMAT   GL_DOUBLE
124
125 #else
126
127 #define glLoadMatrix glLoadMatrixf
128 #define glMultMatrix glMultMatrixf
129 #define glGetMatrix  glGetFloatv
130 #define glVertex3v glVertex3fv
131 #define glNormal3v glNormal3fv
132 #define glTranslate glTranslatef
133 #define glScale glScalef
134 //#define GL_VERTEX_FORMAT   GL_FLOAT
135
136 #endif
137 */
138
139 #define GL_ARRAY_BUFFER_ARB            0x8892
140 #define GL_ELEMENT_ARRAY_BUFFER_ARB    0x8893
141 #define GL_STATIC_DRAW_ARB             0x88E4
142 #define GL_LIGHT_MODEL_COLOR_CONTROL   0x81F8
143 #define GL_SEPARATE_SPECULAR_COLOR     0x81FA
144
145 #define GL_MULTISAMPLE_ARB             0x809D
146
147 #if defined(__WIN32__)
148
149 #define WGL_SAMPLE_BUFFERS_ARB              0x2041
150 #define WGL_SAMPLES_ARB                     0x2042
151
152 #define  WGL_WGLEXT_VERSION   1
153 #define  WGL_FRONT_COLOR_BUFFER_BIT_ARB   0x00000001
154 #define  WGL_BACK_COLOR_BUFFER_BIT_ARB   0x00000002
155 #define  WGL_DEPTH_BUFFER_BIT_ARB   0x00000004
156 #define  WGL_STENCIL_BUFFER_BIT_ARB   0x00000008
157 #define  WGL_NUMBER_PIXEL_FORMATS_ARB   0x2000
158 #define  WGL_DRAW_TO_WINDOW_ARB   0x2001
159 #define  WGL_DRAW_TO_BITMAP_ARB   0x2002
160 #define  WGL_ACCELERATION_ARB   0x2003
161 #define  WGL_NEED_PALETTE_ARB   0x2004
162 #define  WGL_NEED_SYSTEM_PALETTE_ARB   0x2005
163 #define  WGL_SWAP_LAYER_BUFFERS_ARB   0x2006
164 #define  WGL_SWAP_METHOD_ARB   0x2007
165 #define  WGL_NUMBER_OVERLAYS_ARB   0x2008
166 #define  WGL_NUMBER_UNDERLAYS_ARB   0x2009
167 #define  WGL_TRANSPARENT_ARB   0x200A
168 #define  WGL_TRANSPARENT_RED_VALUE_ARB   0x2037
169 #define  WGL_TRANSPARENT_GREEN_VALUE_ARB   0x2038
170 #define  WGL_TRANSPARENT_BLUE_VALUE_ARB   0x2039
171 #define  WGL_TRANSPARENT_ALPHA_VALUE_ARB   0x203A
172 #define  WGL_TRANSPARENT_INDEX_VALUE_ARB   0x203B
173 #define  WGL_SHARE_DEPTH_ARB   0x200C
174 #define  WGL_SHARE_STENCIL_ARB   0x200D
175 #define  WGL_SHARE_ACCUM_ARB   0x200E
176 #define  WGL_SUPPORT_GDI_ARB   0x200F
177 #define  WGL_SUPPORT_OPENGL_ARB   0x2010
178 #define  WGL_DOUBLE_BUFFER_ARB   0x2011
179 #define  WGL_STEREO_ARB   0x2012
180 #define  WGL_PIXEL_TYPE_ARB   0x2013
181 #define  WGL_COLOR_BITS_ARB   0x2014
182 #define  WGL_RED_BITS_ARB   0x2015
183 #define  WGL_RED_SHIFT_ARB   0x2016
184 #define  WGL_GREEN_BITS_ARB   0x2017
185 #define  WGL_GREEN_SHIFT_ARB   0x2018
186 #define  WGL_BLUE_BITS_ARB   0x2019
187 #define  WGL_BLUE_SHIFT_ARB   0x201A
188 #define  WGL_ALPHA_BITS_ARB   0x201B
189 #define  WGL_ALPHA_SHIFT_ARB   0x201C
190 #define  WGL_ACCUM_BITS_ARB   0x201D
191 #define  WGL_ACCUM_RED_BITS_ARB   0x201E
192 #define  WGL_ACCUM_GREEN_BITS_ARB   0x201F
193 #define  WGL_ACCUM_BLUE_BITS_ARB   0x2020
194 #define  WGL_ACCUM_ALPHA_BITS_ARB   0x2021
195 #define  WGL_DEPTH_BITS_ARB   0x2022
196 #define  WGL_STENCIL_BITS_ARB   0x2023
197 #define  WGL_AUX_BUFFERS_ARB   0x2024
198 #define  WGL_NO_ACCELERATION_ARB   0x2025
199 #define  WGL_GENERIC_ACCELERATION_ARB   0x2026
200 #define  WGL_FULL_ACCELERATION_ARB   0x2027
201 #define  WGL_SWAP_EXCHANGE_ARB   0x2028
202 #define  WGL_SWAP_COPY_ARB   0x2029
203 #define  WGL_SWAP_UNDEFINED_ARB   0x202A
204 #define  WGL_TYPE_RGBA_ARB   0x202B
205 #define  WGL_TYPE_COLORINDEX_ARB   0x202C
206 #define  ERROR_INVALID_PIXEL_TYPE_ARB   0x2043
207 #define  ERROR_INCOMPATIBLE_DEVICE_CONTEXTS_ARB   0x2054
208 #define  WGL_DRAW_TO_PBUFFER_ARB   0x202D
209 #define  WGL_MAX_PBUFFER_PIXELS_ARB   0x202E
210 #define  WGL_MAX_PBUFFER_WIDTH_ARB   0x202F
211 #define  WGL_MAX_PBUFFER_HEIGHT_ARB   0x2030
212 #define  WGL_PBUFFER_LARGEST_ARB   0x2033
213 #define  WGL_PBUFFER_WIDTH_ARB   0x2034
214 #define  WGL_PBUFFER_HEIGHT_ARB   0x2035
215 #define  WGL_PBUFFER_LOST_ARB   0x2036
216 #define  ERROR_INVALID_PIXEL_TYPE_EXT   0x2043
217 #define  WGL_NUMBER_PIXEL_FORMATS_EXT   0x2000
218 #define  WGL_DRAW_TO_WINDOW_EXT   0x2001
219 #define  WGL_DRAW_TO_BITMAP_EXT   0x2002
220 #define  WGL_ACCELERATION_EXT   0x2003
221 #define  WGL_NEED_PALETTE_EXT   0x2004
222 #define  WGL_NEED_SYSTEM_PALETTE_EXT   0x2005
223 #define  WGL_SWAP_LAYER_BUFFERS_EXT   0x2006
224 #define  WGL_SWAP_METHOD_EXT   0x2007
225 #define  WGL_NUMBER_OVERLAYS_EXT   0x2008
226 #define  WGL_NUMBER_UNDERLAYS_EXT   0x2009
227 #define  WGL_TRANSPARENT_EXT   0x200A
228 #define  WGL_TRANSPARENT_VALUE_EXT   0x200B
229 #define  WGL_SHARE_DEPTH_EXT   0x200C
230 #define  WGL_SHARE_STENCIL_EXT   0x200D
231 #define  WGL_SHARE_ACCUM_EXT   0x200E
232 #define  WGL_SUPPORT_GDI_EXT   0x200F
233 #define  WGL_SUPPORT_OPENGL_EXT   0x2010
234 #define  WGL_DOUBLE_BUFFER_EXT   0x2011
235 #define  WGL_STEREO_EXT   0x2012
236 #define  WGL_PIXEL_TYPE_EXT   0x2013
237 #define  WGL_COLOR_BITS_EXT   0x2014
238 #define  WGL_RED_BITS_EXT   0x2015
239 #define  WGL_RED_SHIFT_EXT   0x2016
240 #define  WGL_GREEN_BITS_EXT   0x2017
241 #define  WGL_GREEN_SHIFT_EXT   0x2018
242 #define  WGL_BLUE_BITS_EXT   0x2019
243 #define  WGL_BLUE_SHIFT_EXT   0x201A
244 #define  WGL_ALPHA_BITS_EXT   0x201B
245 #define  WGL_ALPHA_SHIFT_EXT   0x201C
246 #define  WGL_ACCUM_BITS_EXT   0x201D
247 #define  WGL_ACCUM_RED_BITS_EXT   0x201E
248 #define  WGL_ACCUM_GREEN_BITS_EXT   0x201F
249 #define  WGL_ACCUM_BLUE_BITS_EXT   0x2020
250 #define  WGL_ACCUM_ALPHA_BITS_EXT   0x2021
251 #define  WGL_DEPTH_BITS_EXT   0x2022
252 #define  WGL_STENCIL_BITS_EXT   0x2023
253 #define  WGL_AUX_BUFFERS_EXT   0x2024
254 #define  WGL_NO_ACCELERATION_EXT   0x2025
255 #define  WGL_GENERIC_ACCELERATION_EXT   0x2026
256 #define  WGL_FULL_ACCELERATION_EXT   0x2027
257 #define  WGL_SWAP_EXCHANGE_EXT   0x2028
258 #define  WGL_SWAP_COPY_EXT   0x2029
259 #define  WGL_SWAP_UNDEFINED_EXT   0x202A
260 #define  WGL_TYPE_RGBA_EXT   0x202B
261 #define  WGL_TYPE_COLORINDEX_EXT   0x202C
262 #define  WGL_DRAW_TO_PBUFFER_EXT   0x202D
263 #define  WGL_MAX_PBUFFER_PIXELS_EXT   0x202E
264 #define  WGL_MAX_PBUFFER_WIDTH_EXT   0x202F
265 #define  WGL_MAX_PBUFFER_HEIGHT_EXT   0x2030
266 #define  WGL_OPTIMAL_PBUFFER_WIDTH_EXT   0x2031
267 #define  WGL_OPTIMAL_PBUFFER_HEIGHT_EXT   0x2032
268 #define  WGL_PBUFFER_LARGEST_EXT   0x2033
269 #define  WGL_PBUFFER_WIDTH_EXT   0x2034
270 #define  WGL_PBUFFER_HEIGHT_EXT   0x2035
271 #define  WGL_DEPTH_FLOAT_EXT   0x2040
272 #define  WGL_SAMPLE_BUFFERS_3DFX   0x2060
273 #define  WGL_SAMPLES_3DFX   0x2061
274 #define  WGL_SAMPLE_BUFFERS_EXT   0x2041
275 #define  WGL_SAMPLES_EXT   0x2042
276 #define  WGL_GENLOCK_SOURCE_MULTIVIEW_I3D   0x2044
277 #define  WGL_GENLOCK_SOURCE_EXTENAL_SYNC_I3D   0x2045
278 #define  WGL_GENLOCK_SOURCE_EXTENAL_FIELD_I3D   0x2046
279 #define  WGL_GENLOCK_SOURCE_EXTENAL_TTL_I3D   0x2047
280 #define  WGL_GENLOCK_SOURCE_DIGITAL_SYNC_I3D   0x2048
281 #define  WGL_GENLOCK_SOURCE_DIGITAL_FIELD_I3D   0x2049
282 #define  WGL_GENLOCK_SOURCE_EDGE_FALLING_I3D   0x204A
283 #define  WGL_GENLOCK_SOURCE_EDGE_RISING_I3D   0x204B
284 #define  WGL_GENLOCK_SOURCE_EDGE_BOTH_I3D   0x204C
285 #define  WGL_GAMMA_TABLE_SIZE_I3D   0x204E
286 #define  WGL_GAMMA_EXCLUDE_DESKTOP_I3D   0x204F
287 #define  WGL_DIGITAL_VIDEO_CURSOR_ALPHA_FRAMEBUFFER_I3D   0x2050
288 #define  WGL_DIGITAL_VIDEO_CURSOR_ALPHA_VALUE_I3D   0x2051
289 #define  WGL_DIGITAL_VIDEO_CURSOR_INCLUDED_I3D   0x2052
290 #define  WGL_DIGITAL_VIDEO_GAMMA_CORRECTED_I3D   0x2053
291 #define  WGL_ARB_buffer_region   1
292 #define  WGL_ARB_extensions_string   1
293 #define  WGL_ARB_pixel_format   1
294 #define  WGL_ARB_make_current_read   1
295 #define  WGL_ARB_pbuffer   1
296 #define  WGL_EXT_display_color_table   1
297 #define  WGL_EXT_extensions_string   1
298 #define  WGL_EXT_make_current_read   1
299 #define  WGL_EXT_pbuffer   1
300 #define  WGL_EXT_pixel_format   1
301 #define  WGL_EXT_swap_control   1
302 #define  WGL_WGL_EXT_depth_float   1
303 #define  WGL_WGL_3DFX_multisample   1
304 #define  WGL_WGL_EXT_multisample   1
305 #define  WGL_NV_allocate_memory   1
306
307 /*
308 typedef void (APIENTRY * PFNGLACTIVETEXTUREARBPROC) (GLenum target);
309 typedef void (APIENTRY * PFNGLMULTITEXCOORD2FARBPROC) (GLenum target, GLfloat s, GLfloat t);
310 typedef void (APIENTRY * PFNGLCLIENTACTIVETEXTUREARBPROC) (GLenum target);
311 typedef void (APIENTRY * PFNGLLOCKARRAYSEXTPROC) (GLint first, GLsizei count);
312 typedef void (APIENTRY * PFNGLUNLOCKARRAYSEXTPROC) (void);
313 */
314
315 /*
316 typedef int (APIENTRY * PFNGLBINDBUFFERARBPROC) (GLenum target, GLuint buffer);
317 typedef int (APIENTRY * PFNGLDELETEBUFFERSARBPROC) (GLsizei n, const GLuint *buffers);
318 typedef int (APIENTRY * PFNGLGENBUFFERSARBPROC) (GLsizei n, GLuint *buffers);
319 typedef int (APIENTRY * PFNGLBUFFERDATAARBPROC) (GLenum target, int size, const GLvoid *data, GLenum usage);
320 */
321 typedef int (APIENTRY * PFNWGLCHOOSEPIXELFORMATARBPROC) ();
322 typedef void * (APIENTRY * PFNWGLCREATEPBUFFERARBPROC) (HDC hDC, int iPixelFormat, int iWidth, int iHeight, const int *piAttribList);
323 typedef HDC (APIENTRY * PFNWGLGETPBUFFERDCARBPROC) (void * hPbuffer);
324 typedef int (APIENTRY * PFNWGLRELEASEPBUFFERDCARBPROC) (void * hPbuffer, HDC hDC);
325 typedef BOOL (APIENTRY * PFNWGLDESTROYPBUFFERARBPROC) (void * hPbuffer);
326 typedef BOOL (APIENTRY * PFNWGLQUERYPBUFFERARBPROC) (void * hPbuffer, int iAttribute, int *piValue);
327 typedef const char * (APIENTRY * PFNWGLGETEXTENSIONSSTRINGARBPROC) (HDC hdc);
328 typedef BOOL (APIENTRY * PFNWGLBINDTEXIMAGEARBPROC) (void * hPbuffer, int iBuffer);
329 typedef BOOL (APIENTRY * PFNWGLRELEASETEXIMAGEARBPROC) (void * hPbuffer, int iBuffer);
330
331 static PFNGLMAPBUFFERARBPROC glMapBufferARB = null;
332 static PFNGLUNMAPBUFFERARBPROC glUnmapBufferARB = null;
333 static PFNGLACTIVETEXTUREARBPROC glActiveTextureARB = null;
334 static PFNGLMULTITEXCOORD2FARBPROC glMultiTexCoord2fARB = null;
335 static PFNGLCLIENTACTIVETEXTUREARBPROC glClientActiveTextureARB = null;
336 static PFNGLLOCKARRAYSEXTPROC glLockArraysEXT = null;
337 static PFNGLUNLOCKARRAYSEXTPROC glUnlockArraysEXT = null;
338 static PFNGLBLENDFUNCSEPARATEPROC glBlendFuncSeparate = null;
339
340 static PFNGLGENBUFFERSARBPROC glGenBuffersARB = null;
341 static PFNGLBINDBUFFERARBPROC glBindBufferARB = null;
342 static PFNGLBUFFERDATAARBPROC glBufferDataARB = null;
343 static PFNGLDELETEBUFFERSARBPROC glDeleteBuffersARB = null;
344 static PFNWGLCHOOSEPIXELFORMATARBPROC wglChoosePixelFormatARB = null;
345 static PFNWGLGETEXTENSIONSSTRINGARBPROC wglGetExtensionsStringARB = null;
346 static PFNWGLCREATEPBUFFERARBPROC wglCreatePbufferARB = null;
347 static PFNWGLGETPBUFFERDCARBPROC wglGetPbufferDCARB = null;
348 static PFNWGLQUERYPBUFFERARBPROC wglQueryPbufferARB = null;
349 static PFNWGLDESTROYPBUFFERARBPROC wglDestroyPbufferARB = null;
350 static PFNWGLRELEASEPBUFFERDCARBPROC wglReleasePbufferDCARB = null;
351 static PFNWGLBINDTEXIMAGEARBPROC wglBindTexImageARB = null;
352 static PFNWGLRELEASETEXIMAGEARBPROC wglReleaseTexImageARB = null;
353
354 #ifdef WGL_WGLEXT_PROTOTYPES
355 extern BOOL WINAPI wglSwapIntervalEXT (int);
356 extern int WINAPI wglGetSwapIntervalEXT (void);
357 #endif /* WGL_WGLEXT_PROTOTYPES */
358 typedef BOOL (WINAPI * PFNWGLSWAPINTERVALEXTPROC) (int interval);
359 typedef int (WINAPI * PFNWGLGETSWAPINTERVALEXTPROC) (void);
360
361 static PFNWGLSWAPINTERVALEXTPROC wglSwapIntervalEXT = NULL;
362
363 #else
364
365 #if defined(__ANDROID__)
366
367 // Our own matrix stack
368 static Matrix matrixStack[3][32];
369 static int matrixIndex[3];
370 static int curStack = 0;
371
372 // OpenGL ES Porting Kit
373
374 #define glBindFramebuffer        glBindFramebufferOES
375 #define glBindRenderbuffer       glBindRenderbufferOES
376 #define GL_FRAMEBUFFER           GL_FRAMEBUFFER_OES
377 #define GL_RENDERBUFFER          GL_RENDERBUFFER_OES
378 #define glFramebufferTexture2D   glFramebufferTexture2DOES
379 #define GL_COLOR_ATTACHMENT0     GL_COLOR_ATTACHMENT0_OES
380 #define glGenFramebuffers        glGenFramebuffersOES
381 #define glGenRenderbuffers       glGenRenderbuffersOES
382 #define glDeleteFramebuffers     glDeleteFramebuffersOES
383 #define glDeleteRenderbuffers    glDeleteRenderbuffersOES
384
385 #define GL_POLYGON_STIPPLE 0xFFFF
386 #define GL_LINE_STIPPLE 0xFFFF
387 #define GL_LINE 0xFFFF
388 #define GL_FILL 0xFFFF
389 #define GL_ALL_ATTRIB_BITS 0xFFFF
390 #define GL_LIGHT_MODEL_LOCAL_VIEWER 0xFFFF
391 #define glDrawElementsi(type, count, start)  glDrawElements(type, count, GL_UNSIGNED_SHORT, start)
392
393 #define GL_UNSIGNED_INT                         0x1405
394 #define GL_DOUBLE                               0x140A
395
396 #define GL_POLYGON      9
397 #define GL_QUADS        7
398
399 #define glBufferDatai         glesBufferDatai
400 #define glBufferDatad         glesBufferDatad
401 #define glVertexPointeri      glesVertexPointeri
402 #define glVertexPointerd      glesVertexPointerd
403
404 #define glRecti               glesRecti
405 #define glBegin               glesBegin
406 #define glTexCoord2i          glesTexCoord2i
407 #define glVertex2i            glesVertex2i
408 #define glTexCoord2d          glesTexCoord2d
409 #define glVertex2d            glesVertex2d
410 #define glTexCoord2f          glesTexCoord2f
411 #define glVertex2f            glesVertex2f
412 #define glEnd                 glesEnd
413 #define glColor3f             glesColor3f
414 #define glColor4ub            glesColor4ub
415 #define glColor4fv            glesColor4fv
416 #define glLineStipple         glesLineStipple
417 #define glNormal3fv           glesNormal3fv
418 #define glTexCoord2fv         glesTexCoord2fv
419 #define glColorMaterial       glesColorMaterial
420
421 #define glLoadMatrixd         glesLoadMatrixd
422 #define glMultMatrixd         glesMultMatrixd
423 #define glFrustum             glesFrustum
424 #define glOrtho               glesOrtho
425 #define glScaled              glesScaled
426 #define glTranslated          glesTranslated
427 #define glRotated             glesRotated
428 #define glVertex3d            glesVertex3d
429 #define glVertex3f            glesVertex3f
430 #define glVertex3fv           glesVertex3fv
431 #define glLightModeli         glesLightModeli
432
433 #define APIENTRY
434 //#define GL_QUADS              0
435 #define GL_QUAD_STRIP         0
436 //#define GL_DOUBLE             0
437 //#define GL_UNSIGNED_INT       0
438 //#define GL_FILL               0
439 //#define GL_LINE               0
440 //#define GL_LINE_STIPPLE       0
441 #define GL_BGRA_EXT           0
442 #define GL_UNPACK_ROW_LENGTH  0
443 #define GL_UNPACK_SKIP_PIXELS 0
444 #define GL_UNPACK_SKIP_ROWS   0
445 #define GL_RGBA8              0
446 #define GL_PACK_ROW_LENGTH    0
447 #define GL_PACK_SKIP_ROWS     0
448 #define GL_PACK_SKIP_PIXELS   0
449
450 static EGLDisplay eglDisplay;
451 static EGLSurface eglSurface;
452 static EGLContext eglContext;
453 static int eglWidth, eglHeight;
454
455 static bool egl_init_display(ANativeWindow* window)
456 {
457    const EGLint attribs[] =
458    {
459       EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
460       EGL_BLUE_SIZE, 8,
461       EGL_GREEN_SIZE, 8,
462       EGL_RED_SIZE, 8,
463       EGL_DEPTH_SIZE, 24,
464       /*EGL_SAMPLE_BUFFERS, 1,
465       EGL_SAMPLES, 0, //2,*/
466       EGL_NONE
467    };
468    EGLint w, h, format;
469    EGLint numConfigs;
470    EGLConfig config;
471    EGLSurface surface;
472    EGLContext context;
473
474    EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
475    eglInitialize(display, 0, 0);
476    eglChooseConfig(display, attribs, &config, 1, &numConfigs);
477    eglGetConfigAttrib(display, config, EGL_NATIVE_VISUAL_ID, &format);
478
479    surface = eglCreateWindowSurface(display, config, window, null);
480    context = eglCreateContext(display, config, null, null);
481
482    if(!eglMakeCurrent(display, surface, surface, context))
483       return false;
484
485    eglQuerySurface(display, surface, EGL_WIDTH, &w);
486    eglQuerySurface(display, surface, EGL_HEIGHT, &h);
487
488    eglDisplay = display;
489    eglContext = context;
490    eglSurface = surface;
491    eglWidth = w;
492    eglHeight = h;
493
494    glEnableClientState(GL_VERTEX_ARRAY);
495    /*
496    // Initialize GL state.
497    glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_FASTEST);
498    glEnable(GL_CULL_FACE);
499    glShadeModel(GL_SMOOTH);
500    glDisable(GL_DEPTH_TEST);
501    */
502    glDisable(GL_CULL_FACE);
503    glDisable(GL_DEPTH_TEST);
504
505    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
506    glEnable(GL_BLEND);
507
508    matrixStack[0][0].Identity();
509    matrixStack[1][0].Identity();
510    matrixStack[2][0].Identity();
511
512    glesMatrixMode(GL_MODELVIEW);
513    glScaled(1.0, 1.0, -1.0);
514    glesMatrixMode(GL_PROJECTION);
515    glShadeModel(GL_FLAT);
516
517    glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);
518    glFogi(GL_FOG_MODE, GL_EXP);
519    glFogf(GL_FOG_DENSITY, 0);
520    glEnable(GL_NORMALIZE);
521    glDepthFunc(GL_LESS);
522    glClearDepth(1.0);
523    glDisable(GL_MULTISAMPLE_ARB);
524
525    glViewport(0,0,w,h);
526    glesLoadIdentity();
527    glOrtho(0,w,h,0,0.0,1.0);
528
529    currentVertexBuffer = 0;
530    return true;
531 }
532
533 static void egl_term_display()
534 {
535    if(stippleTexture)
536    {
537       glDeleteTextures(1, &stippleTexture);
538       stippleTexture = 0;
539    }
540    if(eglDisplay != EGL_NO_DISPLAY)
541    {
542       eglMakeCurrent(eglDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
543       if(eglContext != EGL_NO_CONTEXT)
544          eglDestroyContext(eglDisplay, eglContext);
545       if(eglSurface != EGL_NO_SURFACE)
546          eglDestroySurface(eglDisplay, eglSurface);
547       eglTerminate(eglDisplay);
548    }
549    eglDisplay = EGL_NO_DISPLAY;
550    eglContext = EGL_NO_CONTEXT;
551    eglSurface = EGL_NO_SURFACE;
552 }
553
554 // OpenGL Immediate Mode Porting Kit
555 static int beginCount;
556 static int vertexCount;
557 static int normalCount;
558 static float *vertexPointer;
559 static float *normalPointer;
560 static GLenum beginMode;
561 static unsigned int beginBufferSize, normalBufferSize;
562 static int numVertexCoords = 2;
563
564 void glesRecti(int a, int b, int c, int d)
565 {
566    glBegin(GL_QUADS);
567    glVertex2i(a, b);
568    glVertex2i(a, d);
569    glVertex2i(c, d);
570    glVertex2i(c, b);
571    glEnd();
572 }
573
574 void glesBegin(GLenum mode)
575 {
576    beginMode = mode;
577    beginCount = 0;
578    vertexCount = 0;
579    if(!vertexPointer)
580    {
581       normalBufferSize = beginBufferSize = 1024;  // default number of vertices
582       vertexPointer = new float[beginBufferSize * 5];
583       normalPointer = new float[normalBufferSize * 3];
584    }
585 }
586
587 void glesTexCoord2f(float x, float y)
588 {
589    int count = vertexCount;
590
591    if(vertexCount + numVertexCoords > beginBufferSize)
592    {
593       beginBufferSize = beginBufferSize + beginBufferSize/2;
594       vertexPointer = renew vertexPointer float[beginBufferSize * 5];
595    }
596
597    vertexPointer[count*(2+numVertexCoords)  ] = x;
598    vertexPointer[count*(2+numVertexCoords)+1] = y;
599    count++;
600
601    if(beginMode == GL_QUADS && ((beginCount % 4) == 3))
602    {
603       vertexPointer[count*(2+numVertexCoords)  ] = vertexPointer[(count-4)*(2+numVertexCoords)];
604       vertexPointer[count*(2+numVertexCoords)+1] = vertexPointer[(count-4)*(2+numVertexCoords)+1];
605       count++;
606       vertexPointer[count*(2+numVertexCoords)  ] = vertexPointer[(count-3)*(2+numVertexCoords)];
607       vertexPointer[count*(2+numVertexCoords)+1] = vertexPointer[(count-3)*(2+numVertexCoords)+1];
608       count++;
609    }
610 }
611 void glesTexCoord2i(int x, int y)       { glesTexCoord2f((float)x, (float)y); }
612 void glesTexCoord2d(double x, double y) { glesTexCoord2f((float)x, (float)y); }
613 void glesTexCoord2fv(float * a)         { glesTexCoord2f(a[0], a[1]); }
614
615 void glesVertex2f(float x, float y)
616 {
617    numVertexCoords = 2;
618    if(vertexCount + 4 > beginBufferSize)
619    {
620       beginBufferSize = beginBufferSize + beginBufferSize/2;
621       vertexPointer = renew vertexPointer float[beginBufferSize * 5];
622    }
623
624    vertexPointer[vertexCount*4+2] = x;
625    vertexPointer[vertexCount*4+3] = y;
626    vertexCount++;
627
628    if(beginMode == GL_QUADS && ((beginCount % 4) == 3))
629    {
630       vertexPointer[vertexCount*4+2] = vertexPointer[(vertexCount-4)*4+2];
631       vertexPointer[vertexCount*4+3] = vertexPointer[(vertexCount-4)*4+3];
632       vertexCount++;
633       vertexPointer[vertexCount*4+2] = vertexPointer[(vertexCount-3)*4+2];
634       vertexPointer[vertexCount*4+3] = vertexPointer[(vertexCount-3)*4+3];
635       vertexCount++;
636    }
637    beginCount++;
638 }
639 void glesVertex2i(int x, int y)         { glesVertex2f((float)x, (float)y); }
640 void glesVertex2d(double x, double y)   { glesVertex2f((float)x, (float)y); }
641
642 void glesEnd(void)
643 {
644    int mode = beginMode;
645    if(mode == GL_QUADS)        mode = GL_TRIANGLES;
646    else if(mode == GL_POLYGON) mode = GL_TRIANGLE_FAN;
647    GLSelectVBO(0);
648    glEnableClientState(GL_TEXTURE_COORD_ARRAY);
649    glTexCoordPointer(numVertexCoords, GL_FLOAT, (numVertexCoords+2)*sizeof(float),vertexPointer);
650    glVertexPointer  (numVertexCoords, GL_FLOAT, (numVertexCoords+2)*sizeof(float),vertexPointer+2);
651    if(normalCount && normalCount == vertexCount)
652    {
653       glEnableClientState(GL_NORMAL_ARRAY);
654       glNormalPointer  (GL_FLOAT, 3*sizeof(float),normalPointer);
655    }
656
657    glDrawArrays(mode, 0, vertexCount);
658    if(normalCount)
659       glDisableClientState(GL_NORMAL_ARRAY);
660    glDisableClientState(GL_TEXTURE_COORD_ARRAY);
661    normalCount = 0;
662 }
663
664 // Vertex Pointer
665 static float *floatVPBuffer = null;
666 static short *shortVPBuffer = null;
667 static unsigned int shortVPSize = 0, floatVPSize = 0;
668
669 // Buffer Data
670 //static float *floatVPBuffer = null;  // For floats we reuse floatVPBuffer
671 static unsigned short *shortBDBuffer = null;
672 static unsigned int shortBDSize = 0/*, floatVPSize = 0*/;
673
674 void glesVertexPointeri(int numCoords, int stride, int *pointer, int numVertices)
675 {
676    if(pointer)
677    {
678       int i;
679       if(numVertices*numCoords > shortVPSize)
680       {
681          shortVPSize = numVertices*numCoords;
682          shortVPBuffer = renew shortVPBuffer short[shortVPSize];
683       }
684       for(i = 0; i < numVertices*numCoords; i++)
685          shortVPBuffer[i] = (short)pointer[i];
686       glVertexPointer(numCoords, GL_SHORT, stride, shortVPBuffer);
687    }
688    else
689       glVertexPointer(numCoords, GL_SHORT, stride, 0);
690 }
691
692 void glesVertexPointerd(int numCoords, int stride, double *pointer, int numVertices)
693 {
694    if(pointer)
695    {
696       int i;
697       if(numVertices*numCoords > floatVPSize)
698       {
699          floatVPSize = numVertices*numCoords;
700          floatVPBuffer = renew floatVPBuffer float[floatVPSize];
701       }
702       for(i = 0; i < numVertices*numCoords; i++)
703          floatVPBuffer[i] = (float)pointer[i];
704       glVertexPointer(numCoords, GL_FLOAT, stride, floatVPBuffer);
705    }
706    else
707       glVertexPointer(numCoords, GL_FLOAT, stride, 0);
708 }
709
710 void glesTexReuseIntVP(int numCoords)
711 {
712    glTexCoordPointer(numCoords, GL_SHORT, 0, floatVPBuffer);
713 }
714
715 void glesTexReuseDoubleVP(int numCoords)
716 {
717    glTexCoordPointer(numCoords, GL_FLOAT, 0, floatVPBuffer);
718 }
719
720 void glesColor3f( float r, float g, float b )
721 {
722    glColor4f(r, g, b, 1.0f);
723 }
724
725 void glesColor4ub(unsigned char r, unsigned char g, unsigned char b, unsigned char a)
726 {
727    glColor4f(r/255.0f, g/255.0f, b/255.0f, a/255.0f);
728 }
729
730 void glesColor4fv(float * a)
731 {
732    glColor4f(a[0], a[1], a[2], a[3]);
733 }
734
735 void glesBufferDatad(int target, int size, void * data, int usage)
736 {
737    int numElems = size/sizeof(double);
738    double * dblPtr = (double *)data;
739    int i;
740    if (numElems > floatVPSize)
741    {
742       floatVPSize = numElems;
743       floatVPBuffer = renew floatVPBuffer float[floatVPSize];
744    }
745    for (i=0; i< numElems; i++)
746       floatVPBuffer[i] = (float)dblPtr[i];
747
748    glBufferData(target, numElems*sizeof(float), floatVPBuffer, usage);
749 }
750
751 void glesBufferDatai(int target, int size, void * data, int usage)
752 {
753    int numElems = size/sizeof(unsigned int);
754    unsigned int * pointer = (unsigned int *)data;
755    int i;
756    if (numElems > shortBDSize)
757    {
758       shortBDSize = numElems;
759       shortBDBuffer = renew shortBDBuffer uint16[shortBDSize];
760    }
761    for (i=0; i< numElems; i++)
762       shortBDBuffer[i] = (unsigned short)pointer[i];
763
764    glBufferData(target, numElems*sizeof(unsigned short), shortBDBuffer, usage);
765 }
766
767 // *** Our Custom Matrix Stack ***
768
769 static void LoadCurMatrix()
770 {
771    double * i = matrixStack[curStack][matrixIndex[curStack]].array;
772    float m[16] =
773    {
774       (float)i[0],(float)i[1],(float)i[2],(float)i[3],
775       (float)i[4],(float)i[5],(float)i[6],(float)i[7],
776       (float)i[8],(float)i[9],(float)i[10],(float)i[11],
777       (float)i[12],(float)i[13],(float)i[14],(float)i[15]
778    };
779    glLoadMatrixf(m);
780 }
781
782 void glesLoadIdentity()
783 {
784    matrixStack[curStack][matrixIndex[curStack]].Identity();
785    LoadCurMatrix();
786 }
787
788 void glesPushMatrix()
789 {
790    if(matrixIndex[curStack] + 1 < sizeof(matrixStack[0]) / sizeof(Matrix))
791    {
792       matrixIndex[curStack]++;
793       memcpy(matrixStack[curStack][matrixIndex[curStack]].array, matrixStack[curStack][matrixIndex[curStack]-1].array, sizeof(Matrix));
794    }
795 }
796
797 void glesPopMatrix()
798 {
799    if(matrixIndex[curStack] > 0)
800    {
801       matrixIndex[curStack]--;
802       LoadCurMatrix();
803    }
804 }
805
806 void glesLoadMatrixd(double * i)
807 {
808    memcpy(matrixStack[curStack][matrixIndex[curStack]].array, i, sizeof(Matrix));
809    LoadCurMatrix();
810 }
811
812 void glesOrtho( double l, double r, double b, double t, double n, double f )
813 {
814    Matrix m
815    { {
816       (2 / (r - l)), 0, 0, 0,
817       0, (2 / (t - b)), 0, 0,
818       0, 0, (-2 / (f - n)), 0,
819       (-(r + l) / (r - l)), (-(t + b) / (t - b)), (-(f + n) / (f - n)), 1
820    } };
821    Matrix res;
822    res.Multiply(m, matrixStack[curStack][matrixIndex[curStack]]);
823    matrixStack[curStack][matrixIndex[curStack]] = res;
824    LoadCurMatrix();
825 }
826
827 void glesFrustum( double l, double r, double b, double t, double n, double f )
828 {
829    nearPlane = n;
830    n = 1;
831    l /= nearPlane;
832    r /= nearPlane;
833    b /= nearPlane;
834    t /= nearPlane;
835    f /= nearPlane;
836    {
837       double A = ((r + l) / (r - l));
838       double B = ((t + b) / (t - b));
839       double C = (-(f + n) / (f - n));
840       double D = (-2*f*n/(f-n));
841       Matrix m
842       { {
843          (2.0*n / (r - l)), 0, 0, 0,
844          0, (2.0*n / (t - b)), 0, 0,
845          A, B,             C,-1,
846          0, 0,             D, 0
847       } };
848       Matrix res;
849       res.Multiply(m, matrixStack[curStack][matrixIndex[curStack]]);
850       matrixStack[curStack][matrixIndex[curStack]] = res;
851       LoadCurMatrix();
852    }
853 }
854
855 void glesRotated( double a, double b, double c, double d )
856 {
857    Quaternion q;
858    Matrix m, r;
859
860    q.RotationAxis({(float)b,(float)c,(float)-d}, a );
861    m.RotationQuaternion(q);
862    r.Multiply(m, matrixStack[curStack][matrixIndex[curStack]]);
863    matrixStack[curStack][matrixIndex[curStack]] = r;
864    LoadCurMatrix();
865 }
866 void glesScaled( double a, double b, double c )
867 {
868    Matrix m, r;
869
870    m.Identity();
871    m.Scale(a,b,c);
872    r.Multiply(m, matrixStack[curStack][matrixIndex[curStack]]);
873    matrixStack[curStack][matrixIndex[curStack]] = r;
874    LoadCurMatrix();
875 }
876
877 void glesTranslated( double a, double b, double c )
878 {
879    Matrix m, r;
880
881    m.Identity();
882    m.Translate(a,b,c);
883    r.Multiply(m, matrixStack[curStack][matrixIndex[curStack]]);
884    matrixStack[curStack][matrixIndex[curStack]] = r;
885    LoadCurMatrix();
886 }
887
888 void glesMultMatrixd( double * i )
889 {
890    Matrix r;
891    r.Multiply((Matrix *)i, matrixStack[curStack][matrixIndex[curStack]]);
892    matrixStack[curStack][matrixIndex[curStack]] = r;
893    LoadCurMatrix();
894 }
895
896 void glesMatrixMode(int mode)
897 {
898    curStack = (mode == GL_MODELVIEW) ? 0 : (mode == GL_PROJECTION) ? 1 : 2;
899    glMatrixMode(mode);
900 }
901
902 #define glPushMatrix          glesPushMatrix
903 #define glPopMatrix           glesPopMatrix
904 #define glLoadIdentity        glesLoadIdentity
905 #define glMatrixMode          glesMatrixMode
906
907 /* Using the built-in matrix stack
908 void glesLoadMatrixd( double * i )
909 {
910    float m[16] =
911    {
912       (float)i[0],(float)i[1],(float)i[2],(float)i[3],
913       (float)i[4],(float)i[5],(float)i[6],(float)i[7],
914       (float)i[8],(float)i[9],(float)i[10],(float)i[11],
915       (float)i[12],(float)i[13],(float)i[14],(float)i[15]
916    };
917    glLoadMatrixf(m);
918 }
919
920 void glesOrtho( double l, double r, double b, double t, double n, double f )
921 {
922    float matrix[4][4] =
923    {
924       { (float)(2 / (r - l)), 0, 0, 0 },
925       { 0, (float)(2 / (t - b)), 0, 0 },
926       { 0, 0, (float)(-2 / (f - n)), 0 },
927       { (float)(-(r + l) / (r - l)), (float)(-(t + b) / (t - b)), (float)(-(f + n) / (f - n)), 1 }
928    };
929    glMultMatrixf((float *)matrix);
930 }
931
932 void glesFrustum( double l, double r, double b, double t, double n, double f )
933 {
934    float A = (float)((r + l) / (r - l));
935    float B = (float)((t + b) / (t - b));
936    float C = (float)(-(f + n) / (f - n));
937    float D = (float)(-2*f*n/(f-n));
938    float matrix[4][4] =
939    {
940       { (float)(2*n / (r - l)), 0, 0, 0 },
941       { 0, (float)(2*n / (t - b)), 0, 0 },
942       { A, B,             C,-1 },
943       { 0, 0,             D, 0 }
944    };
945    glMultMatrixf((float *)matrix);
946 }
947
948 void glesRotated( double a, double b, double c, double d ) { glRotatef((float)a, (float)b, (float)c, (float)d); }
949 void glesScaled( double a, double b, double c ) { glScalef((float)a, (float)b, (float)c); }
950 void glesTranslated( double a, double b, double c ) { glTranslatef((float)a, (float)b, (float)c); }
951
952 void glesMultMatrixd( double * i )
953 {
954    float m[16] =
955    {
956       (float)i[0], (float)i[1], (float)i[2], (float)i[3],
957       (float)i[4], (float)i[5], (float)i[6], (float)i[7],
958       (float)i[8], (float)i[9], (float)i[10], (float)i[11],
959       (float)i[12], (float)i[13], (float)i[14], (float)i[15]
960    };
961    glMultMatrixf(m);
962 }
963 */
964
965 // Need to do these...
966 void glesVertex3f( float x, float y, float z )
967 {
968    numVertexCoords = 3;
969    if(vertexCount + 4 > beginBufferSize)
970    {
971       beginBufferSize = beginBufferSize + beginBufferSize/2;
972       vertexPointer = renew vertexPointer float[beginBufferSize * 5];
973    }
974
975    vertexPointer[vertexCount*5+2] = x;
976    vertexPointer[vertexCount*5+3] = y;
977    vertexPointer[vertexCount*5+4] = z;
978    vertexCount++;
979
980    if(beginMode == GL_QUADS && ((beginCount % 4) == 3))
981    {
982       vertexPointer[vertexCount*5+2] = vertexPointer[(vertexCount-4)*5+2];
983       vertexPointer[vertexCount*5+3] = vertexPointer[(vertexCount-4)*5+3];
984       vertexPointer[vertexCount*5+4] = vertexPointer[(vertexCount-4)*5+4];
985       vertexCount++;
986       vertexPointer[vertexCount*5+2] = vertexPointer[(vertexCount-3)*5+2];
987       vertexPointer[vertexCount*5+3] = vertexPointer[(vertexCount-3)*5+3];
988       vertexPointer[vertexCount*5+4] = vertexPointer[(vertexCount-3)*5+4];
989       vertexCount++;
990    }
991    beginCount++;
992 }
993
994 void glesVertex3d( double x, double y, double z )  { glesVertex3f((float)x, (float)y, (float)z); }
995 void glesVertex3fv( float* coords )                { glesVertex3f(coords[0], coords[1], coords[2]); }
996
997 void glesNormal3f(float x, float y, float z)
998 {
999    normalCount = vertexCount;
1000    if(vertexCount + 4 > normalBufferSize)
1001    {
1002       normalBufferSize = normalBufferSize + normalBufferSize/2;
1003       normalPointer = renew normalPointer float[normalBufferSize * 2];
1004    }
1005
1006    normalPointer[normalCount*3+0] = x;
1007    normalPointer[normalCount*3+1] = y;
1008    normalPointer[normalCount*3+2] = z;
1009    normalCount++;
1010
1011    if(beginMode == GL_QUADS && ((beginCount % 4) == 3))
1012    {
1013       normalPointer[normalCount*3+0] = normalPointer[(normalCount-4)*3+0];
1014       normalPointer[normalCount*3+1] = normalPointer[(normalCount-4)*3+1];
1015       normalPointer[normalCount*3+2] = normalPointer[(normalCount-4)*3+2];
1016       normalCount++;
1017       normalPointer[normalCount*3+0] = normalPointer[(normalCount-3)*3+0];
1018       normalPointer[normalCount*3+1] = normalPointer[(normalCount-3)*3+1];
1019       normalPointer[normalCount*3+2] = normalPointer[(normalCount-3)*3+2];
1020       normalCount++;
1021    }
1022 }
1023 void glesNormal3fd(double x, double y, double z)         { glesNormal3f((float)x, (float)y, (float)z); }
1024 void glesNormal3fv(float * coords)                       { glesNormal3f(coords[0], coords[1], coords[2]); }
1025
1026 void glesColorMaterial(int a, int b)
1027 {
1028    PrintLn("glColorMaterial stub");
1029 }
1030
1031 void glesTerminate()
1032 {
1033    delete vertexPointer;
1034    delete normalPointer;
1035    beginBufferSize = 0;
1036
1037    delete floatVPBuffer;
1038    shortVPSize = 0;
1039
1040    delete shortVPBuffer;
1041    floatVPSize = 0;
1042
1043    delete shortBDBuffer;
1044    shortBDSize = 0;
1045 }
1046
1047 static GLuint stippleTexture;
1048 static bool stippleEnabled;
1049
1050 void glesLineStipple( int i, unsigned short j )
1051 {
1052    uint texture[1*16];
1053    int x;
1054    for(x = 0; x < 16; x++)
1055    {
1056       bool v = (j & (1 << x)) != 0;
1057       texture[x] = v ? 0xFFFFFFFF : 0;
1058    }
1059    if(!stippleTexture)
1060       glGenTextures(1, &stippleTexture);
1061    glBindTexture(GL_TEXTURE_2D, stippleTexture);
1062    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, 16, 1, 0, GL_RGBA, GL_UNSIGNED_BYTE, texture);
1063    glEnable(GL_TEXTURE_2D);
1064    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
1065    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
1066    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
1067    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
1068    glMatrixMode(GL_TEXTURE);
1069    glLoadIdentity();
1070    //glTranslated(1.0/backAttrib->texW/2.0f, 1.0/backAttrib->texH/2.0f, 0.0f);
1071    glScaled(i/16.0, 1, 1.0f);
1072    glTranslated(0.5, 0.5, 0);
1073    glMatrixMode(GL_PROJECTION);
1074 }
1075
1076 void glesLightModeli( unsigned int pname, int param )
1077 {
1078    if(pname == GL_LIGHT_MODEL_TWO_SIDE)
1079       glLightModelf(GL_LIGHT_MODEL_TWO_SIDE, param);
1080 }
1081
1082 void glClearDepth( double depth ) { glClearDepthf((float)depth); }
1083 void glFogi( unsigned int pname, int param ) { }
1084 void glPolygonMode( unsigned int i, unsigned int j ) { }
1085
1086
1087 // *** Picking won't be supported for now ***
1088 void glPushName( unsigned int i ) { }
1089 void glLoadName( unsigned int i ) { }
1090 void glPopName() { }
1091
1092 // Probably replace by regular glBlendFunc ...
1093 void glBlendFuncSeparate(int a, int b, int c, int d)
1094 {
1095    glBlendFunc(a, b);
1096 }
1097
1098 // For direct pixel blitting...
1099 void glRasterPos2d(double a, double b) { }
1100 void glPixelZoom(float a, float b) { }
1101 void glDrawPixels(int a, int b, int c, int d, void * e) { }
1102
1103 #else
1104
1105 /* Non OpenGL ES friendly stuff
1106 #undef GL_UNSIGNED_INT
1107 #undef GL_DOUBLE
1108 #undef GL_INT
1109 //#undef GL_POLYGON
1110 //#undef GL_QUADS
1111 #undef GL_QUAD_STRIP
1112 #undef GL_POLYGON_STIPPLE
1113 #undef GL_LINE_STIPPLE
1114 #undef GL_LINE
1115 #undef GL_FILL
1116 #undef GL_ALL_ATTRIB_BITS
1117 #undef GL_LIGHT_MODEL_LOCAL_VIEWER
1118 */
1119
1120 #endif
1121
1122 #if !defined(__APPLE__)
1123 void (APIENTRY * glBindBufferARB) (GLenum target, GLuint buffer);
1124 void (APIENTRY * glGenBuffersARB) (GLsizei n, GLuint *buffers);
1125 void (APIENTRY * glDeleteBuffersARB) (GLsizei n, const GLuint *buffers);
1126 void (APIENTRY * glBufferDataARB) (GLenum target, int size, const GLvoid *data, GLenum usage);
1127 #endif
1128
1129 #endif
1130
1131 static int currentVertexBuffer;
1132
1133 bool GLSelectVBO(uint vbo)
1134 {
1135    if(currentVertexBuffer != vbo)
1136    {
1137       GLBindBuffer(GL_ARRAY_BUFFER, vbo);
1138       currentVertexBuffer = vbo;
1139       return true;
1140    }
1141    return false;
1142 }
1143
1144 void GLGenBuffers(int count, uint * buffer)
1145 {
1146 #ifdef __ANDROID__
1147    glGenBuffers(count, buffer);
1148 #else
1149 #if defined(__WIN32__)
1150    if(glGenBuffersARB)
1151 #endif
1152       glGenBuffersARB(count, buffer);
1153 #endif
1154 }
1155
1156 void GLDeleteBuffers(int count, GLuint * buffer)
1157 {
1158 #ifdef __ANDROID__
1159    glDeleteBuffers(count, buffer);
1160 #else
1161 #if defined(__WIN32__)
1162    if(glDeleteBuffersARB)
1163 #endif
1164       glDeleteBuffersARB(count, buffer);
1165 #endif
1166 }
1167
1168 void GLBindBuffer(int target, uint buffer)
1169 {
1170 #ifdef __ANDROID__
1171    glBindBuffer(target, buffer);
1172 #else
1173 #if defined(__WIN32__)
1174    if(glBindBufferARB)
1175 #endif
1176       glBindBufferARB(target, buffer);
1177 #endif
1178 }
1179
1180 public void GLVertexPointer(int numCoords, int glType, int stride, void *ptr, int numVertices)
1181 {
1182 #ifdef __ANDROID__
1183    if(type == GL_DOUBLE)
1184       glesVertexPointerd(numCoords, stride, pointer, numVertices);
1185    else if(type == GL_INT)
1186       glesVertexPointeri(numCoords, stride, pointer, numVertices);
1187    else
1188 #endif
1189       glVertexPointer(numCoords, glType, stride, ptr);
1190 }
1191
1192 public void GLBufferData(int type, GLenum target, int size, const GLvoid *data, GLenum usage)
1193 {
1194 #ifdef __ANDROID__
1195    if(type == GL_DOUBLE)
1196       glesBufferDatad(target, size, (void *)data, usage);
1197    else if(type == GL_UNSIGNED_INT)
1198       glesBufferDatai(target, size, (void *)data, usage);
1199    else
1200       glBufferData(target, size, data, usage);
1201 #else
1202
1203 #if defined(__WIN32__)
1204    if(glBufferDataARB)
1205 #endif
1206       glBufferDataARB(target, size, data, usage);
1207
1208 #endif
1209 }
1210
1211 static int displayWidth, displayHeight;
1212
1213 #define GL_CLAMP_TO_EDGE 0x812F
1214
1215 static bool vboAvailable;
1216
1217 static bool useSingleGLContext = false;
1218 class OGLDisplay : struct
1219 {
1220 #if defined(__WIN32__)
1221    HDC hdc;
1222    HGLRC glrc;
1223
1224    HBITMAP memBitmap;
1225    HDC memDC;
1226    byte * picture;
1227    uint stride;
1228    void * pBuffer;
1229    /*
1230    int imageBuffers[2];
1231    byte * pboMemory1, * pboMemory2;
1232    */
1233 #elif !defined(__ANDROID__)
1234    GLXContext glContext;
1235
1236    Pixmap pixmap;
1237    XShmSegmentInfo shminfo;
1238    XImage * image;
1239    XShmSegmentInfo shminfoShape;
1240    XImage * shapeImage;
1241    byte * picture;
1242    uint stride;
1243    GLXPbuffer pBuffer;
1244    X11Picture windowPicture;
1245    X11Picture pixmapPicture;
1246    Pixmap shapePixmap;
1247    X11Picture shapePicture;
1248 #endif
1249
1250    ColorAlpha * flippingBuffer;
1251    int flipBufH, flipBufW;
1252    bool depthWrite;
1253    int x, y;
1254 };
1255
1256 class OGLSystem : struct
1257 {
1258    int maxTextureSize;
1259    bool loadingFont;
1260    bool pow2textures;
1261 #if defined(__WIN32__)
1262    PIXELFORMATDESCRIPTOR pfd;
1263    int format;
1264    HDC hdc;
1265    HGLRC glrc;
1266    HWND hwnd;
1267 #elif !defined(__ANDROID__)
1268    XVisualInfo * visualInfo;
1269    GLXContext glContext;
1270    GLXDrawable glxDrawable;
1271 #endif
1272 };
1273
1274 class OGLSurface : struct
1275 {
1276    Font font;
1277    bool opaqueText;
1278    int xOffset;
1279    bool writingText;
1280
1281    float foreground[4], background[4], bitmapMult[4];
1282 } OGLSurface;
1283
1284 class OGLMesh : struct
1285 {
1286    uint vertices;
1287    uint normals;
1288    uint texCoords;
1289    uint texCoords2;
1290    uint colors;
1291 };
1292
1293 class OGLIndices : struct
1294 {
1295    uint16 * indices;
1296    uint buffer;
1297    uint nIndices;
1298 };
1299
1300 #if !defined(ECERE_NO3D) && !defined(ECERE_VANILLA)
1301 static int primitiveTypes[RenderPrimitiveType] =
1302 {
1303    GL_POINTS, GL_LINES, GL_TRIANGLES, GL_TRIANGLE_STRIP, GL_TRIANGLE_FAN, GL_QUADS, GL_QUAD_STRIP, GL_LINE_STRIP
1304 };
1305 #endif
1306
1307 int current;
1308 void * previous;
1309
1310 class OpenGLDisplayDriver : DisplayDriver
1311 {
1312    class_property(name) = "OpenGL";
1313
1314    bool LockSystem(DisplaySystem displaySystem)
1315    {
1316 #if !defined(__ANDROID__)
1317       OGLSystem oglSystem = displaySystem.driverData;
1318       if(useSingleGLContext) return true;
1319    #if defined(__WIN32__)
1320       wglMakeCurrent(oglSystem.hdc, oglSystem.glrc);
1321    #elif defined(__unix__) || defined(__APPLE__)
1322       //if(previous) return true;
1323       // printf("Making SYSTEM current\n");
1324       glXMakeCurrent(xGlobalDisplay, (GLXDrawable)oglSystem.glxDrawable, oglSystem.glContext);
1325       //previous = oglSystem.glContext;
1326    #endif
1327 #endif
1328       return true;
1329    }
1330
1331    void UnlockSystem(DisplaySystem displaySystem)
1332    {
1333       if(useSingleGLContext) return;
1334    #if defined(__WIN32__)
1335       wglMakeCurrent(null, null);
1336    #elif defined(__unix__) || defined(__APPLE__)
1337       // printf("Making NULL current\n");
1338       #if defined(__ANDROID__)
1339       #else
1340       glXMakeCurrent(xGlobalDisplay, None, null);
1341       #endif
1342       // previous = null;
1343    #endif
1344    }
1345
1346    bool Lock(Display display)
1347    {
1348 #if !defined(__ANDROID__)
1349       OGLDisplay oglDisplay = display.driverData;
1350       if(useSingleGLContext) return true;
1351    #if defined(__WIN32__)
1352       wglMakeCurrent(oglDisplay.hdc, oglDisplay.glrc);
1353    #elif defined(__unix__) || defined(__APPLE__)
1354       // if(previous) glXMakeCurrent(xGlobalDisplay, None, null);
1355       // printf("   Making DISPLAY current\n");
1356       glXMakeCurrent(xGlobalDisplay, (GLXDrawable)display.window, oglDisplay.glContext);
1357    #endif
1358 #endif
1359       return true;
1360    }
1361
1362    void Unlock(Display display)
1363    {
1364       if(useSingleGLContext) return;
1365       //printf("   Making NULL current\n");
1366       //glXMakeCurrent(xGlobalDisplay, None, null);
1367       // if(previous)
1368          LockSystem(display.displaySystem);
1369    }
1370
1371    void DestroyDisplay(Display display)
1372    {
1373       OGLDisplay oglDisplay = display.driverData;
1374
1375       if(oglDisplay)
1376       {
1377    #if defined(__WIN32__)
1378          wglMakeCurrent( null, null );
1379
1380          if(oglDisplay.glrc)
1381             wglDeleteContext(oglDisplay.glrc);
1382
1383          if(oglDisplay.hdc && oglDisplay.pBuffer)
1384             wglReleasePbufferDCARB(oglDisplay.pBuffer, oglDisplay.hdc);
1385
1386          if(oglDisplay.pBuffer)
1387             wglDestroyPbufferARB(oglDisplay.pBuffer);
1388
1389          if(oglDisplay.hdc)
1390             ReleaseDC(display.window, oglDisplay.hdc);
1391
1392          if(oglDisplay.memDC) DeleteDC(oglDisplay.memDC);
1393          if(oglDisplay.memBitmap) DeleteObject(oglDisplay.memBitmap);
1394
1395    #elif defined(__unix__) || defined(__APPLE__)
1396       #if defined(__ANDROID__)
1397       #else
1398          if(oglDisplay.shapePixmap)
1399             XFreePixmap(xGlobalDisplay, oglDisplay.shapePixmap);
1400          if(oglDisplay.pixmap)
1401             XFreePixmap(xGlobalDisplay, oglDisplay.pixmap);
1402          if(oglDisplay.image)
1403          {
1404             if(oglDisplay.shminfoShape.shmid != -1)
1405             {
1406                XShmDetach(xGlobalDisplay, &oglDisplay.shminfo);
1407                if(oglDisplay.shminfo.shmaddr != (void *)-1)
1408                   shmdt(oglDisplay.shminfo.shmaddr);
1409                shmctl(oglDisplay.shminfo.shmid, IPC_RMID, 0);
1410             }
1411          }
1412          if(oglDisplay.shapeImage)
1413          {
1414             if(oglDisplay.shminfoShape.shmid != -1)
1415             {
1416                XShmDetach(xGlobalDisplay, &oglDisplay.shminfoShape);
1417                if(oglDisplay.shminfoShape.shmaddr != (void *)-1)
1418                   shmdt(oglDisplay.shminfoShape.shmaddr);
1419                shmctl(oglDisplay.shminfoShape.shmid, IPC_RMID, 0);
1420             }
1421             XDestroyImage(oglDisplay.shapeImage);
1422             oglDisplay.shapeImage = None;
1423          }
1424
1425          glXMakeCurrent(xGlobalDisplay, None, null);
1426
1427          if(oglDisplay.glContext)
1428             glXDestroyContext(xGlobalDisplay, oglDisplay.glContext);
1429       #endif
1430    #endif
1431          delete oglDisplay.flippingBuffer;
1432          delete oglDisplay;
1433          display.driverData = null;
1434       }
1435    }
1436
1437    void ::CheckExtensions(OGLSystem oglSystem)
1438    {
1439       const char * extensions = (const char *)glGetString(GL_EXTENSIONS);
1440       if(extensions)
1441          oglSystem.pow2textures = strstr(extensions, "GL_ARB_texture_non_power_of_two") ? false : true;
1442       glGetIntegerv(GL_MAX_TEXTURE_SIZE, &oglSystem.maxTextureSize);
1443    }
1444
1445    bool CreateDisplaySystem(DisplaySystem displaySystem)
1446    {
1447       bool result = false;
1448       OGLSystem oglSystem = displaySystem.driverData = OGLSystem { };
1449
1450    #ifdef __WIN32__
1451       oglSystem.hwnd = CreateWindow("static", null, 0,0,0,0,0,null,null,null,null);
1452
1453       oglSystem.hdc = GetDC(oglSystem.hwnd);
1454       if(oglSystem.hdc)
1455       {
1456
1457          oglSystem.pfd.nSize = (short)sizeof(oglSystem.pfd);
1458          oglSystem.pfd.nVersion = 1;
1459          oglSystem.pfd.dwFlags = PFD_DRAW_TO_WINDOW /*PFD_DRAW_TO_BITMAP*/ | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;
1460          oglSystem.pfd.iPixelType = PFD_TYPE_RGBA;
1461          oglSystem.pfd.cColorBits = 24;
1462          oglSystem.pfd.cAlphaBits = 8;
1463          oglSystem.pfd.cDepthBits = 24;
1464          oglSystem.pfd.iLayerType = PFD_MAIN_PLANE;
1465
1466          oglSystem.format = ChoosePixelFormat(oglSystem.hdc, &oglSystem.pfd);
1467          DescribePixelFormat(oglSystem.hdc, oglSystem.format, sizeof(oglSystem.pfd), &oglSystem.pfd);
1468
1469          if(oglSystem.pfd.cColorBits > 8)
1470          {
1471             SetPixelFormat(oglSystem.hdc, oglSystem.format, &oglSystem.pfd);
1472             oglSystem.glrc = wglCreateContext(oglSystem.hdc);
1473             if(oglSystem.glrc)
1474             {
1475                wglMakeCurrent(oglSystem.hdc, oglSystem.glrc);
1476
1477                  // Get Pointers To The GL Functions
1478                glActiveTextureARB = (void *) wglGetProcAddress("glActiveTextureARB");
1479                glMultiTexCoord2fARB = (void *) wglGetProcAddress("glMultiTexCoord2fARB");
1480                glClientActiveTextureARB = (void *) wglGetProcAddress("glClientActiveTextureARB");
1481                glLockArraysEXT = (void *) wglGetProcAddress("glLockArraysEXT" );
1482                glUnlockArraysEXT = (void *) wglGetProcAddress("glUnlockArraysEXT");
1483                  glGenBuffersARB = (void *) wglGetProcAddress("glGenBuffersARB");
1484                  glBindBufferARB = (void *) wglGetProcAddress("glBindBufferARB");
1485                  glBufferDataARB = (void *) wglGetProcAddress("glBufferDataARB");
1486                glMapBufferARB  = (void *) wglGetProcAddress("glMapBufferARB");
1487                glUnmapBufferARB  = (void *) wglGetProcAddress("glUnmapBufferARB");
1488                  glDeleteBuffersARB = (void *) wglGetProcAddress("glDeleteBuffersARB");
1489                glBlendFuncSeparate = (void *) wglGetProcAddress("glBlendFuncSeparate");
1490
1491                wglChoosePixelFormatARB = (void *) wglGetProcAddress("wglChoosePixelFormatARB");
1492                wglGetExtensionsStringARB = (void *)wglGetProcAddress("wglGetExtensionsStringARB");
1493                wglCreatePbufferARB = (void *)wglGetProcAddress("wglCreatePbufferARB");
1494                wglGetPbufferDCARB = (void *)wglGetProcAddress("wglGetPbufferDCARB");
1495                wglQueryPbufferARB = (void *)wglGetProcAddress("wglQueryPbufferARB");
1496                wglDestroyPbufferARB = (void *)wglGetProcAddress("wglDestroyPbufferARB");
1497                wglReleasePbufferDCARB = (void *)wglGetProcAddress("wglReleasePbufferDCARB");
1498                wglBindTexImageARB = (void *)wglGetProcAddress("wglBindTexImageARB");
1499                wglReleaseTexImageARB = (void *)wglGetProcAddress("wglReleaseTexImageARB");
1500
1501                wglSwapIntervalEXT = (void *)wglGetProcAddress("wglSwapIntervalEXT");
1502
1503                vboAvailable = glBindBufferARB != null;
1504
1505                // eSystem_LoggingMode(LOG_MSGBOX, null);
1506
1507                if(wglChoosePixelFormatARB)
1508                {
1509                     int pixelFormat;
1510                     int valid;
1511                     int numFormats;
1512                     float fAttributes[] = {0,0};
1513                     int iAttributes[] =
1514                   {
1515                      WGL_DRAW_TO_WINDOW_ARB,GL_TRUE,
1516                             WGL_SUPPORT_OPENGL_ARB,GL_TRUE,
1517                             WGL_ACCELERATION_ARB,WGL_FULL_ACCELERATION_ARB,
1518                             WGL_COLOR_BITS_ARB,24,
1519                             WGL_ALPHA_BITS_ARB,8,
1520                             WGL_DEPTH_BITS_ARB,16,
1521                             WGL_STENCIL_BITS_ARB,0,
1522                             WGL_DOUBLE_BUFFER_ARB,GL_TRUE,
1523                             WGL_SAMPLE_BUFFERS_ARB,GL_TRUE,
1524                             WGL_SAMPLES_ARB, 4,                                         // Check For 4x Multisampling
1525                             0,0
1526                   };
1527
1528                   //Log("Found wglChoosePixelFormatARB\n");
1529
1530                     valid = wglChoosePixelFormatARB(oglSystem.hdc,iAttributes,fAttributes,1,&pixelFormat,&numFormats);
1531                     if(!valid || !numFormats)
1532                     {
1533                      //Log("Can't find 4x multi sampling\n");
1534                        iAttributes[19] = 2;
1535                        valid = wglChoosePixelFormatARB(oglSystem.hdc,iAttributes,fAttributes,1,&pixelFormat,&numFormats);
1536                      if(!valid || !numFormats)
1537                      {
1538                         // Log("Can't find 2x multi sampling\n");
1539                         iAttributes[16] = 0;
1540                         iAttributes[17] = 0;
1541                         valid = wglChoosePixelFormatARB(oglSystem.hdc,iAttributes,fAttributes,1,&pixelFormat,&numFormats);
1542                      }
1543                     }
1544                   if(valid && numFormats)
1545                   {
1546                      oglSystem.format = pixelFormat;
1547                      wglMakeCurrent(null, null);
1548                      wglDeleteContext(oglSystem.glrc);
1549
1550                      // *** DescribePixelFormat does not support WGL pixel formats! ***
1551                      //DescribePixelFormat(oglSystem.hdc, oglSystem.format, sizeof(oglSystem.pfd), &oglSystem.pfd);
1552                      SetPixelFormat(oglSystem.hdc, oglSystem.format, &oglSystem.pfd);
1553                      //Log("Successfully set pixel format\n");
1554
1555                      oglSystem.glrc = wglCreateContext(oglSystem.hdc);
1556                      wglMakeCurrent(oglSystem.hdc, oglSystem.glrc);
1557                   }
1558                }
1559                /*else
1560                   eSystem_Logf("Can't find wglChoosePixelFormatARB\n");*/
1561
1562                result = true;
1563
1564                CheckExtensions(oglSystem);
1565
1566                wglMakeCurrent(null, null);
1567
1568                //eSystem_DumpErrors(true);
1569             }
1570          }
1571       }
1572    #elif defined(__unix__) || defined(__APPLE__)
1573       vboAvailable = true;
1574       #if defined(__ANDROID__)
1575          egl_init_display(guiApp.desktop.windowHandle);
1576          CheckExtensions(oglSystem);
1577          result = true;
1578       #else
1579       {
1580          X11Window root = RootWindow( xGlobalDisplay, DefaultScreen( xGlobalDisplay ) );
1581          XSetWindowAttributes attr;
1582          unsigned long mask;
1583
1584          int attrList[] =
1585          {
1586       #ifndef ECERE_MINIGLX
1587             GLX_USE_GL, GLX_DEPTH_SIZE, 1,
1588       #endif
1589             GLX_RGBA,
1590             GLX_RED_SIZE, 1, GLX_GREEN_SIZE, 1, GLX_BLUE_SIZE, 1,
1591             GLX_DOUBLEBUFFER,
1592             None
1593          };
1594          oglSystem.visualInfo = glXChooseVisual( xGlobalDisplay,  DefaultScreen( xGlobalDisplay ), attrList );
1595          attr.background_pixel = 0;
1596          attr.border_pixel = 0;
1597          attr.colormap = XCreateColormap( xGlobalDisplay, root, oglSystem.visualInfo->visual, AllocNone);
1598          attr.event_mask = StructureNotifyMask | ExposureMask | KeyPressMask;
1599          mask = CWBackPixel | CWBorderPixel | CWColormap | CWEventMask;
1600
1601          oglSystem.glxDrawable = XCreateWindow( xGlobalDisplay, root, 0, 0, 1, 1, 0, oglSystem.visualInfo->depth, InputOutput,
1602             oglSystem.visualInfo->visual, mask, &attr );
1603       }
1604       if(oglSystem.visualInfo)
1605       {
1606          oglSystem.glContext = glXCreateContext(xGlobalDisplay, oglSystem.visualInfo, null, True);
1607          if(oglSystem.glContext)
1608          {
1609             glXMakeCurrent(xGlobalDisplay, oglSystem.glxDrawable, oglSystem.glContext);
1610             // Setup Extensions
1611             CheckExtensions(oglSystem);
1612             glXMakeCurrent(xGlobalDisplay, None, null);
1613             result = true;
1614          }
1615       }
1616       #endif
1617    #endif
1618
1619       displaySystem.flags.alpha = true;
1620       displaySystem.flags.flipping = true;
1621       displaySystem.pixelFormat = pixelFormat888;
1622       return result;
1623    }
1624
1625    void DestroyDisplaySystem(DisplaySystem displaySystem)
1626    {
1627       OGLSystem oglSystem = displaySystem.driverData;
1628
1629    #if defined(__WIN32__)
1630       wglMakeCurrent( null, null );
1631
1632       if(oglSystem.glrc)
1633          wglDeleteContext(oglSystem.glrc);
1634
1635       if(oglSystem.hdc)
1636          ReleaseDC(oglSystem.hwnd, oglSystem.hdc);
1637       DestroyWindow(oglSystem.hwnd);
1638
1639    #elif defined(__unix__) || defined(__APPLE__)
1640       #if defined(__ANDROID__)
1641          egl_term_display();
1642       #else
1643       if(oglSystem.visualInfo)
1644       {
1645    #ifdef   ECERE_MINIGLX
1646          __miniglx_XFree(oglSystem.visualInfo);
1647    #else
1648          XFree(oglSystem.visualInfo);
1649    #endif
1650       }
1651
1652       if(oglSystem.glxDrawable)
1653       {
1654          XDestroyWindow(xGlobalDisplay, oglSystem.glxDrawable);
1655          oglSystem.glxDrawable = 0;
1656       }
1657       #endif
1658    #endif
1659       delete oglSystem;
1660    }
1661
1662    bool CreateDisplay(Display display)
1663    {
1664       bool result = false;
1665       OGLDisplay oglDisplay = display.driverData;
1666 #if !defined(__ANDROID__)
1667       OGLSystem oglSystem = display.displaySystem.driverData;
1668 #endif
1669       if(!oglDisplay)
1670          oglDisplay = display.driverData = OGLDisplay { };
1671       //printf("Inside CreateDisplay\n");
1672
1673 #if defined(__WIN32__) || defined(USEPBUFFER)
1674       if(!display.alphaBlend)
1675 #endif
1676       {
1677    #if defined(__WIN32__)
1678          oglDisplay.hdc = GetDC(display.window);
1679          SetPixelFormat(oglDisplay.hdc, oglSystem.format, &oglSystem.pfd);
1680          if((oglDisplay.glrc = wglCreateContext(oglDisplay.hdc)))
1681          {
1682             wglShareLists(oglSystem.glrc, oglDisplay.glrc);
1683             wglMakeCurrent(oglDisplay.hdc, oglDisplay.glrc);
1684             result = true;
1685          }
1686          else
1687             ReleaseDC(display.window, oglDisplay.hdc);
1688    #elif defined(__unix__) || defined(__APPLE__)
1689       #if defined(__ANDROID__)
1690       #else
1691          XVisualInfo * visualInfo = ((XWindowData)display.windowDriverData).visual;
1692          /*
1693 #if defined(__APPLE__)
1694          XVisualInfo template = { 0 };
1695          XWindowAttributes winAttr;
1696          int n;
1697          XGetWindowAttributes(xGlobalDisplay, (X11Window)display.window, &winAttr);
1698          template.visualid = XVisualIDFromVisual(winAttr.visual);
1699          visualInfo = XGetVisualInfo(xGlobalDisplay, VisualIDMask, &template, &n);
1700 #ifdef _DEBUG
1701          printf("XGetVisualInfo visual ID = %d\n", template.visualid);
1702          printf("visualInfo visual ID = %d\n", visualInfo->visualid);
1703          printf("oglSystem.visualInfo visual ID = %d\n", oglSystem.visualInfo->visualid);
1704          printf("((XWindowData)display.windowDriverData).visual visual ID = %d\n", ((XWindowData)display.windowDriverData).visual->visualid);
1705 #endif
1706          // visualInfo = oglSystem.visualInfo;
1707 //#endif
1708          */
1709          if(visualInfo)
1710          {
1711             //printf("visualInfo is not null\n");
1712             // printf("Creating Display Context, sharing with %x!\n", oglSystem.glContext);
1713             oglDisplay.glContext = glXCreateContext(xGlobalDisplay, visualInfo, oglSystem.glContext, True);
1714             //XFree(visualInfo);
1715          }
1716
1717          // oglDisplay.glContext = glXCreateContext(xGlobalDisplay, oglSystem.visualInfo, oglSystem.glContext, True);
1718          if(oglDisplay.glContext)
1719          {
1720             //printf("CreateDisplay Got a Context\n");
1721             glXMakeCurrent(xGlobalDisplay, (GLXDrawable)display.window, oglDisplay.glContext);
1722             result = true;
1723          }
1724       #endif
1725    #endif
1726       }
1727 #if defined(__WIN32__) || defined(USEPBUFFER)
1728       else
1729          result = true;
1730 #endif
1731       if(result)
1732       {
1733 #if defined(__WIN32__)
1734          if(glBlendFuncSeparate)
1735             glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
1736          else
1737             glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
1738 #else
1739 #if !defined(__OLDX__)
1740           glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
1741 #else
1742          glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
1743 #endif
1744 #endif
1745          glEnable(GL_BLEND);
1746
1747          glMatrixMode(GL_MODELVIEW);
1748          glScaled(1.0, 1.0, -1.0);
1749          // glTranslatef(0.375f, 0.375f, 0.0f);
1750          // glTranslatef(-0.625f, -0.625f, 0.0f);
1751          glMatrixMode(GL_PROJECTION);
1752          glShadeModel(GL_FLAT);
1753
1754          // glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, true);
1755          glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);
1756          glFogi(GL_FOG_MODE, GL_EXP);
1757          glFogf(GL_FOG_DENSITY, 0);
1758          glEnable(GL_NORMALIZE);
1759          glDepthFunc(GL_LESS);
1760          glClearDepth(1.0);
1761          glDisable(GL_MULTISAMPLE_ARB);
1762       }
1763 #if !defined(ECERE_NO3D) && !defined(ECERE_VANILLA)
1764       display.ambient = Color { 50,50,50 };
1765 #endif
1766
1767       if(!useSingleGLContext)
1768       {
1769    #if defined(__WIN32__)
1770          wglMakeCurrent(null, null);
1771    #elif defined(__unix__) || defined(__APPLE__)
1772       #if defined(__ANDROID__)
1773          result = true;
1774       #else
1775          glXMakeCurrent(xGlobalDisplay, None, null);
1776       #endif
1777    #endif
1778       }
1779
1780       return result;
1781    }
1782
1783    bool DisplaySize(Display display, int width, int height)
1784    {
1785       OGLDisplay oglDisplay = display.driverData;
1786
1787       bool result = false;
1788
1789       //printf("Inside DisplaySize\n");
1790 #if defined(__WIN32__) || defined(USEPBUFFER)
1791       OGLSystem oglSystem = display.displaySystem.driverData;
1792       if(display.alphaBlend)
1793       {
1794 #if defined(__WIN32__)
1795          const int attributes[]=
1796          {
1797             /*WGL_TEXTURE_FORMAT_ARB, WGL_TEXTURE_RGBA_ARB,
1798             WGL_TEXTURE_TARGET_ARB, WGL_TEXTURE_2D_ARB, */0
1799          };
1800          int pixelFormat = 0;
1801          if(wglChoosePixelFormatARB)
1802          {
1803             int valid;
1804             int numFormats;
1805             float fAttributes[] = {0,0};
1806             int iAttributes[] =
1807             {
1808                //WGL_DRAW_TO_BITMAP_ARB, GL_TRUE,
1809                WGL_DRAW_TO_PBUFFER_ARB,GL_TRUE,
1810                     WGL_SUPPORT_OPENGL_ARB,GL_TRUE,
1811                     WGL_ACCELERATION_ARB,WGL_FULL_ACCELERATION_ARB,
1812                     WGL_COLOR_BITS_ARB,24,
1813                     WGL_ALPHA_BITS_ARB,8,
1814                     WGL_DEPTH_BITS_ARB,16,
1815                     WGL_STENCIL_BITS_ARB,0,
1816                     WGL_DOUBLE_BUFFER_ARB,GL_FALSE,
1817                     WGL_SAMPLE_BUFFERS_ARB,GL_TRUE,
1818                     WGL_SAMPLES_ARB, 4,                                         // Check For 4x Multisampling
1819                     0,0
1820             };
1821
1822             //Log("Found wglChoosePixelFormatARB\n");
1823
1824             valid = wglChoosePixelFormatARB(oglSystem.hdc,iAttributes,fAttributes,1,&pixelFormat,&numFormats);
1825             if(!valid || !numFormats)
1826             {
1827                //Log("Can't find 4x multi sampling\n");
1828                iAttributes[19] = 2;
1829                valid = wglChoosePixelFormatARB(oglSystem.hdc,iAttributes,fAttributes,1,&pixelFormat,&numFormats);
1830                if(!valid || !numFormats)
1831                {
1832                   // Log("Can't find 2x multi sampling\n");
1833                   iAttributes[16] = 0;
1834                   iAttributes[17] = 0;
1835                   valid = wglChoosePixelFormatARB(oglSystem.hdc,iAttributes,fAttributes,1,&pixelFormat,&numFormats);
1836                   if(!valid || !numFormats)
1837                   {
1838                      int iAttributes[] =
1839                      {
1840                         WGL_DRAW_TO_PBUFFER_ARB,GL_TRUE,
1841                         //WGL_DRAW_TO_BITMAP_ARB,GL_TRUE,
1842                         WGL_SUPPORT_OPENGL_ARB,GL_TRUE,
1843                         WGL_COLOR_BITS_ARB,24,
1844                         WGL_ALPHA_BITS_ARB,8,
1845                         WGL_DEPTH_BITS_ARB,16,
1846                         0,0
1847                      };
1848                      valid = wglChoosePixelFormatARB(oglSystem.hdc,iAttributes,fAttributes,1,&pixelFormat,&numFormats);
1849                   }
1850                }
1851             }
1852             if(valid && numFormats)
1853             {
1854                wglMakeCurrent(null, null);
1855             }
1856          }
1857
1858          wglMakeCurrent( null, null );
1859          wglMakeCurrent( oglDisplay.hdc, oglDisplay.glrc );
1860          if(oglDisplay.hdc && oglDisplay.pBuffer)
1861             wglReleasePbufferDCARB(oglDisplay.pBuffer, oglDisplay.hdc);
1862
1863          wglDestroyPbufferARB(oglDisplay.pBuffer);
1864
1865          if(!useSingleGLContext)
1866             wglMakeCurrent( null, null );
1867
1868          if(oglDisplay.glrc)
1869             wglDeleteContext(oglDisplay.glrc);
1870
1871          oglDisplay.pBuffer = wglCreatePbufferARB(oglSystem.hdc, pixelFormat, width, height, attributes);
1872          oglDisplay.hdc = wglGetPbufferDCARB(oglDisplay.pBuffer);
1873          if((oglDisplay.glrc = wglCreateContext(oglDisplay.hdc)))
1874          {
1875             BITMAPINFO * info;
1876             HDC hdc = GetDC(display.window);
1877
1878             wglShareLists(oglSystem.glrc, oglDisplay.glrc);
1879             wglMakeCurrent(oglDisplay.hdc, oglDisplay.glrc);
1880
1881             //wglQueryPbufferARB(pBuffer, WGL_PBUFFER_WIDTH_ARB, &width);
1882             //wglQueryPbufferARB(pBuffer, WGL_PBUFFER_HEIGHT_ARB, &height);
1883
1884             // glDeleteBuffersARB(2, oglDisplay.imageBuffers);
1885
1886             if((info = (BITMAPINFO *)new0 byte[sizeof(BITMAPINFOHEADER)+sizeof(RGBQUAD)*256]))
1887             {
1888                HBITMAP newBitmap;
1889
1890                if(oglDisplay.memDC) DeleteDC(oglDisplay.memDC);
1891                oglDisplay.memDC = CreateCompatibleDC(hdc);
1892                SetMapMode(oglDisplay.memDC, MM_TEXT);
1893                info->bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
1894                info->bmiHeader.biPlanes = 1;
1895                info->bmiHeader.biCompression = BI_RGB;
1896                info->bmiHeader.biBitCount = 32; //(uint16)GetDeviceCaps(hdc, BITSPIXEL);
1897                info->bmiHeader.biWidth = width;
1898                info->bmiHeader.biHeight = height;
1899                newBitmap = CreateDIBSection(hdc, info, DIB_RGB_COLORS, &oglDisplay.picture, null, 0);
1900                if(newBitmap)
1901                {
1902                   SelectObject(oglDisplay.memDC, newBitmap);
1903                   if(oglDisplay.memBitmap) DeleteObject(oglDisplay.memBitmap);
1904                   /*
1905                   {
1906                      PIXELFORMATDESCRIPTOR pfd = { 0 };
1907                      pfd.nSize = (short)sizeof(pfd);
1908                      pfd.nVersion = 1;
1909                      pfd.dwFlags = PFD_DRAW_TO_BITMAP | PFD_SUPPORT_OPENGL;
1910                      pfd.iPixelType = PFD_TYPE_RGBA;
1911                      pfd.cColorBits = 32;
1912                      //pfd.cAlphaBits = 8;
1913                      pfd.cDepthBits = 24;
1914                      pfd.iLayerType = PFD_MAIN_PLANE;
1915
1916                      oglDisplay.hdc = oglDisplay.memDC;
1917
1918                      pixelFormat = ChoosePixelFormat(oglSystem.hdc, &pfd);
1919                      DescribePixelFormat(oglDisplay.hdc, pixelFormat, sizeof(pfd), &pfd);
1920                      SetPixelFormat(oglDisplay.hdc, pixelFormat, &pfd);
1921
1922                      oglDisplay.glrc = wglCreateContext(oglDisplay.hdc);
1923                      wglShareLists(oglSystem.glrc, oglDisplay.glrc);
1924                      wglMakeCurrent(oglDisplay.hdc, oglDisplay.glrc);
1925                   }
1926                   */
1927                   /*
1928                   {
1929                      const int imageSize = width * height * 4;
1930
1931                      glGenBuffersARB(2, oglDisplay.imageBuffers);
1932
1933                      glBindBufferARB(GL_PIXEL_PACK_BUFFER_ARB, oglDisplay.imageBuffers[0]);
1934                      glBufferDataARB(GL_PIXEL_PACK_BUFFER_ARB, imageSize, null, GL_STREAM_READ);
1935                      // glBindBufferARB(GL_PIXEL_PACK_BUFFER_ARB, oglDisplay.imageBuffers[1]);
1936                      // glBufferDataARB(GL_PIXEL_PACK_BUFFER_ARB, imageSize / 2, null, GL_STREAM_READ);
1937                   }
1938                   */
1939                   oglDisplay.memBitmap = newBitmap;
1940                   oglDisplay.stride = width;
1941
1942                   result = true;
1943                }
1944                delete info;
1945             }
1946             ReleaseDC(display.window, hdc);
1947          }
1948 #elif defined(__unix__) || defined(__APPLE__)
1949       #if defined(__ANDROID__)
1950          result = true;
1951       #else
1952         int attrib[] =
1953         {
1954                 GLX_DOUBLEBUFFER,  True,
1955             GLX_DEPTH_SIZE,    1,
1956                 GLX_RED_SIZE,      8,
1957                 GLX_GREEN_SIZE,    8,
1958                 GLX_BLUE_SIZE,     8,
1959                 GLX_ALPHA_SIZE,    8,
1960                 GLX_STENCIL_SIZE,  1,
1961                 //GLX_DEPTH_SIZE,    24,
1962                 GLX_RENDER_TYPE,   GLX_RGBA_BIT,
1963                 GLX_DRAWABLE_TYPE, GLX_PBUFFER_BIT | GLX_WINDOW_BIT,
1964                 None
1965         };
1966
1967         int PBattrib[] =
1968         {
1969                 GLX_PBUFFER_WIDTH,   width,
1970                 GLX_PBUFFER_HEIGHT,  height,
1971                 GLX_LARGEST_PBUFFER, False,
1972             None
1973         };
1974
1975         // choose a pixel format that meets our minimum requirements
1976         int count = 0;
1977
1978         GLXFBConfig *config = glXChooseFBConfig(xGlobalDisplay, DefaultScreen(xGlobalDisplay), attrib, &count);
1979          if(config)
1980          {
1981             if(oglDisplay.pixmap)
1982             {
1983                XFreePixmap(xGlobalDisplay, oglDisplay.pixmap);
1984                oglDisplay.pixmap = None;
1985             }
1986             if(oglDisplay.shapePixmap)
1987             {
1988                XFreePixmap(xGlobalDisplay, oglDisplay.shapePixmap);
1989                oglDisplay.shapePixmap = None;
1990             }
1991
1992             // Free Shared Memory Pixmap
1993             if(oglDisplay.image)
1994             {
1995                if(oglDisplay.shminfoShape.shmid != -1)
1996                {
1997                   XShmDetach(xGlobalDisplay, &oglDisplay.shminfo);
1998                   if(oglDisplay.shminfo.shmaddr != (void *)-1)
1999                      shmdt(oglDisplay.shminfo.shmaddr);
2000                   shmctl(oglDisplay.shminfo.shmid, IPC_RMID, 0);
2001                }
2002                XDestroyImage(oglDisplay.image);
2003                oglDisplay.image = None;
2004             }
2005             if(oglDisplay.shapeImage)
2006             {
2007                if(oglDisplay.shminfoShape.shmid != -1)
2008                {
2009                   XShmDetach(xGlobalDisplay, &oglDisplay.shminfoShape);
2010                   if(oglDisplay.shminfoShape.shmaddr != (void *)-1)
2011                      shmdt(oglDisplay.shminfoShape.shmaddr);
2012                   shmctl(oglDisplay.shminfoShape.shmid, IPC_RMID, 0);
2013                }
2014                XDestroyImage(oglDisplay.shapeImage);
2015                oglDisplay.shapeImage = None;
2016             }
2017
2018             if(oglDisplay.windowPicture)
2019                XRenderFreePicture(xGlobalDisplay, oglDisplay.windowPicture);
2020             if(oglDisplay.pixmapPicture)
2021                XRenderFreePicture(xGlobalDisplay, oglDisplay.pixmapPicture);
2022
2023             if(oglDisplay.pixmap)
2024                XFreePixmap(xGlobalDisplay, oglDisplay.pixmap);
2025
2026             if(oglDisplay.glContext)
2027                   glXDestroyContext(xGlobalDisplay, oglDisplay.glContext);
2028             if(oglDisplay.pBuffer)
2029                glXDestroyPbuffer(xGlobalDisplay, oglDisplay.pBuffer);
2030
2031                 oglDisplay.pBuffer = glXCreatePbuffer(xGlobalDisplay, config[0], PBattrib);
2032             if(oglDisplay.pBuffer)
2033             {
2034                    oglDisplay.glContext = glXCreateNewContext(xGlobalDisplay, config[0], GLX_RGBA_TYPE, oglSystem.glContext, True);
2035                if(oglDisplay.glContext)
2036                {
2037                   glXMakeCurrent(xGlobalDisplay, None, null);
2038                   glXMakeCurrent(xGlobalDisplay, (GLXDrawable)display.window, oglDisplay.glContext);
2039
2040                   // Initialize Shared Memory Pixmap
2041                   oglDisplay.image = XShmCreateImage(xGlobalDisplay, DefaultVisual(xGlobalDisplay, DefaultScreen(xGlobalDisplay)), 32,
2042                      ZPixmap, null, &oglDisplay.shminfo, width, height);
2043                   if(oglDisplay.image)
2044                   {
2045                      oglDisplay.shminfo.shmid = shmget(IPC_PRIVATE,
2046                         oglDisplay.image->bytes_per_line * oglDisplay.image->height, IPC_CREAT|0777);
2047                      if(oglDisplay.shminfo.shmid != -1)
2048                      {
2049                         oglDisplay.shminfo.shmaddr = shmat(oglDisplay.shminfo.shmid, 0, 0);
2050                         if(oglDisplay.shminfo.shmaddr != (void *)-1)
2051                         {
2052                            oglDisplay.shminfo.readOnly = False;
2053                            if(XShmAttach(xGlobalDisplay, &oglDisplay.shminfo))
2054                            {
2055                               oglDisplay.pixmap = XShmCreatePixmap(xGlobalDisplay, (X11Window)display.window, oglDisplay.shminfo.shmaddr,
2056                                  &oglDisplay.shminfo, width, height, 32);
2057
2058                               // Initialize Shared Memory Shape Pixmap
2059                               oglDisplay.shapeImage = XShmCreateImage(xGlobalDisplay, DefaultVisual(xGlobalDisplay, DefaultScreen(xGlobalDisplay)), 1,
2060                                  ZPixmap, null, &oglDisplay.shminfoShape, width, height);
2061                               if(oglDisplay.shapeImage)
2062                               {
2063                                  oglDisplay.shminfoShape.shmid = shmget(IPC_PRIVATE,
2064                                     oglDisplay.shapeImage->bytes_per_line * oglDisplay.shapeImage->height, IPC_CREAT|0777);
2065                                  if(oglDisplay.shminfoShape.shmid != -1)
2066                                  {
2067                                     oglDisplay.shminfoShape.shmaddr = shmat(oglDisplay.shminfoShape.shmid, 0, 0);
2068                                     if(oglDisplay.shminfoShape.shmaddr != (void *)-1)
2069                                     {
2070                                        oglDisplay.shminfoShape.readOnly = False;
2071                                        if(XShmAttach(xGlobalDisplay, &oglDisplay.shminfoShape))
2072                                        {
2073                                           oglDisplay.shapePixmap = XShmCreatePixmap(xGlobalDisplay, (X11Window)display.window, oglDisplay.shminfoShape.shmaddr,
2074                                              &oglDisplay.shminfoShape, width, height, 1);
2075                                           //oglDisplay.shapePixmap = XCreatePixmap(xGlobalDisplay, (X11Window)display.window, width, height, 1);
2076
2077                                           {
2078                                              XRenderPictureAttributes attributes = { 0 };
2079                                              XRenderPictFormat * format = XRenderFindStandardFormat(xGlobalDisplay, /*PictStandardRGB24*/ PictStandardARGB32);
2080                                              #if !defined(__APPLE__) && !defined(__OLDX__)
2081                                              attributes.repeat = RepeatNormal;
2082                                              #else
2083                                              attributes.repeat = 1;
2084                                              #endif
2085                                              oglDisplay.pixmapPicture = XRenderCreatePicture(xGlobalDisplay, oglDisplay.pixmap, format, CPRepeat, &attributes);
2086                                              oglDisplay.windowPicture = XRenderCreatePicture(xGlobalDisplay, (X11Window)display.window, format, 0, &attributes);
2087                                              oglDisplay.shapePicture = XRenderCreatePicture(xGlobalDisplay, oglDisplay.shapePixmap,
2088                                                 XRenderFindStandardFormat(xGlobalDisplay, PictStandardA1), 0, &attributes);
2089                                           }
2090
2091                                           oglDisplay.picture = oglDisplay.shminfo.shmaddr;
2092                                           oglDisplay.stride = oglDisplay.image->bytes_per_line / 4;
2093
2094                                           result = true;
2095                                        }
2096                                     }
2097                                  }
2098                               }
2099                            }
2100                         }
2101                      }
2102                   }
2103                }
2104             }
2105             XFree(config);
2106          }
2107      #endif
2108 #endif
2109          CreateDisplay(display);
2110 #if defined(__WIN32__)
2111          wglMakeCurrent(oglDisplay.hdc, oglDisplay.glrc);
2112 #elif defined(__unix__) || defined(__APPLE__)
2113       #if defined(__ANDROID__)
2114          width = eglWidth;
2115          height = eglHeight;
2116       #else
2117          glXMakeCurrent(xGlobalDisplay, (GLXDrawable)display.window, oglDisplay.glContext);
2118       #endif
2119 #endif
2120       }
2121       else
2122 #endif
2123          result = true;
2124       if(!result && display.alphaBlend)
2125       {
2126          printf("Alpha blending windows not supported on this display\n");
2127       }
2128       if(!result)
2129          return false;
2130
2131       result = false;
2132
2133       glViewport(0,0,width,height);
2134       glLoadIdentity();
2135       glOrtho(0,width,height,0,0.0,1.0);
2136       displayWidth = display.width = width;
2137       displayHeight = display.height = height;
2138
2139       if(!oglDisplay.flippingBuffer || oglDisplay.flipBufW < width || oglDisplay.flipBufH < height)
2140       {
2141          oglDisplay.flipBufW = width;
2142          oglDisplay.flipBufH = height;
2143 #ifdef _GLES
2144          result = true;
2145 #else
2146          oglDisplay.flippingBuffer = renew oglDisplay.flippingBuffer ColorAlpha [width * height];
2147 #endif
2148       }
2149       if(oglDisplay.flippingBuffer || !width || !height)
2150          result = true;
2151
2152       return result;
2153    }
2154
2155    void DisplayPosition(Display display, int x, int y)
2156    {
2157       OGLDisplay oglDisplay = display.driverData;
2158
2159       oglDisplay.x = x;
2160       oglDisplay.y = y;
2161    }
2162
2163    void SetPalette(Display display, ColorAlpha * palette, bool colorMatch)
2164    {
2165    }
2166
2167    void RestorePalette(Display display)
2168    {
2169    }
2170
2171    void StartUpdate(Display display)
2172    {
2173    }
2174
2175    void EndUpdate(Display display)
2176    {
2177    }
2178
2179    void Scroll(Display display, Box scroll, int x, int y, Extent dirty)
2180    {
2181    }
2182
2183    void Update(Display display, Box updateBox)
2184    {
2185 #if defined(__WIN32__) || defined(USEPBUFFER)
2186       OGLDisplay oglDisplay = display.driverData;
2187 #endif
2188       //Logf("DisplayScreen\n");
2189
2190       glFlush();
2191       glFinish();
2192 #if defined(__WIN32__) || defined(USEPBUFFER)
2193       if(display.alphaBlend)
2194       {
2195          glPixelStorei(GL_PACK_ALIGNMENT, 4);
2196          glPixelStorei(GL_PACK_ROW_LENGTH, oglDisplay.stride);
2197          glPixelStorei(GL_PACK_SKIP_ROWS, 0);
2198          glPixelStorei(GL_PACK_SKIP_PIXELS, 0);
2199          glReadPixels(0,0,display.width,display.height,GL_BGRA_EXT,GL_UNSIGNED_BYTE, oglDisplay.picture);
2200
2201          {
2202 #if defined(__WIN32__)
2203             HDC hdc = GetDC(0);
2204             POINT point = { oglDisplay.x, oglDisplay.y};
2205             POINT srcPoint = { 0, 0 };
2206             BLENDFUNCTION blend = { 0 };
2207             SIZE size;
2208             size.cx = display.width;
2209             size.cy = display.height;
2210             blend.BlendOp = AC_SRC_OVER;
2211             blend.BlendFlags = 0;
2212             blend.SourceConstantAlpha = 255;
2213             blend.AlphaFormat = AC_SRC_ALPHA;
2214
2215             /*
2216             // Process partial images.  Mapping the buffer waits for
2217             // outstanding DMA transfers into the buffer to finish.
2218             glBindBufferARB(GL_PIXEL_PACK_BUFFER_ARB, oglDisplay.imageBuffers[0]);
2219             oglDisplay.pboMemory1 = (byte *)glMapBufferARB(GL_PIXEL_PACK_BUFFER_ARB, GL_READ_ONLY);
2220
2221             // glBindBufferARB(GL_PIXEL_PACK_BUFFER_ARB, oglDisplay.imageBuffers[1]);
2222             // oglDisplay.pboMemory2 = (byte *)glMapBufferARB(GL_PIXEL_PACK_BUFFER_ARB,GL_READ_ONLY);
2223
2224
2225             memcpy(oglDisplay.picture, oglDisplay.pboMemory1, display.width * display.height * 4);
2226             //memcpy(oglDisplay.picture + display.width * display.height * 4 / 2, oglDisplay.pboMemory2, display.width * display.height * 4/ 2);
2227             */
2228
2229             UpdateLayeredWindow(display.window, hdc, &point, &size, oglDisplay.memDC, &srcPoint, 0, &blend, ULW_ALPHA);
2230             /*
2231
2232             // Unmap the image buffers
2233             glBindBufferARB(GL_PIXEL_PACK_BUFFER_ARB, oglDisplay.imageBuffers[0]);
2234             glUnmapBufferARB(GL_PIXEL_PACK_BUFFER_ARB);
2235
2236             // glBindBufferARB(GL_PIXEL_PACK_BUFFER_ARB, oglDisplay.imageBuffers[1]);
2237             // glUnmapBufferARB(GL_PIXEL_PACK_BUFFER_ARB);
2238
2239             // Bind two different buffer objects and start the glReadPixels
2240             // asynchronously. Each call will return directly after
2241             // starting the DMA transfer.
2242             glBindBufferARB(GL_PIXEL_PACK_BUFFER_ARB, oglDisplay.imageBuffers[0]);
2243             glReadPixels(0, 0, display.width, display.height, GL_BGRA, GL_UNSIGNED_BYTE, 0);
2244
2245             // glBindBufferARB(GL_PIXEL_PACK_BUFFER_ARB, oglDisplay.imageBuffers[1]);
2246             // glReadPixels(0, display.height/2, display.width, display.height/2, GL_BGRA, GL_UNSIGNED_BYTE, 0);
2247             */
2248
2249             ReleaseDC(0, hdc);
2250 #elif defined(__unix__) || defined(__APPLE__)
2251       #if defined(__ANDROID__)
2252       #else
2253             XTransform transform =
2254             {
2255                {
2256                   { (int)(1.0f * (1<<16)), (int)(0.0f * (1<<16)),  (int)(0 * (1 << 16)) },
2257                   { (int)(0.0f),           (int)(-1.0f * (1<<16)), (int)(0 * (1<<16)) },
2258                   { (int)(0.0f * (1<<16)), (int)(0.0f * (1<<16)),  (int)(1.0f * (1<<16)) }
2259                }
2260             };
2261             XRenderSetPictureTransform(xGlobalDisplay, oglDisplay.pixmapPicture, &transform);
2262             XRenderComposite(xGlobalDisplay, PictOpSrc, oglDisplay.pixmapPicture, None, oglDisplay.shapePicture, 0, 0, 0, 0, 0, 0, display.width, display.height);
2263             XRenderComposite(xGlobalDisplay, PictOpSrc, oglDisplay.pixmapPicture, None, oglDisplay.windowPicture, 0, 0, 0, 0, 0, 0, display.width, display.height);
2264             #if !defined(__APPLE__) && !defined(__OLDX__)
2265             XShapeCombineMask(xGlobalDisplay, (X11Window)display.window, ShapeInput, 0, 0, oglDisplay.shapePixmap, ShapeSet);
2266             #else
2267             XShapeCombineMask(xGlobalDisplay, display.window, 2, 0, 0, oglDisplay.shapePixmap, ShapeSet);
2268             #endif
2269             XFlush(xGlobalDisplay);
2270      #endif
2271 #endif
2272          }
2273       }
2274       else
2275 #endif
2276       {
2277 #if defined(__WIN32__)
2278          //wglSwapLayerBuffers(oglDisplay.hdc,WGL_SWAP_MAIN_PLANE);
2279          SwapBuffers(oglDisplay.hdc);
2280 #elif defined(__unix__) || defined(__APPLE__)
2281       #if defined(__ANDROID__)
2282          eglSwapBuffers(eglDisplay, eglSurface);
2283       #else
2284          glXSwapBuffers(xGlobalDisplay, (GLXDrawable)display.window);
2285       #endif
2286 #endif
2287       }
2288       //Logf("Out of DisplayScreen\n");
2289    }
2290
2291    void FreeBitmap(DisplaySystem displaySystem, Bitmap bitmap)
2292    {
2293       if(bitmap.driverData)
2294       {
2295          GLuint tex = (GLuint)(uintptr)bitmap.driverData;
2296          glDeleteTextures(1, &tex);
2297          bitmap.driverData = 0;
2298       }
2299       bitmap.driver = ((subclass(DisplayDriver))class(LFBDisplayDriver));
2300    }
2301
2302    bool AllocateBitmap(DisplaySystem displaySystem, Bitmap bitmap, int width, int height, int stride, PixelFormat format, bool allocatePalette)
2303    {
2304       OGLSystem oglSystem = displaySystem.driverData;
2305       bool result = false;
2306       Bitmap mipMap { };
2307       GLuint glBitmap = 0;
2308
2309       uint w = width, h = height;
2310       if(oglSystem.pow2textures)
2311       {
2312          w = pow2i(w);
2313          h = pow2i(h);
2314       }
2315       w = Min(w, oglSystem.maxTextureSize);
2316       h = Min(h, oglSystem.maxTextureSize);
2317
2318       glGenTextures(1, &glBitmap);
2319       glBindTexture(GL_TEXTURE_2D, glBitmap);
2320
2321       glPixelStorei( GL_UNPACK_ALIGNMENT, 1 );
2322
2323       glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
2324       glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
2325
2326       glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
2327       glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
2328
2329       glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
2330
2331       mipMap.Allocate(null, w, h, w, pixelFormatRGBA, false);
2332
2333       // glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, mipMap.picture);
2334       glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, mipMap.picture);
2335
2336       delete mipMap;
2337
2338       bitmap.driverData = (void *)(uintptr)glBitmap;
2339       bitmap.driver = displaySystem.driver;
2340       bitmap.width = w;
2341       bitmap.height = h;
2342
2343       result = true;
2344       return result;
2345    }
2346
2347    bool MakeDDBitmap(DisplaySystem displaySystem, Bitmap bitmap, bool mipMaps)
2348    {
2349       bool result = false;
2350       OGLSystem oglSystem = displaySystem.driverData;
2351
2352       // Pre process the bitmap... First make it 32 bit
2353       if(/*bitmap.pixelFormat == pixelFormatRGBA || */bitmap.Convert(null, pixelFormat888, null))
2354       {
2355          int c, level;
2356          uint w = bitmap.width, h = bitmap.height;
2357          GLuint glBitmap = 0;
2358          if(oglSystem.pow2textures)
2359          {
2360             w = pow2i(w);
2361             h = pow2i(h);
2362          }
2363          w = Min(w, oglSystem.maxTextureSize);
2364          h = Min(h, oglSystem.maxTextureSize);
2365
2366          if(mipMaps)
2367          {
2368             while(w * 2 < h) w *= 2;
2369             while(h * 2 < w) h *= 2;
2370          }
2371
2372          // Switch ARGB to RGBA
2373          //if(bitmap.format != pixelFormatRGBA)
2374          {
2375             for(c=0; c<bitmap.size; c++)
2376             {
2377                // ((ColorRGBA *)bitmap.picture)[c] = ((ColorAlpha *)bitmap.picture)[c];
2378                // TODO:
2379                ColorAlpha color = ((ColorAlpha *)bitmap.picture)[c];
2380                ((ColorRGBA *)bitmap.picture)[c] = ColorRGBA { color.color.r, color.color.g, color.color.b, color.a };
2381             }
2382          }
2383          bitmap.pixelFormat = pixelFormat888;
2384
2385          glGetError();
2386          glGenTextures(1, &glBitmap);
2387          if(glBitmap == 0)
2388          {
2389             //int error = glGetError();
2390             return false;
2391          }
2392
2393          glBindTexture(GL_TEXTURE_2D, glBitmap);
2394          glPixelStorei( GL_UNPACK_ALIGNMENT, 1 );
2395
2396          glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, mipMaps ? GL_LINEAR_MIPMAP_LINEAR : GL_LINEAR);
2397          glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
2398
2399          //glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
2400
2401          //glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
2402          //glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
2403
2404          glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
2405          glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
2406
2407          glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
2408
2409          result = true;
2410
2411          for(level = 0; result && (w >= 1 || h >= 1); level++, w >>= 1, h >>= 1)
2412          {
2413             Bitmap mipMap;
2414             if(!w) w = 1;
2415             if(!h) h = 1;
2416             if(bitmap.width != w || bitmap.height != h)
2417             {
2418                mipMap = Bitmap { };
2419                if(mipMap.Allocate(null, w, h, w, bitmap.pixelFormat, false))
2420                {
2421                   Surface mipSurface = mipMap.GetSurface(0,0,null);
2422                   mipSurface.Filter(bitmap, 0,0,0,0, w, h, bitmap.width, bitmap.height);
2423                   delete mipSurface;
2424                }
2425                else
2426                {
2427                   result = false;
2428                   delete mipMap;
2429                }
2430             }
2431             else
2432                mipMap = bitmap;
2433
2434             if(result)
2435             {
2436                int error;
2437                //int width = 0;
2438                glGetError();
2439                // glTexImage2D(GL_TEXTURE_2D, level, GL_RGBA8, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, mipMap.picture);
2440                glTexImage2D(GL_TEXTURE_2D, level, GL_RGBA, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, mipMap.picture);
2441                //printf("Calling glTexImage2D\n");
2442                //glGetTexLevelParameteriv(GL_TEXTURE_2D, level, GL_TEXTURE_WIDTH, &width);
2443                //printf("width = %d (Should be %d, %d)\n", width, w, h);
2444                if((error = glGetError()))
2445                {
2446                   //Logf("OpenGL Bitmap MakeDD error: %d...\n", error);
2447                   //printf("OpenGL Bitmap MakeDD error: %d...\n", error);
2448                   result = false;
2449                }
2450             }
2451             if(mipMap != bitmap)
2452                delete mipMap;
2453             if(!mipMaps) break;
2454          }
2455
2456          if(!bitmap.keepData)
2457             bitmap.driver.FreeBitmap(bitmap.displaySystem, bitmap);
2458          bitmap.driverData = (void *)(uintptr)glBitmap;
2459          bitmap.driver = displaySystem.driver;
2460
2461          if(!result)
2462             FreeBitmap(displaySystem, bitmap);
2463          else if(oglSystem.loadingFont)
2464          {
2465             glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
2466             glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
2467             oglSystem.loadingFont = false;
2468          }
2469       }
2470       return result;
2471    }
2472
2473    void ReleaseSurface(Display display, Surface surface)
2474    {
2475       glDisable(GL_SCISSOR_TEST);
2476       delete surface.driverData;
2477       surface.driverData = null;
2478    }
2479
2480    bool GetBitmapSurface(DisplaySystem displaySystem, Surface surface, Bitmap bitmap, int x, int y, Box clip)
2481    {
2482       return false;
2483    }
2484
2485    bool GetSurface(Display display, Surface surface, int x,int y, Box clip)
2486    {
2487       bool result = false;
2488       OGLSurface oglSurface = surface.driverData = OGLSurface { };
2489
2490       //Logf("GetSurface\n");
2491
2492       if(oglSurface)
2493       {
2494          if(displayWidth != display.width || displayHeight != display.height)
2495          {
2496             displayWidth = display.width;
2497             displayHeight = display.height;
2498
2499             glViewport(0,0,display.width,display.height);
2500             glLoadIdentity();
2501             glOrtho(0,display.width,display.height,0,0.0,1.0);
2502          }
2503
2504          surface.offset.x = x;
2505          surface.offset.y = y;
2506          surface.unclippedBox = surface.box = clip;
2507          oglSurface.bitmapMult[0] = 1;
2508          oglSurface.bitmapMult[1] = 1;
2509          oglSurface.bitmapMult[2] = 1;
2510          oglSurface.bitmapMult[3] = 1;
2511
2512          glEnable(GL_SCISSOR_TEST);
2513          glScissor(
2514             x+clip.left,
2515             (display.height) -(y+clip.bottom)-1,
2516             clip.right-clip.left+1,
2517             clip.bottom-clip.top+1);
2518          result = true;
2519       }
2520       return result;
2521    }
2522
2523    void Clip(Display display, Surface surface, Box clip)
2524    {
2525       Box box;
2526
2527       //Logf("Clip\n");
2528
2529       if(clip != null)
2530       {
2531          box = clip;
2532          box.Clip(surface.unclippedBox);
2533          surface.box = box;
2534       }
2535       else
2536          box = surface.box = surface.unclippedBox;
2537       box.left += surface.offset.x;
2538       box.top  += surface.offset.y;
2539       box.right+= surface.offset.x;
2540       box.bottom += surface.offset.y;
2541
2542       glScissor(
2543          box.left,display.height - box.bottom - 1,
2544          box.right-box.left+1, box.bottom-box.top+1);
2545    }
2546
2547    bool GrabScreen(Display display, Bitmap bitmap, int x, int y, unsigned int w, unsigned int h)
2548    {
2549       bool result = false;
2550       OGLDisplay oglDisplay = display.driverData;
2551       ColorAlpha * flippingBuffer = oglDisplay.flippingBuffer;
2552
2553       if(oglDisplay.flippingBuffer)
2554       {
2555          if(bitmap.pixelFormat != pixelFormat888 || bitmap.width < w || bitmap.height < h)
2556          {
2557             bitmap.Free();
2558             bitmap.Allocate(null, w,h,w, pixelFormat888, false);
2559          }
2560          if(bitmap)
2561          {
2562             uint row;
2563
2564             glPixelStorei(GL_PACK_ALIGNMENT, 4);
2565             glPixelStorei(GL_PACK_ROW_LENGTH, bitmap.stride);
2566             glPixelStorei(GL_PACK_SKIP_ROWS, 0);
2567             glPixelStorei(GL_PACK_SKIP_PIXELS, 0);
2568             glReadPixels(x,display.height-h-y,w,h,GL_BGRA_EXT,GL_UNSIGNED_BYTE, flippingBuffer);
2569
2570             // Need a flip...
2571             for(row = 0; row<h; row++)
2572                CopyBytesBy4(((ColorAlpha *)bitmap.picture) + row * w, ((ColorAlpha *)flippingBuffer) + (h-row-1) * w, w);
2573             result = true;
2574          }
2575       }
2576       return result;
2577    }
2578
2579    void SetForeground(Display display, Surface surface, ColorAlpha color)
2580    {
2581       OGLSurface oglSurface = surface.driverData;
2582
2583       //Logf("SetForeground\n");
2584
2585       oglSurface.foreground[0] = color.color.r/255.0f;
2586       oglSurface.foreground[1] = color.color.g/255.0f;
2587       oglSurface.foreground[2] = color.color.b/255.0f;
2588       //oglSurface.foreground[3] = 1.0f;
2589       oglSurface.foreground[3] = color.a/255.0f;
2590
2591       //if(!oglSurface.foreground[3])printf("bug");
2592    }
2593
2594    void SetBackground(Display display, Surface surface, ColorAlpha color)
2595    {
2596       OGLSurface oglSurface = surface.driverData;
2597
2598       //Logf("SetBackground\n");
2599
2600       oglSurface.background[0] = color.color.r/255.0f;
2601       oglSurface.background[1] = color.color.g/255.0f;
2602       oglSurface.background[2] = color.color.b/255.0f;
2603       //oglSurface.background[3] = 1.0;
2604       oglSurface.background[3] = color.a/255.0f;
2605    }
2606
2607    void SetBlitTint(Display display, Surface surface, ColorAlpha color)
2608    {
2609       OGLSurface oglSurface = surface.driverData;
2610
2611       oglSurface.bitmapMult[0] = color.color.r/255.0f;
2612       oglSurface.bitmapMult[1] = color.color.g/255.0f;
2613       oglSurface.bitmapMult[2] = color.color.b/255.0f;
2614       oglSurface.bitmapMult[3] = color.a/255.0f;
2615    }
2616
2617    ColorAlpha GetPixel(Display display, Surface surface,int x,int y)
2618    {
2619       return 0;
2620    }
2621
2622    void PutPixel(Display display, Surface surface,int x,int y)
2623    {
2624       OGLSurface oglSurface = surface.driverData;
2625
2626       //Logf("PutPixel\n");
2627
2628       glColor4fv(oglSurface.foreground);
2629       glBegin(GL_POINTS);
2630       // glVertex2i(x+surface.offset.x, y+surface.offset.y);
2631       glVertex2f(x+surface.offset.x + 0.5f, y+surface.offset.y + 0.5f);
2632
2633       glEnd();
2634    }
2635
2636    void DrawLine(Display display, Surface surface, int _x1, int _y1, int _x2, int _y2)
2637    {
2638       OGLSurface oglSurface = surface.driverData;
2639       float x1 = _x1, x2 = _x2, y1 = _y1, y2 = _y2;
2640       if(_x1 == _x2)
2641       {
2642          if(_y2 >= _y1)
2643             y2 += 1;
2644          else
2645             y1 += 1;
2646       }
2647       else if(_y1 == _y2)
2648       {
2649          if(_x2 >= _x1)
2650             x2 += 1;
2651          else
2652             x1 += 1;
2653       }
2654       x1 += surface.offset.x;
2655       y1 += surface.offset.y;
2656       x2 += surface.offset.x;
2657       y2 += surface.offset.y;
2658
2659       //Logf("Line\n");
2660
2661       glColor4fv(oglSurface.foreground);
2662       glBegin(GL_LINES);
2663 #ifdef __ANDROID__
2664       if(stippleEnabled)
2665       {
2666          glTexCoord2f(0.5f, 0);
2667          glVertex2f(x1 + 0.5f, y1 + 0.5f);
2668          glTexCoord2f(Max(x2-x1, y2-y1) + 0.5f, 0);
2669          glVertex2f(x2 + 0.5f, y2 + 0.5f);
2670       }
2671       else
2672 #endif
2673       {
2674          /*
2675          glVertex2i(x1, y1);
2676          glVertex2i(x2, y2);
2677          */
2678          glVertex2f(x1 + 0.5f, y1 + 0.5f);
2679          glVertex2f(x2 + 0.5f, y2 + 0.5f);
2680       }
2681
2682       glEnd();
2683    }
2684
2685    void Rectangle(Display display, Surface surface,int x1,int y1,int x2,int y2)
2686    {
2687       OGLSurface oglSurface = surface.driverData;
2688       x1 += surface.offset.x;
2689       y1 += surface.offset.y;
2690       x2 += surface.offset.x;
2691       y2 += surface.offset.y;
2692
2693       //Logf("Rectangle\n");
2694
2695       glColor4fv(oglSurface.foreground);
2696 #ifdef __ANDROID__
2697       if(stippleEnabled)
2698       {
2699          glBegin(GL_LINES);
2700
2701          glTexCoord2f(0.5f, 0);
2702          glVertex2f(x1 + 0.5f, y1 + 0.5f);
2703          glTexCoord2f(y2-y1 + 0.5f, 0);
2704          glVertex2f(x1 + 0.5f, y2 + 0.5f);
2705
2706          glTexCoord2f(0.5f, 0);
2707          glVertex2f(x1 + 0.5f, y2 + 0.5f);
2708          glTexCoord2f(x2 - x1 + 0.5f, 0);
2709          glVertex2f(x2 + 0.5f, y2 + 0.5f);
2710
2711          glTexCoord2f(0.5f, 0);
2712          glVertex2f(x2 + 0.5f, y2 + 0.5f);
2713          glTexCoord2f(y1 - y2 + 0.5f, 0);
2714          glVertex2f(x2 + 0.5f, y1 + 0.5f);
2715
2716          glTexCoord2f(0.5f, 0);
2717          glVertex2f(x2 + 0.5f, y1 + 0.5f);
2718          glTexCoord2f(x1 - x2 + 0.5f, 0);
2719          glVertex2f(x1 + 0.5f, y1 + 0.5f);
2720       }
2721       else
2722 #endif
2723       {
2724          glBegin(GL_LINE_LOOP);
2725          /*
2726          glVertex2i(x1, y1);
2727          glVertex2i(x1, y2);
2728          glVertex2i(x2, y2);
2729          glVertex2i(x2, y1);
2730          */
2731          glVertex2f(x1 + 0.5f, y1 + 0.5f);
2732          glVertex2f(x1 + 0.5f, y2 + 0.5f);
2733          glVertex2f(x2 + 0.5f, y2 + 0.5f);
2734          glVertex2f(x2 + 0.5f, y1 + 0.5f);
2735       }
2736       glEnd();
2737    }
2738
2739    void Area(Display display, Surface surface,int x1,int y1,int x2,int y2)
2740    {
2741       OGLSurface oglSurface = surface.driverData;
2742       //Logf("Area\n");
2743
2744       glColor4fv(oglSurface.background);
2745       glRecti(x1+surface.offset.x, y1+surface.offset.y,
2746               x2+surface.offset.x + 1, y2+surface.offset.y + 1);
2747
2748       /*
2749       glRectf(x1+surface.offset.x, y1+surface.offset.y,
2750               x2+surface.offset.x + 1, y2+surface.offset.y + 1);
2751       */
2752    }
2753
2754    void Clear(Display display, Surface surface, ClearType type)
2755    {
2756       OGLDisplay oglDisplay = display.driverData;
2757       OGLSurface oglSurface = surface.driverData;
2758
2759       //Logf("Clear\n");
2760       if(type != depthBuffer)
2761          glClearColor(oglSurface.background[0], oglSurface.background[1], oglSurface.background[2], oglSurface.background[3]);
2762       if(type != colorBuffer && !oglDisplay.depthWrite)
2763       {
2764          glDepthMask((byte)bool::true);
2765       }
2766       glClear(((type != depthBuffer) ? GL_COLOR_BUFFER_BIT : 0) |
2767               ((type != colorBuffer) ? GL_DEPTH_BUFFER_BIT : 0));
2768       if(type != colorBuffer && !oglDisplay.depthWrite)
2769       {
2770          glDepthMask((byte)bool::false);
2771       }
2772    }
2773
2774    bool ConvertBitmap(DisplaySystem displaySystem, Bitmap bitmap, PixelFormat format, ColorAlpha * palette)
2775    {
2776       return true;
2777    }
2778
2779    void Blit(Display display, Surface surface, Bitmap bitmap, int dx, int dy, int sx, int sy, int w, int h)
2780    {
2781       OGLSurface oglSurface = surface.driverData;
2782
2783 #if !defined(__OLDX__)
2784          // WHY DO WE HAVE GL_ONE HERE ?
2785          /*if(glBlendFuncSeparate && !oglSurface.writingText)
2786             glBlendFuncSeparate(GL_ONE, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA);*/
2787 #endif
2788
2789       if(!oglSurface.writingText)
2790       {
2791          // glTranslatef(-0.375f, -0.375f, 0.0f);
2792          glEnable(GL_TEXTURE_2D);
2793          glColor4fv(oglSurface.bitmapMult);
2794       }
2795       else if(oglSurface.xOffset)
2796          glTranslated(oglSurface.xOffset / 64.0/*-0.375*/, 0.0, 0.0);
2797
2798       glBindTexture(GL_TEXTURE_2D, (GLuint)(uintptr)bitmap.driverData);
2799       glBegin(GL_QUADS);
2800
2801       if(h < 0)
2802       {
2803          glTexCoord2f((float)sx/ bitmap.width, (float)(sy-h)/ bitmap.height);
2804          glVertex2i(dx+surface.offset.x, dy+surface.offset.y);
2805          glTexCoord2f((float)(sx+w) / bitmap.width, (float)(sy-h)/ bitmap.height);
2806          glVertex2i(dx+w+surface.offset.x, dy+surface.offset.y);
2807          glTexCoord2f((float)(sx+w)/ bitmap.width, (float)sy/ bitmap.height);
2808          glVertex2i(dx+w+surface.offset.x, dy-h+surface.offset.y);
2809          glTexCoord2f((float)sx / bitmap.width, (float)sy/ bitmap.height);
2810          glVertex2i(dx+surface.offset.x, dy-h+surface.offset.y);
2811       }
2812       else
2813       {
2814          /*
2815          glTexCoord2f((float)sx / bitmap.width, (float)sy/ bitmap.height);
2816          glVertex2i(dx+surface.offset.x, dy+surface.offset.y);
2817          glTexCoord2f((float)(sx+w)/ bitmap.width, (float)sy/ bitmap.height);
2818          glVertex2i(dx+w+surface.offset.x, dy+surface.offset.y);
2819          glTexCoord2f((float)(sx+w) / bitmap.width, (float)(sy+h)/ bitmap.height);
2820          glVertex2i(dx+w+surface.offset.x, dy+h+surface.offset.y);
2821          glTexCoord2f((float)sx/ bitmap.width, (float)(sy+h)/ bitmap.height);
2822          glVertex2i(dx+surface.offset.x, dy+h+surface.offset.y);
2823          */
2824
2825          glTexCoord2f((float)sx / bitmap.width, (float)sy/ bitmap.height);
2826          glVertex2f((float)dx+surface.offset.x, (float)dy+surface.offset.y);
2827          glTexCoord2f((float)(sx+w)/ bitmap.width, (float)sy/ bitmap.height);
2828          glVertex2f((float)dx+w+surface.offset.x, (float)dy+surface.offset.y);
2829          glTexCoord2f((float)(sx+w) / bitmap.width, (float)(sy+h)/ bitmap.height);
2830          glVertex2f((float)dx+w+surface.offset.x, (float)dy+h+surface.offset.y);
2831          glTexCoord2f((float)sx/ bitmap.width, (float)(sy+h)/ bitmap.height);
2832          glVertex2f((float)dx+surface.offset.x, (float)dy+h+surface.offset.y);
2833       }
2834       glEnd();
2835
2836       if(!oglSurface.writingText)
2837       {
2838          glDisable(GL_TEXTURE_2D);
2839
2840          //glTranslate(0.375, 0.375, 0.0);
2841       }
2842       else if(oglSurface.xOffset)
2843          glTranslated(-oglSurface.xOffset / 64.0/*+0.375*/, 0.0, 0.0);
2844
2845 #if !defined(__OLDX__)
2846          /*if(glBlendFuncSeparate && !oglSurface.writingText)
2847             glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA);*/
2848 #endif
2849    }
2850
2851    void Stretch(Display display, Surface surface, Bitmap bitmap, int dx, int dy, int sx, int sy, int w, int h, int sw, int sh)
2852    {
2853       OGLSurface oglSurface = surface.driverData;
2854
2855       //glTranslate(-0.375, -0.375, 0.0);
2856
2857       //Logf("Stretch\n");
2858
2859 #if !defined(__OLDX__)
2860       /*if(glBlendFuncSeparate)
2861          glBlendFuncSeparate(GL_ONE, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA);*/
2862 #endif
2863
2864       glEnable(GL_TEXTURE_2D);
2865       glBindTexture(GL_TEXTURE_2D, (GLuint)(uintptr)bitmap.driverData);
2866
2867       glColor4fv(oglSurface.bitmapMult);
2868
2869       glBegin(GL_QUADS);
2870
2871       if(h < 0)
2872       {
2873          glTexCoord2f((float)(sx)/ bitmap.width, (float)(sy+sh)/ bitmap.height);
2874          glVertex2i(dx+surface.offset.x, dy+surface.offset.y);
2875
2876          glTexCoord2f((float)(sx+sw) / bitmap.width, (float)(sy+sh)/ bitmap.height);
2877          glVertex2i(dx+w+surface.offset.x, dy+surface.offset.y);
2878
2879          glTexCoord2f((float)(sx+sw)/ bitmap.width, (float)(sy)/ bitmap.height);
2880          glVertex2i(dx+w+surface.offset.x, dy-h+surface.offset.y);
2881
2882          glTexCoord2f((float)(sx) / bitmap.width, (float)(sy)/ bitmap.height);
2883          glVertex2i(dx+surface.offset.x, dy-h+surface.offset.y);
2884       }
2885       else
2886       {
2887          glTexCoord2f((float)(sx) / bitmap.width, (float)(sy)/ bitmap.height);
2888          glVertex2i(dx+surface.offset.x, dy+surface.offset.y);
2889
2890          glTexCoord2f((float)(sx+sw)/ bitmap.width, (float)(sy)/ bitmap.height);
2891          glVertex2i(dx+w+surface.offset.x, dy+surface.offset.y);
2892
2893          glTexCoord2f((float)(sx+sw) / bitmap.width, (float)(sy+sh)/ bitmap.height);
2894          glVertex2i(dx+w+surface.offset.x, dy+h+surface.offset.y);
2895
2896          glTexCoord2f((float)(sx)/ bitmap.width, (float)(sy+sh)/ bitmap.height);
2897          glVertex2i(dx+surface.offset.x, dy+h+surface.offset.y);
2898       }
2899
2900       glEnd();
2901
2902       glDisable(GL_TEXTURE_2D);
2903
2904       //glTranslate(0.375, 0.375, 0.0);
2905 #if !defined(__OLDX__)
2906       /*if(glBlendFuncSeparate)
2907          glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA);*/
2908 #endif
2909
2910    }
2911
2912    void Filter(Display display, Surface surface, Bitmap bitmap, int dx, int dy, int sx, int sy, int w, int h, int sw, int sh)
2913    {
2914       Stretch(display, surface, bitmap, dx, dy, sx, sy, w, h, sw, sh);
2915    }
2916
2917    void StretchDI(Display display, Surface surface, Bitmap bitmap, int dx, int dy, int sx, int sy, int w, int h, int sw, int sh)
2918    {
2919       float s2dw,s2dh,d2sw,d2sh;
2920       //bool flipX = false, flipY = false;
2921
2922       //Logf("StretchDI\n");
2923
2924       if(Sgn(w) != Sgn(sw))
2925       {
2926          w = Abs(w);
2927          sw = Abs(sw);
2928          //flipX = true;
2929       }
2930       if(Sgn(h) != Sgn(sh))
2931       {
2932          h = Abs(h);
2933          sh = Abs(sh);
2934          //flipY = true;
2935       }
2936
2937       s2dw=(float)w / sw;
2938       s2dh=(float)h / sh;
2939       d2sw=(float)sw / w;
2940       d2sh=(float)sh / h;
2941
2942       //Clip against the edges of the source
2943       if(sx<0)
2944       {
2945          dx+=(int)((0-sx) * s2dw);
2946          w-=(int)((0-sx) * s2dw);
2947          sw-=0-sx;
2948          sx=0;
2949       }
2950       if(sy<0)
2951       {
2952          dy+=(int)((0-sy) * s2dh);
2953          h-=(int)((0-sy) * s2dh);
2954
2955          sh-=0-sy;
2956          sy=0;
2957       }
2958       if(sx+sw>bitmap.width-1)
2959       {
2960          w-=(int)((sx+sw-(bitmap.width-1)-1)*s2dw);
2961          sw-=sx+sw-(bitmap.width-1)-1;
2962       }
2963       if(sy+sh>(bitmap.height-1))
2964       {
2965          h-=(int)((sy+sh-(bitmap.height-1)-1)*s2dh);
2966          sh-=sy+sh-(bitmap.height-1)-1;
2967       }
2968       //Clip against the edges of the surfaceination
2969       if(dx<surface.box.left)
2970       {
2971          //if(!flip)
2972          sx+=(int)((surface.box.left-dx)*d2sw);
2973          sw-=(int)((surface.box.left-dx)*d2sw);
2974          w-=surface.box.left-dx;
2975          dx=surface.box.left;
2976       }
2977       if(dy<surface.box.top)
2978       {
2979          sy+=(int)((surface.box.top-dy)*d2sh);
2980          sh-=(int)((surface.box.top-dy)*d2sh);
2981          h-=surface.box.top-dy;
2982          dy=surface.box.top;
2983       }
2984       if(dx+w>surface.box.right)
2985       {
2986          //if(flip) sx+=(int)((dx+w-surface.box.right-1)*d2sw);
2987          sw-=(int)((dx+w-surface.box.right-1)*d2sw);
2988          w-=dx+w-surface.box.right-1;
2989       }
2990       if(dy+h>surface.box.bottom)
2991       {
2992          sh-=(int)((dy+h-surface.box.bottom-1)*d2sh);
2993          h-=dy+h-surface.box.bottom-1;
2994       }
2995       if((w<=0)||(h<=0)||(sw<=0)||(sh<=0)) return;
2996
2997       dx += surface.offset.x;
2998       dy += surface.offset.y;
2999
3000       if(bitmap.pixelFormat == pixelFormat888 && !bitmap.paletteShades)
3001       {
3002          glPixelStorei(GL_UNPACK_ALIGNMENT, 4);
3003          glPixelStorei(GL_UNPACK_ROW_LENGTH, bitmap.stride);
3004          glPixelStorei(GL_UNPACK_SKIP_PIXELS, sx);
3005          glPixelStorei(GL_UNPACK_SKIP_ROWS, sy);
3006          glRasterPos2d(dx,dy);
3007          //glPixelZoom(flipX ? -s2dw : s2dw, flipY ? s2dh : -s2dh);
3008          glPixelZoom(s2dw, -s2dh);
3009          glDrawPixels(sw,sh,GL_BGRA_EXT,GL_UNSIGNED_BYTE, bitmap.picture);
3010          glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
3011          glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
3012          glPixelStorei(GL_UNPACK_SKIP_PIXELS, 0);
3013          glPixelStorei(GL_UNPACK_SKIP_ROWS, 0);
3014       }
3015    }
3016
3017    void BlitDI(Display display, Surface surface, Bitmap bitmap, int dx, int dy, int sx, int sy, int w, int h)
3018    {
3019       //Logf("BlitDI\n");
3020
3021       //Clip against the edges of the source
3022       if(sx<0)
3023       {
3024          dx+=-sx;
3025          w-=-sx;
3026          sx=0;
3027       }
3028       if(sy<0)
3029       {
3030          dy+=0-sy;
3031          h-=0-sy;
3032          sy=0;
3033       }
3034       if(sx+w>bitmap.width-1)
3035          w-=sx+w-(bitmap.width-1)-1;
3036       if(sy+h>bitmap.height-1)
3037          h-=sy+h-(bitmap.height-1)-1;
3038       //Clip against the edges of the surfaceination
3039       if(dx<surface.box.left)
3040       {
3041          //if(!flip)
3042          sx+=surface.box.left-dx;
3043          w-=surface.box.left-dx;
3044          dx=surface.box.left;
3045       }
3046       if(dy<surface.box.top)
3047       {
3048          sy+=surface.box.top-dy;
3049          h-=surface.box.top-dy;
3050          dy=surface.box.top;
3051       }
3052       if(dx+w>surface.box.right)
3053       {
3054          //if(flip) sx+=dx+w-surface.box.right-1;
3055          w-=dx+w-surface.box.right-1;
3056       }
3057       if(dy+h>surface.box.bottom)
3058          h-=dy+h-surface.box.bottom-1;
3059       if((w<=0)||(h<=0))
3060          return;
3061
3062       dx += surface.offset.x;
3063       dy += surface.offset.y;
3064
3065       if(bitmap.pixelFormat == pixelFormat888 && !bitmap.paletteShades)
3066       {
3067          glPixelStorei(GL_UNPACK_ALIGNMENT, 4);
3068          glPixelStorei(GL_UNPACK_ROW_LENGTH, bitmap.stride);
3069          glPixelStorei(GL_UNPACK_SKIP_PIXELS, sx);
3070          glPixelStorei(GL_UNPACK_SKIP_ROWS, sy);
3071          glRasterPos2d(dx,dy);
3072          glPixelZoom(1,-1);
3073          glDrawPixels(w,h,GL_BGRA_EXT,GL_UNSIGNED_BYTE, bitmap.picture);
3074          glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
3075          glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
3076          glPixelStorei(GL_UNPACK_SKIP_PIXELS, 0);
3077          glPixelStorei(GL_UNPACK_SKIP_ROWS, 0);
3078       }
3079    }
3080
3081    void FilterDI(Display display, Surface surface, Bitmap bitmap, int dx, int dy, int sx, int sy, int w, int h, int sw, int sh)
3082    {
3083       StretchDI(display, surface, bitmap, dx, dy, sx, sy, w, h, sw, sh);
3084    }
3085
3086    void UnloadFont(DisplaySystem displaySystem, Font font)
3087    {
3088       ((subclass(DisplayDriver))class(LFBDisplayDriver)).UnloadFont(displaySystem, font);
3089    }
3090
3091    Font LoadFont(DisplaySystem displaySystem, const char * faceName, float size, FontFlags flags)
3092    {
3093       Font font;
3094       OGLSystem oglSystem = displaySystem.driverData;
3095       oglSystem.loadingFont = true;
3096       font = ((subclass(DisplayDriver))class(LFBDisplayDriver)).LoadFont(displaySystem, faceName, size, flags);
3097       return font;
3098    }
3099
3100    void FontExtent(DisplaySystem displaySystem, Font font, const char * text, int len, int * width, int * height)
3101    {
3102       ((subclass(DisplayDriver))class(LFBDisplayDriver)).FontExtent(displaySystem, font, text, len, width, height);
3103    }
3104
3105    void WriteText(Display display, Surface surface, int x, int y, const char * text, int len)
3106    {
3107       OGLSurface oglSurface = surface.driverData;
3108       OGLSystem oglSystem = display.displaySystem.driverData;
3109       oglSystem.loadingFont = true;
3110
3111       //glTranslated(-0.375, -0.375, 0.0);
3112
3113       //Logf("Blit\n");
3114
3115       if(surface.textOpacity)
3116       {
3117          int w, h;
3118          FontExtent(display.displaySystem, surface.font, text, len, &w, &h);
3119          display.displaySystem.driver.Area(display, surface,x,y,x+w-1,y+h-1);
3120       }
3121
3122       oglSurface.writingText = true;
3123
3124       glEnable(GL_TEXTURE_2D);
3125       glColor4fv(oglSurface.foreground);
3126
3127       ((subclass(DisplayDriver))class(LFBDisplayDriver)).WriteText(display, surface, x, y, text, len);
3128       oglSurface.writingText = false;
3129       oglSystem.loadingFont = false;
3130
3131       glDisable(GL_TEXTURE_2D);
3132
3133       //glTranslated(0.375, 0.375, 0.0);
3134    }
3135
3136    void TextFont(Display display, Surface surface, Font font)
3137    {
3138       ((subclass(DisplayDriver))class(LFBDisplayDriver)).TextFont(display, surface, font);
3139    }
3140
3141    void TextOpacity(Display display, Surface surface, bool opaque)
3142    {
3143       OGLSurface oglSurface = surface.driverData;
3144       oglSurface.opaqueText = opaque;
3145    }
3146
3147    void TextExtent(Display display, Surface surface, const char * text, int len, int * width, int * height)
3148    {
3149       OGLSurface oglSurface = surface.driverData;
3150       OGLSystem oglSystem = display.displaySystem.driverData;
3151       oglSystem.loadingFont = true;
3152       FontExtent(display.displaySystem, oglSurface.font, text, len, width, height);
3153       oglSystem.loadingFont = false;
3154    }
3155
3156    void DrawingChar(Display display, Surface surface, char character)
3157    {
3158
3159    }
3160
3161    void LineStipple(Display display, Surface surface, uint32 stipple)
3162    {
3163       //Logf("Stipple\n");
3164
3165       if(stipple)
3166       {
3167 #if defined(__ANDROID__)
3168          stippleEnabled = true;
3169          glesLineStipple(1, (uint16)stipple);
3170 #else
3171          glLineStipple(1, (uint16)stipple);
3172          glEnable(GL_LINE_STIPPLE);
3173 #endif
3174       }
3175       else
3176       {
3177 #if defined(__ANDROID__)
3178          stippleEnabled = false;
3179          glMatrixMode(GL_TEXTURE);
3180          glLoadIdentity();
3181          glMatrixMode(GL_PROJECTION);
3182          glDisable(GL_TEXTURE_2D);
3183 #else
3184          glDisable(GL_LINE_STIPPLE);
3185 #endif
3186       }
3187    }
3188 #if !defined(ECERE_NO3D) && !defined(ECERE_VANILLA)
3189    void SetRenderState(Display display, RenderState state, uint value)
3190    {
3191       OGLDisplay oglDisplay = display.driverData;
3192       //Logf("RenderState\n");
3193
3194       switch(state)
3195       {
3196          case antiAlias:
3197             if(value)
3198                glEnable(GL_MULTISAMPLE_ARB);
3199             else
3200                glDisable(GL_MULTISAMPLE_ARB);
3201             break;
3202          case fillMode:
3203             glPolygonMode(GL_FRONT_AND_BACK, ((FillModeValue)value == solid) ? GL_FILL : GL_LINE);
3204             break;
3205          case depthTest:
3206             if(value) glEnable(GL_DEPTH_TEST); else glDisable(GL_DEPTH_TEST);
3207             break;
3208          case depthWrite:
3209             if(value) glDepthMask((byte)bool::true); else glDepthMask((byte)bool::false);
3210             oglDisplay.depthWrite = (bool)value;
3211             break;
3212          case fogColor:
3213          {
3214             float color[4] = { ((Color)value).r/255.0f, ((Color)value).g/255.0f, ((Color)value).b/255.0f, 1.0f };
3215             glFogfv(GL_FOG_COLOR, (float *)&color);
3216             break;
3217          }
3218          case fogDensity:
3219             glFogf(GL_FOG_DENSITY, (float)(RenderStateFloat { ui = value }.f * nearPlane));
3220             break;
3221          case blend:
3222             if(value) glEnable(GL_BLEND); else glDisable(GL_BLEND);
3223             break;
3224          case ambient:
3225          {
3226             float ambient[4] = { ((Color)value).r/255.0f, ((Color)value).g/255.0f, ((Color)value).b/255.0f, 1.0f };
3227             glLightModelfv(GL_LIGHT_MODEL_AMBIENT, ambient);
3228             break;
3229          }
3230          case alphaWrite:
3231          {
3232             if(value) glColorMask(1,1,1,1); else glColorMask(1,1,1,0);
3233             break;
3234          }
3235          case vSync:
3236          {
3237 #if defined(__WIN32__)
3238             wglSwapIntervalEXT(value ? 1 : 0);
3239 #endif
3240             break;
3241          }
3242       }
3243    }
3244
3245    void SetLight(Display display, int id, Light light)
3246    {
3247       //Logf("SetLight\n");
3248
3249       if(light != null)
3250       {
3251          Object lightObject = light.lightObject;
3252          float position[4] = { 0, 0, 0, 0 };
3253          float color[4] = { 0, 0, 0, 1 };
3254
3255          glEnable(GL_LIGHT0 + id);
3256          /*
3257          glLightfv(GL_LIGHT0 + id, GL_DIFFUSE, (float *)&light.diffuse);
3258          glLightfv(GL_LIGHT0 + id, GL_AMBIENT, (float *)&light.ambient);
3259          glLightfv(GL_LIGHT0 + id, GL_SPECULAR,(float *)&light.specular);
3260          */
3261
3262          if(!light.multiplier) light.multiplier = 1.0f;
3263
3264          color[0] = light.diffuse.r * light.multiplier;
3265          color[1] = light.diffuse.g * light.multiplier;
3266          color[2] = light.diffuse.b * light.multiplier;
3267          glLightfv(GL_LIGHT0 + id, GL_DIFFUSE, color);
3268
3269          color[0] = light.ambient.r * light.multiplier;
3270          color[1] = light.ambient.g * light.multiplier;
3271          color[2] = light.ambient.b * light.multiplier;
3272          glLightfv(GL_LIGHT0 + id, GL_AMBIENT, color);
3273          color[0] = light.specular.r * light.multiplier;
3274          color[1] = light.specular.g * light.multiplier;
3275          color[2] = light.specular.b * light.multiplier;
3276          glLightfv(GL_LIGHT0 + id, GL_SPECULAR,color);
3277
3278          if(lightObject)
3279          {
3280             Vector3D positionVector;
3281             if(light.flags.spot)
3282             {
3283                if(lightObject.flags.root || !lightObject.parent)
3284                {
3285                   positionVector = lightObject.transform.position;
3286                   positionVector.Subtract(positionVector, display.display3D.camera.cPosition);
3287                }
3288                else
3289                {
3290                   positionVector.MultMatrix(lightObject.transform.position, lightObject.parent.matrix);
3291                   if(display.display3D.camera)
3292                      positionVector.Subtract(positionVector, display.display3D.camera.cPosition);
3293                }
3294                position[3] = 1;
3295             }
3296             else
3297             {
3298                if(!light.direction.x && !light.direction.y && !light.direction.z)
3299                {
3300                   Vector3Df vector { 0,0,-1 };
3301                   Matrix mat;
3302                   mat.RotationQuaternion(light.orientation);
3303                   positionVector.MultMatrixf(vector, mat);
3304                }
3305                else
3306                {
3307                   positionVector = light.direction;
3308                   position[3] = 1;
3309                }
3310             }
3311
3312             position[0] = (float)positionVector.x;
3313             position[1] = (float)positionVector.y;
3314             position[2] = (float)positionVector.z;
3315
3316             glLightfv(GL_LIGHT0 + id, GL_POSITION, position);
3317
3318             /*
3319             // Display Light Position
3320             glDisable(GL_LIGHTING);
3321             glDisable(GL_DEPTH_TEST);
3322             glColor3f(1,1,1);
3323             glPointSize(10);
3324             glBegin(GL_POINTS);
3325             glVertex3fv(position);
3326             glEnd();
3327             glEnable(GL_DEPTH_TEST);
3328             glEnable(GL_LIGHTING);
3329
3330
3331             // Display Target
3332             if(lightObject.flags.root || !lightObject.parent)
3333             {
3334                positionVector = light.target.transform.position;
3335                positionVector.Subtract(positionVector, display.camera.cPosition);
3336             }
3337             else
3338             {
3339                positionVector.MultMatrix(light.target.transform.position,
3340                   lightObject.light.target.parent.matrix);
3341                positionVector.Subtract(positionVector, display.camera.cPosition);
3342             }
3343
3344             position[0] = positionVector.x;
3345             position[1] = positionVector.y;
3346             position[2] = positionVector.z;
3347
3348             glDisable(GL_LIGHTING);
3349             glDisable(GL_DEPTH_TEST);
3350             glColor3f(1,1,0);
3351             glPointSize(10);
3352             glBegin(GL_POINTS);
3353             glVertex3fv(position);
3354             glEnd();
3355             glEnable(GL_DEPTH_TEST);
3356             glEnable(GL_LIGHTING);
3357             */
3358
3359             if(light.flags.attenuation)
3360             {
3361                glLightf(GL_LIGHT0 + id, GL_CONSTANT_ATTENUATION, light.Kc);
3362                glLightf(GL_LIGHT0 + id, GL_LINEAR_ATTENUATION, light.Kl);
3363                glLightf(GL_LIGHT0 + id, GL_QUADRATIC_ATTENUATION, light.Kq);
3364             }
3365
3366             if(light.flags.spot)
3367             {
3368                float exponent = 0;
3369                #define MAXLIGHT  0.9
3370                float direction[4] = { (float)light.direction.x, (float)light.direction.y, (float)light.direction.z, 1 };
3371                // Figure out exponent out of the hot spot
3372                exponent = (float)(log(MAXLIGHT) / log(cos((light.hotSpot / 2))));
3373
3374                glLightfv(GL_LIGHT0 + id, GL_SPOT_DIRECTION, direction);
3375                glLightf(GL_LIGHT0 + id, GL_SPOT_CUTOFF, (float)(light.fallOff / 2));
3376                glLightf(GL_LIGHT0 + id, GL_SPOT_EXPONENT, exponent);
3377             }
3378          }
3379          else
3380          {
3381
3382             Vector3Df vector { 0,0,-1 };
3383             Vector3Df direction;
3384             Matrix mat;
3385
3386             mat.RotationQuaternion(light.orientation);
3387             direction.MultMatrix(vector, mat);
3388
3389             position[0] = direction.x;
3390             position[1] = direction.y;
3391             position[2] = direction.z;
3392
3393             glLightfv(GL_LIGHT0 + id, GL_POSITION, position);
3394          }
3395       }
3396       else
3397          glDisable(GL_LIGHT0 + id);
3398    }
3399
3400    void SetCamera(Display display, Surface surface, Camera camera)
3401    {
3402       OGLDisplay oglDisplay = display.driverData;
3403       //Logf("SetCamera\n");
3404
3405       if(camera)
3406       {
3407          int left = surface.box.left + surface.offset.x;
3408          int top = surface.box.top  + surface.offset.y;
3409          int right = surface.box.right + surface.offset.x;
3410          int bottom = surface.box.bottom + surface.offset.y;
3411          float origX = surface.offset.x + camera.origin.x;
3412          float origY = surface.offset.y + camera.origin.y;
3413          int x = left;
3414          int y = display.height - bottom - 1;
3415          int w = right - left + 1;
3416          int h = bottom - top + 1;
3417
3418          // *** ViewPort ***
3419          glViewport(x, y, w, h);
3420
3421          // *** Projection Matrix ***
3422          if(!display.display3D.camera)
3423             glPushMatrix();
3424          else
3425             glMatrixMode(GL_PROJECTION);
3426          if(display.display3D.collectingHits)
3427          {
3428             float pickX = display.display3D.pickX + surface.offset.x;
3429             float pickY = display.height - (display.display3D.pickY + surface.offset.y) - 1;
3430             Matrix pickMatrix
3431             {
3432                {
3433                   w / display.display3D.pickWidth, 0, 0, 0,
3434                   0, h / display.display3D.pickHeight, 0, 0,
3435                   0, 0, 1, 0,
3436                   (w + 2.0f * (x - pickX)) / display.display3D.pickWidth,
3437                   (h + 2.0f * (y - pickY)) / display.display3D.pickHeight, 0, 1
3438                }
3439             };
3440             glLoadMatrixd(pickMatrix.array);
3441          }
3442          else
3443             glLoadIdentity();
3444          glFrustum(
3445             (left   - origX) * camera.zMin / camera.focalX,
3446             (right  - origX) * camera.zMin / camera.focalX,
3447             (bottom - origY) * camera.zMin / camera.focalY,
3448             (top    - origY) * camera.zMin / camera.focalY,
3449             camera.zMin, camera.zMax);
3450
3451          glDisable(GL_BLEND);
3452
3453          // *** Z Inverted Identity Matrix ***
3454          glMatrixMode(GL_MODELVIEW);
3455          if(!display.display3D.camera)
3456             glPushMatrix();
3457
3458          glLoadIdentity();
3459
3460          glScaled(1.0/nearPlane, 1.0/nearPlane, -1.0/nearPlane);
3461
3462          // *** View Matrix ***
3463          glMultMatrixd(camera.viewMatrix.array);
3464
3465          // *** Lights ***
3466          // ...
3467
3468          glEnable(GL_DEPTH_TEST);
3469          glEnable(GL_LIGHTING);
3470          glShadeModel(GL_SMOOTH);
3471          glDepthMask((byte)bool::true);
3472          oglDisplay.depthWrite = true;
3473
3474          glEnable(GL_MULTISAMPLE_ARB);
3475       }
3476       else if(display.display3D.camera)
3477       {
3478          oglDisplay.depthWrite = false;
3479          glViewport(0,0,display.width,display.height);
3480
3481          glDisable(GL_CULL_FACE);
3482          glDisable(GL_DEPTH_TEST);
3483          glDisable(GL_LIGHTING);
3484          glDisable(GL_FOG);
3485          glDisable(GL_TEXTURE_2D);
3486          glShadeModel(GL_FLAT);
3487          glEnable(GL_BLEND);
3488          glDisable(GL_MULTISAMPLE_ARB);
3489
3490          // *** Restore 2D MODELVIEW Matrix ***
3491          glPopMatrix();
3492
3493          // *** Restore 2D PROJECTION Matrix ***
3494          glMatrixMode(GL_PROJECTION);
3495          glPopMatrix();
3496       }
3497
3498       GLBindBuffer(GL_ARRAY_BUFFER_ARB, 0);
3499    }
3500
3501    void ApplyMaterial(Display display, Material material, Mesh mesh)
3502    {
3503       //Logf("ApplyMaterial\n");
3504
3505       // Basic Properties
3506       if(material.flags.doubleSided)
3507       {
3508          glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, !material.flags.singleSideLight);
3509          glDisable(GL_CULL_FACE);
3510       }
3511       else
3512       {
3513          glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, bool::false);
3514          glEnable(GL_CULL_FACE);
3515       }
3516
3517       // Fog
3518       if(material.flags.noFog)
3519          glDisable(GL_FOG);
3520       else
3521          glEnable(GL_FOG);
3522
3523       // Maps
3524       if(material.baseMap && (mesh.texCoords || mesh.flags.texCoords1))
3525       {
3526          Bitmap map = material.baseMap;
3527          glEnable(GL_TEXTURE_2D);
3528          glBindTexture(GL_TEXTURE_2D, (GLuint)(uintptr)map.driverData);
3529
3530          glMatrixMode(GL_TEXTURE);
3531          glLoadIdentity();
3532          if(material.uScale && material.vScale)
3533             glScalef(material.uScale, material.vScale, 1);
3534          glMatrixMode(GL_MODELVIEW);
3535
3536          if(material.flags.tile)
3537          {
3538             glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
3539             glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
3540          }
3541          else
3542          {
3543             glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
3544             glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
3545          }
3546       }
3547       else
3548          glDisable(GL_TEXTURE_2D);
3549
3550       if(mesh.flags.colors)
3551       {
3552          glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE);
3553          glEnable(GL_COLOR_MATERIAL);
3554       }
3555       else
3556       {
3557          glDisable(GL_COLOR_MATERIAL);
3558          {
3559             float color[4] = { material.diffuse.r, material.diffuse.g, material.diffuse.b, material.opacity };
3560             glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, color);
3561          }
3562          {
3563             float color[4] = { material.ambient.r, material.ambient.g, material.ambient.b, 0 };
3564             glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, color);
3565          }
3566       }
3567       {
3568          float color[4] = { material.specular.r, material.specular.g, material.specular.b, 0 };
3569          glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, color);
3570       }
3571       {
3572          float color[4] = { material.emissive.r, material.emissive.g, material.emissive.b, 0 };
3573          glMaterialfv(GL_FRONT_AND_BACK, GL_EMISSION, color);
3574       }
3575
3576       glMaterialfv(GL_FRONT_AND_BACK, GL_SHININESS, &material.power);
3577    }
3578
3579    void FreeMesh(DisplaySystem displaySystem, Mesh mesh)
3580    {
3581       OGLMesh oglMesh = mesh.data;
3582       if(oglMesh)
3583       {
3584          if(!mesh.flags.vertices)
3585          {
3586             if(oglMesh.vertices)
3587             {
3588                GLDeleteBuffers(1, &oglMesh.vertices);
3589                oglMesh.vertices = 0;
3590             }
3591             delete mesh.vertices;
3592          }
3593          if(!mesh.flags.normals)
3594          {
3595             if(oglMesh.normals)
3596             {
3597                GLDeleteBuffers(1, &oglMesh.normals);
3598                oglMesh.normals = 0;
3599             }
3600             delete mesh.normals;
3601          }
3602          if(!mesh.flags.texCoords1)
3603          {
3604             if(oglMesh.texCoords)
3605             {
3606                GLDeleteBuffers(1, &oglMesh.texCoords);
3607                oglMesh.texCoords = 0;
3608             }
3609             delete mesh.texCoords;
3610          }
3611          if(!mesh.flags.texCoords2)
3612          {
3613             if(oglMesh.texCoords2)
3614             {
3615                GLDeleteBuffers(1, &oglMesh.texCoords2);
3616                oglMesh.texCoords2 = 0;
3617             }
3618             /*
3619             delete mesh.texCoords2;
3620             */
3621          }
3622          if(!mesh.flags.colors)
3623          {
3624             if(oglMesh.colors)
3625             {
3626                GLDeleteBuffers(1, &oglMesh.colors);
3627                oglMesh.colors = 0;
3628             }
3629          }
3630          if(!mesh.flags)
3631          {
3632             delete oglMesh;
3633             mesh.data = null;
3634          }
3635       }
3636    }
3637
3638    bool AllocateMesh(DisplaySystem displaySystem, Mesh mesh, MeshFeatures flags, int nVertices)
3639    {
3640       bool result = false;
3641
3642       if(!mesh.data)
3643          mesh.data = OGLMesh { };
3644       if(mesh.data)
3645       {
3646          OGLMesh oglMesh = mesh.data;
3647          if(mesh.nVertices == nVertices)
3648          {
3649             // Same number of vertices, adding features (Leaves the other features pointers alone)
3650             if(mesh.flags != flags)
3651             {
3652                if(!mesh.flags.vertices && flags.vertices)
3653                {
3654                   if(flags.doubleVertices)
3655                   {
3656                      mesh.vertices = (Vector3Df *)new Vector3D[nVertices];
3657                   }
3658                   else
3659                      mesh.vertices = new Vector3Df[nVertices];
3660                   if(!oglMesh.vertices)
3661                      GLGenBuffers(1, &oglMesh.vertices);
3662                }
3663                if(!mesh.flags.normals && flags.normals)
3664                {
3665                   if(flags.doubleNormals)
3666                   {
3667                      mesh.normals = (Vector3Df *)new Vector3D[nVertices];
3668                   }
3669                   else
3670                      mesh.normals = new Vector3Df[nVertices];
3671                   if(!oglMesh.normals)
3672                      GLGenBuffers( 1, &oglMesh.normals);
3673                }
3674                if(!mesh.flags.texCoords1 && flags.texCoords1)
3675                {
3676                   mesh.texCoords = new Pointf[nVertices];
3677                   if(!oglMesh.texCoords)
3678                      GLGenBuffers( 1, &oglMesh.texCoords);
3679                }
3680                if(!mesh.flags.colors && flags.colors)
3681                {
3682                   mesh.colors = new ColorRGBAf[nVertices];
3683                   if(!oglMesh.colors)
3684                      GLGenBuffers( 1, &oglMesh.colors);
3685                }
3686             }
3687          }
3688          else
3689          {
3690             // New number of vertices, reallocate all current and new features
3691             flags |= mesh.flags;
3692             if(flags.vertices)
3693             {
3694                if(flags.doubleVertices)
3695                {
3696                   mesh.vertices = (Vector3Df *)renew mesh.vertices Vector3D[nVertices];
3697                }
3698                else
3699                   mesh.vertices = renew mesh.vertices Vector3Df[nVertices];
3700                if(!oglMesh.vertices)
3701                   GLGenBuffers(1, &oglMesh.vertices);
3702             }
3703             if(flags.normals)
3704             {
3705                if(flags.doubleNormals)
3706                {
3707                   mesh.normals = (Vector3Df *)renew mesh.normals Vector3D[nVertices];
3708                }
3709                else
3710                   mesh.normals = renew mesh.normals Vector3Df[nVertices];
3711                if(!oglMesh.normals)
3712                   GLGenBuffers( 1, &oglMesh.normals);
3713             }
3714             if(flags.texCoords1)
3715             {
3716                mesh.texCoords = renew mesh.texCoords Pointf[nVertices];
3717                if(!oglMesh.texCoords)
3718                   GLGenBuffers( 1, &oglMesh.texCoords);
3719             }
3720             if(flags.colors)
3721             {
3722                mesh.colors = renew mesh.colors ColorRGBAf[nVertices];
3723                if(!oglMesh.colors)
3724                   GLGenBuffers( 1, &oglMesh.colors);
3725             }
3726          }
3727          result = true;
3728       }
3729       return result;
3730    }
3731
3732    void UnlockMesh(DisplaySystem displaySystem, Mesh mesh, MeshFeatures flags)
3733    {
3734       OGLMesh oglMesh = mesh.data;
3735       if(!flags) flags = mesh.flags;
3736
3737       if(vboAvailable)
3738       {
3739          if(flags.vertices && oglMesh.vertices)
3740          {
3741             GLBindBuffer(GL_ARRAY_BUFFER_ARB, oglMesh.vertices);
3742             GLBufferData( mesh.flags.doubleVertices ? GL_DOUBLE : GL_FLOAT, GL_ARRAY_BUFFER_ARB, mesh.nVertices * (mesh.flags.doubleVertices ? sizeof(Vector3D) : sizeof(Vector3Df)), mesh.vertices, GL_STATIC_DRAW_ARB );
3743          }
3744
3745          if(flags.normals && oglMesh.normals)
3746          {
3747             GLBindBuffer(GL_ARRAY_BUFFER_ARB, oglMesh.normals);
3748             GLBufferData( mesh.flags.doubleNormals ? GL_DOUBLE : GL_FLOAT, GL_ARRAY_BUFFER_ARB, mesh.nVertices * (mesh.flags.doubleNormals ? sizeof(Vector3D) : sizeof(Vector3Df)), mesh.normals, GL_STATIC_DRAW_ARB );
3749          }
3750
3751          if(flags.texCoords1 && oglMesh.texCoords)
3752          {
3753             GLBindBuffer(GL_ARRAY_BUFFER_ARB, oglMesh.texCoords);
3754             GLBufferData( GL_FLOAT, GL_ARRAY_BUFFER_ARB, mesh.nVertices * sizeof(Pointf), mesh.texCoords, GL_STATIC_DRAW_ARB );
3755          }
3756
3757          if(flags.colors && oglMesh.colors)
3758          {
3759             GLBindBuffer( GL_ARRAY_BUFFER_ARB, oglMesh.colors);
3760             GLBufferData( GL_FLOAT, GL_ARRAY_BUFFER_ARB, mesh.nVertices * sizeof(ColorRGBAf), mesh.colors, GL_STATIC_DRAW_ARB );
3761          }
3762
3763          GLBindBuffer( GL_ARRAY_BUFFER_ARB, 0);
3764       }
3765    }
3766
3767    bool LockMesh(DisplaySystem displaySystem, Mesh mesh, MeshFeatures flags)
3768    {
3769       bool result = true;
3770
3771         return result;
3772    }
3773
3774    void FreeIndices(DisplaySystem displaySystem, OGLIndices oglIndices)
3775    {
3776       if(oglIndices)
3777       {
3778          if(oglIndices.buffer)
3779             GLDeleteBuffers(1, &oglIndices.buffer);
3780          delete oglIndices.indices;
3781          delete oglIndices;
3782       }
3783    }
3784
3785    void * AllocateIndices(DisplaySystem displaySystem, int nIndices, bool indices32bit)
3786    {
3787       OGLIndices oglIndices = OGLIndices { };
3788       if(oglIndices)
3789       {
3790          oglIndices.indices = (void *)(indices32bit ? new uint32[nIndices] : new uint16[nIndices]);
3791          GLGenBuffers( 1, &oglIndices.buffer);
3792          oglIndices.nIndices = nIndices;
3793       }
3794       return oglIndices;
3795    }
3796
3797    void UnlockIndices(DisplaySystem displaySystem, OGLIndices oglIndices, bool indices32bit, int nIndices)
3798    {
3799       if(vboAvailable)
3800       {
3801          GLBindBuffer( GL_ELEMENT_ARRAY_BUFFER_ARB, oglIndices.buffer);
3802          GLBufferData( indices32bit ? GL_UNSIGNED_INT : GL_UNSIGNED_SHORT, GL_ELEMENT_ARRAY_BUFFER_ARB, nIndices * (indices32bit ? sizeof(uint32) : sizeof(uint16)),
3803             oglIndices.indices, GL_STATIC_DRAW_ARB);
3804          GLBindBuffer( GL_ELEMENT_ARRAY_BUFFER_ARB, 0);
3805       }
3806    }
3807
3808    uint16 * LockIndices(DisplaySystem displaySystem, OGLIndices oglIndices)
3809    {
3810
3811       return oglIndices.indices;
3812    }
3813
3814    void SelectMesh(Display display, Mesh mesh)
3815    {
3816       //Logf("SelectMesh\n");
3817
3818 #if !defined( __ANDROID__) && !defined(__APPLE__)
3819
3820 #if defined(__WIN32__)
3821       if(glUnlockArraysEXT)
3822 #endif
3823          if(!vboAvailable && display.display3D.mesh)
3824             glUnlockArraysEXT();
3825
3826 #endif
3827       if(mesh)
3828       {
3829          OGLMesh oglMesh = mesh.data;
3830
3831          // *** Vertex Stream ***
3832          glEnableClientState(GL_VERTEX_ARRAY);
3833          if(!display.display3D.collectingHits && oglMesh)
3834          {
3835             GLBindBuffer(GL_ARRAY_BUFFER_ARB, oglMesh.vertices );
3836             glVertexPointer(3, mesh.flags.doubleVertices ? GL_DOUBLE : GL_FLOAT, 0, vboAvailable ? null : mesh.vertices);
3837
3838             // *** Normals Stream ***
3839             if(mesh.normals || mesh.flags.normals)
3840             {
3841                glEnableClientState(GL_NORMAL_ARRAY);
3842                GLBindBuffer(GL_ARRAY_BUFFER_ARB, oglMesh.normals);
3843                glNormalPointer(mesh.flags.doubleNormals ? GL_DOUBLE : GL_FLOAT, 0, vboAvailable ? null : mesh.normals);
3844             }
3845             else
3846                glDisableClientState(GL_NORMAL_ARRAY);
3847
3848             // *** Texture Coordinates Stream ***
3849             if(mesh.texCoords || mesh.flags.texCoords1)
3850             {
3851                glEnableClientState(GL_TEXTURE_COORD_ARRAY);
3852                GLBindBuffer( GL_ARRAY_BUFFER_ARB, oglMesh.texCoords);
3853                glTexCoordPointer(2, GL_FLOAT, 0, vboAvailable ? null : mesh.texCoords);
3854             }
3855             else
3856                glDisableClientState(GL_TEXTURE_COORD_ARRAY);
3857
3858             // *** Color Stream ***
3859             if(mesh.colors || mesh.flags.colors)
3860             {
3861                glEnableClientState(GL_COLOR_ARRAY);
3862                GLBindBuffer( GL_ARRAY_BUFFER_ARB, oglMesh.colors);
3863                glColorPointer(4, GL_FLOAT, 0, vboAvailable ? null : mesh.colors);
3864             }
3865             else
3866                glDisableClientState(GL_COLOR_ARRAY);
3867
3868          }
3869          else
3870          {
3871             GLBindBuffer( GL_ARRAY_BUFFER_ARB, 0);
3872             glVertexPointer(3,mesh.flags.doubleVertices ? GL_DOUBLE : GL_FLOAT,0,mesh.vertices);
3873             if((mesh.normals || mesh.flags.normals) && !display.display3D.collectingHits)
3874             {
3875                glEnableClientState(GL_NORMAL_ARRAY);
3876                glNormalPointer(mesh.flags.doubleNormals ? GL_DOUBLE : GL_FLOAT, 0, mesh.normals);
3877             }
3878             else
3879                glDisableClientState(GL_NORMAL_ARRAY);
3880             if((mesh.texCoords || mesh.flags.texCoords1) && !display.display3D.collectingHits)
3881             {
3882                glEnableClientState(GL_TEXTURE_COORD_ARRAY);
3883                glTexCoordPointer(2, GL_FLOAT, 0, mesh.texCoords);
3884             }
3885             else
3886                glDisableClientState(GL_TEXTURE_COORD_ARRAY);
3887             if((mesh.colors || mesh.flags.colors) && !display.display3D.collectingHits)
3888             {
3889                glEnableClientState(GL_COLOR_ARRAY);
3890                glColorPointer(4, GL_FLOAT, 0, mesh.colors);
3891             }
3892             else
3893                glDisableClientState(GL_COLOR_ARRAY);
3894          }
3895
3896 #if !defined(__ANDROID__) && !defined(__APPLE__)
3897
3898 #if defined(__WIN32__)
3899          if(glLockArraysEXT)
3900 #endif
3901             if(!vboAvailable)
3902                glLockArraysEXT(0, mesh.nVertices);
3903
3904 #endif
3905       }
3906       else
3907          GLBindBuffer(GL_ARRAY_BUFFER_ARB, 0);
3908    }
3909
3910    void DrawPrimitives(Display display, PrimitiveSingle * primitive, Mesh mesh)
3911    {
3912       //Logf("DrawPrimitives\n");
3913
3914       if(primitive->type.vertexRange)
3915          glDrawArrays(primitiveTypes[primitive->type.primitiveType], primitive->first, primitive->nVertices);
3916       else
3917       {
3918          //    *** Hoping the data won't be uploaded at all (Won't really work if another group of the mesh is using the mesh ) ***
3919          // HACK TO SPEED THINGS UP...
3920 #ifndef __ANDROID__
3921          GLBindBuffer(GL_ELEMENT_ARRAY_BUFFER_ARB, 0);
3922          if(primitive->nIndices < (mesh.nVertices >> 2) && !primitive->type.indices32bit)
3923          {
3924             int c;
3925             glBegin(primitiveTypes[primitive->type.primitiveType]);
3926             if(primitive->data)
3927             {
3928                OGLIndices oglIndices = primitive->data;
3929                MeshFeatures flags = mesh.flags;
3930                for(c = 0; c<primitive->nIndices; c++)
3931                {
3932                   uint16 index = ((uint16 *) oglIndices.indices)[c];
3933                   if(flags.normals) glNormal3fv((float *)&mesh.normals[index]);
3934                   if(flags.texCoords1) glTexCoord2fv((float *)&mesh.texCoords[index]);
3935                   if(flags.colors) glColor4fv((float *)&mesh.colors[index]);
3936                   glVertex3fv((float *)&mesh.vertices[index]);
3937                }
3938             }
3939             glEnd();
3940          }
3941          else
3942 #endif
3943          {
3944             OGLIndices oglIndices = primitive->data;
3945
3946             if(!display.display3D.collectingHits && vboAvailable && oglIndices)
3947             {
3948                GLBindBuffer(GL_ELEMENT_ARRAY_BUFFER_ARB, oglIndices.buffer);
3949                glDrawElements(primitiveTypes[primitive->type.primitiveType], primitive->nIndices,
3950                   primitive->type.indices32bit ? GL_UNSIGNED_INT : GL_UNSIGNED_SHORT, 0);
3951                GLBindBuffer(GL_ELEMENT_ARRAY_BUFFER_ARB, 0);
3952             }
3953             else
3954                glDrawElements(primitiveTypes[primitive->type.primitiveType], primitive->nIndices,
3955                   primitive->type.indices32bit ? GL_UNSIGNED_INT : GL_UNSIGNED_SHORT, oglIndices ? oglIndices.indices : primitive->indices);
3956          }
3957       }
3958    }
3959
3960    void PushMatrix(Display display)
3961    {
3962       glPushMatrix();
3963    }
3964
3965    void PopMatrix(Display display, bool setMatrix)
3966    {
3967       glPopMatrix();
3968    }
3969
3970    void SetTransform(Display display, Matrix transMatrix, bool viewSpace, bool useCamera)
3971    {
3972       Matrix matrix = transMatrix;
3973       Camera camera = useCamera ? display.display3D.camera : null;
3974
3975       if(viewSpace)
3976       {
3977          glLoadIdentity();
3978          glScaled(1.0/nearPlane, 1.0/nearPlane, -1.0/nearPlane);
3979       }
3980       else if(camera)
3981       {
3982          glTranslated(
3983             matrix.m[3][0] - camera.cPosition.x,
3984             matrix.m[3][1] - camera.cPosition.y,
3985             matrix.m[3][2] - camera.cPosition.z);
3986       }
3987       else
3988          glTranslated(
3989             matrix.m[3][0],
3990             matrix.m[3][1],
3991             matrix.m[3][2]);
3992
3993       matrix.m[3][0] = 0;
3994       matrix.m[3][1] = 0;
3995       matrix.m[3][2] = 0;
3996
3997       glMultMatrixd(matrix.array);
3998    }
3999 #endif
4000 }
4001
4002 public void UseSingleGLContext(bool useSingle)
4003 {
4004    useSingleGLContext = useSingle;
4005 }
4006
4007 default dllexport void *
4008 #if defined(__WIN32__)
4009 __attribute__((stdcall))
4010 #endif
4011 IS_GLGetContext(DisplaySystem displaySystem)
4012 {
4013    if(displaySystem)
4014    {
4015 #if defined(__WIN32__)
4016       OGLSystem system = displaySystem.driverData;
4017       return system.glrc;
4018 #elif !defined(__ANDROID__)
4019       OGLSystem system = displaySystem.driverData;
4020       return system.glContext;
4021 #else
4022       return eglContext;
4023 #endif
4024    }
4025    return null;
4026 }
4027
4028 #endif