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