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