ecere/gfx/newFonts/drawManager: Avoiding crashes on VBO not available
[sdk] / ecere / src / gfx / newFonts / drawManager.ec
1 import "OpenGLDisplayDriver"
2
3 #include <stdio.h>
4 #include <math.h>
5 #include <stdlib.h>
6
7 #if defined(_GLES)
8    #define ES1_1
9 #else
10    #define SHADERS
11 #endif
12
13 #if !defined(__ANDROID__) && !defined(__EMSCRIPTEN__) && !defined(__ODROID__)
14 #  if defined(SHADERS)
15 //#     include "gl_core_3_3.h"
16 #     include "gl_compat_4_4.h"     // FIXME: no glPushAttrib() in core profile
17 #  else
18 #     include "gl_compat_4_4.h"
19 #  endif
20 #endif
21
22 #ifdef SHADERS
23
24 #undef glEnableClientState
25 #undef glDisableClientState
26 #undef GL_VERTEX_ARRAY
27 #undef GL_NORMAL_ARRAY
28 #undef GL_TEXTURE_COORD_ARRAY
29 #undef GL_COLOR_ARRAY
30 #undef glVertexPointer
31 #undef glTexCoordPointer
32 #undef glColorPointer
33
34 #define glEnableClientState      glEnableVertexAttribArray
35 #define glDisableClientState     glDisableVertexAttribArray
36 #define GL_VERTEX_ARRAY          GLBufferContents::vertex
37 #define GL_NORMAL_ARRAY          GLBufferContents::normal
38 #define GL_TEXTURE_COORD_ARRAY   GLBufferContents::texCoord
39 #define GL_COLOR_ARRAY           GLBufferContents::color
40 #define glVertexPointer(n, t, s, p)    glVertexAttribPointer(GLBufferContents::vertex,   n, t, GL_FALSE, s, p)
41 #define glTexCoordPointer(n, t, s, p)  glVertexAttribPointer(GLBufferContents::texCoord, n, t, GL_FALSE, s, p)
42 #define glColorPointer(n, t, s, p)     glVertexAttribPointer(GLBufferContents::color,    n, t, GL_FALSE, s, p)
43
44 #endif
45
46 #if defined(ES1_1) || defined(ES2) || defined(SHADERS)
47
48    #undef glRecti
49    #undef glBegin
50    #undef glTexCoord2i
51    #undef glVertex2i
52    #undef glTexCoord2d
53    #undef glVertex2d
54    #undef glTexCoord2f
55    #undef glVertex2f
56    #undef glEnd
57    #undef glColor3f
58    #undef glColor4ub
59    #undef glColor4fv
60    #undef glNormal3fv
61    #undef glNormal3f
62    #undef glTexCoord2fv
63    #undef glVertex3d
64    #undef glVertex3dv
65    #undef glVertex3f
66    #undef glVertex3fv
67
68    #undef glLoadMatrixd
69    #undef glMultMatrixd
70    #undef glFrustum
71    #undef glOrtho
72    #undef glScaled
73    #undef glScalef
74    #undef glTranslated
75    #undef glRotated
76    #undef glMatrixMode
77    #undef glLoadIdentity
78    #undef glPushMatrix
79    #undef glPopMatrix
80
81    #undef glLineStipple
82    #undef glColorMaterial
83    #undef glLightModeli
84
85    #define glRecti               glimtkRecti
86    #define glBegin               glimtkBegin
87    #define glTexCoord2i          glimtkTexCoord2i
88    #define glVertex2i            glimtkVertex2i
89    #define glTexCoord2d          glimtkTexCoord2d
90    #define glVertex2d            glimtkVertex2d
91    #define glTexCoord2f          glimtkTexCoord2f
92    #define glVertex2f            glimtkVertex2f
93    #define glEnd                 glimtkEnd
94    #define glColor3f             glimtkColor3f
95    #define glColor4ub            glimtkColor4ub
96    #define glColor4fv            glimtkColor4fv
97    #define glNormal3fv           glimtkNormal3fv
98    #define glNormal3f            glimtkNormal3f
99    #define glTexCoord2fv         glimtkTexCoord2fv
100    #define glVertex3d            glimtkVertex3d
101    #define glVertex3dv           glimtkVertex3dv
102    #define glVertex3f            glimtkVertex3f
103    #define glVertex3fv           glimtkVertex3fv
104
105    #define glLoadMatrixd         glmsLoadMatrixd
106    #define glMultMatrixd         glmsMultMatrixd
107    #define glFrustum             glmsFrustum
108    #define glOrtho               glmsOrtho
109    #define glScaled              glmsScaled
110    #define glScalef              glmsScaled
111    #define glTranslated          glmsTranslated
112    #define glRotated             glmsRotated
113    #define glMatrixMode          glmsMatrixMode
114    #define glLoadIdentity        glmsLoadIdentity
115    #define glPushMatrix          glmsPushMatrix
116    #define glPopMatrix           glmsPopMatrix
117
118    #define glLineStipple         glesLineStipple
119    #define glColorMaterial       glesColorMaterial
120    #define glLightModeli         glesLightModeli
121
122 #endif
123
124 #include "cc.h"
125
126 #define OFFSET(s, m) ((uint)(uintptr) (&((s *) 0)->m))
127
128 import "textureManager"
129
130
131 #define DM_ENABLE_IMAGE_ROTATION (1)
132 #define DM_ENABLE_EXT_COLOR (1)
133
134 ////
135
136 static struct DMDrawVertexFlat
137 {
138   float vertex[2];
139   float texcoord0[2];
140   uint32 color;
141 #if DM_ENABLE_EXT_COLOR
142   uint32 extcolor;
143 #endif
144 } __attribute__((aligned(16)));
145
146 static struct DMDrawVertex
147 {
148   short vertex[2];
149   short texcoord0[2];
150   uint32 color;
151 #if DM_ENABLE_EXT_COLOR
152   uint32 extcolor;
153 #endif
154 } __attribute__((aligned(16)));
155
156 struct DMDrawBuffer
157 {
158    GLuint vbo;
159    int glType;
160    int vertexCount;
161    int vertexAlloc;
162    void *vertexBuffer;
163 };
164
165 class DMProgramFlags : uint { bool valid:1; }
166
167 struct DMProgram
168 {
169   GLuint glProgram;
170   GLuint vertexShader;
171   GLuint fragmentShader;
172   GLint matrixloc;
173   GLint vertexloc;
174   GLint texcoord0loc;
175   GLint texcoord1loc;
176   GLint colorloc;
177 #if DM_ENABLE_EXT_COLOR
178   GLint extcolorloc;
179 #endif
180   GLint texbaseloc;
181   DMProgramFlags flags;
182   int64 lastUpdateCount;
183 };
184
185 class DMImageFlags : uint16
186 {
187    bool empty:1;     // Image is empty, do not draw
188    bool blending:1;  // Must draw image with blending
189 }
190
191 public struct DMImage
192 {
193 private:
194    Texture texture;
195    DMImageFlags flags;
196    short programIndex;
197    short srcx, srcy;
198    short sizex, sizey;
199
200    // Computed order for sorted rendering, in defineImage()
201    uint32 orderMask;
202
203 public:
204    void clear()
205    {
206       this = { flags = { empty = true } };
207    }
208
209    void defineImage( Texture texture, int offsetx, int offsety, int sizex, int sizey, bool blending, int programIndex, int layerindex )
210    {
211       int ordx = offsetx >> 6;
212       int ordy = offsety >> 6;
213       uint32 orderimage = ccMortonNumber32( ordx, ordy ) & ( ( 1 << DM_IMAGE_ORDER_BITS ) - 1 );
214       this =
215       {
216          texture = texture;
217          srcx = (short)offsetx;
218          srcy = (short)offsety;
219          sizex = (short)sizex;
220          sizey = (short)sizey;
221          programIndex = (short)programIndex;
222          flags = { blending = blending };
223          orderMask = (orderimage << DM_IMAGE_ORDER_SHIFT) |
224                      (( blending == true ) << DM_BLEND_ORDER_SHIFT) |
225                      (programIndex << DM_PROGRAM_ORDER_SHIFT) |
226                      texture.orderMask |
227                      (layerindex << DM_LAYER_ORDER_SHIFT);
228       };
229    }
230 };
231
232 struct DMImageBuffer
233 {
234   DMImage *image;
235   short offsetx;
236   short offsety;
237   short sizex;
238   short sizey;
239 #if DM_ENABLE_IMAGE_ROTATION
240   short angcos;
241   short angsin;
242 #endif
243 #if DM_ENABLE_EXT_COLOR
244   uint32 extcolor;
245 #endif
246   uint32 color;
247   uint32 orderindex;
248 };
249
250
251 ////
252
253
254 define DM_IMAGE_ORDER_BITS = 8;
255 define DM_BLEND_ORDER_BITS = 1;
256 define DM_PROGRAM_ORDER_BITS = 4;
257 define DM_TEXTURE_ORDER_BITS = 10;
258 define DM_LAYER_ORDER_BITS = 4;
259 define DM_BARRIER_ORDER_BITS = 5;
260
261 define DM_IMAGE_ORDER_SHIFT = 0;
262 define DM_BLEND_ORDER_SHIFT = DM_IMAGE_ORDER_BITS;
263 define DM_PROGRAM_ORDER_SHIFT = DM_IMAGE_ORDER_BITS+DM_BLEND_ORDER_BITS;
264 define DM_TEXTURE_ORDER_SHIFT = DM_IMAGE_ORDER_BITS+DM_BLEND_ORDER_BITS+DM_PROGRAM_ORDER_BITS;
265 define DM_LAYER_ORDER_SHIFT = DM_IMAGE_ORDER_BITS+DM_BLEND_ORDER_BITS+DM_PROGRAM_ORDER_BITS+DM_TEXTURE_ORDER_BITS;
266 define DM_BARRIER_ORDER_SHIFT = DM_IMAGE_ORDER_BITS+DM_BLEND_ORDER_BITS+DM_PROGRAM_ORDER_BITS+DM_TEXTURE_ORDER_BITS+DM_LAYER_ORDER_BITS;
267
268 define DM_LAYER_COUNT = 1<<DM_LAYER_ORDER_BITS;
269 define DM_PROGRAM_COUNT = 1<<DM_PROGRAM_ORDER_BITS;
270
271 define DM_CONTEXT_DRAW_BUFFER_COUNT = 64;
272 define DM_CONTEXT_DRAW_BUFFER_VERTEX_ALLOC = 1024;
273
274
275 /* Range is from zero to DM_LAYER_COUNT */
276 enum DMLayer
277 {
278   DM_LAYER_0_BOTTOM,
279   DM_LAYER_1_BOTTOM,
280   DM_LAYER_2_BELOW,
281   DM_LAYER_3_BELOW,
282   DM_LAYER_4_BELOW,
283   DM_LAYER_5_NORMAL,
284   DM_LAYER_6_NORMAL,
285   DM_LAYER_7_NORMAL,
286   DM_LAYER_8_ABOVE,
287   DM_LAYER_9_ABOVE,
288   DM_LAYER_10_ABOVE,
289   DM_LAYER_11_OVERLAY,
290   DM_LAYER_12_OVERLAY,
291   DM_LAYER_13_OVERLAY,
292   DM_LAYER_14_TOP,
293   DM_LAYER_15_TOP,
294 };
295
296 define DM_LAYER_BOTTOM = DMLayer::DM_LAYER_0_BOTTOM;
297 define DM_LAYER_BELOW = DMLayer::DM_LAYER_3_BELOW;
298 define DM_LAYER_NORMAL = DMLayer::DM_LAYER_6_NORMAL;
299 define DM_LAYER_ABOVE = DMLayer::DM_LAYER_9_ABOVE;
300 define DM_LAYER_TOP = DMLayer::DM_LAYER_15_TOP;
301
302 define DM_PROGRAM_NORMAL = 0;
303 define DM_PROGRAM_ALPHABLEND = 1;
304 define DM_PROGRAM_ALPHABLEND_INTENSITY = 2;
305 define DM_PROGRAM_ALPHABLEND_INTENSITY_EXTCOLOR = 3;
306
307 #ifdef _DEBUG
308 static inline void OpenGLErrorCheck( const char *file, int line )
309 {
310    int error = glGetError();
311    if( error != GL_NO_ERROR )
312       printf( "ERROR %d at %s:%d\n", error, file, line );
313 }
314
315 #define ERRORCHECK() OpenGLErrorCheck(__FILE__,__LINE__)
316 #else
317 #define ERRORCHECK()
318 #endif
319
320 #define DM_IMAGE_ROTATION_NORMFACTOR (32767.0f)
321
322 #define DM_VERTEX_NORMSHIFT (2)
323 #define DM_VERTEX_NORMFACTOR (4.0f)
324
325 #define DM_TEXCOORD_NORMSHIFT (13)
326 #define DM_TEXCOORD_NORMFACTOR (8192.0f)
327
328 static GLuint dmCreateShader( GLenum type, const char *shadersource, const char *optionstring )
329 {
330   GLuint shader;
331   GLint status;
332   GLsizei loglength;
333   char infolog[8192];
334   const GLchar *sourcearray[2];
335
336   shader = glCreateShader( type );
337   if( !( shader ) )
338     return 0;
339
340   if( !( optionstring ) )
341     optionstring = "";
342   sourcearray[0] = optionstring;
343   sourcearray[1] = shadersource;
344   glShaderSource( shader, 2, sourcearray, NULL );
345   glCompileShader( shader );
346   glGetShaderiv( shader, GL_COMPILE_STATUS, &status );
347   if( status != GL_TRUE )
348   {
349     fprintf( stderr, "ERROR: Failed to compile shader\n" );
350     glGetShaderInfoLog( shader, 8192, &loglength,infolog );
351     fprintf( stderr, "ERROR: \n%s\n\n", infolog );
352     glDeleteShader( shader );
353     return 0;
354   }
355   return shader;
356 }
357
358
359 static bool dmCreateProgram( DMProgram program, const char *vertexsource, const char *fragmentsource, char *optionstring )
360 {
361   GLint status;
362   GLsizei loglength;
363   char infolog[8192];
364
365   program.glProgram = 0;
366   program.vertexShader = 0;
367   program.fragmentShader = 0;
368
369   program.vertexShader = dmCreateShader( GL_VERTEX_SHADER, vertexsource, optionstring );
370   if( !( program.vertexShader ) )
371   {
372     fprintf(stderr, "ERROR: Unable to load vertex shader\n");
373     goto error;
374   }
375   program.fragmentShader = dmCreateShader( GL_FRAGMENT_SHADER, fragmentsource, optionstring );
376   if( !( program.fragmentShader ) )
377   {
378     fprintf(stderr, "ERROR: Unable to load fragment shader\n");
379     goto error;
380   }
381   program.glProgram = glCreateProgram();
382   if( !( program.glProgram ) )
383   {
384     fprintf(stderr, "ERROR: Unable to create program\n");
385     goto error;
386   }
387
388   glAttachShader( program.glProgram, program.vertexShader );
389   glAttachShader( program.glProgram, program.fragmentShader );
390
391    glBindAttribLocation(program.glProgram, GLBufferContents::vertex, "vertex");
392    glBindAttribLocation(program.glProgram, GLBufferContents::texCoord, "texCoord");
393    glBindAttribLocation(program.glProgram, GLBufferContents::color, "color");
394    glBindAttribLocation(program.glProgram, GLBufferContents::normal, "normal");
395
396   glLinkProgram( program.glProgram );
397   glGetProgramiv( program.glProgram, GL_LINK_STATUS, &status );
398   if( status != GL_TRUE )
399   {
400     fprintf( stderr, "ERROR, failed to link shader program\n" );
401     glGetProgramInfoLog( program.glProgram, 8192, &loglength, infolog );
402     fprintf( stderr, "ERROR: \n%s\n\n", infolog );
403     goto error;
404   }
405
406   // glUseProgram( program.glProgram );
407
408   program.matrixloc = glGetUniformLocation( program.glProgram, "uniMatrix" );
409   program.vertexloc = glGetAttribLocation( program.glProgram, "inVertex" );
410   program.texcoord0loc = glGetAttribLocation( program.glProgram, "inTexcoord0" );
411   program.texcoord1loc = glGetAttribLocation( program.glProgram, "inTexcoord1" );
412   program.colorloc = glGetAttribLocation( program.glProgram, "inColor" );
413 #if DM_ENABLE_EXT_COLOR
414   program.extcolorloc = glGetAttribLocation( program.glProgram, "inExtColor" );
415 #endif
416   program.texbaseloc = glGetUniformLocation( program.glProgram, "texBase" );
417   program.flags.valid = true;
418
419   return true;
420
421   error:
422   if( program.fragmentShader )
423     glDeleteShader( program.fragmentShader );
424   if( program.vertexShader )
425     glDeleteShader( program.vertexShader );
426   if( program.glProgram )
427     glDeleteProgram( program.glProgram );
428   return false;
429 }
430
431
432 ////
433
434
435 const char *dmVertexShaderNormal =
436 "#version 130\n"
437 "uniform mat4 uniMatrix;\n"
438 "in vec2 inVertex;\n"
439 "in vec2 inTexcoord0;\n"
440 "in vec4 inColor;\n"
441 "out vec2 varTexcoord0;\n"
442 "out vec4 varColor;\n"
443 "void main()\n"
444 "{\n"
445 " \n"
446 "  varTexcoord0 = inTexcoord0 * (1.0/" CC_STRINGIFY(DM_TEXCOORD_NORMFACTOR) ");\n"
447 "  varColor = inColor;\n"
448 "  gl_Position = uniMatrix * vec4( inVertex, 0.0, 1.0 );\n"
449 "  return;\n"
450 "}\n"
451 ;
452
453
454 const char *dmFragmentShaderNormal =
455 "#version 130\n"
456 "uniform sampler2D texBase;\n"
457 "in vec2 varTexcoord0;\n"
458 "in vec4 varColor;\n"
459 "void main()\n"
460 "{\n"
461 "  gl_FragColor = varColor * texture2D( texBase, varTexcoord0 );\n"
462 "  return;\n"
463 "}\n"
464 ;
465
466
467 const char *dmVertexShaderAlpha =
468 "#version 130\n"
469 "uniform mat4 uniMatrix;\n"
470 "in vec2 inVertex;\n"
471 "in vec2 inTexcoord0;\n"
472 "in vec4 inColor;\n"
473 "out vec2 varTexcoord0;\n"
474 "out vec4 varColor;\n"
475 "void main()\n"
476 "{\n"
477 " \n"
478 "  varTexcoord0 = inTexcoord0 * (1.0/" CC_STRINGIFY(DM_TEXCOORD_NORMFACTOR) ");\n"
479 "  varColor = inColor;\n"
480 "  gl_Position = uniMatrix * vec4( inVertex, 0.0, 1.0 );\n"
481 "  return;\n"
482 "}\n"
483 ;
484
485
486 const char *dmFragmentShaderAlpha =
487 "#version 130\n"
488 "uniform sampler2D texBase;\n"
489 "in vec2 varTexcoord0;\n"
490 "in vec4 varColor;\n"
491 "void main()\n"
492 "{\n"
493 "  gl_FragColor = vec4( varColor.rgb, varColor.a * texture2D( texBase, varTexcoord0 ).r );\n"
494 "  return;\n"
495 "}\n"
496 ;
497
498 const char *dmVertexShaderAlphaIntensity =
499 "#version 130\n"
500 "uniform mat4 uniMatrix;\n"
501 "in vec2 inVertex;\n"
502 "in vec2 inTexcoord0;\n"
503 "in vec4 inColor;\n"
504 "out vec2 varTexcoord0;\n"
505 "out vec4 varColor;\n"
506 "void main()\n"
507 "{\n"
508 " \n"
509 "  varTexcoord0 = inTexcoord0 * (1.0/" CC_STRINGIFY(DM_TEXCOORD_NORMFACTOR) ");\n"
510 "  varColor = inColor;\n"
511 "  gl_Position = uniMatrix * vec4( inVertex, 0.0, 1.0 );\n"
512 "  return;\n"
513 "}\n"
514 ;
515
516
517 const char *dmFragmentShaderAlphaIntensity =
518 "#version 130\n"
519 "uniform sampler2D texBase;\n"
520 "in vec2 varTexcoord0;\n"
521 "in vec4 varColor;\n"
522 "void main()\n"
523 "{\n"
524 "  vec2 tex;\n"
525 "  tex = texture2D( texBase, varTexcoord0 ).rg;\n"
526 "  gl_FragColor = vec4( varColor.rgb * tex.g, varColor.a * tex.r );\n"
527 "  return;\n"
528 "}\n"
529 ;
530
531 const char *dmVertexShaderAlphaIntensityExtColor =
532 "#version 130\n"
533 "uniform mat4 uniMatrix;\n"
534 "in vec2 inVertex;\n"
535 "in vec2 inTexcoord0;\n"
536 "in vec4 inColor;\n"
537 "in vec4 inExtColor;\n"
538 "out vec2 varTexcoord0;\n"
539 "out vec4 varColor;\n"
540 "out vec4 varExtColor;\n"
541 "void main()\n"
542 "{\n"
543 " \n"
544 "  varTexcoord0 = inTexcoord0 * (1.0/" CC_STRINGIFY(DM_TEXCOORD_NORMFACTOR) ");\n"
545 "  varColor = inColor;\n"
546 "  varExtColor = inExtColor;\n"
547 "  gl_Position = uniMatrix * vec4( inVertex, 0.0, 1.0 );\n"
548 "  return;\n"
549 "}\n"
550 ;
551
552
553 const char *dmFragmentShaderAlphaIntensityExtColor =
554 "#version 130\n"
555 "uniform sampler2D texBase;\n"
556 "in vec2 varTexcoord0;\n"
557 "in vec4 varColor;\n"
558 "in vec4 varExtColor;\n"
559 "void main()\n"
560 "{\n"
561 "  vec2 tex;\n"
562 "  tex = texture2D( texBase, varTexcoord0 ).rg;\n"
563 "  gl_FragColor = vec4( mix( varExtColor.rgb, varColor.rgb, tex.g ), mix( varExtColor.a, varColor.a, tex.g ) * tex.r );\n"
564 "  return;\n"
565 "}\n"
566 ;
567
568 ////
569
570
571 static void matrixOrtho( float *m, float left, float right, float bottom, float top, float nearval, float farval )
572 {
573   float x = 2.0f / ( right - left );
574   float y = 2.0f / ( top - bottom );
575   float z = -2.0f / ( farval - nearval );
576   float tx = -( right + left ) / ( right - left );
577   float ty = -( top + bottom ) / ( top - bottom );
578   float tz = -( farval + nearval ) / ( farval - nearval );
579
580 #define M(row,col)  m[col*4+row]
581   M(0,0) = x;    M(0,1) = 0.0;  M(0,2) = 0.0;  M(0,3) = tx;
582   M(1,0) = 0.0;  M(1,1) = y;     M(1,2) = 0.0;  M(1,3) = ty;
583   M(2,0) = 0.0;  M(2,1) = 0.0;  M(2,2) = z;     M(2,3) = tz;
584   M(3,0) = 0.0;  M(3,1) = 0.0;  M(3,2) = 0.0;  M(3,3) = 1.0;
585 #undef M
586 }
587
588 ////
589
590
591 /* FIXME: Radix sort, not hybrid sort! */
592
593 static inline int dmSortImagesCmp( DMImageBuffer *draw0, DMImageBuffer *draw1 )
594 {
595   return ( ( draw0->orderindex < draw1->orderindex ) ? 0 : 1 );
596 }
597
598 #define HSORT_MAIN dmSortImages
599 #define HSORT_CMP dmSortImagesCmp
600 #define HSORT_TYPE DMImageBuffer
601 #include "cchybridsort.h"
602 #undef HSORT_MAIN
603 #undef HSORT_CMP
604 #undef HSORT_TYPE
605
606
607 ////
608
609 // TOFIX: Make this private, have a property
610 public class DrawManagerFlags : uint32 { public: bool prehistoricOpenGL:1; }
611
612 public class DrawManager
613 {
614    DrawManagerFlags flags;
615    DMProgram shaderPrograms[DM_PROGRAM_COUNT];
616
617    // Matrix
618    float matrix[16];
619
620    int imageBufferCount;
621    int imageBufferSize;
622    DMImageBuffer *imageBuffer;
623    DMImageBuffer *imageBufferTmp;
624
625    // Buffers for drawimages() batching
626    DMDrawBuffer drawBuffer[DM_CONTEXT_DRAW_BUFFER_COUNT];
627    int drawBufferIndex;
628    int drawBarrierIndex;
629    uint32 orderBarrierMask;
630
631    // Counter to track program uniforms and such
632    int64 updateCount;
633
634    GLuint prevProgram;
635
636    static DMProgram *flushUseProgram( int programIndex )
637    {
638       DMProgram *program = &shaderPrograms[ programIndex ];
639       if( !program->flags.valid)
640       {
641          glUseProgram( 0 );
642          return 0;
643       }
644
645       glUseProgram( program->glProgram );
646       if( program->lastUpdateCount != this.updateCount )
647       {
648          glUniformMatrix4fv( program->matrixloc, 1, GL_FALSE, this.matrix );
649          glUniform1i( program->texbaseloc, 0 );
650          program->lastUpdateCount = this.updateCount;
651       }
652
653       return program;
654    }
655
656    static void flushRenderDrawBufferArchaic( DMDrawBuffer drawBuffer, DMProgram program, int vertexCount )
657    {
658       glEnable( GL_TEXTURE_2D );
659       glBindBuffer( GL_ARRAY_BUFFER, drawBuffer.vbo );
660       glColor3f( 1.0, 1.0, 1.0 );
661
662       glEnableClientState( GL_VERTEX_ARRAY );
663       glEnableClientState( GL_TEXTURE_COORD_ARRAY );
664       glEnableClientState( GL_COLOR_ARRAY );
665
666       glVertexPointer( 2, GL_FLOAT, sizeof(DMDrawVertexFlat), (void *)OFFSET(DMDrawVertexFlat,vertex) );
667       glTexCoordPointer( 2, GL_FLOAT, sizeof(DMDrawVertexFlat), (void *)OFFSET(DMDrawVertexFlat,texcoord0) );
668       glColorPointer( 4, GL_UNSIGNED_BYTE, sizeof(DMDrawVertexFlat), (void *)OFFSET(DMDrawVertexFlat,color) );
669
670       glDrawArrays( GL_TRIANGLES, 0, vertexCount );
671
672       glDisableClientState( GL_VERTEX_ARRAY );
673       glDisableClientState( GL_TEXTURE_COORD_ARRAY );
674       glDisableClientState( GL_COLOR_ARRAY );
675       glDisable( GL_TEXTURE_2D );
676
677    #if DM_FLUSH_EACH_RENDER_DRAW_BUFFER
678       glFlush();
679    #endif
680    }
681
682    void flushDrawImagesArchaic( )
683    {
684      bool flushflag, stateBlend;
685      int index, vertexCount, programIndex;
686      float vx0, vx1, vx2, vx3, vy0, vy1, vy2, vy3;
687    #if DM_ENABLE_IMAGE_ROTATION
688      float angsin, angcos, sizex, sizey;
689    #endif
690      float tx0, tx1, ty0, ty1;
691      DMImageBuffer *imageBuffer;
692      DMImage *image, *bindimage;
693      Texture texture, bindTexture;
694      DMDrawBuffer *drawBuffer;
695      DMDrawVertexFlat *vboVertex;
696      DMProgram *program;
697
698      ERRORCHECK();
699
700      drawBarrierIndex = 0;
701      orderBarrierMask = drawBarrierIndex << DM_BARRIER_ORDER_SHIFT;
702      if(imageBufferCount)
703      {
704         // Sort by image type and texture, minimize state changes
705         dmSortImages( this.imageBuffer, imageBufferTmp, imageBufferCount, (uint32)( (intptr_t)this.imageBuffer >> 4 ) );
706
707         // Fill a drawBuffer, write vertex and texcoords
708         drawBuffer = &this.drawBuffer[drawBufferIndex];
709         drawBufferIndex = ( drawBufferIndex + 1 ) % DM_CONTEXT_DRAW_BUFFER_COUNT;
710         glBindBuffer( GL_ARRAY_BUFFER, drawBuffer->vbo );
711         vboVertex = glMapBuffer( GL_ARRAY_BUFFER, GL_WRITE_ONLY );
712         vertexCount = 0;
713
714         glActiveTexture( GL_TEXTURE0 );
715         glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA );
716         glDisable( GL_BLEND );
717
718       #if DM_RENDER_IMAGE_DEBUG
719       printf( " Flush %d images\n", (int)imageBufferCount );
720       #endif
721
722         bindimage = 0;
723         bindTexture = 0;
724         stateBlend = 0;
725         programIndex = -1;
726         program = 0;
727         imageBuffer = this.imageBuffer;
728         for( index = 0 ; index < imageBufferCount ; index++, imageBuffer++ )
729         {
730           image = imageBuffer->image;
731           texture = image->texture;
732
733           flushflag = 0;
734           if( image != bindimage )
735           {
736             if( stateBlend != image->flags.blending )
737               flushflag = 1;
738             if( texture != bindTexture )
739               flushflag = 1;
740           }
741           if( vertexCount >= ( drawBuffer->vertexAlloc - 6 ) )
742             flushflag = 1;
743
744           if( flushflag )
745           {
746             if( vertexCount )
747             {
748               glUnmapBuffer( GL_ARRAY_BUFFER );
749               // Flush font manager texture updates
750               flush( );
751               // Render buffered images
752               flushRenderDrawBufferArchaic( drawBuffer, program, vertexCount );
753               drawBuffer = &this.drawBuffer[drawBufferIndex];
754               drawBufferIndex = ( drawBufferIndex + 1 ) % DM_CONTEXT_DRAW_BUFFER_COUNT;
755               glBindBuffer( GL_ARRAY_BUFFER, drawBuffer->vbo );
756               vboVertex = glMapBuffer( GL_ARRAY_BUFFER, GL_WRITE_ONLY );
757               vertexCount = 0;
758             }
759
760             if( stateBlend != ( image->flags.blending ) )
761             {
762               stateBlend = image->flags.blending;
763               ( stateBlend ? glEnable : glDisable )( GL_BLEND );
764       #if DM_RENDER_IMAGE_DEBUG
765       printf( "  Switch blending %d\n", stateBlend != false );
766       #endif
767             }
768             if( programIndex != image->programIndex )
769             {
770               programIndex = image->programIndex;
771               program = flushUseProgram( programIndex );
772             }
773             if( texture != bindTexture )
774             {
775               bindTexture = texture;
776               glBindTexture( GL_TEXTURE_2D, bindTexture.glTex );
777       #if DM_RENDER_IMAGE_DEBUG
778       printf( "  Switch to texture 0x%x\n", (int)texture.orderMask );
779       #endif
780             }
781             bindimage = image;
782           }
783
784       #if DM_RENDER_IMAGE_DEBUG
785       printf( "   Render image at %d %d, order 0x%x, texture %p\n", (int)imageBuffer->offsetx, (int)imageBuffer->offsety, (int)imageBuffer->orderindex, texture );
786       #endif
787
788       #if DM_ENABLE_IMAGE_ROTATION
789           angsin = (float)imageBuffer->angsin * (1.0f/DM_IMAGE_ROTATION_NORMFACTOR);
790           angcos = (float)imageBuffer->angcos * (1.0f/DM_IMAGE_ROTATION_NORMFACTOR);
791           sizex = (float)imageBuffer->sizex;
792           sizey = (float)imageBuffer->sizey;
793           vx0 = (float)imageBuffer->offsetx * (1.0f/DM_VERTEX_NORMFACTOR);
794           vy0 = (float)imageBuffer->offsety * (1.0f/DM_VERTEX_NORMFACTOR);
795           vx1 = vx0 + ( angcos * sizex );
796           vy1 = vy0 + ( angsin * sizex );
797           vx2 = vx0 - ( angsin * sizey );
798           vy2 = vy0 + ( angcos * sizey );
799           vx3 = vx0 + ( angcos * sizex ) - ( angsin * sizey );
800           vy3 = vy0 + ( angsin * sizex ) + ( angcos * sizey );
801       #else
802           vx0 = (float)imageBuffer->offsetx * (1.0f/DM_VERTEX_NORMFACTOR);
803           vy0 = (float)imageBuffer->offsety * (1.0f/DM_VERTEX_NORMFACTOR);
804           vx3 = vx0 + (float)( imageBuffer->sizex );
805           vy3 = vy0 + (float)( imageBuffer->sizey );
806           vx1 = vx3;
807           vy1 = vy0;
808           vx2 = vx0;
809           vy2 = vy3;
810       #endif
811
812           tx0 = (float)( image->srcx ) * texture.widthinv;
813           ty0 = (float)( image->srcy ) * texture.heightinv;
814           tx1 = (float)( image->srcx + image->sizex ) * texture.widthinv;
815           ty1 = (float)( image->srcy + image->sizey ) * texture.heightinv;
816
817           // Write data to VBO
818           vboVertex[0].vertex[0] = vx3;
819           vboVertex[0].vertex[1] = vy3;
820           vboVertex[0].texcoord0[0] = tx1;
821           vboVertex[0].texcoord0[1] = ty1;
822           vboVertex[0].color = imageBuffer->color;
823       #if DM_ENABLE_EXT_COLOR
824           vboVertex[0].extcolor = imageBuffer->extcolor;
825       #endif
826           vboVertex[1].vertex[0] = vx1;
827           vboVertex[1].vertex[1] = vy1;
828           vboVertex[1].texcoord0[0] = tx1;
829           vboVertex[1].texcoord0[1] = ty0;
830           vboVertex[1].color = imageBuffer->color;
831       #if DM_ENABLE_EXT_COLOR
832           vboVertex[1].extcolor = imageBuffer->extcolor;
833       #endif
834           vboVertex[2].vertex[0] = vx2;
835           vboVertex[2].vertex[1] = vy2;
836           vboVertex[2].texcoord0[0] = tx0;
837           vboVertex[2].texcoord0[1] = ty1;
838           vboVertex[2].color = imageBuffer->color;
839       #if DM_ENABLE_EXT_COLOR
840           vboVertex[2].extcolor = imageBuffer->extcolor;
841       #endif
842           vboVertex[3].vertex[0] = vx0;
843           vboVertex[3].vertex[1] = vy0;
844           vboVertex[3].texcoord0[0] = tx0;
845           vboVertex[3].texcoord0[1] = ty0;
846           vboVertex[3].color = imageBuffer->color;
847       #if DM_ENABLE_EXT_COLOR
848           vboVertex[3].extcolor = imageBuffer->extcolor;
849       #endif
850           vboVertex[4].vertex[0] = vx2;
851           vboVertex[4].vertex[1] = vy2;
852           vboVertex[4].texcoord0[0] = tx0;
853           vboVertex[4].texcoord0[1] = ty1;
854           vboVertex[4].color = imageBuffer->color;
855       #if DM_ENABLE_EXT_COLOR
856           vboVertex[4].extcolor = imageBuffer->extcolor;
857       #endif
858           vboVertex[5].vertex[0] = vx1;
859           vboVertex[5].vertex[1] = vy1;
860           vboVertex[5].texcoord0[0] = tx1;
861           vboVertex[5].texcoord0[1] = ty0;
862           vboVertex[5].color = imageBuffer->color;
863       #if DM_ENABLE_EXT_COLOR
864           vboVertex[5].extcolor = imageBuffer->extcolor;
865       #endif
866
867           vboVertex += 6;
868           vertexCount += 6;
869         }
870
871         glUnmapBuffer( GL_ARRAY_BUFFER );
872
873         // Flush font manager texture updates
874         flush();
875
876         // Render buffered images
877         flushRenderDrawBufferArchaic( drawBuffer, program, vertexCount );
878         imageBufferCount = 0;
879
880         ERRORCHECK();
881
882      }
883    }
884
885    void flushRenderDrawBuffer( DMDrawBuffer drawBuffer, DMProgram program, int vertexCount )
886    {
887       glBindBuffer( GL_ARRAY_BUFFER, drawBuffer.vbo );
888       if( program.vertexloc != -1 )
889       {
890          glEnableVertexAttribArray( program.vertexloc );
891          glVertexAttribPointer( program.vertexloc, 2, GL_SHORT, GL_FALSE, sizeof(DMDrawVertex), (void *)OFFSET(DMDrawVertex,vertex) );
892       }
893       if( program.texcoord0loc != -1 )
894       {
895          glEnableVertexAttribArray( program.texcoord0loc );
896          glVertexAttribPointer( program.texcoord0loc, 2, GL_SHORT, GL_FALSE, sizeof(DMDrawVertex), (void *)OFFSET(DMDrawVertex,texcoord0) );
897       }
898       if( program.colorloc != -1 )
899       {
900          glEnableVertexAttribArray( program.colorloc );
901          glVertexAttribPointer( program.colorloc, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(DMDrawVertex), (void *)OFFSET(DMDrawVertex,color) );
902       }
903
904    #if DM_ENABLE_EXT_COLOR
905       if( program.extcolorloc != -1 )
906       {
907          glEnableVertexAttribArray( program.extcolorloc );
908          glVertexAttribPointer( program.extcolorloc, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(DMDrawVertex), (void *)OFFSET(DMDrawVertex,extcolor) );
909       }
910    #endif
911
912       glDrawArrays( GL_TRIANGLES, 0, vertexCount );
913
914       if( program.vertexloc != -1 )
915          glDisableVertexAttribArray( program.vertexloc );
916       if( program.texcoord0loc != -1 )
917          glDisableVertexAttribArray( program.texcoord0loc );
918       if( program.colorloc != -1 )
919          glDisableVertexAttribArray( program.colorloc );
920
921    #if DM_FLUSH_EACH_RENDER_DRAW_BUFFER
922       glFlush();
923    #endif
924    }
925
926    void flushDrawImages( )
927    {
928       int index, stateblend, vertexcount, flushflag, programIndex;
929       float vx0, vx1, vx2, vx3, vy0, vy1, vy2, vy3;
930       #if DM_ENABLE_IMAGE_ROTATION
931       float angsin, angcos, sizex, sizey;
932       #endif
933       float tx0, tx1, ty0, ty1;
934       DMImageBuffer *imageBuffer;
935       DMImage *image, *bindimage;
936       Texture texture, bindtexture;
937       DMDrawBuffer *drawBuffer;
938       DMDrawVertex *vboVertex;
939       DMProgram *program;
940
941       ERRORCHECK();
942
943       this.drawBarrierIndex = 0;
944       orderBarrierMask = drawBarrierIndex << DM_BARRIER_ORDER_SHIFT;
945       if( imageBufferCount )
946       {
947          /* Sort by image type and texture, minimize state changes */
948          dmSortImages( this.imageBuffer, this.imageBufferTmp, imageBufferCount, (uint32)( (uintptr)this.imageBuffer >> 4 ) );
949
950          /* Fill a drawBuffer, write vertex and texcoords */
951          drawBuffer = &this.drawBuffer[this.drawBufferIndex];
952          this.drawBufferIndex = ( this.drawBufferIndex + 1 ) % DM_CONTEXT_DRAW_BUFFER_COUNT;
953          glBindBuffer( GL_ARRAY_BUFFER, drawBuffer->vbo );
954          vboVertex = glMapBuffer( GL_ARRAY_BUFFER, GL_WRITE_ONLY );
955          vertexcount = 0;
956
957          glActiveTexture( GL_TEXTURE0 );
958          glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA );
959          glDisable( GL_BLEND );
960
961          #if DM_RENDER_IMAGE_DEBUG
962          printf( " Flush %d images\n", (int)imageBufferCount );
963          #endif
964
965          bindimage = 0;
966          bindtexture = 0;
967          stateblend = 0;
968          programIndex = -1;
969          program = 0;
970          imageBuffer = this.imageBuffer;
971          for( index = 0 ; index < imageBufferCount ; index++, imageBuffer++ )
972          {
973           image = imageBuffer->image;
974           texture = image->texture;
975
976           flushflag = 0;
977           if( image != bindimage )
978           {
979             if( stateblend != ( image->flags.blending ) )
980               flushflag = 1;
981             if( texture != bindtexture )
982               flushflag = 1;
983           }
984           if( vertexcount >= ( drawBuffer->vertexAlloc - 6 ) )
985             flushflag = 1;
986
987           if( flushflag )
988           {
989             if( vertexcount )
990             {
991               glUnmapBuffer( GL_ARRAY_BUFFER );
992               // Flush font manager texture updates
993               flush();
994
995               // Render buffered images
996               flushRenderDrawBuffer( drawBuffer, program, vertexcount );
997               drawBuffer = &this.drawBuffer[this.drawBufferIndex];
998               this.drawBufferIndex = ( this.drawBufferIndex + 1 ) % DM_CONTEXT_DRAW_BUFFER_COUNT;
999               glBindBuffer( GL_ARRAY_BUFFER, drawBuffer->vbo );
1000               vboVertex = glMapBuffer( GL_ARRAY_BUFFER, GL_WRITE_ONLY );
1001               vertexcount = 0;
1002             }
1003
1004             if( stateblend != ( image->flags.blending ) )
1005             {
1006               stateblend = image->flags.blending;
1007               ( stateblend ? glEnable : glDisable )( GL_BLEND );
1008             #if DM_RENDER_IMAGE_DEBUG
1009                printf( "  Switch blending %d\n", ( stateblend != 0 ) );
1010             #endif
1011             }
1012             if( programIndex != image->programIndex )
1013             {
1014               programIndex = image->programIndex;
1015               program = flushUseProgram( programIndex );
1016             }
1017             if( texture != bindtexture )
1018             {
1019               bindtexture = texture;
1020               glBindTexture( GL_TEXTURE_2D, bindtexture.glTex );
1021       #if DM_RENDER_IMAGE_DEBUG
1022               printf( "  Switch to texture 0x%x\n", (int)texture.orderMask );
1023       #endif
1024             }
1025             bindimage = image;
1026           }
1027
1028          #if DM_RENDER_IMAGE_DEBUG
1029          printf( "   Render image at %d %d, order 0x%x, texture %p\n", (int)imageBuffer->offsetx, (int)imageBuffer->offsety, (int)imageBuffer->orderindex, texture );
1030          #endif
1031
1032       #if DM_ENABLE_IMAGE_ROTATION
1033           /* FIXME TODO: Don't go through float, compute texcoord integers directly */
1034           angsin = (float)imageBuffer->angsin * (1.0f/DM_IMAGE_ROTATION_NORMFACTOR);
1035           angcos = (float)imageBuffer->angcos * (1.0f/DM_IMAGE_ROTATION_NORMFACTOR);
1036           sizex = (float)imageBuffer->sizex;
1037           sizey = (float)imageBuffer->sizey;
1038           vx0 = (float)imageBuffer->offsetx * (1.0f/DM_VERTEX_NORMFACTOR);
1039           vy0 = (float)imageBuffer->offsety * (1.0f/DM_VERTEX_NORMFACTOR);
1040           vx1 = vx0 + ( angcos * sizex );
1041           vy1 = vy0 + ( angsin * sizex );
1042           vx2 = vx0 - ( angsin * sizey );
1043           vy2 = vy0 + ( angcos * sizey );
1044           vx3 = vx0 + ( angcos * sizex ) - ( angsin * sizey );
1045           vy3 = vy0 + ( angsin * sizex ) + ( angcos * sizey );
1046       #else
1047           /* FIXME TODO: Don't go through float, compute texcoord integers directly */
1048           vx0 = (float)imageBuffer->offsetx * (1.0f/DM_VERTEX_NORMFACTOR);
1049           vy0 = (float)imageBuffer->offsety * (1.0f/DM_VERTEX_NORMFACTOR);
1050           vx3 = vx0 + (float)( imageBuffer->sizex );
1051           vy3 = vy0 + (float)( imageBuffer->sizey );
1052           vx1 = vx3;
1053           vy1 = vy0;
1054           vx2 = vx0;
1055           vy2 = vy3;
1056       #endif
1057
1058           /* FIXME TODO: Don't go through float, compute texcoord integers directly */
1059           tx0 = (float)( image->srcx ) * texture.widthinv;
1060           ty0 = (float)( image->srcy ) * texture.heightinv;
1061           tx1 = (float)( image->srcx + image->sizex ) * texture.widthinv;
1062           ty1 = (float)( image->srcy + image->sizey ) * texture.heightinv;
1063
1064           /* Write data to VBO */
1065           /* TODO: write vertex/texcoord all at once with SSE */
1066           vboVertex[0].vertex[0] = (short)( vx3 * DM_VERTEX_NORMFACTOR );
1067           vboVertex[0].vertex[1] = (short)( vy3 * DM_VERTEX_NORMFACTOR );
1068           vboVertex[0].texcoord0[0] = (short)( tx1 * DM_TEXCOORD_NORMFACTOR );
1069           vboVertex[0].texcoord0[1] = (short)( ty1 * DM_TEXCOORD_NORMFACTOR );
1070           vboVertex[0].color = imageBuffer->color;
1071           vboVertex[0].extcolor = imageBuffer->extcolor;
1072           vboVertex[1].vertex[0] = (short)( vx1 * DM_VERTEX_NORMFACTOR );
1073           vboVertex[1].vertex[1] = (short)( vy1 * DM_VERTEX_NORMFACTOR );
1074           vboVertex[1].texcoord0[0] = (short)( tx1 * DM_TEXCOORD_NORMFACTOR );
1075           vboVertex[1].texcoord0[1] = (short)( ty0 * DM_TEXCOORD_NORMFACTOR );
1076           vboVertex[1].color = imageBuffer->color;
1077           vboVertex[1].extcolor = imageBuffer->extcolor;
1078           vboVertex[2].vertex[0] = (short)( vx2 * DM_VERTEX_NORMFACTOR );
1079           vboVertex[2].vertex[1] = (short)( vy2 * DM_VERTEX_NORMFACTOR );
1080           vboVertex[2].texcoord0[0] = (short)( tx0 * DM_TEXCOORD_NORMFACTOR );
1081           vboVertex[2].texcoord0[1] = (short)( ty1 * DM_TEXCOORD_NORMFACTOR );
1082           vboVertex[2].color = imageBuffer->color;
1083           vboVertex[2].extcolor = imageBuffer->extcolor;
1084           vboVertex[3].vertex[0] = (short)( vx0 * DM_VERTEX_NORMFACTOR );
1085           vboVertex[3].vertex[1] = (short)( vy0 * DM_VERTEX_NORMFACTOR );
1086           vboVertex[3].texcoord0[0] = (short)( tx0 * DM_TEXCOORD_NORMFACTOR );
1087           vboVertex[3].texcoord0[1] = (short)( ty0 * DM_TEXCOORD_NORMFACTOR );
1088           vboVertex[3].color = imageBuffer->color;
1089           vboVertex[3].extcolor = imageBuffer->extcolor;
1090           vboVertex[4].vertex[0] = (short)( vx2 * DM_VERTEX_NORMFACTOR );
1091           vboVertex[4].vertex[1] = (short)( vy2 * DM_VERTEX_NORMFACTOR );
1092           vboVertex[4].texcoord0[0] = (short)( tx0 * DM_TEXCOORD_NORMFACTOR );
1093           vboVertex[4].texcoord0[1] = (short)( ty1 * DM_TEXCOORD_NORMFACTOR );
1094           vboVertex[4].color = imageBuffer->color;
1095           vboVertex[4].extcolor = imageBuffer->extcolor;
1096           vboVertex[5].vertex[0] = (short)( vx1 * DM_VERTEX_NORMFACTOR );
1097           vboVertex[5].vertex[1] = (short)( vy1 * DM_VERTEX_NORMFACTOR );
1098           vboVertex[5].texcoord0[0] = (short)( tx1 * DM_TEXCOORD_NORMFACTOR );
1099           vboVertex[5].texcoord0[1] = (short)( ty0 * DM_TEXCOORD_NORMFACTOR );
1100           vboVertex[5].color = imageBuffer->color;
1101           vboVertex[5].extcolor = imageBuffer->extcolor;
1102
1103           vboVertex += 6;
1104           vertexcount += 6;
1105         }
1106
1107         glUnmapBuffer( GL_ARRAY_BUFFER );
1108         // Flush font manager texture updates
1109         flush();
1110         // Render buffered images
1111         flushRenderDrawBuffer( drawBuffer, program, vertexcount );
1112         imageBufferCount = 0;
1113
1114         ERRORCHECK();
1115       }
1116    }
1117
1118 public:
1119
1120    virtual void flush();
1121
1122    bool init( DrawManagerFlags flags )
1123    {
1124       int drawBufferIndex, programIndex;
1125       DMDrawBuffer *drawBuffer;
1126       uint vertexSize;
1127
1128       imageBufferCount = 0;
1129       imageBufferSize = 4096;
1130       imageBuffer = new DMImageBuffer[imageBufferSize];
1131       imageBufferTmp = new DMImageBuffer[imageBufferSize];
1132
1133       this.flags = flags;
1134
1135       if( flags.prehistoricOpenGL )
1136          vertexSize = sizeof(DMDrawVertexFlat);
1137       else
1138       {
1139          DMProgram *program;
1140          for( programIndex = 0 ; programIndex < DM_PROGRAM_COUNT ; programIndex++ )
1141          {
1142             program = &shaderPrograms[ programIndex ];
1143             program->flags = 0;
1144             program->lastUpdateCount = -1;
1145          }
1146          program = &shaderPrograms[ DM_PROGRAM_NORMAL ];
1147          if( !( dmCreateProgram( program, dmVertexShaderNormal, dmFragmentShaderNormal, 0 ) ) )
1148             return false;
1149          program = &shaderPrograms[ DM_PROGRAM_ALPHABLEND ];
1150          if( !( dmCreateProgram( program, dmVertexShaderAlpha, dmFragmentShaderAlpha, 0 ) ) )
1151             return false;
1152          program = &shaderPrograms[ DM_PROGRAM_ALPHABLEND_INTENSITY ];
1153          if( !( dmCreateProgram( program, dmVertexShaderAlphaIntensity, dmFragmentShaderAlphaIntensity, 0 ) ) )
1154             return false;
1155         program = &shaderPrograms[ DM_PROGRAM_ALPHABLEND_INTENSITY_EXTCOLOR ];
1156         if( !( dmCreateProgram( program, dmVertexShaderAlphaIntensityExtColor, dmFragmentShaderAlphaIntensityExtColor, 0 ) ) )
1157             return false;
1158          // glUseProgram( 0 );
1159          vertexSize = sizeof(DMDrawVertex);
1160       }
1161
1162       for( drawBufferIndex = 0 ; drawBufferIndex < DM_CONTEXT_DRAW_BUFFER_COUNT ; drawBufferIndex++ )
1163       {
1164          drawBuffer = &this.drawBuffer[drawBufferIndex];
1165          drawBuffer->glType = GL_FLOAT;
1166          drawBuffer->vertexCount = 0;
1167          drawBuffer->vertexAlloc = DM_CONTEXT_DRAW_BUFFER_VERTEX_ALLOC;
1168          if(vboAvailable)
1169          {
1170             glGenBuffers( 1, &drawBuffer->vbo );
1171             glBindBuffer( GL_ARRAY_BUFFER, drawBuffer->vbo );
1172             glBufferData( GL_ARRAY_BUFFER, drawBuffer->vertexAlloc * vertexSize, 0, GL_DYNAMIC_DRAW );
1173          }
1174          drawBuffer->vertexBuffer = new byte[drawBuffer->vertexAlloc * vertexSize];
1175       }
1176
1177       updateCount = 0;
1178
1179       return true;
1180    }
1181
1182
1183    void end( )
1184    {
1185       int i;
1186
1187       for( i = 0 ; i < DM_CONTEXT_DRAW_BUFFER_COUNT ; i++ )
1188       {
1189          DMDrawBuffer *db = &drawBuffer[i];
1190          if(db->vbo)
1191             glDeleteBuffers( 1, &db->vbo );
1192          delete db->vertexBuffer;
1193       }
1194
1195       // TODO: Destroy the shaders!
1196       delete imageBuffer;
1197       delete imageBufferTmp;
1198    }
1199
1200    void ready( int viewportwidth, int viewportheight )
1201    {
1202       int mindex;
1203       float norminv;
1204       glGetIntegerv(GL_CURRENT_PROGRAM, (GLint *)&prevProgram);
1205       // while(glGetError());
1206
1207       // ERRORCHECK();
1208
1209       // Save OpenGL state
1210       // FIXME: no glPushAttrib() in core profile
1211 //#ifndef SHADERS
1212       glPushClientAttrib( GL_CLIENT_ALL_ATTRIB_BITS );
1213       glPushAttrib( GL_ALL_ATTRIB_BITS );
1214 //#endif
1215
1216       // Prepare rendering pass
1217       matrixOrtho( matrix, 0.0, (float)viewportwidth, (float)viewportheight, 0.0, -1.0f, 1.0 );
1218       norminv = 1.0f / DM_VERTEX_NORMFACTOR;
1219       for( mindex = 0 ; mindex < 12 ; mindex += 4 )
1220       {
1221         matrix[mindex+0] *= norminv;
1222         matrix[mindex+1] *= norminv;
1223         matrix[mindex+2] *= norminv;
1224       }
1225       drawBarrierIndex = 0;
1226       orderBarrierMask = drawBarrierIndex << DM_BARRIER_ORDER_SHIFT;
1227       orderBarrierMask = 0;
1228
1229       updateCount++;
1230    }
1231
1232    void drawImage( DMImage image, int offsetx, int offsety, int sizex, int sizey, uint32 color )
1233    {
1234      DMImageBuffer *imageBuffer;
1235
1236      if( image.flags.empty || ( sizex <= 0 ) || ( sizey <= 0 ) )
1237        return;
1238
1239      if( imageBufferCount >= imageBufferSize )
1240      {
1241        imageBufferSize <<= 1;
1242        this.imageBuffer = renew this.imageBuffer DMImageBuffer[imageBufferSize];
1243        imageBufferTmp = renew imageBufferTmp DMImageBuffer[imageBufferSize];
1244      }
1245
1246      imageBuffer = &this.imageBuffer[ imageBufferCount ];
1247      imageBuffer->image = image;
1248      imageBuffer->offsetx = (short)(offsetx << DM_VERTEX_NORMSHIFT);
1249      imageBuffer->offsety = (short)(offsety << DM_VERTEX_NORMSHIFT);
1250      imageBuffer->sizex = (short)sizex;
1251      imageBuffer->sizey = (short)sizey;
1252    #if DM_ENABLE_IMAGE_ROTATION
1253      imageBuffer->angsin = 0;
1254      imageBuffer->angcos = (short)DM_IMAGE_ROTATION_NORMFACTOR;
1255    #endif
1256      imageBuffer->color = color;
1257      imageBuffer->orderindex = image.orderMask | orderBarrierMask;
1258
1259    #if DM_RENDER_IMAGE_DEBUG
1260    printf( "  Queue image at %d %d, order 0x%x\n", (int)imageBuffer->offsetx, (int)imageBuffer->offsety, (int)imageBuffer->orderindex );
1261    #endif
1262
1263      imageBufferCount++;
1264    }
1265
1266    void drawImageExtColor( DMImage image, int offsetx, int offsety, int sizex, int sizey, uint32 color, uint32 extcolor )
1267    {
1268      DMImageBuffer *imageBuffer;
1269
1270      if( ( image.flags.empty ) || ( sizex <= 0 ) || ( sizey <= 0 ) )
1271        return;
1272
1273      if( imageBufferCount >= imageBufferSize )
1274      {
1275        imageBufferSize <<= 1;
1276        this.imageBuffer = renew this.imageBuffer DMImageBuffer[imageBufferSize];
1277        imageBufferTmp = renew imageBufferTmp DMImageBuffer[imageBufferSize];
1278      }
1279
1280      imageBuffer = &this.imageBuffer[ imageBufferCount ];
1281      imageBuffer->image = image;
1282      imageBuffer->offsetx = (short)(offsetx << DM_VERTEX_NORMSHIFT);
1283      imageBuffer->offsety = (short)(offsety << DM_VERTEX_NORMSHIFT);
1284      imageBuffer->sizex = (short)sizex;
1285      imageBuffer->sizey = (short)sizey;
1286    #if DM_ENABLE_IMAGE_ROTATION
1287      imageBuffer->angsin = 0;
1288      imageBuffer->angcos = (short)DM_IMAGE_ROTATION_NORMFACTOR;
1289    #endif
1290      imageBuffer->color = color;
1291    #if DM_ENABLE_EXT_COLOR
1292      imageBuffer->extcolor = extcolor;
1293    #endif
1294      imageBuffer->orderindex = image.orderMask | orderBarrierMask;
1295
1296    #if DM_RENDER_IMAGE_DEBUG
1297    printf( "  Queue image at %d %d, order 0x%x\n", (int)imageBuffer->offsetx, (int)imageBuffer->offsety, (int)imageBuffer->orderindex );
1298    #endif
1299
1300      this.imageBufferCount++;
1301    }
1302
1303    void drawImageFloat( DMImage image, float offsetx, float offsety, float sizex, float sizey, float angsin, float angcos, uint32 color )
1304    {
1305      DMImageBuffer *imageBuffer;
1306
1307      if( image.flags.empty || sizex <= 0 || sizey <= 0 )
1308        return;
1309
1310      if( imageBufferCount >= imageBufferSize )
1311      {
1312        imageBufferSize <<= 1;
1313        this.imageBuffer = renew this.imageBuffer DMImageBuffer[imageBufferSize];
1314        imageBufferTmp = renew imageBufferTmp DMImageBuffer[imageBufferSize];
1315      }
1316
1317      imageBuffer = &this.imageBuffer[ imageBufferCount ];
1318      imageBuffer->image = image;
1319      imageBuffer->offsetx = (short)roundf(offsetx * DM_VERTEX_NORMFACTOR);
1320      imageBuffer->offsety = (short)roundf(offsety * DM_VERTEX_NORMFACTOR);
1321      imageBuffer->sizex = (short)sizex;
1322      imageBuffer->sizey = (short)sizey;
1323    #if DM_ENABLE_IMAGE_ROTATION
1324      imageBuffer->angsin = (short)roundf( angsin * DM_IMAGE_ROTATION_NORMFACTOR );
1325      imageBuffer->angcos = (short)roundf( angcos * DM_IMAGE_ROTATION_NORMFACTOR );
1326    #endif
1327      imageBuffer->color = color;
1328      imageBuffer->orderindex = image.orderMask | orderBarrierMask;
1329
1330    #if DM_RENDER_IMAGE_DEBUG
1331    printf( "  Queue image at %d %d, order 0x%x\n", (int)imageBuffer->offsetx, (int)imageBuffer->offsety, (int)imageBuffer->orderindex );
1332    #endif
1333
1334      imageBufferCount++;
1335    }
1336
1337    void drawImageFloatExtColor( DMImage image, float offsetx, float offsety, float sizex, float sizey, float angsin, float angcos, uint32 color, uint32 extcolor )
1338    {
1339      DMImageBuffer *imageBuffer;
1340
1341      if( ( image.flags.empty ) || ( sizex <= 0 ) || ( sizey <= 0 ) )
1342        return;
1343
1344      if( this.imageBufferCount >= this.imageBufferSize )
1345      {
1346        imageBufferSize <<= 1;
1347        this.imageBuffer = renew this.imageBuffer DMImageBuffer[imageBufferSize];
1348        imageBufferTmp = renew imageBufferTmp DMImageBuffer[imageBufferSize];
1349      }
1350
1351      imageBuffer = &this.imageBuffer[ imageBufferCount ];
1352      imageBuffer->image = image;
1353      imageBuffer->offsetx = (short)roundf( offsetx * DM_VERTEX_NORMFACTOR );
1354      imageBuffer->offsety = (short)roundf( offsety * DM_VERTEX_NORMFACTOR );
1355      imageBuffer->sizex = (short)sizex;
1356      imageBuffer->sizey = (short)sizey;
1357    #if DM_ENABLE_IMAGE_ROTATION
1358      imageBuffer->angsin = (short)roundf( angsin * DM_IMAGE_ROTATION_NORMFACTOR );
1359      imageBuffer->angcos = (short)roundf( angcos * DM_IMAGE_ROTATION_NORMFACTOR );
1360    #endif
1361      imageBuffer->color = color;
1362    #if DM_ENABLE_EXT_COLOR
1363      imageBuffer->extcolor = extcolor;
1364    #endif
1365      imageBuffer->orderindex = image.orderMask | orderBarrierMask;
1366
1367    #if DM_RENDER_IMAGE_DEBUG
1368    printf( "  Queue image at %d %d, order 0x%x\n", (int)imageBuffer->offsetx, (int)imageBuffer->offsety, (int)imageBuffer->orderindex );
1369    #endif
1370
1371      this.imageBufferCount++;
1372    }
1373
1374    void flushImages( )
1375    {
1376      if( flags.prehistoricOpenGL )
1377        flushDrawImagesArchaic( );
1378      else
1379        flushDrawImages( );
1380
1381      if(vboAvailable)
1382         glBindBuffer( GL_ARRAY_BUFFER, 0 );
1383      glabCurArrayBuffer = 0;
1384      if( !flags.prehistoricOpenGL )
1385          glUseProgram( prevProgram );
1386       // Restore OpenGL state
1387       // FIXME: no glPushAttrib() in core profile
1388 //#ifndef SHADERS
1389       glPopAttrib();
1390       glPopClientAttrib();
1391 //#endif
1392    }
1393
1394    void drawBarrier( )
1395    {
1396       drawBarrierIndex++;
1397       if( drawBarrierIndex >= ( 1 << DM_BARRIER_ORDER_BITS ) )
1398          flushImages( );
1399       orderBarrierMask = drawBarrierIndex << DM_BARRIER_ORDER_SHIFT;
1400    }
1401 }