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