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