ecere/gfx/drivers/OpenGL: Added '0' checks for freeing buffer
[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 && buffer)
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 && buffer)
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 #ifdef _GLES
1430       type = GL_UNSIGNED_SHORT;
1431 #endif
1432       glDrawElements(primType, count, type, indices);
1433    }
1434 };
1435
1436 public void GLGenBuffers(int count, GLAB * buffers)
1437 {
1438 #if defined(__ANDROID__) || defined(__ODROID__)
1439    glGenBuffers(count, (GLuint *)buffers);
1440 #else
1441 #if defined(__WIN32__)
1442    if(glGenBuffersARB)
1443 #endif
1444       glGenBuffersARB(count, (GLuint *)buffers);
1445 #endif
1446 }
1447
1448 public void GLDeleteBuffers(int count, GLAB * buffers)
1449 {
1450    int i;
1451    for(i = 0; i < count; i++)
1452    {
1453       uint buffer = buffers[i].buffer;
1454       if(buffer)
1455       {
1456          if(buffer == curArrayBuffer)
1457             GLBindBuffer(GL_ARRAY_BUFFER_ARB, 0);
1458          else if(buffer == curElementBuffer)
1459             GLBindBuffer(GL_ELEMENT_ARRAY_BUFFER_ARB, 0);
1460       }
1461    }
1462 #if defined(__ANDROID__) || defined(__ODROID__)
1463    if(count && buffers[0].buffer)
1464       glDeleteBuffers(count, (GLuint *)buffers);
1465 #else
1466 #if defined(__WIN32__)
1467    if(glDeleteBuffersARB)
1468 #endif
1469       glDeleteBuffersARB(count, (GLuint *)buffers);
1470 #endif
1471 }
1472
1473 void GLBindBuffer(int target, uint buffer)
1474 {
1475 #if defined(__ANDROID__) || defined(__ODROID__)
1476    glBindBuffer(target, buffer);
1477 #else
1478 #if defined(__WIN32__)
1479    if(glBindBufferARB)
1480 #endif
1481       glBindBufferARB(target, buffer);
1482 #endif
1483    if(target == GL_ARRAY_BUFFER_ARB)
1484       curArrayBuffer = buffer;
1485    else if(target == GL_ELEMENT_ARRAY_BUFFER_ARB)
1486       curElementBuffer = buffer;
1487 }
1488
1489 public void GLVertexPointer(int numCoords, int glType, int stride, void *ptr, int numVertices)
1490 {
1491 #ifdef _GLES
1492    if(glType == GL_DOUBLE)
1493       glesVertexPointerd(numCoords, stride, ptr, numVertices);
1494    else if(glType == GL_INT)
1495       glesVertexPointeri(numCoords, stride, ptr, numVertices);
1496    else
1497 #endif
1498       glVertexPointer(numCoords, glType, stride, ptr);
1499 }
1500
1501 public void GLBufferData(int type, GLenum target, int size, const GLvoid *data, GLenum usage)
1502 {
1503 #ifdef _GLES
1504    if(type == GL_DOUBLE)
1505       glesBufferDatad(target, size, (void *)data, usage);
1506    else if(type == GL_UNSIGNED_INT)
1507       glesBufferDatai(target, size, (void *)data, usage);
1508    else
1509 #endif
1510
1511 #if defined(__ANDROID__) || defined(__ODROID__)
1512       glBufferData(target, size, data, usage);
1513 #else
1514
1515 #if defined(__WIN32__)
1516    if(glBufferDataARB)
1517 #endif
1518       glBufferDataARB(target, size, data, usage);
1519 #endif
1520 }
1521
1522 #if !defined(ECERE_NO3D) && !defined(ECERE_VANILLA)
1523 static int primitiveTypes[RenderPrimitiveType] =
1524 {
1525    GL_POINTS, GL_LINES, GL_TRIANGLES, GL_TRIANGLE_STRIP, GL_TRIANGLE_FAN, GL_QUADS, GL_QUAD_STRIP, GL_LINE_STRIP
1526 };
1527 #endif
1528
1529
1530 // Non OpenGL ES friendly stuff
1531
1532 #if defined(_GLES)
1533
1534 //#undef GL_UNSIGNED_INT
1535 //#undef GL_DOUBLE
1536 #undef GL_INT
1537 //#undef GL_POLYGON
1538 //#undef GL_QUADS
1539 #undef GL_QUAD_STRIP
1540 #undef GL_POLYGON_STIPPLE
1541 #undef GL_LINE_STIPPLE
1542 #undef GL_LINE
1543 #undef GL_FILL
1544 #undef GL_ALL_ATTRIB_BITS
1545 #undef GL_LIGHT_MODEL_LOCAL_VIEWER
1546
1547 #endif
1548
1549 static int displayWidth, displayHeight;
1550
1551 #define GL_CLAMP_TO_EDGE 0x812F
1552
1553 static bool vboAvailable;
1554
1555 static bool useSingleGLContext = false;
1556 class OGLDisplay : struct
1557 {
1558 #if defined(__WIN32__)
1559    HDC hdc;
1560    HGLRC glrc;
1561
1562    HBITMAP memBitmap;
1563    HDC memDC;
1564    byte * picture;
1565    uint stride;
1566    void * pBuffer;
1567    /*
1568    int imageBuffers[2];
1569    byte * pboMemory1, * pboMemory2;
1570    */
1571 #elif !defined(__ANDROID__) && !defined(__ODROID__)
1572    GLXContext glContext;
1573
1574    Pixmap pixmap;
1575    XShmSegmentInfo shminfo;
1576    XImage * image;
1577    XShmSegmentInfo shminfoShape;
1578    XImage * shapeImage;
1579    byte * picture;
1580    uint stride;
1581    GLXPbuffer pBuffer;
1582    X11Picture windowPicture;
1583    X11Picture pixmapPicture;
1584    Pixmap shapePixmap;
1585    X11Picture shapePicture;
1586 #endif
1587
1588    ColorAlpha * flippingBuffer;
1589    int flipBufH, flipBufW;
1590    bool depthWrite;
1591    int x, y;
1592 };
1593
1594 class OGLSystem : struct
1595 {
1596    int maxTextureSize;
1597    bool loadingFont;
1598    bool pow2textures;
1599 #if defined(__WIN32__)
1600    PIXELFORMATDESCRIPTOR pfd;
1601    int format;
1602    HDC hdc;
1603    HGLRC glrc;
1604    HWND hwnd;
1605 #elif !defined(__ANDROID__) && !defined(__ODROID__)
1606    XVisualInfo * visualInfo;
1607    GLXContext glContext;
1608    GLXDrawable glxDrawable;
1609 #endif
1610 };
1611
1612 class OGLSurface : struct
1613 {
1614    Font font;
1615    bool opaqueText;
1616    int xOffset;
1617    bool writingText;
1618
1619    float foreground[4], background[4], bitmapMult[4];
1620 } OGLSurface;
1621
1622 class OGLMesh : struct
1623 {
1624    GLAB vertices;
1625    GLAB normals;
1626    GLAB texCoords;
1627    GLAB texCoords2;
1628    GLAB colors;
1629 };
1630
1631 class OGLIndices : struct
1632 {
1633    uint16 * indices;
1634    GLEAB buffer;
1635    uint nIndices;
1636 };
1637
1638 int current;
1639 void * previous;
1640
1641 class OpenGLDisplayDriver : DisplayDriver
1642 {
1643    class_property(name) = "OpenGL";
1644
1645    bool LockSystem(DisplaySystem displaySystem)
1646    {
1647 #if !defined(__ANDROID__) && !defined(__ODROID__)
1648       OGLSystem oglSystem = displaySystem.driverData;
1649       if(useSingleGLContext) return true;
1650    #if defined(__WIN32__)
1651       wglMakeCurrent(oglSystem.hdc, oglSystem.glrc);
1652    #elif defined(__unix__) || defined(__APPLE__)
1653       //if(previous) return true;
1654       // printf("Making SYSTEM current\n");
1655       glXMakeCurrent(xGlobalDisplay, (GLXDrawable)oglSystem.glxDrawable, oglSystem.glContext);
1656       //previous = oglSystem.glContext;
1657    #endif
1658 #endif
1659       return true;
1660    }
1661
1662    void UnlockSystem(DisplaySystem displaySystem)
1663    {
1664       if(useSingleGLContext) return;
1665    #if defined(__WIN32__)
1666       wglMakeCurrent(null, null);
1667    #elif defined(__unix__) || defined(__APPLE__)
1668       // printf("Making NULL current\n");
1669       #if defined(__ANDROID__) || defined(__ODROID__)
1670       #else
1671       glXMakeCurrent(xGlobalDisplay, None, null);
1672       #endif
1673       // previous = null;
1674    #endif
1675    }
1676
1677    bool Lock(Display display)
1678    {
1679 #if !defined(__ANDROID__) && !defined(__ODROID__)
1680       OGLDisplay oglDisplay = display.driverData;
1681       if(useSingleGLContext) return true;
1682    #if defined(__WIN32__)
1683       wglMakeCurrent(oglDisplay.hdc, oglDisplay.glrc);
1684    #elif defined(__unix__) || defined(__APPLE__)
1685       // if(previous) glXMakeCurrent(xGlobalDisplay, None, null);
1686       // printf("   Making DISPLAY current\n");
1687       glXMakeCurrent(xGlobalDisplay, (GLXDrawable)display.window, oglDisplay.glContext);
1688    #endif
1689 #endif
1690       return true;
1691    }
1692
1693    void Unlock(Display display)
1694    {
1695       if(useSingleGLContext) return;
1696       //printf("   Making NULL current\n");
1697       //glXMakeCurrent(xGlobalDisplay, None, null);
1698       // if(previous)
1699          LockSystem(display.displaySystem);
1700    }
1701
1702    void DestroyDisplay(Display display)
1703    {
1704       OGLDisplay oglDisplay = display.driverData;
1705
1706       if(oglDisplay)
1707       {
1708    #if defined(__WIN32__)
1709          wglMakeCurrent( null, null );
1710
1711          if(oglDisplay.glrc)
1712             wglDeleteContext(oglDisplay.glrc);
1713
1714          if(oglDisplay.hdc && oglDisplay.pBuffer)
1715             wglReleasePbufferDCARB(oglDisplay.pBuffer, oglDisplay.hdc);
1716
1717          if(oglDisplay.pBuffer)
1718             wglDestroyPbufferARB(oglDisplay.pBuffer);
1719
1720          if(oglDisplay.hdc)
1721             ReleaseDC(display.window, oglDisplay.hdc);
1722
1723          if(oglDisplay.memDC) DeleteDC(oglDisplay.memDC);
1724          if(oglDisplay.memBitmap) DeleteObject(oglDisplay.memBitmap);
1725
1726    #elif defined(__unix__) || defined(__APPLE__)
1727       #if defined(__ANDROID__) || defined(__ODROID__)
1728       #else
1729          if(oglDisplay.shapePixmap)
1730             XFreePixmap(xGlobalDisplay, oglDisplay.shapePixmap);
1731          if(oglDisplay.pixmap)
1732             XFreePixmap(xGlobalDisplay, oglDisplay.pixmap);
1733          if(oglDisplay.image)
1734          {
1735             if(oglDisplay.shminfoShape.shmid != -1)
1736             {
1737                XShmDetach(xGlobalDisplay, &oglDisplay.shminfo);
1738                if(oglDisplay.shminfo.shmaddr != (void *)-1)
1739                   shmdt(oglDisplay.shminfo.shmaddr);
1740                shmctl(oglDisplay.shminfo.shmid, IPC_RMID, 0);
1741             }
1742          }
1743          if(oglDisplay.shapeImage)
1744          {
1745             if(oglDisplay.shminfoShape.shmid != -1)
1746             {
1747                XShmDetach(xGlobalDisplay, &oglDisplay.shminfoShape);
1748                if(oglDisplay.shminfoShape.shmaddr != (void *)-1)
1749                   shmdt(oglDisplay.shminfoShape.shmaddr);
1750                shmctl(oglDisplay.shminfoShape.shmid, IPC_RMID, 0);
1751             }
1752             XDestroyImage(oglDisplay.shapeImage);
1753             oglDisplay.shapeImage = None;
1754          }
1755
1756          glXMakeCurrent(xGlobalDisplay, None, null);
1757
1758          if(oglDisplay.glContext)
1759             glXDestroyContext(xGlobalDisplay, oglDisplay.glContext);
1760       #endif
1761    #endif
1762          delete oglDisplay.flippingBuffer;
1763          delete oglDisplay;
1764          display.driverData = null;
1765       }
1766    }
1767
1768    void ::CheckExtensions(OGLSystem oglSystem)
1769    {
1770       const char * extensions = (const char *)glGetString(GL_EXTENSIONS);
1771       if(extensions)
1772          oglSystem.pow2textures = strstr(extensions, "GL_ARB_texture_non_power_of_two") ? false : true;
1773       glGetIntegerv(GL_MAX_TEXTURE_SIZE, &oglSystem.maxTextureSize);
1774    }
1775
1776    bool CreateDisplaySystem(DisplaySystem displaySystem)
1777    {
1778       bool result = false;
1779       OGLSystem oglSystem = displaySystem.driverData = OGLSystem { };
1780
1781    #ifdef __WIN32__
1782       oglSystem.hwnd = CreateWindow("static", null, 0,0,0,0,0,null,null,null,null);
1783
1784       oglSystem.hdc = GetDC(oglSystem.hwnd);
1785       if(oglSystem.hdc)
1786       {
1787
1788          oglSystem.pfd.nSize = (short)sizeof(oglSystem.pfd);
1789          oglSystem.pfd.nVersion = 1;
1790          oglSystem.pfd.dwFlags = PFD_DRAW_TO_WINDOW /*PFD_DRAW_TO_BITMAP*/ | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;
1791          oglSystem.pfd.iPixelType = PFD_TYPE_RGBA;
1792          oglSystem.pfd.cColorBits = 24;
1793          oglSystem.pfd.cAlphaBits = 8;
1794          oglSystem.pfd.cDepthBits = 24;
1795          oglSystem.pfd.iLayerType = PFD_MAIN_PLANE;
1796
1797          oglSystem.format = ChoosePixelFormat(oglSystem.hdc, &oglSystem.pfd);
1798          DescribePixelFormat(oglSystem.hdc, oglSystem.format, sizeof(oglSystem.pfd), &oglSystem.pfd);
1799
1800          if(oglSystem.pfd.cColorBits > 8)
1801          {
1802             SetPixelFormat(oglSystem.hdc, oglSystem.format, &oglSystem.pfd);
1803             oglSystem.glrc = wglCreateContext(oglSystem.hdc);
1804             if(oglSystem.glrc)
1805             {
1806                wglMakeCurrent(oglSystem.hdc, oglSystem.glrc);
1807
1808                  // Get Pointers To The GL Functions
1809                glActiveTextureARB = (void *) wglGetProcAddress("glActiveTextureARB");
1810                glMultiTexCoord2fARB = (void *) wglGetProcAddress("glMultiTexCoord2fARB");
1811                glClientActiveTextureARB = (void *) wglGetProcAddress("glClientActiveTextureARB");
1812                glLockArraysEXT = (void *) wglGetProcAddress("glLockArraysEXT" );
1813                glUnlockArraysEXT = (void *) wglGetProcAddress("glUnlockArraysEXT");
1814                  glGenBuffersARB = (void *) wglGetProcAddress("glGenBuffersARB");
1815                  glBindBufferARB = (void *) wglGetProcAddress("glBindBufferARB");
1816                  glBufferDataARB = (void *) wglGetProcAddress("glBufferDataARB");
1817                glMapBufferARB  = (void *) wglGetProcAddress("glMapBufferARB");
1818                glUnmapBufferARB  = (void *) wglGetProcAddress("glUnmapBufferARB");
1819                  glDeleteBuffersARB = (void *) wglGetProcAddress("glDeleteBuffersARB");
1820                glBlendFuncSeparate = (void *) wglGetProcAddress("glBlendFuncSeparate");
1821
1822                wglChoosePixelFormatARB = (void *) wglGetProcAddress("wglChoosePixelFormatARB");
1823                wglGetExtensionsStringARB = (void *)wglGetProcAddress("wglGetExtensionsStringARB");
1824                wglCreatePbufferARB = (void *)wglGetProcAddress("wglCreatePbufferARB");
1825                wglGetPbufferDCARB = (void *)wglGetProcAddress("wglGetPbufferDCARB");
1826                wglQueryPbufferARB = (void *)wglGetProcAddress("wglQueryPbufferARB");
1827                wglDestroyPbufferARB = (void *)wglGetProcAddress("wglDestroyPbufferARB");
1828                wglReleasePbufferDCARB = (void *)wglGetProcAddress("wglReleasePbufferDCARB");
1829                wglBindTexImageARB = (void *)wglGetProcAddress("wglBindTexImageARB");
1830                wglReleaseTexImageARB = (void *)wglGetProcAddress("wglReleaseTexImageARB");
1831
1832                wglSwapIntervalEXT = (void *)wglGetProcAddress("wglSwapIntervalEXT");
1833
1834                vboAvailable = glBindBufferARB != null;
1835
1836                // eSystem_LoggingMode(LOG_MSGBOX, null);
1837
1838                if(wglChoosePixelFormatARB)
1839                {
1840                     int pixelFormat;
1841                     int valid;
1842                     int numFormats;
1843                     float fAttributes[] = {0,0};
1844                     int iAttributes[] =
1845                   {
1846                      WGL_DRAW_TO_WINDOW_ARB,GL_TRUE,
1847                             WGL_SUPPORT_OPENGL_ARB,GL_TRUE,
1848                             WGL_ACCELERATION_ARB,WGL_FULL_ACCELERATION_ARB,
1849                             WGL_COLOR_BITS_ARB,24,
1850                             WGL_ALPHA_BITS_ARB,8,
1851                             WGL_DEPTH_BITS_ARB,16,
1852                             WGL_STENCIL_BITS_ARB,0,
1853                             WGL_DOUBLE_BUFFER_ARB,GL_TRUE,
1854                             WGL_SAMPLE_BUFFERS_ARB,GL_TRUE,
1855                             WGL_SAMPLES_ARB, 4,                                         // Check For 4x Multisampling
1856                             0,0
1857                   };
1858
1859                   //Log("Found wglChoosePixelFormatARB\n");
1860
1861                     valid = wglChoosePixelFormatARB(oglSystem.hdc,iAttributes,fAttributes,1,&pixelFormat,&numFormats);
1862                     if(!valid || !numFormats)
1863                     {
1864                      //Log("Can't find 4x multi sampling\n");
1865                        iAttributes[19] = 2;
1866                        valid = wglChoosePixelFormatARB(oglSystem.hdc,iAttributes,fAttributes,1,&pixelFormat,&numFormats);
1867                      if(!valid || !numFormats)
1868                      {
1869                         // Log("Can't find 2x multi sampling\n");
1870                         iAttributes[16] = 0;
1871                         iAttributes[17] = 0;
1872                         valid = wglChoosePixelFormatARB(oglSystem.hdc,iAttributes,fAttributes,1,&pixelFormat,&numFormats);
1873                      }
1874                     }
1875                   if(valid && numFormats)
1876                   {
1877                      oglSystem.format = pixelFormat;
1878                      wglMakeCurrent(null, null);
1879                      wglDeleteContext(oglSystem.glrc);
1880
1881                      // *** DescribePixelFormat does not support WGL pixel formats! ***
1882                      //DescribePixelFormat(oglSystem.hdc, oglSystem.format, sizeof(oglSystem.pfd), &oglSystem.pfd);
1883                      SetPixelFormat(oglSystem.hdc, oglSystem.format, &oglSystem.pfd);
1884                      //Log("Successfully set pixel format\n");
1885
1886                      oglSystem.glrc = wglCreateContext(oglSystem.hdc);
1887                      wglMakeCurrent(oglSystem.hdc, oglSystem.glrc);
1888                   }
1889                }
1890                /*else
1891                   eSystem_Logf("Can't find wglChoosePixelFormatARB\n");*/
1892
1893                result = true;
1894
1895                CheckExtensions(oglSystem);
1896
1897                wglMakeCurrent(null, null);
1898
1899                //eSystem_DumpErrors(true);
1900             }
1901          }
1902       }
1903    #elif defined(__unix__) || defined(__APPLE__)
1904       vboAvailable = true;
1905       #if defined(__ANDROID__)
1906          egl_init_display(guiApp.desktop.windowHandle);
1907       #elif defined(__ODROID__)
1908          egl_init_display((uint)displaySystem.window);
1909          CheckExtensions(oglSystem);
1910          result = true;
1911       #else
1912       {
1913          X11Window root = RootWindow( xGlobalDisplay, DefaultScreen( xGlobalDisplay ) );
1914          XSetWindowAttributes attr;
1915          unsigned long mask;
1916
1917          int attrList[] =
1918          {
1919       #ifndef ECERE_MINIGLX
1920             GLX_USE_GL, GLX_DEPTH_SIZE, 1,
1921       #endif
1922             GLX_RGBA,
1923             GLX_RED_SIZE, 1, GLX_GREEN_SIZE, 1, GLX_BLUE_SIZE, 1,
1924             GLX_DOUBLEBUFFER,
1925             None
1926          };
1927          oglSystem.visualInfo = glXChooseVisual( xGlobalDisplay,  DefaultScreen( xGlobalDisplay ), attrList );
1928          attr.background_pixel = 0;
1929          attr.border_pixel = 0;
1930          attr.colormap = XCreateColormap( xGlobalDisplay, root, oglSystem.visualInfo->visual, AllocNone);
1931          attr.event_mask = StructureNotifyMask | ExposureMask | KeyPressMask;
1932          mask = CWBackPixel | CWBorderPixel | CWColormap | CWEventMask;
1933
1934          oglSystem.glxDrawable = XCreateWindow( xGlobalDisplay, root, 0, 0, 1, 1, 0, oglSystem.visualInfo->depth, InputOutput,
1935             oglSystem.visualInfo->visual, mask, &attr );
1936       }
1937       if(oglSystem.visualInfo)
1938       {
1939          oglSystem.glContext = glXCreateContext(xGlobalDisplay, oglSystem.visualInfo, null, True);
1940          if(oglSystem.glContext)
1941          {
1942             glXMakeCurrent(xGlobalDisplay, oglSystem.glxDrawable, oglSystem.glContext);
1943             // Setup Extensions
1944             CheckExtensions(oglSystem);
1945             glXMakeCurrent(xGlobalDisplay, None, null);
1946             result = true;
1947          }
1948       }
1949       #endif
1950    #endif
1951
1952       displaySystem.flags.alpha = true;
1953       displaySystem.flags.flipping = true;
1954       displaySystem.pixelFormat = pixelFormat888;
1955       return result;
1956    }
1957
1958    void DestroyDisplaySystem(DisplaySystem displaySystem)
1959    {
1960       OGLSystem oglSystem = displaySystem.driverData;
1961
1962    #if defined(__WIN32__)
1963       wglMakeCurrent( null, null );
1964
1965       if(oglSystem.glrc)
1966          wglDeleteContext(oglSystem.glrc);
1967
1968       if(oglSystem.hdc)
1969          ReleaseDC(oglSystem.hwnd, oglSystem.hdc);
1970       DestroyWindow(oglSystem.hwnd);
1971
1972    #elif defined(__unix__) || defined(__APPLE__)
1973       #if defined(__ANDROID__) || defined(__ODROID__)
1974          egl_term_display();
1975       #else
1976       if(oglSystem.visualInfo)
1977       {
1978    #ifdef   ECERE_MINIGLX
1979          __miniglx_XFree(oglSystem.visualInfo);
1980    #else
1981          XFree(oglSystem.visualInfo);
1982    #endif
1983       }
1984
1985       if(oglSystem.glxDrawable)
1986       {
1987          XDestroyWindow(xGlobalDisplay, oglSystem.glxDrawable);
1988          oglSystem.glxDrawable = 0;
1989       }
1990       #endif
1991    #endif
1992       delete oglSystem;
1993    }
1994
1995    bool CreateDisplay(Display display)
1996    {
1997       bool result = false;
1998       OGLDisplay oglDisplay = display.driverData;
1999 #if !defined(__ANDROID__) && !defined(__ODROID__)
2000       OGLSystem oglSystem = display.displaySystem.driverData;
2001 #endif
2002       if(!oglDisplay)
2003          oglDisplay = display.driverData = OGLDisplay { };
2004       //printf("Inside CreateDisplay\n");
2005
2006 #if defined(__WIN32__) || defined(USEPBUFFER)
2007       if(!display.alphaBlend)
2008 #endif
2009       {
2010    #if defined(__WIN32__)
2011          oglDisplay.hdc = GetDC(display.window);
2012          SetPixelFormat(oglDisplay.hdc, oglSystem.format, &oglSystem.pfd);
2013          if((oglDisplay.glrc = wglCreateContext(oglDisplay.hdc)))
2014          {
2015             wglShareLists(oglSystem.glrc, oglDisplay.glrc);
2016             wglMakeCurrent(oglDisplay.hdc, oglDisplay.glrc);
2017             result = true;
2018          }
2019          else
2020             ReleaseDC(display.window, oglDisplay.hdc);
2021    #elif defined(__unix__) || defined(__APPLE__)
2022       #if defined(__ANDROID__) || defined(__ODROID__)
2023       #else
2024          XVisualInfo * visualInfo = ((XWindowData)display.windowDriverData).visual;
2025          /*
2026 #if defined(__APPLE__)
2027          XVisualInfo template = { 0 };
2028          XWindowAttributes winAttr;
2029          int n;
2030          XGetWindowAttributes(xGlobalDisplay, (X11Window)display.window, &winAttr);
2031          template.visualid = XVisualIDFromVisual(winAttr.visual);
2032          visualInfo = XGetVisualInfo(xGlobalDisplay, VisualIDMask, &template, &n);
2033 #ifdef _DEBUG
2034          printf("XGetVisualInfo visual ID = %d\n", template.visualid);
2035          printf("visualInfo visual ID = %d\n", visualInfo->visualid);
2036          printf("oglSystem.visualInfo visual ID = %d\n", oglSystem.visualInfo->visualid);
2037          printf("((XWindowData)display.windowDriverData).visual visual ID = %d\n", ((XWindowData)display.windowDriverData).visual->visualid);
2038 #endif
2039          // visualInfo = oglSystem.visualInfo;
2040 //#endif
2041          */
2042          if(visualInfo)
2043          {
2044             //printf("visualInfo is not null\n");
2045             // printf("Creating Display Context, sharing with %x!\n", oglSystem.glContext);
2046             oglDisplay.glContext = glXCreateContext(xGlobalDisplay, visualInfo, oglSystem.glContext, True);
2047             //XFree(visualInfo);
2048          }
2049
2050          // oglDisplay.glContext = glXCreateContext(xGlobalDisplay, oglSystem.visualInfo, oglSystem.glContext, True);
2051          if(oglDisplay.glContext)
2052          {
2053             //printf("CreateDisplay Got a Context\n");
2054             glXMakeCurrent(xGlobalDisplay, (GLXDrawable)display.window, oglDisplay.glContext);
2055             result = true;
2056          }
2057       #endif
2058    #endif
2059       }
2060 #if defined(__WIN32__) || defined(USEPBUFFER)
2061       else
2062          result = true;
2063 #endif
2064       if(result)
2065       {
2066 #if defined(__WIN32__)
2067          if(glBlendFuncSeparate)
2068             glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
2069          else
2070             glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
2071 #else
2072 #if !defined(__OLDX__)
2073           glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
2074 #else
2075          glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
2076 #endif
2077 #endif
2078          glEnable(GL_BLEND);
2079
2080          glMatrixMode(GL_MODELVIEW);
2081          glLoadIdentity(); // For setting up GLES stack
2082          glScaled(1.0, 1.0, -1.0);
2083          // glTranslatef(0.375f, 0.375f, 0.0f);
2084          // glTranslatef(-0.625f, -0.625f, 0.0f);
2085          glMatrixMode(GL_PROJECTION);
2086          glShadeModel(GL_FLAT);
2087
2088          // glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, true);
2089          glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);
2090          glFogi(GL_FOG_MODE, GL_EXP);
2091          glFogf(GL_FOG_DENSITY, 0);
2092          glEnable(GL_NORMALIZE);
2093          glDepthFunc(GL_LESS);
2094          glClearDepth(1.0);
2095          glDisable(GL_MULTISAMPLE_ARB);
2096       }
2097 #if !defined(ECERE_NO3D) && !defined(ECERE_VANILLA)
2098       display.ambient = Color { 50,50,50 };
2099 #endif
2100
2101       if(!useSingleGLContext)
2102       {
2103    #if defined(__WIN32__)
2104          wglMakeCurrent(null, null);
2105    #elif defined(__unix__) || defined(__APPLE__)
2106       #if defined(__ANDROID__) || defined(__ODROID__)
2107          result = true;
2108       #else
2109          glXMakeCurrent(xGlobalDisplay, None, null);
2110       #endif
2111    #endif
2112       }
2113       else
2114       {
2115       #if defined(__ANDROID__) || defined(__EMSCRIPTEN__) || defined(__ODROID__)
2116          result = true;
2117       #endif
2118       }
2119
2120       return result;
2121    }
2122
2123    bool DisplaySize(Display display, int width, int height)
2124    {
2125       OGLDisplay oglDisplay = display.driverData;
2126
2127       bool result = false;
2128
2129       //printf("Inside DisplaySize\n");
2130 #if defined(__WIN32__) || defined(USEPBUFFER)
2131       OGLSystem oglSystem = display.displaySystem.driverData;
2132       if(display.alphaBlend)
2133       {
2134 #if defined(__WIN32__)
2135          const int attributes[]=
2136          {
2137             /*WGL_TEXTURE_FORMAT_ARB, WGL_TEXTURE_RGBA_ARB,
2138             WGL_TEXTURE_TARGET_ARB, WGL_TEXTURE_2D_ARB, */0
2139          };
2140          int pixelFormat = 0;
2141          if(wglChoosePixelFormatARB)
2142          {
2143             int valid;
2144             int numFormats;
2145             float fAttributes[] = {0,0};
2146             int iAttributes[] =
2147             {
2148                //WGL_DRAW_TO_BITMAP_ARB, GL_TRUE,
2149                WGL_DRAW_TO_PBUFFER_ARB,GL_TRUE,
2150                     WGL_SUPPORT_OPENGL_ARB,GL_TRUE,
2151                     WGL_ACCELERATION_ARB,WGL_FULL_ACCELERATION_ARB,
2152                     WGL_COLOR_BITS_ARB,24,
2153                     WGL_ALPHA_BITS_ARB,8,
2154                     WGL_DEPTH_BITS_ARB,16,
2155                     WGL_STENCIL_BITS_ARB,0,
2156                     WGL_DOUBLE_BUFFER_ARB,GL_FALSE,
2157                     WGL_SAMPLE_BUFFERS_ARB,GL_TRUE,
2158                     WGL_SAMPLES_ARB, 4,                                         // Check For 4x Multisampling
2159                     0,0
2160             };
2161
2162             //Log("Found wglChoosePixelFormatARB\n");
2163
2164             valid = wglChoosePixelFormatARB(oglSystem.hdc,iAttributes,fAttributes,1,&pixelFormat,&numFormats);
2165             if(!valid || !numFormats)
2166             {
2167                //Log("Can't find 4x multi sampling\n");
2168                iAttributes[19] = 2;
2169                valid = wglChoosePixelFormatARB(oglSystem.hdc,iAttributes,fAttributes,1,&pixelFormat,&numFormats);
2170                if(!valid || !numFormats)
2171                {
2172                   // Log("Can't find 2x multi sampling\n");
2173                   iAttributes[16] = 0;
2174                   iAttributes[17] = 0;
2175                   valid = wglChoosePixelFormatARB(oglSystem.hdc,iAttributes,fAttributes,1,&pixelFormat,&numFormats);
2176                   if(!valid || !numFormats)
2177                   {
2178                      int iAttributes[] =
2179                      {
2180                         WGL_DRAW_TO_PBUFFER_ARB,GL_TRUE,
2181                         //WGL_DRAW_TO_BITMAP_ARB,GL_TRUE,
2182                         WGL_SUPPORT_OPENGL_ARB,GL_TRUE,
2183                         WGL_COLOR_BITS_ARB,24,
2184                         WGL_ALPHA_BITS_ARB,8,
2185                         WGL_DEPTH_BITS_ARB,16,
2186                         0,0
2187                      };
2188                      valid = wglChoosePixelFormatARB(oglSystem.hdc,iAttributes,fAttributes,1,&pixelFormat,&numFormats);
2189                   }
2190                }
2191             }
2192             if(valid && numFormats)
2193             {
2194                wglMakeCurrent(null, null);
2195             }
2196          }
2197
2198          wglMakeCurrent( null, null );
2199          wglMakeCurrent( oglDisplay.hdc, oglDisplay.glrc );
2200          if(oglDisplay.hdc && oglDisplay.pBuffer)
2201             wglReleasePbufferDCARB(oglDisplay.pBuffer, oglDisplay.hdc);
2202
2203          wglDestroyPbufferARB(oglDisplay.pBuffer);
2204
2205          if(!useSingleGLContext)
2206             wglMakeCurrent( null, null );
2207
2208          if(oglDisplay.glrc)
2209             wglDeleteContext(oglDisplay.glrc);
2210
2211          oglDisplay.pBuffer = wglCreatePbufferARB(oglSystem.hdc, pixelFormat, width, height, attributes);
2212          oglDisplay.hdc = wglGetPbufferDCARB(oglDisplay.pBuffer);
2213          if((oglDisplay.glrc = wglCreateContext(oglDisplay.hdc)))
2214          {
2215             BITMAPINFO * info;
2216             HDC hdc = GetDC(display.window);
2217
2218             wglShareLists(oglSystem.glrc, oglDisplay.glrc);
2219             wglMakeCurrent(oglDisplay.hdc, oglDisplay.glrc);
2220
2221             //wglQueryPbufferARB(pBuffer, WGL_PBUFFER_WIDTH_ARB, &width);
2222             //wglQueryPbufferARB(pBuffer, WGL_PBUFFER_HEIGHT_ARB, &height);
2223
2224             // glDeleteBuffersARB(2, oglDisplay.imageBuffers);
2225
2226             if((info = (BITMAPINFO *)new0 byte[sizeof(BITMAPINFOHEADER)+sizeof(RGBQUAD)*256]))
2227             {
2228                HBITMAP newBitmap;
2229
2230                if(oglDisplay.memDC) DeleteDC(oglDisplay.memDC);
2231                oglDisplay.memDC = CreateCompatibleDC(hdc);
2232                SetMapMode(oglDisplay.memDC, MM_TEXT);
2233                info->bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
2234                info->bmiHeader.biPlanes = 1;
2235                info->bmiHeader.biCompression = BI_RGB;
2236                info->bmiHeader.biBitCount = 32; //(uint16)GetDeviceCaps(hdc, BITSPIXEL);
2237                info->bmiHeader.biWidth = width;
2238                info->bmiHeader.biHeight = height;
2239                newBitmap = CreateDIBSection(hdc, info, DIB_RGB_COLORS, &oglDisplay.picture, null, 0);
2240                if(newBitmap)
2241                {
2242                   SelectObject(oglDisplay.memDC, newBitmap);
2243                   if(oglDisplay.memBitmap) DeleteObject(oglDisplay.memBitmap);
2244                   /*
2245                   {
2246                      PIXELFORMATDESCRIPTOR pfd = { 0 };
2247                      pfd.nSize = (short)sizeof(pfd);
2248                      pfd.nVersion = 1;
2249                      pfd.dwFlags = PFD_DRAW_TO_BITMAP | PFD_SUPPORT_OPENGL;
2250                      pfd.iPixelType = PFD_TYPE_RGBA;
2251                      pfd.cColorBits = 32;
2252                      //pfd.cAlphaBits = 8;
2253                      pfd.cDepthBits = 24;
2254                      pfd.iLayerType = PFD_MAIN_PLANE;
2255
2256                      oglDisplay.hdc = oglDisplay.memDC;
2257
2258                      pixelFormat = ChoosePixelFormat(oglSystem.hdc, &pfd);
2259                      DescribePixelFormat(oglDisplay.hdc, pixelFormat, sizeof(pfd), &pfd);
2260                      SetPixelFormat(oglDisplay.hdc, pixelFormat, &pfd);
2261
2262                      oglDisplay.glrc = wglCreateContext(oglDisplay.hdc);
2263                      wglShareLists(oglSystem.glrc, oglDisplay.glrc);
2264                      wglMakeCurrent(oglDisplay.hdc, oglDisplay.glrc);
2265                   }
2266                   */
2267                   /*
2268                   {
2269                      const int imageSize = width * height * 4;
2270
2271                      glGenBuffersARB(2, oglDisplay.imageBuffers);
2272
2273                      glBindBufferARB(GL_PIXEL_PACK_BUFFER_ARB, oglDisplay.imageBuffers[0]);
2274                      glBufferDataARB(GL_PIXEL_PACK_BUFFER_ARB, imageSize, null, GL_STREAM_READ);
2275                      // glBindBufferARB(GL_PIXEL_PACK_BUFFER_ARB, oglDisplay.imageBuffers[1]);
2276                      // glBufferDataARB(GL_PIXEL_PACK_BUFFER_ARB, imageSize / 2, null, GL_STREAM_READ);
2277                   }
2278                   */
2279                   oglDisplay.memBitmap = newBitmap;
2280                   oglDisplay.stride = width;
2281
2282                   result = true;
2283                }
2284                delete info;
2285             }
2286             ReleaseDC(display.window, hdc);
2287          }
2288 #elif defined(__unix__) || defined(__APPLE__)
2289       #if defined(__ANDROID__) || defined(__ODROID__)
2290          result = true;
2291       #else
2292         int attrib[] =
2293         {
2294                 GLX_DOUBLEBUFFER,  True,
2295             GLX_DEPTH_SIZE,    1,
2296                 GLX_RED_SIZE,      8,
2297                 GLX_GREEN_SIZE,    8,
2298                 GLX_BLUE_SIZE,     8,
2299                 GLX_ALPHA_SIZE,    8,
2300                 GLX_STENCIL_SIZE,  1,
2301                 //GLX_DEPTH_SIZE,    24,
2302                 GLX_RENDER_TYPE,   GLX_RGBA_BIT,
2303                 GLX_DRAWABLE_TYPE, GLX_PBUFFER_BIT | GLX_WINDOW_BIT,
2304                 None
2305         };
2306
2307         int PBattrib[] =
2308         {
2309                 GLX_PBUFFER_WIDTH,   width,
2310                 GLX_PBUFFER_HEIGHT,  height,
2311                 GLX_LARGEST_PBUFFER, False,
2312             None
2313         };
2314
2315         // choose a pixel format that meets our minimum requirements
2316         int count = 0;
2317
2318         GLXFBConfig *config = glXChooseFBConfig(xGlobalDisplay, DefaultScreen(xGlobalDisplay), attrib, &count);
2319          if(config)
2320          {
2321             if(oglDisplay.pixmap)
2322             {
2323                XFreePixmap(xGlobalDisplay, oglDisplay.pixmap);
2324                oglDisplay.pixmap = None;
2325             }
2326             if(oglDisplay.shapePixmap)
2327             {
2328                XFreePixmap(xGlobalDisplay, oglDisplay.shapePixmap);
2329                oglDisplay.shapePixmap = None;
2330             }
2331
2332             // Free Shared Memory Pixmap
2333             if(oglDisplay.image)
2334             {
2335                if(oglDisplay.shminfoShape.shmid != -1)
2336                {
2337                   XShmDetach(xGlobalDisplay, &oglDisplay.shminfo);
2338                   if(oglDisplay.shminfo.shmaddr != (void *)-1)
2339                      shmdt(oglDisplay.shminfo.shmaddr);
2340                   shmctl(oglDisplay.shminfo.shmid, IPC_RMID, 0);
2341                }
2342                XDestroyImage(oglDisplay.image);
2343                oglDisplay.image = None;
2344             }
2345             if(oglDisplay.shapeImage)
2346             {
2347                if(oglDisplay.shminfoShape.shmid != -1)
2348                {
2349                   XShmDetach(xGlobalDisplay, &oglDisplay.shminfoShape);
2350                   if(oglDisplay.shminfoShape.shmaddr != (void *)-1)
2351                      shmdt(oglDisplay.shminfoShape.shmaddr);
2352                   shmctl(oglDisplay.shminfoShape.shmid, IPC_RMID, 0);
2353                }
2354                XDestroyImage(oglDisplay.shapeImage);
2355                oglDisplay.shapeImage = None;
2356             }
2357
2358             if(oglDisplay.windowPicture)
2359                XRenderFreePicture(xGlobalDisplay, oglDisplay.windowPicture);
2360             if(oglDisplay.pixmapPicture)
2361                XRenderFreePicture(xGlobalDisplay, oglDisplay.pixmapPicture);
2362
2363             if(oglDisplay.pixmap)
2364                XFreePixmap(xGlobalDisplay, oglDisplay.pixmap);
2365
2366             if(oglDisplay.glContext)
2367                   glXDestroyContext(xGlobalDisplay, oglDisplay.glContext);
2368             if(oglDisplay.pBuffer)
2369                glXDestroyPbuffer(xGlobalDisplay, oglDisplay.pBuffer);
2370
2371                 oglDisplay.pBuffer = glXCreatePbuffer(xGlobalDisplay, config[0], PBattrib);
2372             if(oglDisplay.pBuffer)
2373             {
2374                    oglDisplay.glContext = glXCreateNewContext(xGlobalDisplay, config[0], GLX_RGBA_TYPE, oglSystem.glContext, True);
2375                if(oglDisplay.glContext)
2376                {
2377                   glXMakeCurrent(xGlobalDisplay, None, null);
2378                   glXMakeCurrent(xGlobalDisplay, (GLXDrawable)display.window, oglDisplay.glContext);
2379
2380                   // Initialize Shared Memory Pixmap
2381                   oglDisplay.image = XShmCreateImage(xGlobalDisplay, DefaultVisual(xGlobalDisplay, DefaultScreen(xGlobalDisplay)), 32,
2382                      ZPixmap, null, &oglDisplay.shminfo, width, height);
2383                   if(oglDisplay.image)
2384                   {
2385                      oglDisplay.shminfo.shmid = shmget(IPC_PRIVATE,
2386                         oglDisplay.image->bytes_per_line * oglDisplay.image->height, IPC_CREAT|0777);
2387                      if(oglDisplay.shminfo.shmid != -1)
2388                      {
2389                         oglDisplay.shminfo.shmaddr = shmat(oglDisplay.shminfo.shmid, 0, 0);
2390                         if(oglDisplay.shminfo.shmaddr != (void *)-1)
2391                         {
2392                            oglDisplay.shminfo.readOnly = False;
2393                            if(XShmAttach(xGlobalDisplay, &oglDisplay.shminfo))
2394                            {
2395                               oglDisplay.pixmap = XShmCreatePixmap(xGlobalDisplay, (X11Window)display.window, oglDisplay.shminfo.shmaddr,
2396                                  &oglDisplay.shminfo, width, height, 32);
2397
2398                               // Initialize Shared Memory Shape Pixmap
2399                               oglDisplay.shapeImage = XShmCreateImage(xGlobalDisplay, DefaultVisual(xGlobalDisplay, DefaultScreen(xGlobalDisplay)), 1,
2400                                  ZPixmap, null, &oglDisplay.shminfoShape, width, height);
2401                               if(oglDisplay.shapeImage)
2402                               {
2403                                  oglDisplay.shminfoShape.shmid = shmget(IPC_PRIVATE,
2404                                     oglDisplay.shapeImage->bytes_per_line * oglDisplay.shapeImage->height, IPC_CREAT|0777);
2405                                  if(oglDisplay.shminfoShape.shmid != -1)
2406                                  {
2407                                     oglDisplay.shminfoShape.shmaddr = shmat(oglDisplay.shminfoShape.shmid, 0, 0);
2408                                     if(oglDisplay.shminfoShape.shmaddr != (void *)-1)
2409                                     {
2410                                        oglDisplay.shminfoShape.readOnly = False;
2411                                        if(XShmAttach(xGlobalDisplay, &oglDisplay.shminfoShape))
2412                                        {
2413                                           oglDisplay.shapePixmap = XShmCreatePixmap(xGlobalDisplay, (X11Window)display.window, oglDisplay.shminfoShape.shmaddr,
2414                                              &oglDisplay.shminfoShape, width, height, 1);
2415                                           //oglDisplay.shapePixmap = XCreatePixmap(xGlobalDisplay, (X11Window)display.window, width, height, 1);
2416
2417                                           {
2418                                              XRenderPictureAttributes attributes = { 0 };
2419                                              XRenderPictFormat * format = XRenderFindStandardFormat(xGlobalDisplay, /*PictStandardRGB24*/ PictStandardARGB32);
2420                                              #if !defined(__APPLE__) && !defined(__OLDX__)
2421                                              attributes.repeat = RepeatNormal;
2422                                              #else
2423                                              attributes.repeat = 1;
2424                                              #endif
2425                                              oglDisplay.pixmapPicture = XRenderCreatePicture(xGlobalDisplay, oglDisplay.pixmap, format, CPRepeat, &attributes);
2426                                              oglDisplay.windowPicture = XRenderCreatePicture(xGlobalDisplay, (X11Window)display.window, format, 0, &attributes);
2427                                              oglDisplay.shapePicture = XRenderCreatePicture(xGlobalDisplay, oglDisplay.shapePixmap,
2428                                                 XRenderFindStandardFormat(xGlobalDisplay, PictStandardA1), 0, &attributes);
2429                                           }
2430
2431                                           oglDisplay.picture = oglDisplay.shminfo.shmaddr;
2432                                           oglDisplay.stride = oglDisplay.image->bytes_per_line / 4;
2433
2434                                           result = true;
2435                                        }
2436                                     }
2437                                  }
2438                               }
2439                            }
2440                         }
2441                      }
2442                   }
2443                }
2444             }
2445             XFree(config);
2446          }
2447      #endif
2448 #endif
2449          CreateDisplay(display);
2450 #if defined(__WIN32__)
2451          wglMakeCurrent(oglDisplay.hdc, oglDisplay.glrc);
2452 #elif defined(__unix__) || defined(__APPLE__)
2453       #if defined(__ANDROID__) || defined(__ODROID__)
2454          width = eglWidth;
2455          height = eglHeight;
2456       #else
2457          glXMakeCurrent(xGlobalDisplay, (GLXDrawable)display.window, oglDisplay.glContext);
2458       #endif
2459 #endif
2460       }
2461       else
2462 #endif
2463          result = true;
2464       if(!result && display.alphaBlend)
2465       {
2466          printf("Alpha blending windows not supported on this display\n");
2467       }
2468       if(!result)
2469          return false;
2470
2471       result = false;
2472
2473       glViewport(0,0,width,height);
2474       glMatrixMode(GL_PROJECTION);
2475       glLoadIdentity();
2476       glOrtho(0,width,height,0,0.0,1.0);
2477       displayWidth = display.width = width;
2478       displayHeight = display.height = height;
2479
2480       if(!oglDisplay.flippingBuffer || oglDisplay.flipBufW < width || oglDisplay.flipBufH < height)
2481       {
2482          oglDisplay.flipBufW = width;
2483          oglDisplay.flipBufH = height;
2484 #ifdef _GLES
2485          result = true;
2486 #else
2487          oglDisplay.flippingBuffer = renew oglDisplay.flippingBuffer ColorAlpha [width * height];
2488 #endif
2489       }
2490       if(oglDisplay.flippingBuffer || !width || !height)
2491          result = true;
2492
2493       return result;
2494    }
2495
2496    void DisplayPosition(Display display, int x, int y)
2497    {
2498       OGLDisplay oglDisplay = display.driverData;
2499
2500       oglDisplay.x = x;
2501       oglDisplay.y = y;
2502    }
2503
2504    void SetPalette(Display display, ColorAlpha * palette, bool colorMatch)
2505    {
2506    }
2507
2508    void RestorePalette(Display display)
2509    {
2510    }
2511
2512    void StartUpdate(Display display)
2513    {
2514    }
2515
2516    void EndUpdate(Display display)
2517    {
2518    }
2519
2520    void Scroll(Display display, Box scroll, int x, int y, Extent dirty)
2521    {
2522    }
2523
2524    void Update(Display display, Box updateBox)
2525    {
2526 #if defined(__WIN32__) || defined(USEPBUFFER)
2527       OGLDisplay oglDisplay = display.driverData;
2528 #endif
2529       //Logf("DisplayScreen\n");
2530
2531       glFlush();
2532       glFinish();
2533 #if defined(__WIN32__) || defined(USEPBUFFER)
2534       if(display.alphaBlend)
2535       {
2536          glPixelStorei(GL_PACK_ALIGNMENT, 4);
2537          glPixelStorei(GL_PACK_ROW_LENGTH, oglDisplay.stride);
2538          glPixelStorei(GL_PACK_SKIP_ROWS, 0);
2539          glPixelStorei(GL_PACK_SKIP_PIXELS, 0);
2540          glReadPixels(0,0,display.width,display.height,GL_BGRA_EXT,GL_UNSIGNED_BYTE, oglDisplay.picture);
2541
2542          {
2543 #if defined(__WIN32__)
2544             HDC hdc = GetDC(0);
2545             POINT point = { oglDisplay.x, oglDisplay.y};
2546             POINT srcPoint = { 0, 0 };
2547             BLENDFUNCTION blend = { 0 };
2548             SIZE size;
2549             size.cx = display.width;
2550             size.cy = display.height;
2551             blend.BlendOp = AC_SRC_OVER;
2552             blend.BlendFlags = 0;
2553             blend.SourceConstantAlpha = 255;
2554             blend.AlphaFormat = AC_SRC_ALPHA;
2555
2556             /*
2557             // Process partial images.  Mapping the buffer waits for
2558             // outstanding DMA transfers into the buffer to finish.
2559             glBindBufferARB(GL_PIXEL_PACK_BUFFER_ARB, oglDisplay.imageBuffers[0]);
2560             oglDisplay.pboMemory1 = (byte *)glMapBufferARB(GL_PIXEL_PACK_BUFFER_ARB, GL_READ_ONLY);
2561
2562             // glBindBufferARB(GL_PIXEL_PACK_BUFFER_ARB, oglDisplay.imageBuffers[1]);
2563             // oglDisplay.pboMemory2 = (byte *)glMapBufferARB(GL_PIXEL_PACK_BUFFER_ARB,GL_READ_ONLY);
2564
2565
2566             memcpy(oglDisplay.picture, oglDisplay.pboMemory1, display.width * display.height * 4);
2567             //memcpy(oglDisplay.picture + display.width * display.height * 4 / 2, oglDisplay.pboMemory2, display.width * display.height * 4/ 2);
2568             */
2569
2570             UpdateLayeredWindow(display.window, hdc, &point, &size, oglDisplay.memDC, &srcPoint, 0, &blend, ULW_ALPHA);
2571             /*
2572
2573             // Unmap the image buffers
2574             glBindBufferARB(GL_PIXEL_PACK_BUFFER_ARB, oglDisplay.imageBuffers[0]);
2575             glUnmapBufferARB(GL_PIXEL_PACK_BUFFER_ARB);
2576
2577             // glBindBufferARB(GL_PIXEL_PACK_BUFFER_ARB, oglDisplay.imageBuffers[1]);
2578             // glUnmapBufferARB(GL_PIXEL_PACK_BUFFER_ARB);
2579
2580             // Bind two different buffer objects and start the glReadPixels
2581             // asynchronously. Each call will return directly after
2582             // starting the DMA transfer.
2583             glBindBufferARB(GL_PIXEL_PACK_BUFFER_ARB, oglDisplay.imageBuffers[0]);
2584             glReadPixels(0, 0, display.width, display.height, GL_BGRA, GL_UNSIGNED_BYTE, 0);
2585
2586             // glBindBufferARB(GL_PIXEL_PACK_BUFFER_ARB, oglDisplay.imageBuffers[1]);
2587             // glReadPixels(0, display.height/2, display.width, display.height/2, GL_BGRA, GL_UNSIGNED_BYTE, 0);
2588             */
2589
2590             ReleaseDC(0, hdc);
2591 #elif defined(__unix__) || defined(__APPLE__)
2592       #if defined(__ANDROID__) || defined(__ODROID__)
2593       #else
2594             XTransform transform =
2595             {
2596                {
2597                   { (int)(1.0f * (1<<16)), (int)(0.0f * (1<<16)),  (int)(0 * (1 << 16)) },
2598                   { (int)(0.0f),           (int)(-1.0f * (1<<16)), (int)(0 * (1<<16)) },
2599                   { (int)(0.0f * (1<<16)), (int)(0.0f * (1<<16)),  (int)(1.0f * (1<<16)) }
2600                }
2601             };
2602             XRenderSetPictureTransform(xGlobalDisplay, oglDisplay.pixmapPicture, &transform);
2603             XRenderComposite(xGlobalDisplay, PictOpSrc, oglDisplay.pixmapPicture, None, oglDisplay.shapePicture, 0, 0, 0, 0, 0, 0, display.width, display.height);
2604             XRenderComposite(xGlobalDisplay, PictOpSrc, oglDisplay.pixmapPicture, None, oglDisplay.windowPicture, 0, 0, 0, 0, 0, 0, display.width, display.height);
2605             #if !defined(__APPLE__) && !defined(__OLDX__)
2606             XShapeCombineMask(xGlobalDisplay, (X11Window)display.window, ShapeInput, 0, 0, oglDisplay.shapePixmap, ShapeSet);
2607             #else
2608             XShapeCombineMask(xGlobalDisplay, display.window, 2, 0, 0, oglDisplay.shapePixmap, ShapeSet);
2609             #endif
2610             XFlush(xGlobalDisplay);
2611      #endif
2612 #endif
2613          }
2614       }
2615       else
2616 #endif
2617       {
2618 #if defined(__WIN32__)
2619          //wglSwapLayerBuffers(oglDisplay.hdc,WGL_SWAP_MAIN_PLANE);
2620          SwapBuffers(oglDisplay.hdc);
2621 #elif defined(__unix__) || defined(__APPLE__)
2622       #if defined(__ANDROID__) || defined(__ODROID__)
2623          eglSwapBuffers(eglDisplay, eglSurface);
2624       #else
2625          glXSwapBuffers(xGlobalDisplay, (GLXDrawable)display.window);
2626       #endif
2627 #endif
2628       }
2629       //Logf("Out of DisplayScreen\n");
2630    }
2631
2632    void FreeBitmap(DisplaySystem displaySystem, Bitmap bitmap)
2633    {
2634       if(bitmap.driverData)
2635       {
2636          GLuint tex = (GLuint)(uintptr)bitmap.driverData;
2637          glDeleteTextures(1, &tex);
2638          bitmap.driverData = 0;
2639       }
2640       bitmap.driver = ((subclass(DisplayDriver))class(LFBDisplayDriver));
2641    }
2642
2643    bool AllocateBitmap(DisplaySystem displaySystem, Bitmap bitmap, int width, int height, int stride, PixelFormat format, bool allocatePalette)
2644    {
2645       OGLSystem oglSystem = displaySystem.driverData;
2646       bool result = false;
2647       Bitmap mipMap { };
2648       GLuint glBitmap = 0;
2649
2650       uint w = width, h = height;
2651       if(oglSystem.pow2textures)
2652       {
2653          w = pow2i(w);
2654          h = pow2i(h);
2655       }
2656       w = Min(w, oglSystem.maxTextureSize);
2657       h = Min(h, oglSystem.maxTextureSize);
2658
2659       glGenTextures(1, &glBitmap);
2660       glBindTexture(GL_TEXTURE_2D, glBitmap);
2661
2662       glPixelStorei( GL_UNPACK_ALIGNMENT, 1 );
2663
2664       glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
2665       glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
2666
2667       glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
2668       glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
2669
2670       glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
2671
2672       mipMap.Allocate(null, w, h, w, pixelFormatRGBA, false);
2673
2674       // glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, mipMap.picture);
2675       glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, mipMap.picture);
2676
2677       delete mipMap;
2678
2679       bitmap.driverData = (void *)(uintptr)glBitmap;
2680       bitmap.driver = displaySystem.driver;
2681       bitmap.width = w;
2682       bitmap.height = h;
2683
2684       result = true;
2685       return result;
2686    }
2687
2688    bool MakeDDBitmap(DisplaySystem displaySystem, Bitmap bitmap, bool mipMaps)
2689    {
2690       bool result = false;
2691       OGLSystem oglSystem = displaySystem.driverData;
2692
2693       // Pre process the bitmap... First make it 32 bit
2694       if(/*bitmap.pixelFormat == pixelFormatRGBA || */bitmap.Convert(null, pixelFormat888, null))
2695       {
2696          int c, level;
2697          uint w = bitmap.width, h = bitmap.height;
2698          GLuint glBitmap = 0;
2699          if(oglSystem.pow2textures)
2700          {
2701             w = pow2i(w);
2702             h = pow2i(h);
2703          }
2704          w = Min(w, oglSystem.maxTextureSize);
2705          h = Min(h, oglSystem.maxTextureSize);
2706
2707          if(mipMaps)
2708          {
2709             while(w * 2 < h) w *= 2;
2710             while(h * 2 < w) h *= 2;
2711          }
2712
2713          // Switch ARGB to RGBA
2714          //if(bitmap.format != pixelFormatRGBA)
2715          {
2716             for(c=0; c<bitmap.size; c++)
2717             {
2718                // ((ColorRGBA *)bitmap.picture)[c] = ((ColorAlpha *)bitmap.picture)[c];
2719                // TODO:
2720                ColorAlpha color = ((ColorAlpha *)bitmap.picture)[c];
2721                ((ColorRGBA *)bitmap.picture)[c] = ColorRGBA { color.color.r, color.color.g, color.color.b, color.a };
2722             }
2723          }
2724          bitmap.pixelFormat = pixelFormat888;
2725
2726          glGetError();
2727          glGenTextures(1, &glBitmap);
2728          if(glBitmap == 0)
2729          {
2730             //int error = glGetError();
2731             return false;
2732          }
2733
2734          glBindTexture(GL_TEXTURE_2D, glBitmap);
2735          glPixelStorei( GL_UNPACK_ALIGNMENT, 1 );
2736
2737          glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, mipMaps ? GL_LINEAR_MIPMAP_LINEAR : GL_LINEAR);
2738          glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
2739
2740          //glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
2741
2742          //glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
2743          //glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
2744
2745          glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
2746          glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
2747
2748          glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
2749
2750          result = true;
2751
2752          for(level = 0; result && (w >= 1 || h >= 1); level++, w >>= 1, h >>= 1)
2753          {
2754             Bitmap mipMap;
2755             if(!w) w = 1;
2756             if(!h) h = 1;
2757             if(bitmap.width != w || bitmap.height != h)
2758             {
2759                mipMap = Bitmap { };
2760                if(mipMap.Allocate(null, w, h, w, bitmap.pixelFormat, false))
2761                {
2762                   Surface mipSurface = mipMap.GetSurface(0,0,null);
2763                   mipSurface.Filter(bitmap, 0,0,0,0, w, h, bitmap.width, bitmap.height);
2764                   delete mipSurface;
2765                }
2766                else
2767                {
2768                   result = false;
2769                   delete mipMap;
2770                }
2771             }
2772             else
2773                mipMap = bitmap;
2774
2775             if(result)
2776             {
2777                int error;
2778                //int width = 0;
2779                glGetError();
2780                // glTexImage2D(GL_TEXTURE_2D, level, GL_RGBA8, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, mipMap.picture);
2781                glTexImage2D(GL_TEXTURE_2D, level, GL_RGBA, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, mipMap.picture);
2782                //printf("Calling glTexImage2D\n");
2783                //glGetTexLevelParameteriv(GL_TEXTURE_2D, level, GL_TEXTURE_WIDTH, &width);
2784                //printf("width = %d (Should be %d, %d)\n", width, w, h);
2785                if((error = glGetError()))
2786                {
2787                   //Logf("OpenGL Bitmap MakeDD error: %d...\n", error);
2788                   //printf("OpenGL Bitmap MakeDD error: %d...\n", error);
2789                   result = false;
2790                }
2791             }
2792             if(mipMap != bitmap)
2793                delete mipMap;
2794             if(!mipMaps) break;
2795          }
2796
2797          if(!bitmap.keepData)
2798             bitmap.driver.FreeBitmap(bitmap.displaySystem, bitmap);
2799          bitmap.driverData = (void *)(uintptr)glBitmap;
2800          bitmap.driver = displaySystem.driver;
2801
2802          if(!result)
2803             FreeBitmap(displaySystem, bitmap);
2804          else if(oglSystem.loadingFont)
2805          {
2806             glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
2807             glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
2808             oglSystem.loadingFont = false;
2809          }
2810       }
2811       return result;
2812    }
2813
2814    void ReleaseSurface(Display display, Surface surface)
2815    {
2816       glDisable(GL_SCISSOR_TEST);
2817       delete surface.driverData;
2818       surface.driverData = null;
2819    }
2820
2821    bool GetBitmapSurface(DisplaySystem displaySystem, Surface surface, Bitmap bitmap, int x, int y, Box clip)
2822    {
2823       return false;
2824    }
2825
2826    bool GetSurface(Display display, Surface surface, int x,int y, Box clip)
2827    {
2828       bool result = false;
2829       OGLSurface oglSurface = surface.driverData = OGLSurface { };
2830
2831       //Logf("GetSurface\n");
2832
2833       if(oglSurface)
2834       {
2835          if(displayWidth != display.width || displayHeight != display.height)
2836          {
2837             displayWidth = display.width;
2838             displayHeight = display.height;
2839
2840             glViewport(0,0,display.width,display.height);
2841             glLoadIdentity();
2842             glOrtho(0,display.width,display.height,0,0.0,1.0);
2843          }
2844
2845          surface.offset.x = x;
2846          surface.offset.y = y;
2847          surface.unclippedBox = surface.box = clip;
2848          oglSurface.bitmapMult[0] = 1;
2849          oglSurface.bitmapMult[1] = 1;
2850          oglSurface.bitmapMult[2] = 1;
2851          oglSurface.bitmapMult[3] = 1;
2852
2853          glEnable(GL_SCISSOR_TEST);
2854          glScissor(
2855             x+clip.left,
2856             (display.height) -(y+clip.bottom)-1,
2857             clip.right-clip.left+1,
2858             clip.bottom-clip.top+1);
2859          result = true;
2860       }
2861       return result;
2862    }
2863
2864    void Clip(Display display, Surface surface, Box clip)
2865    {
2866       Box box;
2867
2868       //Logf("Clip\n");
2869
2870       if(clip != null)
2871       {
2872          box = clip;
2873          box.Clip(surface.unclippedBox);
2874          surface.box = box;
2875       }
2876       else
2877          box = surface.box = surface.unclippedBox;
2878       box.left += surface.offset.x;
2879       box.top  += surface.offset.y;
2880       box.right+= surface.offset.x;
2881       box.bottom += surface.offset.y;
2882
2883       glScissor(
2884          box.left,display.height - box.bottom - 1,
2885          box.right-box.left+1, box.bottom-box.top+1);
2886    }
2887
2888    bool GrabScreen(Display display, Bitmap bitmap, int x, int y, unsigned int w, unsigned int h)
2889    {
2890       bool result = false;
2891       OGLDisplay oglDisplay = display.driverData;
2892       ColorAlpha * flippingBuffer = oglDisplay.flippingBuffer;
2893
2894       if(oglDisplay.flippingBuffer)
2895       {
2896          if(bitmap.pixelFormat != pixelFormat888 || bitmap.width < w || bitmap.height < h)
2897          {
2898             bitmap.Free();
2899             bitmap.Allocate(null, w,h,w, pixelFormat888, false);
2900          }
2901          if(bitmap)
2902          {
2903             uint row;
2904
2905             glPixelStorei(GL_PACK_ALIGNMENT, 4);
2906             glPixelStorei(GL_PACK_ROW_LENGTH, bitmap.stride);
2907             glPixelStorei(GL_PACK_SKIP_ROWS, 0);
2908             glPixelStorei(GL_PACK_SKIP_PIXELS, 0);
2909             glReadPixels(x,display.height-h-y,w,h,GL_BGRA_EXT,GL_UNSIGNED_BYTE, flippingBuffer);
2910
2911             // Need a flip...
2912             for(row = 0; row<h; row++)
2913                CopyBytesBy4(((ColorAlpha *)bitmap.picture) + row * w, ((ColorAlpha *)flippingBuffer) + (h-row-1) * w, w);
2914             result = true;
2915          }
2916       }
2917       return result;
2918    }
2919
2920    void SetForeground(Display display, Surface surface, ColorAlpha color)
2921    {
2922       OGLSurface oglSurface = surface.driverData;
2923
2924       //Logf("SetForeground\n");
2925
2926       oglSurface.foreground[0] = color.color.r/255.0f;
2927       oglSurface.foreground[1] = color.color.g/255.0f;
2928       oglSurface.foreground[2] = color.color.b/255.0f;
2929       //oglSurface.foreground[3] = 1.0f;
2930       oglSurface.foreground[3] = color.a/255.0f;
2931
2932       //if(!oglSurface.foreground[3])printf("bug");
2933    }
2934
2935    void SetBackground(Display display, Surface surface, ColorAlpha color)
2936    {
2937       OGLSurface oglSurface = surface.driverData;
2938
2939       //Logf("SetBackground\n");
2940
2941       oglSurface.background[0] = color.color.r/255.0f;
2942       oglSurface.background[1] = color.color.g/255.0f;
2943       oglSurface.background[2] = color.color.b/255.0f;
2944       //oglSurface.background[3] = 1.0;
2945       oglSurface.background[3] = color.a/255.0f;
2946    }
2947
2948    void SetBlitTint(Display display, Surface surface, ColorAlpha color)
2949    {
2950       OGLSurface oglSurface = surface.driverData;
2951
2952       oglSurface.bitmapMult[0] = color.color.r/255.0f;
2953       oglSurface.bitmapMult[1] = color.color.g/255.0f;
2954       oglSurface.bitmapMult[2] = color.color.b/255.0f;
2955       oglSurface.bitmapMult[3] = color.a/255.0f;
2956    }
2957
2958    ColorAlpha GetPixel(Display display, Surface surface,int x,int y)
2959    {
2960       return 0;
2961    }
2962
2963    void PutPixel(Display display, Surface surface,int x,int y)
2964    {
2965       OGLSurface oglSurface = surface.driverData;
2966
2967       //Logf("PutPixel\n");
2968
2969       glColor4fv(oglSurface.foreground);
2970       glBegin(GL_POINTS);
2971       // glVertex2i(x+surface.offset.x, y+surface.offset.y);
2972       glVertex2f(x+surface.offset.x + 0.5f, y+surface.offset.y + 0.5f);
2973
2974       glEnd();
2975    }
2976
2977    void DrawLine(Display display, Surface surface, int _x1, int _y1, int _x2, int _y2)
2978    {
2979       OGLSurface oglSurface = surface.driverData;
2980       float x1 = _x1, x2 = _x2, y1 = _y1, y2 = _y2;
2981       if(_x1 == _x2)
2982       {
2983          if(_y2 >= _y1)
2984             y2 += 1;
2985          else
2986             y1 += 1;
2987       }
2988       else if(_y1 == _y2)
2989       {
2990          if(_x2 >= _x1)
2991             x2 += 1;
2992          else
2993             x1 += 1;
2994       }
2995       x1 += surface.offset.x;
2996       y1 += surface.offset.y;
2997       x2 += surface.offset.x;
2998       y2 += surface.offset.y;
2999
3000       //Logf("Line\n");
3001
3002       glColor4fv(oglSurface.foreground);
3003       glBegin(GL_LINES);
3004 #ifdef _GLES
3005       if(stippleEnabled)
3006       {
3007          glTexCoord2f(0.5f, 0);
3008          glVertex2f(x1 + 0.5f, y1 + 0.5f);
3009          glTexCoord2f(Max(x2-x1, y2-y1) + 0.5f, 0);
3010          glVertex2f(x2 + 0.5f, y2 + 0.5f);
3011       }
3012       else
3013 #endif
3014       {
3015          /*
3016          glVertex2i(x1, y1);
3017          glVertex2i(x2, y2);
3018          */
3019          glVertex2f(x1 + 0.5f, y1 + 0.5f);
3020          glVertex2f(x2 + 0.5f, y2 + 0.5f);
3021       }
3022
3023       glEnd();
3024    }
3025
3026    void Rectangle(Display display, Surface surface,int x1,int y1,int x2,int y2)
3027    {
3028       OGLSurface oglSurface = surface.driverData;
3029       x1 += surface.offset.x;
3030       y1 += surface.offset.y;
3031       x2 += surface.offset.x;
3032       y2 += surface.offset.y;
3033
3034       //Logf("Rectangle\n");
3035
3036       glColor4fv(oglSurface.foreground);
3037 #ifdef _GLES
3038       if(stippleEnabled)
3039       {
3040          glBegin(GL_LINES);
3041
3042          glTexCoord2f(0.5f, 0);
3043          glVertex2f(x1 + 0.5f, y1 + 0.5f);
3044          glTexCoord2f(y2-y1 + 0.5f, 0);
3045          glVertex2f(x1 + 0.5f, y2 + 0.5f);
3046
3047          glTexCoord2f(0.5f, 0);
3048          glVertex2f(x1 + 0.5f, y2 + 0.5f);
3049          glTexCoord2f(x2 - x1 + 0.5f, 0);
3050          glVertex2f(x2 + 0.5f, y2 + 0.5f);
3051
3052          glTexCoord2f(0.5f, 0);
3053          glVertex2f(x2 + 0.5f, y2 + 0.5f);
3054          glTexCoord2f(y1 - y2 + 0.5f, 0);
3055          glVertex2f(x2 + 0.5f, y1 + 0.5f);
3056
3057          glTexCoord2f(0.5f, 0);
3058          glVertex2f(x2 + 0.5f, y1 + 0.5f);
3059          glTexCoord2f(x1 - x2 + 0.5f, 0);
3060          glVertex2f(x1 + 0.5f, y1 + 0.5f);
3061       }
3062       else
3063 #endif
3064       {
3065          glBegin(GL_LINE_LOOP);
3066          /*
3067          glVertex2i(x1, y1);
3068          glVertex2i(x1, y2);
3069          glVertex2i(x2, y2);
3070          glVertex2i(x2, y1);
3071          */
3072          glVertex2f(x1 + 0.5f, y1 + 0.5f);
3073          glVertex2f(x1 + 0.5f, y2 + 0.5f);
3074          glVertex2f(x2 + 0.5f, y2 + 0.5f);
3075          glVertex2f(x2 + 0.5f, y1 + 0.5f);
3076       }
3077       glEnd();
3078    }
3079
3080    void Area(Display display, Surface surface,int x1,int y1,int x2,int y2)
3081    {
3082       OGLSurface oglSurface = surface.driverData;
3083       //Logf("Area\n");
3084
3085       glColor4fv(oglSurface.background);
3086       glRecti(x1+surface.offset.x, y1+surface.offset.y,
3087               x2+surface.offset.x + 1, y2+surface.offset.y + 1);
3088
3089       /*
3090       glRectf(x1+surface.offset.x, y1+surface.offset.y,
3091               x2+surface.offset.x + 1, y2+surface.offset.y + 1);
3092       */
3093    }
3094
3095    void Clear(Display display, Surface surface, ClearType type)
3096    {
3097       OGLDisplay oglDisplay = display.driverData;
3098       OGLSurface oglSurface = surface.driverData;
3099
3100       //Logf("Clear\n");
3101       if(type != depthBuffer)
3102          glClearColor(oglSurface.background[0], oglSurface.background[1], oglSurface.background[2], oglSurface.background[3]);
3103       if(type != colorBuffer && !oglDisplay.depthWrite)
3104       {
3105          glDepthMask((byte)bool::true);
3106       }
3107       glClear(((type != depthBuffer) ? GL_COLOR_BUFFER_BIT : 0) |
3108               ((type != colorBuffer) ? GL_DEPTH_BUFFER_BIT : 0));
3109       if(type != colorBuffer && !oglDisplay.depthWrite)
3110       {
3111          glDepthMask((byte)bool::false);
3112       }
3113    }
3114
3115    bool ConvertBitmap(DisplaySystem displaySystem, Bitmap bitmap, PixelFormat format, ColorAlpha * palette)
3116    {
3117       return true;
3118    }
3119
3120    void Blit(Display display, Surface surface, Bitmap bitmap, int dx, int dy, int sx, int sy, int w, int h)
3121    {
3122       OGLSurface oglSurface = surface.driverData;
3123
3124 #if !defined(__OLDX__)
3125          // WHY DO WE HAVE GL_ONE HERE ?
3126          /*if(glBlendFuncSeparate && !oglSurface.writingText)
3127             glBlendFuncSeparate(GL_ONE, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA);*/
3128 #endif
3129
3130       if(!oglSurface.writingText)
3131       {
3132          // glTranslatef(-0.375f, -0.375f, 0.0f);
3133          glEnable(GL_TEXTURE_2D);
3134          glColor4fv(oglSurface.bitmapMult);
3135       }
3136       else if(oglSurface.xOffset)
3137          glTranslated(oglSurface.xOffset / 64.0/*-0.375*/, 0.0, 0.0);
3138
3139       glBindTexture(GL_TEXTURE_2D, (GLuint)(uintptr)bitmap.driverData);
3140       glBegin(GL_QUADS);
3141
3142       if(h < 0)
3143       {
3144          glTexCoord2f((float)sx/ bitmap.width, (float)(sy-h)/ bitmap.height);
3145          glVertex2i(dx+surface.offset.x, dy+surface.offset.y);
3146          glTexCoord2f((float)(sx+w) / bitmap.width, (float)(sy-h)/ bitmap.height);
3147          glVertex2i(dx+w+surface.offset.x, dy+surface.offset.y);
3148          glTexCoord2f((float)(sx+w)/ bitmap.width, (float)sy/ bitmap.height);
3149          glVertex2i(dx+w+surface.offset.x, dy-h+surface.offset.y);
3150          glTexCoord2f((float)sx / bitmap.width, (float)sy/ bitmap.height);
3151          glVertex2i(dx+surface.offset.x, dy-h+surface.offset.y);
3152       }
3153       else
3154       {
3155          /*
3156          glTexCoord2f((float)sx / bitmap.width, (float)sy/ bitmap.height);
3157          glVertex2i(dx+surface.offset.x, dy+surface.offset.y);
3158          glTexCoord2f((float)(sx+w)/ bitmap.width, (float)sy/ bitmap.height);
3159          glVertex2i(dx+w+surface.offset.x, dy+surface.offset.y);
3160          glTexCoord2f((float)(sx+w) / bitmap.width, (float)(sy+h)/ bitmap.height);
3161          glVertex2i(dx+w+surface.offset.x, dy+h+surface.offset.y);
3162          glTexCoord2f((float)sx/ bitmap.width, (float)(sy+h)/ bitmap.height);
3163          glVertex2i(dx+surface.offset.x, dy+h+surface.offset.y);
3164          */
3165
3166          glTexCoord2f((float)sx / bitmap.width, (float)sy/ bitmap.height);
3167          glVertex2f((float)dx+surface.offset.x, (float)dy+surface.offset.y);
3168          glTexCoord2f((float)(sx+w)/ bitmap.width, (float)sy/ bitmap.height);
3169          glVertex2f((float)dx+w+surface.offset.x, (float)dy+surface.offset.y);
3170          glTexCoord2f((float)(sx+w) / bitmap.width, (float)(sy+h)/ bitmap.height);
3171          glVertex2f((float)dx+w+surface.offset.x, (float)dy+h+surface.offset.y);
3172          glTexCoord2f((float)sx/ bitmap.width, (float)(sy+h)/ bitmap.height);
3173          glVertex2f((float)dx+surface.offset.x, (float)dy+h+surface.offset.y);
3174       }
3175       glEnd();
3176
3177       if(!oglSurface.writingText)
3178       {
3179          glDisable(GL_TEXTURE_2D);
3180
3181          //glTranslate(0.375, 0.375, 0.0);
3182       }
3183       else if(oglSurface.xOffset)
3184          glTranslated(-oglSurface.xOffset / 64.0/*+0.375*/, 0.0, 0.0);
3185
3186 #if !defined(__OLDX__)
3187          /*if(glBlendFuncSeparate && !oglSurface.writingText)
3188             glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA);*/
3189 #endif
3190    }
3191
3192    void Stretch(Display display, Surface surface, Bitmap bitmap, int dx, int dy, int sx, int sy, int w, int h, int sw, int sh)
3193    {
3194       OGLSurface oglSurface = surface.driverData;
3195
3196       //glTranslate(-0.375, -0.375, 0.0);
3197
3198       //Logf("Stretch\n");
3199
3200 #if !defined(__OLDX__)
3201       /*if(glBlendFuncSeparate)
3202          glBlendFuncSeparate(GL_ONE, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA);*/
3203 #endif
3204
3205       glEnable(GL_TEXTURE_2D);
3206       glBindTexture(GL_TEXTURE_2D, (GLuint)(uintptr)bitmap.driverData);
3207
3208       glColor4fv(oglSurface.bitmapMult);
3209
3210       glBegin(GL_QUADS);
3211
3212       if(h < 0)
3213       {
3214          glTexCoord2f((float)(sx)/ bitmap.width, (float)(sy+sh)/ bitmap.height);
3215          glVertex2i(dx+surface.offset.x, dy+surface.offset.y);
3216
3217          glTexCoord2f((float)(sx+sw) / bitmap.width, (float)(sy+sh)/ bitmap.height);
3218          glVertex2i(dx+w+surface.offset.x, dy+surface.offset.y);
3219
3220          glTexCoord2f((float)(sx+sw)/ bitmap.width, (float)(sy)/ bitmap.height);
3221          glVertex2i(dx+w+surface.offset.x, dy-h+surface.offset.y);
3222
3223          glTexCoord2f((float)(sx) / bitmap.width, (float)(sy)/ bitmap.height);
3224          glVertex2i(dx+surface.offset.x, dy-h+surface.offset.y);
3225       }
3226       else
3227       {
3228          glTexCoord2f((float)(sx) / bitmap.width, (float)(sy)/ bitmap.height);
3229          glVertex2i(dx+surface.offset.x, dy+surface.offset.y);
3230
3231          glTexCoord2f((float)(sx+sw)/ bitmap.width, (float)(sy)/ bitmap.height);
3232          glVertex2i(dx+w+surface.offset.x, dy+surface.offset.y);
3233
3234          glTexCoord2f((float)(sx+sw) / bitmap.width, (float)(sy+sh)/ bitmap.height);
3235          glVertex2i(dx+w+surface.offset.x, dy+h+surface.offset.y);
3236
3237          glTexCoord2f((float)(sx)/ bitmap.width, (float)(sy+sh)/ bitmap.height);
3238          glVertex2i(dx+surface.offset.x, dy+h+surface.offset.y);
3239       }
3240
3241       glEnd();
3242
3243       glDisable(GL_TEXTURE_2D);
3244
3245       //glTranslate(0.375, 0.375, 0.0);
3246 #if !defined(__OLDX__)
3247       /*if(glBlendFuncSeparate)
3248          glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA);*/
3249 #endif
3250
3251    }
3252
3253    void Filter(Display display, Surface surface, Bitmap bitmap, int dx, int dy, int sx, int sy, int w, int h, int sw, int sh)
3254    {
3255       Stretch(display, surface, bitmap, dx, dy, sx, sy, w, h, sw, sh);
3256    }
3257
3258    void StretchDI(Display display, Surface surface, Bitmap bitmap, int dx, int dy, int sx, int sy, int w, int h, int sw, int sh)
3259    {
3260       float s2dw,s2dh,d2sw,d2sh;
3261       //bool flipX = false, flipY = false;
3262
3263       //Logf("StretchDI\n");
3264
3265       if(Sgn(w) != Sgn(sw))
3266       {
3267          w = Abs(w);
3268          sw = Abs(sw);
3269          //flipX = true;
3270       }
3271       if(Sgn(h) != Sgn(sh))
3272       {
3273          h = Abs(h);
3274          sh = Abs(sh);
3275          //flipY = true;
3276       }
3277
3278       s2dw=(float)w / sw;
3279       s2dh=(float)h / sh;
3280       d2sw=(float)sw / w;
3281       d2sh=(float)sh / h;
3282
3283       //Clip against the edges of the source
3284       if(sx<0)
3285       {
3286          dx+=(int)((0-sx) * s2dw);
3287          w-=(int)((0-sx) * s2dw);
3288          sw-=0-sx;
3289          sx=0;
3290       }
3291       if(sy<0)
3292       {
3293          dy+=(int)((0-sy) * s2dh);
3294          h-=(int)((0-sy) * s2dh);
3295
3296          sh-=0-sy;
3297          sy=0;
3298       }
3299       if(sx+sw>bitmap.width-1)
3300       {
3301          w-=(int)((sx+sw-(bitmap.width-1)-1)*s2dw);
3302          sw-=sx+sw-(bitmap.width-1)-1;
3303       }
3304       if(sy+sh>(bitmap.height-1))
3305       {
3306          h-=(int)((sy+sh-(bitmap.height-1)-1)*s2dh);
3307          sh-=sy+sh-(bitmap.height-1)-1;
3308       }
3309       //Clip against the edges of the surfaceination
3310       if(dx<surface.box.left)
3311       {
3312          //if(!flip)
3313          sx+=(int)((surface.box.left-dx)*d2sw);
3314          sw-=(int)((surface.box.left-dx)*d2sw);
3315          w-=surface.box.left-dx;
3316          dx=surface.box.left;
3317       }
3318       if(dy<surface.box.top)
3319       {
3320          sy+=(int)((surface.box.top-dy)*d2sh);
3321          sh-=(int)((surface.box.top-dy)*d2sh);
3322          h-=surface.box.top-dy;
3323          dy=surface.box.top;
3324       }
3325       if(dx+w>surface.box.right)
3326       {
3327          //if(flip) sx+=(int)((dx+w-surface.box.right-1)*d2sw);
3328          sw-=(int)((dx+w-surface.box.right-1)*d2sw);
3329          w-=dx+w-surface.box.right-1;
3330       }
3331       if(dy+h>surface.box.bottom)
3332       {
3333          sh-=(int)((dy+h-surface.box.bottom-1)*d2sh);
3334          h-=dy+h-surface.box.bottom-1;
3335       }
3336       if((w<=0)||(h<=0)||(sw<=0)||(sh<=0)) return;
3337
3338       dx += surface.offset.x;
3339       dy += surface.offset.y;
3340
3341       if(bitmap.pixelFormat == pixelFormat888 && !bitmap.paletteShades)
3342       {
3343          glPixelStorei(GL_UNPACK_ALIGNMENT, 4);
3344          glPixelStorei(GL_UNPACK_ROW_LENGTH, bitmap.stride);
3345          glPixelStorei(GL_UNPACK_SKIP_PIXELS, sx);
3346          glPixelStorei(GL_UNPACK_SKIP_ROWS, sy);
3347          glRasterPos2d(dx,dy);
3348          //glPixelZoom(flipX ? -s2dw : s2dw, flipY ? s2dh : -s2dh);
3349          glPixelZoom(s2dw, -s2dh);
3350          glDrawPixels(sw,sh,GL_BGRA_EXT,GL_UNSIGNED_BYTE, bitmap.picture);
3351          glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
3352          glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
3353          glPixelStorei(GL_UNPACK_SKIP_PIXELS, 0);
3354          glPixelStorei(GL_UNPACK_SKIP_ROWS, 0);
3355       }
3356    }
3357
3358    void BlitDI(Display display, Surface surface, Bitmap bitmap, int dx, int dy, int sx, int sy, int w, int h)
3359    {
3360       //Logf("BlitDI\n");
3361
3362       //Clip against the edges of the source
3363       if(sx<0)
3364       {
3365          dx+=-sx;
3366          w-=-sx;
3367          sx=0;
3368       }
3369       if(sy<0)
3370       {
3371          dy+=0-sy;
3372          h-=0-sy;
3373          sy=0;
3374       }
3375       if(sx+w>bitmap.width-1)
3376          w-=sx+w-(bitmap.width-1)-1;
3377       if(sy+h>bitmap.height-1)
3378          h-=sy+h-(bitmap.height-1)-1;
3379       //Clip against the edges of the surfaceination
3380       if(dx<surface.box.left)
3381       {
3382          //if(!flip)
3383          sx+=surface.box.left-dx;
3384          w-=surface.box.left-dx;
3385          dx=surface.box.left;
3386       }
3387       if(dy<surface.box.top)
3388       {
3389          sy+=surface.box.top-dy;
3390          h-=surface.box.top-dy;
3391          dy=surface.box.top;
3392       }
3393       if(dx+w>surface.box.right)
3394       {
3395          //if(flip) sx+=dx+w-surface.box.right-1;
3396          w-=dx+w-surface.box.right-1;
3397       }
3398       if(dy+h>surface.box.bottom)
3399          h-=dy+h-surface.box.bottom-1;
3400       if((w<=0)||(h<=0))
3401          return;
3402
3403       dx += surface.offset.x;
3404       dy += surface.offset.y;
3405
3406       if(bitmap.pixelFormat == pixelFormat888 && !bitmap.paletteShades)
3407       {
3408          glPixelStorei(GL_UNPACK_ALIGNMENT, 4);
3409          glPixelStorei(GL_UNPACK_ROW_LENGTH, bitmap.stride);
3410          glPixelStorei(GL_UNPACK_SKIP_PIXELS, sx);
3411          glPixelStorei(GL_UNPACK_SKIP_ROWS, sy);
3412          glRasterPos2d(dx,dy);
3413          glPixelZoom(1,-1);
3414          glDrawPixels(w,h,GL_BGRA_EXT,GL_UNSIGNED_BYTE, bitmap.picture);
3415          glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
3416          glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
3417          glPixelStorei(GL_UNPACK_SKIP_PIXELS, 0);
3418          glPixelStorei(GL_UNPACK_SKIP_ROWS, 0);
3419       }
3420    }
3421
3422    void FilterDI(Display display, Surface surface, Bitmap bitmap, int dx, int dy, int sx, int sy, int w, int h, int sw, int sh)
3423    {
3424       StretchDI(display, surface, bitmap, dx, dy, sx, sy, w, h, sw, sh);
3425    }
3426
3427    void UnloadFont(DisplaySystem displaySystem, Font font)
3428    {
3429       ((subclass(DisplayDriver))class(LFBDisplayDriver)).UnloadFont(displaySystem, font);
3430    }
3431
3432    Font LoadFont(DisplaySystem displaySystem, const char * faceName, float size, FontFlags flags)
3433    {
3434       Font font;
3435       OGLSystem oglSystem = displaySystem.driverData;
3436       oglSystem.loadingFont = true;
3437       font = ((subclass(DisplayDriver))class(LFBDisplayDriver)).LoadFont(displaySystem, faceName, size, flags);
3438       return font;
3439    }
3440
3441    void FontExtent(DisplaySystem displaySystem, Font font, const char * text, int len, int * width, int * height)
3442    {
3443       ((subclass(DisplayDriver))class(LFBDisplayDriver)).FontExtent(displaySystem, font, text, len, width, height);
3444    }
3445
3446    void WriteText(Display display, Surface surface, int x, int y, const char * text, int len)
3447    {
3448       OGLSurface oglSurface = surface.driverData;
3449       OGLSystem oglSystem = display.displaySystem.driverData;
3450       oglSystem.loadingFont = true;
3451
3452       //glTranslated(-0.375, -0.375, 0.0);
3453
3454       //Logf("Blit\n");
3455
3456       if(surface.textOpacity)
3457       {
3458          int w, h;
3459          FontExtent(display.displaySystem, surface.font, text, len, &w, &h);
3460          display.displaySystem.driver.Area(display, surface,x,y,x+w-1,y+h-1);
3461       }
3462
3463       oglSurface.writingText = true;
3464
3465       glEnable(GL_TEXTURE_2D);
3466       glColor4fv(oglSurface.foreground);
3467
3468       ((subclass(DisplayDriver))class(LFBDisplayDriver)).WriteText(display, surface, x, y, text, len);
3469       oglSurface.writingText = false;
3470       oglSystem.loadingFont = false;
3471
3472       glDisable(GL_TEXTURE_2D);
3473
3474       //glTranslated(0.375, 0.375, 0.0);
3475    }
3476
3477    void TextFont(Display display, Surface surface, Font font)
3478    {
3479       ((subclass(DisplayDriver))class(LFBDisplayDriver)).TextFont(display, surface, font);
3480    }
3481
3482    void TextOpacity(Display display, Surface surface, bool opaque)
3483    {
3484       OGLSurface oglSurface = surface.driverData;
3485       oglSurface.opaqueText = opaque;
3486    }
3487
3488    void TextExtent(Display display, Surface surface, const char * text, int len, int * width, int * height)
3489    {
3490       OGLSurface oglSurface = surface.driverData;
3491       OGLSystem oglSystem = display.displaySystem.driverData;
3492       oglSystem.loadingFont = true;
3493       FontExtent(display.displaySystem, oglSurface.font, text, len, width, height);
3494       oglSystem.loadingFont = false;
3495    }
3496
3497    void DrawingChar(Display display, Surface surface, char character)
3498    {
3499
3500    }
3501
3502    void LineStipple(Display display, Surface surface, uint32 stipple)
3503    {
3504       //Logf("Stipple\n");
3505
3506       if(stipple)
3507       {
3508 #if defined(_GLES)
3509          stippleEnabled = true;
3510          glesLineStipple(1, (uint16)stipple);
3511 #else
3512          glLineStipple(1, (uint16)stipple);
3513          glEnable(GL_LINE_STIPPLE);
3514 #endif
3515       }
3516       else
3517       {
3518 #if defined(_GLES)
3519          stippleEnabled = false;
3520          glMatrixMode(GL_TEXTURE);
3521          glLoadIdentity();
3522          glMatrixMode(GL_PROJECTION);
3523          glDisable(GL_TEXTURE_2D);
3524 #else
3525          glDisable(GL_LINE_STIPPLE);
3526 #endif
3527       }
3528    }
3529 #if !defined(ECERE_NO3D) && !defined(ECERE_VANILLA)
3530    void SetRenderState(Display display, RenderState state, uint value)
3531    {
3532       OGLDisplay oglDisplay = display.driverData;
3533       //Logf("RenderState\n");
3534
3535       switch(state)
3536       {
3537          case antiAlias:
3538             if(value)
3539                glEnable(GL_MULTISAMPLE_ARB);
3540             else
3541                glDisable(GL_MULTISAMPLE_ARB);
3542             break;
3543          case fillMode:
3544 #if !defined(_GLES)
3545             glPolygonMode(GL_FRONT_AND_BACK, ((FillModeValue)value == solid) ? GL_FILL : GL_LINE);
3546 #endif
3547             break;
3548          case depthTest:
3549             if(value) glEnable(GL_DEPTH_TEST); else glDisable(GL_DEPTH_TEST);
3550             break;
3551          case depthWrite:
3552             if(value) glDepthMask((byte)bool::true); else glDepthMask((byte)bool::false);
3553             oglDisplay.depthWrite = (bool)value;
3554             break;
3555          case fogColor:
3556          {
3557             float color[4] = { ((Color)value).r/255.0f, ((Color)value).g/255.0f, ((Color)value).b/255.0f, 1.0f };
3558             glFogfv(GL_FOG_COLOR, (float *)&color);
3559             break;
3560          }
3561          case fogDensity:
3562             glFogf(GL_FOG_DENSITY, (float)(RenderStateFloat { ui = value }.f * nearPlane));
3563             break;
3564          case blend:
3565             if(value) glEnable(GL_BLEND); else glDisable(GL_BLEND);
3566             break;
3567          case ambient:
3568          {
3569             float ambient[4] = { ((Color)value).r/255.0f, ((Color)value).g/255.0f, ((Color)value).b/255.0f, 1.0f };
3570             glLightModelfv(GL_LIGHT_MODEL_AMBIENT, ambient);
3571             break;
3572          }
3573          case alphaWrite:
3574          {
3575             if(value) glColorMask(1,1,1,1); else glColorMask(1,1,1,0);
3576             break;
3577          }
3578          case vSync:
3579          {
3580 #if defined(__WIN32__)
3581             wglSwapIntervalEXT(value ? 1 : 0);
3582 #endif
3583             break;
3584          }
3585       }
3586    }
3587
3588    void SetLight(Display display, int id, Light light)
3589    {
3590       //Logf("SetLight\n");
3591
3592       if(light != null)
3593       {
3594          Object lightObject = light.lightObject;
3595          float position[4] = { 0, 0, 0, 0 };
3596          float color[4] = { 0, 0, 0, 1 };
3597
3598          glEnable(GL_LIGHT0 + id);
3599          /*
3600          glLightfv(GL_LIGHT0 + id, GL_DIFFUSE, (float *)&light.diffuse);
3601          glLightfv(GL_LIGHT0 + id, GL_AMBIENT, (float *)&light.ambient);
3602          glLightfv(GL_LIGHT0 + id, GL_SPECULAR,(float *)&light.specular);
3603          */
3604
3605          if(!light.multiplier) light.multiplier = 1.0f;
3606
3607          color[0] = light.diffuse.r * light.multiplier;
3608          color[1] = light.diffuse.g * light.multiplier;
3609          color[2] = light.diffuse.b * light.multiplier;
3610          glLightfv(GL_LIGHT0 + id, GL_DIFFUSE, color);
3611
3612          color[0] = light.ambient.r * light.multiplier;
3613          color[1] = light.ambient.g * light.multiplier;
3614          color[2] = light.ambient.b * light.multiplier;
3615          glLightfv(GL_LIGHT0 + id, GL_AMBIENT, color);
3616          color[0] = light.specular.r * light.multiplier;
3617          color[1] = light.specular.g * light.multiplier;
3618          color[2] = light.specular.b * light.multiplier;
3619          glLightfv(GL_LIGHT0 + id, GL_SPECULAR,color);
3620
3621          if(lightObject)
3622          {
3623             Vector3D positionVector;
3624             if(light.flags.spot)
3625             {
3626                if(lightObject.flags.root || !lightObject.parent)
3627                {
3628                   positionVector = lightObject.transform.position;
3629                   positionVector.Subtract(positionVector, display.display3D.camera.cPosition);
3630                }
3631                else
3632                {
3633                   positionVector.MultMatrix(lightObject.transform.position, lightObject.parent.matrix);
3634                   if(display.display3D.camera)
3635                      positionVector.Subtract(positionVector, display.display3D.camera.cPosition);
3636                }
3637                position[3] = 1;
3638             }
3639             else
3640             {
3641                if(!light.direction.x && !light.direction.y && !light.direction.z)
3642                {
3643                   Vector3Df vector { 0,0,-1 };
3644                   Matrix mat;
3645                   mat.RotationQuaternion(light.orientation);
3646                   positionVector.MultMatrixf(vector, mat);
3647                }
3648                else
3649                {
3650                   positionVector = light.direction;
3651                   position[3] = 1;
3652                }
3653             }
3654
3655             position[0] = (float)positionVector.x;
3656             position[1] = (float)positionVector.y;
3657             position[2] = (float)positionVector.z;
3658
3659             glLightfv(GL_LIGHT0 + id, GL_POSITION, position);
3660
3661             /*
3662             // Display Light Position
3663             glDisable(GL_LIGHTING);
3664             glDisable(GL_DEPTH_TEST);
3665             glColor3f(1,1,1);
3666             glPointSize(10);
3667             glBegin(GL_POINTS);
3668             glVertex3fv(position);
3669             glEnd();
3670             glEnable(GL_DEPTH_TEST);
3671             glEnable(GL_LIGHTING);
3672
3673
3674             // Display Target
3675             if(lightObject.flags.root || !lightObject.parent)
3676             {
3677                positionVector = light.target.transform.position;
3678                positionVector.Subtract(positionVector, display.camera.cPosition);
3679             }
3680             else
3681             {
3682                positionVector.MultMatrix(light.target.transform.position,
3683                   lightObject.light.target.parent.matrix);
3684                positionVector.Subtract(positionVector, display.camera.cPosition);
3685             }
3686
3687             position[0] = positionVector.x;
3688             position[1] = positionVector.y;
3689             position[2] = positionVector.z;
3690
3691             glDisable(GL_LIGHTING);
3692             glDisable(GL_DEPTH_TEST);
3693             glColor3f(1,1,0);
3694             glPointSize(10);
3695             glBegin(GL_POINTS);
3696             glVertex3fv(position);
3697             glEnd();
3698             glEnable(GL_DEPTH_TEST);
3699             glEnable(GL_LIGHTING);
3700             */
3701
3702             if(light.flags.attenuation)
3703             {
3704                glLightf(GL_LIGHT0 + id, GL_CONSTANT_ATTENUATION, light.Kc);
3705                glLightf(GL_LIGHT0 + id, GL_LINEAR_ATTENUATION, light.Kl);
3706                glLightf(GL_LIGHT0 + id, GL_QUADRATIC_ATTENUATION, light.Kq);
3707             }
3708
3709             if(light.flags.spot)
3710             {
3711                float exponent = 0;
3712                #define MAXLIGHT  0.9
3713                float direction[4] = { (float)light.direction.x, (float)light.direction.y, (float)light.direction.z, 1 };
3714                // Figure out exponent out of the hot spot
3715                exponent = (float)(log(MAXLIGHT) / log(cos((light.hotSpot / 2))));
3716
3717                glLightfv(GL_LIGHT0 + id, GL_SPOT_DIRECTION, direction);
3718                glLightf(GL_LIGHT0 + id, GL_SPOT_CUTOFF, (float)(light.fallOff / 2));
3719                glLightf(GL_LIGHT0 + id, GL_SPOT_EXPONENT, exponent);
3720             }
3721          }
3722          else
3723          {
3724
3725             Vector3Df vector { 0,0,-1 };
3726             Vector3Df direction;
3727             Matrix mat;
3728
3729             mat.RotationQuaternion(light.orientation);
3730             direction.MultMatrix(vector, mat);
3731
3732             position[0] = direction.x;
3733             position[1] = direction.y;
3734             position[2] = direction.z;
3735
3736             glLightfv(GL_LIGHT0 + id, GL_POSITION, position);
3737          }
3738       }
3739       else
3740          glDisable(GL_LIGHT0 + id);
3741    }
3742
3743    void SetCamera(Display display, Surface surface, Camera camera)
3744    {
3745       OGLDisplay oglDisplay = display.driverData;
3746       //Logf("SetCamera\n");
3747
3748       if(camera)
3749       {
3750          int left = surface.box.left + surface.offset.x;
3751          int top = surface.box.top  + surface.offset.y;
3752          int right = surface.box.right + surface.offset.x;
3753          int bottom = surface.box.bottom + surface.offset.y;
3754          float origX = surface.offset.x + camera.origin.x;
3755          float origY = surface.offset.y + camera.origin.y;
3756          int x = left;
3757          int y = display.height - bottom - 1;
3758          int w = right - left + 1;
3759          int h = bottom - top + 1;
3760
3761          // *** ViewPort ***
3762          glViewport(x, y, w, h);
3763
3764          // *** Projection Matrix ***
3765          glMatrixMode(GL_PROJECTION);
3766          if(!display.display3D.camera)
3767             glPushMatrix();
3768
3769          if(display.display3D.collectingHits)
3770          {
3771             float pickX = display.display3D.pickX + surface.offset.x;
3772             float pickY = display.height - (display.display3D.pickY + surface.offset.y) - 1;
3773             Matrix pickMatrix
3774             {
3775                {
3776                   w / display.display3D.pickWidth, 0, 0, 0,
3777                   0, h / display.display3D.pickHeight, 0, 0,
3778                   0, 0, 1, 0,
3779                   (w + 2.0f * (x - pickX)) / display.display3D.pickWidth,
3780                   (h + 2.0f * (y - pickY)) / display.display3D.pickHeight, 0, 1
3781                }
3782             };
3783             glLoadMatrixd(pickMatrix.array);
3784          }
3785          else
3786             glLoadIdentity();
3787          glFrustum(
3788             (left   - origX) * camera.zMin / camera.focalX,
3789             (right  - origX) * camera.zMin / camera.focalX,
3790             (bottom - origY) * camera.zMin / camera.focalY,
3791             (top    - origY) * camera.zMin / camera.focalY,
3792             camera.zMin, camera.zMax);
3793
3794          glDisable(GL_BLEND);
3795
3796          // *** Z Inverted Identity Matrix ***
3797          glMatrixMode(GL_MODELVIEW);
3798          if(!display.display3D.camera)
3799             glPushMatrix();
3800
3801          glLoadIdentity();
3802
3803          glScaled(1.0/nearPlane, 1.0/nearPlane, -1.0/nearPlane);
3804
3805          // *** View Matrix ***
3806          glMultMatrixd(camera.viewMatrix.array);
3807
3808          // *** Lights ***
3809          // ...
3810
3811          glEnable(GL_DEPTH_TEST);
3812          glEnable(GL_LIGHTING);
3813          glShadeModel(GL_SMOOTH);
3814          glDepthMask((byte)bool::true);
3815          oglDisplay.depthWrite = true;
3816
3817          glEnable(GL_MULTISAMPLE_ARB);
3818       }
3819       else if(display.display3D.camera)
3820       {
3821          oglDisplay.depthWrite = false;
3822          glViewport(0,0,display.width,display.height);
3823
3824          glDisable(GL_CULL_FACE);
3825          glDisable(GL_DEPTH_TEST);
3826          glDisable(GL_LIGHTING);
3827          glDisable(GL_FOG);
3828          glDisable(GL_TEXTURE_2D);
3829          glShadeModel(GL_FLAT);
3830          glEnable(GL_BLEND);
3831          glDisable(GL_MULTISAMPLE_ARB);
3832
3833          // *** Restore 2D MODELVIEW Matrix ***
3834          glPopMatrix();
3835
3836          // *** Restore 2D PROJECTION Matrix ***
3837          glMatrixMode(GL_PROJECTION);
3838          glPopMatrix();
3839       }
3840
3841    }
3842
3843    void ApplyMaterial(Display display, Material material, Mesh mesh)
3844    {
3845       //Logf("ApplyMaterial\n");
3846
3847       // Basic Properties
3848       if(material.flags.doubleSided)
3849       {
3850          glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, !material.flags.singleSideLight);
3851          glDisable(GL_CULL_FACE);
3852       }
3853       else
3854       {
3855          glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, bool::false);
3856          glEnable(GL_CULL_FACE);
3857       }
3858
3859       // Fog
3860       if(material.flags.noFog)
3861          glDisable(GL_FOG);
3862       else
3863          glEnable(GL_FOG);
3864
3865       // Maps
3866       if(material.baseMap && (mesh.texCoords || mesh.flags.texCoords1))
3867       {
3868          Bitmap map = material.baseMap;
3869          glEnable(GL_TEXTURE_2D);
3870          glBindTexture(GL_TEXTURE_2D, (GLuint)(uintptr)map.driverData);
3871
3872          glMatrixMode(GL_TEXTURE);
3873          glLoadIdentity();
3874          if(material.uScale && material.vScale)
3875             glScalef(material.uScale, material.vScale, 1);
3876          glMatrixMode(GL_MODELVIEW);
3877
3878          if(material.flags.tile)
3879          {
3880             glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
3881             glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
3882          }
3883          else
3884          {
3885             glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
3886             glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
3887          }
3888       }
3889       else
3890          glDisable(GL_TEXTURE_2D);
3891
3892       if(mesh.flags.colors)
3893       {
3894          glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE);
3895          glEnable(GL_COLOR_MATERIAL);
3896       }
3897       else
3898       {
3899          glDisable(GL_COLOR_MATERIAL);
3900          {
3901             float color[4] = { material.diffuse.r, material.diffuse.g, material.diffuse.b, material.opacity };
3902             glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, color);
3903          }
3904          {
3905             float color[4] = { material.ambient.r, material.ambient.g, material.ambient.b, 0 };
3906             glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, color);
3907          }
3908       }
3909       {
3910          float color[4] = { material.specular.r, material.specular.g, material.specular.b, 0 };
3911          glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, color);
3912       }
3913       {
3914          float color[4] = { material.emissive.r, material.emissive.g, material.emissive.b, 0 };
3915          glMaterialfv(GL_FRONT_AND_BACK, GL_EMISSION, color);
3916       }
3917
3918       glMaterialfv(GL_FRONT_AND_BACK, GL_SHININESS, &material.power);
3919    }
3920
3921    void FreeMesh(DisplaySystem displaySystem, Mesh mesh)
3922    {
3923       OGLMesh oglMesh = mesh.data;
3924       if(oglMesh)
3925       {
3926          if(!mesh.flags.vertices)
3927          {
3928             oglMesh.vertices.free();
3929             delete mesh.vertices;
3930          }
3931          if(!mesh.flags.normals)
3932          {
3933             oglMesh.normals.free();
3934             delete mesh.normals;
3935          }
3936          if(!mesh.flags.texCoords1)
3937          {
3938             oglMesh.texCoords.free();
3939             delete mesh.texCoords;
3940          }
3941          if(!mesh.flags.texCoords2)
3942          {
3943             oglMesh.texCoords2.free();
3944             // delete mesh.texCoords2;
3945          }
3946          if(!mesh.flags.colors)
3947          {
3948             oglMesh.colors.free();
3949             delete mesh.colors;
3950          }
3951          if(!mesh.flags)
3952          {
3953             delete oglMesh;
3954             mesh.data = null;
3955          }
3956       }
3957    }
3958
3959    bool AllocateMesh(DisplaySystem displaySystem, Mesh mesh, MeshFeatures flags, int nVertices)
3960    {
3961       bool result = false;
3962
3963       if(!mesh.data)
3964          mesh.data = OGLMesh { };
3965       if(mesh.data)
3966       {
3967          if(mesh.nVertices == nVertices)
3968          {
3969             // Same number of vertices, adding features (Leaves the other features pointers alone)
3970             if(mesh.flags != flags)
3971             {
3972                if(!mesh.flags.vertices && flags.vertices)
3973                {
3974                   if(flags.doubleVertices)
3975                   {
3976                      mesh.vertices = (Vector3Df *)new Vector3D[nVertices];
3977                   }
3978                   else
3979                      mesh.vertices = new Vector3Df[nVertices];
3980                }
3981                if(!mesh.flags.normals && flags.normals)
3982                {
3983                   if(flags.doubleNormals)
3984                   {
3985                      mesh.normals = (Vector3Df *)new Vector3D[nVertices];
3986                   }
3987                   else
3988                      mesh.normals = new Vector3Df[nVertices];
3989                }
3990                if(!mesh.flags.texCoords1 && flags.texCoords1)
3991                {
3992                   mesh.texCoords = new Pointf[nVertices];
3993                }
3994                if(!mesh.flags.colors && flags.colors)
3995                {
3996                   mesh.colors = new ColorRGBAf[nVertices];
3997                }
3998             }
3999          }
4000          else
4001          {
4002             // New number of vertices, reallocate all current and new features
4003             flags |= mesh.flags;
4004             if(flags.vertices)
4005             {
4006                if(flags.doubleVertices)
4007                {
4008                   mesh.vertices = (Vector3Df *)renew mesh.vertices Vector3D[nVertices];
4009                }
4010                else
4011                   mesh.vertices = renew mesh.vertices Vector3Df[nVertices];
4012             }
4013             if(flags.normals)
4014             {
4015                if(flags.doubleNormals)
4016                {
4017                   mesh.normals = (Vector3Df *)renew mesh.normals Vector3D[nVertices];
4018                }
4019                else
4020                   mesh.normals = renew mesh.normals Vector3Df[nVertices];
4021             }
4022             if(flags.texCoords1)
4023             {
4024                mesh.texCoords = renew mesh.texCoords Pointf[nVertices];
4025             }
4026             if(flags.colors)
4027             {
4028                mesh.colors = renew mesh.colors ColorRGBAf[nVertices];
4029             }
4030          }
4031          result = true;
4032       }
4033       return result;
4034    }
4035
4036    void UnlockMesh(DisplaySystem displaySystem, Mesh mesh, MeshFeatures flags)
4037    {
4038       OGLMesh oglMesh = mesh.data;
4039       if(!flags) flags = mesh.flags;
4040
4041       if(vboAvailable)
4042       {
4043          if(flags.vertices)
4044             oglMesh.vertices.upload(
4045                mesh.nVertices * (mesh.flags.doubleVertices ? sizeof(Vector3D) : sizeof(Vector3Df)), mesh.vertices); //, GL_STATIC_DRAW_ARB );
4046
4047          if(flags.normals)
4048             oglMesh.normals.upload(
4049                mesh.nVertices * (mesh.flags.doubleNormals ? sizeof(Vector3D) : sizeof(Vector3Df)), mesh.normals); //, GL_STATIC_DRAW_ARB );
4050
4051          if(flags.texCoords1)
4052             oglMesh.texCoords.upload(
4053                mesh.nVertices * sizeof(Pointf), mesh.texCoords); //, GL_STATIC_DRAW_ARB );
4054
4055          if(flags.colors)
4056             oglMesh.colors.upload(
4057                mesh.nVertices * sizeof(ColorRGBAf), mesh.colors); //, GL_STATIC_DRAW_ARB );
4058       }
4059    }
4060
4061    bool LockMesh(DisplaySystem displaySystem, Mesh mesh, MeshFeatures flags)
4062    {
4063       bool result = true;
4064
4065         return result;
4066    }
4067
4068    void FreeIndices(DisplaySystem displaySystem, OGLIndices oglIndices)
4069    {
4070       if(oglIndices)
4071       {
4072          oglIndices.buffer.free();
4073          delete oglIndices.indices;
4074          delete oglIndices;
4075       }
4076    }
4077
4078    void * AllocateIndices(DisplaySystem displaySystem, int nIndices, bool indices32bit)
4079    {
4080       OGLIndices oglIndices = OGLIndices { };
4081       if(oglIndices)
4082       {
4083          oglIndices.indices = (void *)(indices32bit ? new uint32[nIndices] : new uint16[nIndices]);
4084          oglIndices.nIndices = nIndices;
4085       }
4086       return oglIndices;
4087    }
4088
4089    void UnlockIndices(DisplaySystem displaySystem, OGLIndices oglIndices, bool indices32bit, int nIndices)
4090    {
4091       if(vboAvailable)
4092       {
4093 #ifdef _GLES
4094          if(indices32bit)
4095          {
4096             if(!oglIndices.buffer.buffer)
4097                GLGenBuffers(1, (GLAB *)&oglIndices.buffer);
4098             if(curElementBuffer != oglIndices.buffer.buffer)
4099                GLBindBuffer(GL_ELEMENT_ARRAY_BUFFER, oglIndices.buffer.buffer);
4100             glesBufferDatai(GL_ELEMENT_ARRAY_BUFFER, sizeof(uint32) * nIndices, oglIndices.indices, GL_STATIC_DRAW_ARB);
4101          }
4102          else
4103 #endif
4104          oglIndices.buffer.upload(
4105             nIndices * (indices32bit ? sizeof(uint32) : sizeof(uint16)),
4106             oglIndices.indices); //GL_STATIC_DRAW_ARB);
4107       }
4108    }
4109
4110    uint16 * LockIndices(DisplaySystem displaySystem, OGLIndices oglIndices)
4111    {
4112
4113       return oglIndices.indices;
4114    }
4115
4116    void SelectMesh(Display display, Mesh mesh)
4117    {
4118       //Logf("SelectMesh\n");
4119
4120 #if !defined( __ANDROID__) && !defined(__APPLE__) && !defined(__ODROID__)
4121
4122 #if defined(__WIN32__)
4123       if(glUnlockArraysEXT)
4124 #endif
4125          if(!vboAvailable && display.display3D.mesh)
4126             glUnlockArraysEXT();
4127
4128 #endif
4129       if(mesh)
4130       {
4131          OGLMesh oglMesh = mesh.data;
4132
4133          // *** Vertex Stream ***
4134          glEnableClientState(GL_VERTEX_ARRAY);
4135          if(!display.display3D.collectingHits && oglMesh)
4136          {
4137             oglMesh.vertices.use(vertex, 3, (mesh.flags.doubleVertices ? GL_DOUBLE : GL_FLOAT), 0, oglMesh.vertices.buffer ? null : (double *)mesh.vertices);
4138
4139             // *** Normals Stream ***
4140             if(mesh.normals || mesh.flags.normals)
4141             {
4142                glEnableClientState(GL_NORMAL_ARRAY);
4143                oglMesh.normals.use(normal, 3, GL_FLOAT, 0, oglMesh.normals.buffer ? null : mesh.normals);
4144             }
4145             else
4146                glDisableClientState(GL_NORMAL_ARRAY);
4147
4148             // *** Texture Coordinates Stream ***
4149             if(mesh.texCoords || mesh.flags.texCoords1)
4150             {
4151                glEnableClientState(GL_TEXTURE_COORD_ARRAY);
4152                oglMesh.texCoords.use(texCoord, 2, GL_FLOAT, 0, oglMesh.texCoords.buffer ? null : mesh.texCoords);
4153             }
4154             else
4155                glDisableClientState(GL_TEXTURE_COORD_ARRAY);
4156
4157             // *** Color Stream ***
4158             if(mesh.colors || mesh.flags.colors)
4159             {
4160                glEnableClientState(GL_COLOR_ARRAY);
4161                oglMesh.colors.use(color, 4, GL_FLOAT, 0, oglMesh.colors.buffer ? null : mesh.colors);
4162             }
4163             else
4164                glDisableClientState(GL_COLOR_ARRAY);
4165          }
4166          else
4167          {
4168             noAB.use(vertex, 3, (mesh.flags.doubleVertices ? GL_DOUBLE : GL_FLOAT), 0, (double *)mesh.vertices);
4169             if((mesh.normals || mesh.flags.normals) && !display.display3D.collectingHits)
4170             {
4171                glEnableClientState(GL_NORMAL_ARRAY);
4172                noAB.use(normal, 3, GL_FLOAT, 0, mesh.normals);
4173             }
4174             else
4175                glDisableClientState(GL_NORMAL_ARRAY);
4176             if((mesh.texCoords || mesh.flags.texCoords1) && !display.display3D.collectingHits)
4177             {
4178                glEnableClientState(GL_TEXTURE_COORD_ARRAY);
4179                noAB.use(texCoord, 2, GL_FLOAT, 0, mesh.texCoords);
4180             }
4181             else
4182                glDisableClientState(GL_TEXTURE_COORD_ARRAY);
4183             if((mesh.colors || mesh.flags.colors) && !display.display3D.collectingHits)
4184             {
4185                glEnableClientState(GL_COLOR_ARRAY);
4186                noAB.use(color, 4, GL_FLOAT, 0, mesh.colors);
4187             }
4188             else
4189                glDisableClientState(GL_COLOR_ARRAY);
4190          }
4191
4192 #if !defined(__ANDROID__) && !defined(__APPLE__) && !defined(__ODROID__)
4193
4194 #if defined(__WIN32__)
4195          if(glLockArraysEXT)
4196 #endif
4197             if(!vboAvailable)
4198                glLockArraysEXT(0, mesh.nVertices);
4199
4200 #endif
4201       }
4202    }
4203
4204    void DrawPrimitives(Display display, PrimitiveSingle * primitive, Mesh mesh)
4205    {
4206       //Logf("DrawPrimitives\n");
4207
4208       if(primitive->type.vertexRange)
4209          glDrawArrays(primitiveTypes[primitive->type.primitiveType], primitive->first, primitive->nVertices);
4210       else
4211       {
4212          //    *** Hoping the data won't be uploaded at all (Won't really work if another group of the mesh is using the mesh ) ***
4213          // HACK TO SPEED THINGS UP...
4214 #ifndef __ANDROID__
4215          /*GLBindBuffer(GL_ELEMENT_ARRAY_BUFFER_ARB, 0);
4216          if(primitive->nIndices < (mesh.nVertices >> 2) && !primitive->type.indices32bit)
4217          {
4218             int c;
4219             glBegin(primitiveTypes[primitive->type.primitiveType]);
4220             if(primitive->data)
4221             {
4222                OGLIndices oglIndices = primitive->data;
4223                MeshFeatures flags = mesh.flags;
4224                for(c = 0; c<primitive->nIndices; c++)
4225                {
4226                   uint16 index = ((uint16 *) oglIndices.indices)[c];
4227                   if(flags.normals) glNormal3fv((float *)&mesh.normals[index]);
4228                   if(flags.texCoords1) glTexCoord2fv((float *)&mesh.texCoords[index]);
4229                   if(flags.colors) glColor4fv((float *)&mesh.colors[index]);
4230                   glVertex3fv((float *)&mesh.vertices[index]);
4231                }
4232             }
4233             glEnd();
4234          }
4235          else*/
4236 #endif
4237
4238          {
4239             OGLIndices oglIndices = primitive->data;
4240             GLEAB eab = ((!display.display3D.collectingHits && oglIndices) ? oglIndices.buffer : noEAB);
4241
4242             eab.draw(primitiveTypes[primitive->type.primitiveType], primitive->nIndices,
4243                primitive->type.indices32bit ? GL_UNSIGNED_INT : GL_UNSIGNED_SHORT,
4244                eab.buffer ? 0 : (oglIndices ? oglIndices.indices : primitive->indices));
4245             GLBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
4246          }
4247       }
4248    }
4249
4250    void PushMatrix(Display display)
4251    {
4252       glPushMatrix();
4253    }
4254
4255    void PopMatrix(Display display, bool setMatrix)
4256    {
4257       glPopMatrix();
4258    }
4259
4260    void SetTransform(Display display, Matrix transMatrix, bool viewSpace, bool useCamera)
4261    {
4262       Matrix matrix = transMatrix;
4263       Camera camera = useCamera ? display.display3D.camera : null;
4264
4265       if(viewSpace)
4266       {
4267          glLoadIdentity();
4268          glScaled(1.0/nearPlane, 1.0/nearPlane, -1.0/nearPlane);
4269       }
4270       else if(camera)
4271       {
4272          glTranslated(
4273             matrix.m[3][0] - camera.cPosition.x,
4274             matrix.m[3][1] - camera.cPosition.y,
4275             matrix.m[3][2] - camera.cPosition.z);
4276       }
4277       else
4278          glTranslated(
4279             matrix.m[3][0],
4280             matrix.m[3][1],
4281             matrix.m[3][2]);
4282
4283       matrix.m[3][0] = 0;
4284       matrix.m[3][1] = 0;
4285       matrix.m[3][2] = 0;
4286
4287       glMultMatrixd(matrix.array);
4288    }
4289 #endif
4290 }
4291
4292 public void UseSingleGLContext(bool useSingle)
4293 {
4294    useSingleGLContext = useSingle;
4295 }
4296
4297 default dllexport void *
4298 #if defined(__WIN32__)
4299 __attribute__((stdcall))
4300 #endif
4301 IS_GLGetContext(DisplaySystem displaySystem)
4302 {
4303    if(displaySystem)
4304    {
4305 #if defined(__WIN32__)
4306       OGLSystem system = displaySystem.driverData;
4307       return system.glrc;
4308 #elif defined(__ANDROID__) || defined(__ODROID__)
4309       return eglContext;
4310 #else
4311       OGLSystem system = displaySystem.driverData;
4312       return system.glContext;
4313 #endif
4314    }
4315    return null;
4316 }
4317
4318 #endif