]> git.cworth.org Git - apitrace/blob - glstate.py
Show call name on glGetError warning messages.
[apitrace] / glstate.py
1 ##########################################################################
2 #
3 # Copyright 2011 Jose Fonseca
4 # All Rights Reserved.
5 #
6 # Permission is hereby granted, free of charge, to any person obtaining a copy
7 # of this software and associated documentation files (the "Software"), to deal
8 # in the Software without restriction, including without limitation the rights
9 # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 # copies of the Software, and to permit persons to whom the Software is
11 # furnished to do so, subject to the following conditions:
12 #
13 # The above copyright notice and this permission notice shall be included in
14 # all copies or substantial portions of the Software.
15 #
16 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 # THE SOFTWARE.
23 #
24 ##########################################################################/
25
26
27 '''Generate code to dump most GL state into JSON.'''
28
29
30 from stdapi import *
31
32 from gltypes import *
33 from glparams import *
34
35
36 texture_targets = [
37     ('GL_TEXTURE_1D', 'GL_TEXTURE_BINDING_1D'),
38     ('GL_TEXTURE_2D', 'GL_TEXTURE_BINDING_2D'),
39     ('GL_TEXTURE_3D', 'GL_TEXTURE_BINDING_3D'),
40     ('GL_TEXTURE_RECTANGLE', 'GL_TEXTURE_BINDING_RECTANGLE'),
41     ('GL_TEXTURE_CUBE_MAP', 'GL_TEXTURE_BINDING_CUBE_MAP')
42 ]
43
44
45 class GetInflector:
46     '''Objects that describes how to inflect.'''
47
48     reduced_types = {
49         B: I,
50         E: I,
51         I: F,
52     }
53
54     def __init__(self, radical, inflections, suffix = ''):
55         self.radical = radical
56         self.inflections = inflections
57         self.suffix = suffix
58
59     def reduced_type(self, type):
60         if type in self.inflections:
61             return type
62         if type in self.reduced_types:
63             return self.reduced_type(self.reduced_types[type])
64         raise NotImplementedError
65
66     def inflect(self, type):
67         return self.radical + self.inflection(type) + self.suffix
68
69     def inflection(self, type):
70         type = self.reduced_type(type)
71         assert type in self.inflections
72         return self.inflections[type]
73
74     def __str__(self):
75         return self.radical + self.suffix
76
77
78 class StateGetter(Visitor):
79     '''Type visitor that is able to extract the state via one of the glGet*
80     functions.
81
82     It will declare any temporary variable
83     '''
84
85     def __init__(self, radical, inflections, suffix=''):
86         self.inflector = GetInflector(radical, inflections)
87         self.suffix = suffix
88
89     def __call__(self, *args):
90         pname = args[-1]
91
92         for function, type, count, name in parameters:
93             if type is X:
94                 continue
95             if name == pname:
96                 if count != 1:
97                     type = Array(type, str(count))
98
99                 return type, self.visit(type, args)
100
101         raise NotImplementedError
102
103     def temp_name(self, args):
104         '''Return the name of a temporary variable to hold the state.'''
105         pname = args[-1]
106
107         return pname[3:].lower()
108
109     def visit_const(self, const, args):
110         return self.visit(const.type, args)
111
112     def visit_scalar(self, type, args):
113         temp_name = self.temp_name(args)
114         elem_type = self.inflector.reduced_type(type)
115         inflection = self.inflector.inflect(type)
116         if inflection.endswith('v'):
117             print '    %s %s = 0;' % (elem_type, temp_name)
118             print '    %s(%s, &%s);' % (inflection + self.suffix, ', '.join(args), temp_name)
119         else:
120             print '    %s %s = %s(%s);' % (elem_type, temp_name, inflection + self.suffix, ', '.join(args))
121         return temp_name
122
123     def visit_string(self, string, args):
124         temp_name = self.temp_name(args)
125         inflection = self.inflector.inflect(string)
126         assert not inflection.endswith('v')
127         print '    %s %s = (%s)%s(%s);' % (string, temp_name, string, inflection + self.suffix, ', '.join(args))
128         return temp_name
129
130     def visit_alias(self, alias, args):
131         return self.visit_scalar(alias, args)
132
133     def visit_enum(self, enum, args):
134         return self.visit(GLint, args)
135
136     def visit_bitmask(self, bitmask, args):
137         return self.visit(GLint, args)
138
139     def visit_array(self, array, args):
140         temp_name = self.temp_name(args)
141         if array.length == '1':
142             return self.visit(array.type)
143         elem_type = self.inflector.reduced_type(array.type)
144         inflection = self.inflector.inflect(array.type)
145         assert inflection.endswith('v')
146         print '    %s %s[%s];' % (elem_type, temp_name, array.length)
147         print '    memset(%s, 0, %s * sizeof *%s);' % (temp_name, array.length, temp_name)
148         print '    %s(%s, %s);' % (inflection + self.suffix, ', '.join(args), temp_name)
149         return temp_name
150
151     def visit_opaque(self, pointer, args):
152         temp_name = self.temp_name(args)
153         inflection = self.inflector.inflect(pointer)
154         assert inflection.endswith('v')
155         print '    GLvoid *%s;' % temp_name
156         print '    %s(%s, &%s);' % (inflection + self.suffix, ', '.join(args), temp_name)
157         return temp_name
158
159
160 glGet = StateGetter('glGet', {
161     B: 'Booleanv',
162     I: 'Integerv',
163     F: 'Floatv',
164     D: 'Doublev',
165     S: 'String',
166     P: 'Pointerv',
167 })
168
169 glGetMaterial = StateGetter('glGetMaterial', {I: 'iv', F: 'fv'})
170 glGetLight = StateGetter('glGetLight', {I: 'iv', F: 'fv'})
171 glGetVertexAttrib = StateGetter('glGetVertexAttrib', {I: 'iv', F: 'fv', D: 'dv', P: 'Pointerv'})
172 glGetTexParameter = StateGetter('glGetTexParameter', {I: 'iv', F: 'fv'})
173 glGetTexEnv = StateGetter('glGetTexEnv', {I: 'iv', F: 'fv'})
174 glGetTexLevelParameter = StateGetter('glGetTexLevelParameter', {I: 'iv', F: 'fv'})
175 glGetProgramARB = StateGetter('glGetProgram', {I: 'iv', F: 'fv', S: 'Stringv'}, 'ARB')
176
177
178 class JsonWriter(Visitor):
179     '''Type visitor that will dump a value of the specified type through the
180     JSON writer.
181     
182     It expects a previously declared JSONWriter instance named "json".'''
183
184     def visit_literal(self, literal, instance):
185         if literal.format == 'Bool':
186             print '    json.writeBool(%s);' % instance
187         elif literal.format in ('SInt', 'Uint', 'Float', 'Double'):
188             print '    json.writeNumber(%s);' % instance
189         else:
190             raise NotImplementedError
191
192     def visit_string(self, string, instance):
193         assert string.length is None
194         print '    json.writeString((const char *)%s);' % instance
195
196     def visit_enum(self, enum, instance):
197         if enum.expr == 'GLenum':
198             print '    writeEnum(json, %s);' % instance
199         else:
200             print '    json.writeNumber(%s);' % instance
201
202     def visit_bitmask(self, bitmask, instance):
203         raise NotImplementedError
204
205     def visit_alias(self, alias, instance):
206         self.visit(alias.type, instance)
207
208     def visit_opaque(self, opaque, instance):
209         print '    json.writeNumber((size_t)%s);' % instance
210
211     __index = 0
212
213     def visit_array(self, array, instance):
214         index = '__i%u' % JsonWriter.__index
215         JsonWriter.__index += 1
216         print '    json.beginArray();'
217         print '    for (unsigned %s = 0; %s < %s; ++%s) {' % (index, index, array.length, index)
218         self.visit(array.type, '%s[%s]' % (instance, index))
219         print '    }'
220         print '    json.endArray();'
221
222
223
224 class StateDumper:
225     '''Class to generate code to dump all GL state in JSON format via
226     stdout.'''
227
228     def __init__(self):
229         pass
230
231     def dump(self):
232         print '#include <string.h>'
233         print '#include <iostream>'
234         print '#include <algorithm>'
235         print
236         print '#include "image.hpp"'
237         print '#include "json.hpp"'
238         print '#include "glimports.hpp"'
239         print '#include "glproc.hpp"'
240         print '#include "glsize.hpp"'
241         print '#include "glretrace.hpp"'
242         print
243
244         print 'static const char *'
245         print '_enum_string(GLenum pname)'
246         print '{'
247         print '    switch(pname) {'
248         for name in GLenum.values:
249             print '    case %s:' % name
250             print '        return "%s";' % name
251         print '    default:'
252         print '        return NULL;'
253         print '    }'
254         print '}'
255         print
256
257         print 'static const char *'
258         print 'enum_string(GLenum pname)'
259         print '{'
260         print '    const char *s = _enum_string(pname);'
261         print '    if (s) {'
262         print '        return s;'
263         print '    } else {'
264         print '        static char buf[16];'
265         print '        snprintf(buf, sizeof buf, "0x%04x", pname);'
266         print '        return buf;'
267         print '    }'
268         print '}'
269         print
270
271         print 'static inline void'
272         print 'writeEnum(JSONWriter &json, GLenum pname)'
273         print '{'
274         print '    const char *s = _enum_string(pname);'
275         print '    if (s) {'
276         print '        json.writeString(s);'
277         print '    } else {'
278         print '        json.writeNumber(pname);'
279         print '    }'
280         print '}'
281         print
282
283         # shaders
284         print '''
285 static void
286 writeShader(JSONWriter &json, GLuint shader)
287 {
288     if (!shader) {
289         return;
290     }
291
292     GLint shader_type = 0;
293     glGetShaderiv(shader, GL_SHADER_TYPE, &shader_type);
294     if (!shader_type) {
295         return;
296     }
297
298     GLint source_length = 0;
299     glGetShaderiv(shader, GL_SHADER_SOURCE_LENGTH, &source_length);
300     if (!source_length) {
301         return;
302     }
303
304     GLchar *source = new GLchar[source_length];
305     GLsizei length = 0;
306     source[0] = 0;
307     glGetShaderSource(shader, source_length, &length, source);
308
309     json.beginMember(enum_string(shader_type));
310     json.writeString(source);
311     json.endMember();
312
313     delete [] source;
314 }
315
316 static inline void
317 writeCurrentProgram(JSONWriter &json)
318 {
319     GLint program = 0;
320     glGetIntegerv(GL_CURRENT_PROGRAM, &program);
321     if (!program) {
322         return;
323     }
324
325     GLint attached_shaders = 0;
326     glGetProgramiv(program, GL_ATTACHED_SHADERS, &attached_shaders);
327     if (!attached_shaders) {
328         return;
329     }
330
331     GLuint *shaders = new GLuint[attached_shaders];
332     GLsizei count = 0;
333     glGetAttachedShaders(program, attached_shaders, &count, shaders);
334     for (GLsizei i = 0; i < count; ++ i) {
335        writeShader(json, shaders[i]);
336     }
337     delete [] shaders;
338 }
339
340 static inline void
341 writeArbProgram(JSONWriter &json, GLenum target)
342 {
343     if (!glIsEnabled(target)) {
344         return;
345     }
346
347     GLint program_length = 0;
348     glGetProgramivARB(target, GL_PROGRAM_LENGTH_ARB, &program_length);
349     if (!program_length) {
350         return;
351     }
352
353     GLchar *source = new GLchar[program_length + 1];
354     source[0] = 0;
355     glGetProgramStringARB(target, GL_PROGRAM_STRING_ARB, source);
356     source[program_length] = 0;
357
358     json.beginMember(enum_string(target));
359     json.writeString(source);
360     json.endMember();
361
362     delete [] source;
363 }
364 '''
365
366         # texture image
367         print '''
368 static inline void
369 writeTextureImage(JSONWriter &json, GLenum target, GLint level)
370 {
371     GLint width, height = 1, depth = 1;
372
373     width = 0;
374     glGetTexLevelParameteriv(target, level, GL_TEXTURE_WIDTH, &width);
375
376     if (target != GL_TEXTURE_1D) {
377         height = 0;
378         glGetTexLevelParameteriv(target, level, GL_TEXTURE_HEIGHT, &height);
379         if (target == GL_TEXTURE_3D) {
380             depth = 0;
381             glGetTexLevelParameteriv(target, level, GL_TEXTURE_DEPTH, &depth);
382         }
383     }
384
385     if (width <= 0 || height <= 0 || depth <= 0) {
386         return;
387     } else {
388         char label[512];
389
390         GLint active_texture = GL_TEXTURE0;
391         glGetIntegerv(GL_ACTIVE_TEXTURE, &active_texture);
392         snprintf(label, sizeof label, "%s, %s, level = %i", _enum_string(active_texture), _enum_string(target), level);
393
394         json.beginMember(label);
395
396         json.beginObject();
397
398         // Tell the GUI this is no ordinary object, but an image
399         json.writeStringMember("__class__", "image");
400
401         json.writeNumberMember("__width__", width);
402         json.writeNumberMember("__height__", height);
403         json.writeNumberMember("__depth__", depth);
404
405         // Hardcoded for now, but we could chose types more adequate to the
406         // texture internal format
407         json.writeStringMember("__type__", "uint8");
408         json.writeBoolMember("__normalized__", true);
409         json.writeNumberMember("__channels__", 4);
410         
411         GLubyte *pixels = new GLubyte[depth*width*height*4];
412
413         glGetTexImage(target, level, GL_RGBA, GL_UNSIGNED_BYTE, pixels);
414
415         json.beginMember("__data__");
416         char *pngBuffer;
417         int pngBufferSize;
418         Image::writePixelsToBuffer(pixels, width, height, 4, false, &pngBuffer, &pngBufferSize);
419         json.writeBase64(pngBuffer, pngBufferSize);
420         free(pngBuffer);
421         json.endMember(); // __data__
422
423         delete [] pixels;
424         json.endObject();
425     }
426 }
427
428 static inline void
429 writeDrawBufferImage(JSONWriter &json, GLenum format)
430 {
431     GLint channels = __gl_format_channels(format);
432
433     if (!glretrace::drawable) {
434         json.writeNull();
435     } else {
436         GLint width  = glretrace::drawable->width;
437         GLint height = glretrace::drawable->height;
438
439         json.beginObject();
440
441         // Tell the GUI this is no ordinary object, but an image
442         json.writeStringMember("__class__", "image");
443
444         json.writeNumberMember("__width__", width);
445         json.writeNumberMember("__height__", height);
446         json.writeNumberMember("__depth__", 1);
447
448         // Hardcoded for now, but we could chose types more adequate to the
449         // texture internal format
450         json.writeStringMember("__type__", "uint8");
451         json.writeBoolMember("__normalized__", true);
452         json.writeNumberMember("__channels__", channels);
453
454         GLubyte *pixels = new GLubyte[width*height*channels];
455         
456         GLint drawbuffer = glretrace::double_buffer ? GL_BACK : GL_FRONT;
457         GLint readbuffer = glretrace::double_buffer ? GL_BACK : GL_FRONT;
458         glGetIntegerv(GL_DRAW_BUFFER, &drawbuffer);
459         glGetIntegerv(GL_READ_BUFFER, &readbuffer);
460         glReadBuffer(drawbuffer);
461
462         glPushClientAttrib(GL_CLIENT_PIXEL_STORE_BIT);
463         glPixelStorei(GL_PACK_ALIGNMENT, 1);
464
465         glReadPixels(0, 0, width, height, format, GL_UNSIGNED_BYTE, pixels);
466
467         glPopClientAttrib();
468         glReadBuffer(readbuffer);
469
470         json.beginMember("__data__");
471         char *pngBuffer;
472         int pngBufferSize;
473         Image::writePixelsToBuffer(pixels, width, height, channels, false, &pngBuffer, &pngBufferSize);
474         //std::cerr <<" Before = "<<(width * height * channels * sizeof *pixels)
475         //          <<", after = "<<pngBufferSize << ", ratio = " << double(width * height * channels * sizeof *pixels)/pngBufferSize;
476         json.writeBase64(pngBuffer, pngBufferSize);
477         free(pngBuffer);
478         json.endMember(); // __data__
479
480         delete [] pixels;
481         json.endObject();
482     }
483 }
484
485 static inline GLuint
486 downsampledFramebuffer(GLuint oldFbo, GLint drawbuffer,
487                        GLint colorRb, GLint depthRb, GLint stencilRb,
488                        GLuint *rbs, GLint *numRbs)
489 {
490     GLuint fbo;
491     GLint format;
492     GLint w, h;
493
494     *numRbs = 0;
495
496     glGenFramebuffers(1, &fbo);
497     glBindFramebuffer(GL_FRAMEBUFFER, fbo);
498
499     glBindRenderbuffer(GL_RENDERBUFFER, colorRb);
500     glGetRenderbufferParameteriv(GL_RENDERBUFFER,
501                                  GL_RENDERBUFFER_WIDTH, &w);
502     glGetRenderbufferParameteriv(GL_RENDERBUFFER,
503                                  GL_RENDERBUFFER_HEIGHT, &h);
504     glGetRenderbufferParameteriv(GL_RENDERBUFFER,
505                                  GL_RENDERBUFFER_INTERNAL_FORMAT, &format);
506
507     glGenRenderbuffers(1, &rbs[*numRbs]);
508     glBindRenderbuffer(GL_RENDERBUFFER, rbs[*numRbs]);
509     glRenderbufferStorage(GL_RENDERBUFFER, format, w, h);
510     glFramebufferRenderbuffer(GL_FRAMEBUFFER, drawbuffer,
511                               GL_RENDERBUFFER, rbs[*numRbs]);
512
513     glBindFramebuffer(GL_READ_FRAMEBUFFER, oldFbo);
514     glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbo);
515     glDrawBuffer(drawbuffer);
516     glReadBuffer(drawbuffer);
517     glBlitFramebuffer(0, 0, w, h, 0, 0, w, h,
518                       GL_COLOR_BUFFER_BIT, GL_NEAREST);
519     glBindFramebuffer(GL_FRAMEBUFFER, fbo);
520     ++*numRbs;
521
522     if (stencilRb == depthRb && stencilRb) {
523         //combined depth and stencil buffer
524         glBindRenderbuffer(GL_RENDERBUFFER, depthRb);
525         glGetRenderbufferParameteriv(GL_RENDERBUFFER,
526                                      GL_RENDERBUFFER_WIDTH, &w);
527         glGetRenderbufferParameteriv(GL_RENDERBUFFER,
528                                      GL_RENDERBUFFER_HEIGHT, &h);
529         glGetRenderbufferParameteriv(GL_RENDERBUFFER,
530                                      GL_RENDERBUFFER_INTERNAL_FORMAT, &format);
531
532         glGenRenderbuffers(1, &rbs[*numRbs]);
533         glBindRenderbuffer(GL_RENDERBUFFER, rbs[*numRbs]);
534         glRenderbufferStorage(GL_RENDERBUFFER, format, w, h);
535         glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT,
536                                   GL_RENDERBUFFER, rbs[*numRbs]);
537         glBindFramebuffer(GL_READ_FRAMEBUFFER, oldFbo);
538         glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbo);
539         glBlitFramebuffer(0, 0, w, h, 0, 0, w, h,
540                           GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT, GL_NEAREST);
541         glBindFramebuffer(GL_FRAMEBUFFER, fbo);
542         ++*numRbs;
543     } else {
544         if (depthRb) {
545             glBindRenderbuffer(GL_RENDERBUFFER, depthRb);
546             glGetRenderbufferParameteriv(GL_RENDERBUFFER,
547                                          GL_RENDERBUFFER_WIDTH, &w);
548             glGetRenderbufferParameteriv(GL_RENDERBUFFER,
549                                          GL_RENDERBUFFER_HEIGHT, &h);
550             glGetRenderbufferParameteriv(GL_RENDERBUFFER,
551                                          GL_RENDERBUFFER_INTERNAL_FORMAT, &format);
552
553             glGenRenderbuffers(1, &rbs[*numRbs]);
554             glBindRenderbuffer(GL_RENDERBUFFER, rbs[*numRbs]);
555             glRenderbufferStorage(GL_RENDERBUFFER, format, w, h);
556             glFramebufferRenderbuffer(GL_FRAMEBUFFER,
557                                       GL_DEPTH_ATTACHMENT,
558                                       GL_RENDERBUFFER, rbs[*numRbs]);
559             glBindFramebuffer(GL_READ_FRAMEBUFFER, oldFbo);
560             glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbo);
561             glDrawBuffer(GL_DEPTH_ATTACHMENT);
562             glReadBuffer(GL_DEPTH_ATTACHMENT);
563             glBlitFramebuffer(0, 0, w, h, 0, 0, w, h,
564                               GL_DEPTH_BUFFER_BIT, GL_NEAREST);
565             ++*numRbs;
566         }
567         if (stencilRb) {
568             glBindRenderbuffer(GL_RENDERBUFFER, stencilRb);
569             glGetRenderbufferParameteriv(GL_RENDERBUFFER,
570                                          GL_RENDERBUFFER_WIDTH, &w);
571             glGetRenderbufferParameteriv(GL_RENDERBUFFER,
572                                          GL_RENDERBUFFER_HEIGHT, &h);
573             glGetRenderbufferParameteriv(GL_RENDERBUFFER,
574                                      GL_RENDERBUFFER_INTERNAL_FORMAT, &format);
575
576             glGenRenderbuffers(1, &rbs[*numRbs]);
577             glBindRenderbuffer(GL_RENDERBUFFER, rbs[*numRbs]);
578             glRenderbufferStorage(GL_RENDERBUFFER, format, w, h);
579             glFramebufferRenderbuffer(GL_FRAMEBUFFER,
580                                       GL_STENCIL_ATTACHMENT,
581                                       GL_RENDERBUFFER, rbs[*numRbs]);
582             glBindFramebuffer(GL_READ_FRAMEBUFFER, oldFbo);
583             glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbo);
584             glDrawBuffer(GL_STENCIL_ATTACHMENT);
585             glReadBuffer(GL_STENCIL_ATTACHMENT);
586             glBlitFramebuffer(0, 0, w, h, 0, 0, w, h,
587                               GL_STENCIL_BUFFER_BIT, GL_NEAREST);
588             ++*numRbs;
589         }
590     }
591
592     return fbo;
593 }
594
595 static void
596 writeDrawBuffers(JSONWriter &json, GLboolean writeDepth, GLboolean writeStencil)
597 {
598     json.beginMember("GL_RGBA");
599     writeDrawBufferImage(json, GL_RGBA);
600     json.endMember();
601
602     if (writeDepth) {
603         json.beginMember("GL_DEPTH_COMPONENT");
604         writeDrawBufferImage(json, GL_DEPTH_COMPONENT);
605         json.endMember();
606     }
607
608     if (writeStencil) {
609         json.beginMember("GL_STENCIL_INDEX");
610         writeDrawBufferImage(json, GL_STENCIL_INDEX);
611         json.endMember();
612     }
613 }
614
615 '''
616
617         # textures
618         print 'static inline void'
619         print 'writeTexture(JSONWriter &json, GLenum target, GLenum binding)'
620         print '{'
621         print '    GLint texture_binding = 0;'
622         print '    glGetIntegerv(binding, &texture_binding);'
623         print '    if (!glIsEnabled(target) && !texture_binding) {'
624         print '        return;'
625         print '    }'
626         print
627         print '    GLint level = 0;'
628         print '    do {'
629         print '        GLint width = 0, height = 0;'
630         print '        glGetTexLevelParameteriv(target, level, GL_TEXTURE_WIDTH, &width);'
631         print '        glGetTexLevelParameteriv(target, level, GL_TEXTURE_HEIGHT, &height);'
632         print '        if (!width || !height) {'
633         print '            break;'
634         print '        }'
635         print
636         print '        if (target == GL_TEXTURE_CUBE_MAP) {'
637         print '            for (int face = 0; face < 6; ++face) {'
638         print '                writeTextureImage(json, GL_TEXTURE_CUBE_MAP_POSITIVE_X + face, level);'
639         print '            }'
640         print '        } else {'
641         print '            writeTextureImage(json, target, level);'
642         print '        }'
643         print
644         print '        ++level;'
645         print '    } while(true);'
646         print '}'
647         print
648
649         print 'void glretrace::state_dump(std::ostream &os)'
650         print '{'
651         print '    JSONWriter json(os);'
652         self.dump_parameters()
653         self.dump_current_program()
654         self.dump_textures()
655         self.dump_framebuffer()
656         print '}'
657         print
658
659     def dump_parameters(self):
660         print '    json.beginMember("parameters");'
661         print '    json.beginObject();'
662         
663         self.dump_atoms(glGet)
664         
665         self.dump_material_params()
666         self.dump_light_params()
667         self.dump_vertex_attribs()
668         self.dump_texenv_params()
669         self.dump_program_params()
670         self.dump_texture_parameters()
671
672         print '    json.endObject();'
673         print '    json.endMember(); // parameters'
674         print
675
676     def dump_material_params(self):
677         for face in ['GL_FRONT', 'GL_BACK']:
678             print '    json.beginMember("%s");' % face
679             print '    json.beginObject();'
680             self.dump_atoms(glGetMaterial, face)
681             print '    json.endObject();'
682         print
683
684     def dump_light_params(self):
685         print '    GLint max_lights = 0;'
686         print '    __glGetIntegerv(GL_MAX_LIGHTS, &max_lights);'
687         print '    for (GLint index = 0; index < max_lights; ++index) {'
688         print '        GLenum light = GL_LIGHT0 + index;'
689         print '        if (glIsEnabled(light)) {'
690         print '            char name[32];'
691         print '            snprintf(name, sizeof name, "GL_LIGHT%i", index);'
692         print '            json.beginMember(name);'
693         print '            json.beginObject();'
694         self.dump_atoms(glGetLight, '    GL_LIGHT0 + index')
695         print '            json.endObject();'
696         print '            json.endMember(); // GL_LIGHTi'
697         print '        }'
698         print '    }'
699         print
700
701     def dump_texenv_params(self):
702         for target in ['GL_TEXTURE_ENV', 'GL_TEXTURE_FILTER_CONTROL', 'GL_POINT_SPRITE']:
703             if target != 'GL_TEXTURE_FILTER_CONTROL':
704                 print '    if (glIsEnabled(%s)) {' % target
705             else:
706                 print '    {'
707             print '        json.beginMember("%s");' % target
708             print '        json.beginObject();'
709             self.dump_atoms(glGetTexEnv, target)
710             print '        json.endObject();'
711             print '    }'
712
713     def dump_vertex_attribs(self):
714         print '    GLint max_vertex_attribs = 0;'
715         print '    __glGetIntegerv(GL_MAX_VERTEX_ATTRIBS, &max_vertex_attribs);'
716         print '    for (GLint index = 0; index < max_vertex_attribs; ++index) {'
717         print '        char name[32];'
718         print '        snprintf(name, sizeof name, "GL_VERTEX_ATTRIB_ARRAY%i", index);'
719         print '        json.beginMember(name);'
720         print '        json.beginObject();'
721         self.dump_atoms(glGetVertexAttrib, 'index')
722         print '        json.endObject();'
723         print '        json.endMember(); // GL_VERTEX_ATTRIB_ARRAYi'
724         print '    }'
725         print
726
727     program_targets = [
728         'GL_FRAGMENT_PROGRAM_ARB',
729         'GL_VERTEX_PROGRAM_ARB',
730     ]
731
732     def dump_program_params(self):
733         for target in self.program_targets:
734             print '    if (glIsEnabled(%s)) {' % target
735             print '        json.beginMember("%s");' % target
736             print '        json.beginObject();'
737             self.dump_atoms(glGetProgramARB, target)
738             print '        json.endObject();'
739             print '    }'
740
741     def dump_texture_parameters(self):
742         print '    {'
743         print '        GLint active_texture = GL_TEXTURE0;'
744         print '        glGetIntegerv(GL_ACTIVE_TEXTURE, &active_texture);'
745         print '        GLint max_texture_coords = 0;'
746         print '        glGetIntegerv(GL_MAX_TEXTURE_COORDS, &max_texture_coords);'
747         print '        GLint max_combined_texture_image_units = 0;'
748         print '        glGetIntegerv(GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS, &max_combined_texture_image_units);'
749         print '        GLint max_units = std::max(max_combined_texture_image_units, max_texture_coords);'
750         print '        for (GLint unit = 0; unit < max_units; ++unit) {'
751         print '            char name[32];'
752         print '            snprintf(name, sizeof name, "GL_TEXTURE%i", unit);'
753         print '            json.beginMember(name);'
754         print '            glActiveTexture(GL_TEXTURE0 + unit);'
755         print '            json.beginObject();'
756         print '            GLint texture;'
757         print
758         for target, binding in texture_targets:
759             print '            // %s' % target
760             print '            texture = 0;'
761             print '            glGetIntegerv(%s, &texture);' % binding
762             print '            if (glIsEnabled(%s) || texture) {' % target
763             print '                json.beginMember("%s");' % target
764             print '                json.beginObject();'
765             self.dump_atoms(glGetTexParameter, target)
766             # We only dump the first level parameters
767             self.dump_atoms(glGetTexLevelParameter, target, "0")
768             print '                json.endObject();'
769             print '                json.endMember(); // %s' % target
770             print '            }'
771             print
772         print '            json.endObject();'
773         print '            json.endMember(); // GL_TEXTUREi'
774         print '        }'
775         print '        glActiveTexture(active_texture);'
776         print '    }'
777         print
778
779     def dump_current_program(self):
780         print '    json.beginMember("shaders");'
781         print '    json.beginObject();'
782         print '    writeCurrentProgram(json);'
783         for target in self.program_targets:
784             print '    writeArbProgram(json, %s);' % target
785         print '    json.endObject();'
786         print '    json.endMember(); //shaders'
787         print
788
789     def dump_textures(self):
790         print '    {'
791         print '        json.beginMember("textures");'
792         print '        json.beginObject();'
793         print '        GLint active_texture = GL_TEXTURE0;'
794         print '        glGetIntegerv(GL_ACTIVE_TEXTURE, &active_texture);'
795         print '        GLint max_texture_coords = 0;'
796         print '        glGetIntegerv(GL_MAX_TEXTURE_COORDS, &max_texture_coords);'
797         print '        GLint max_combined_texture_image_units = 0;'
798         print '        glGetIntegerv(GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS, &max_combined_texture_image_units);'
799         print '        GLint max_units = std::max(max_combined_texture_image_units, max_texture_coords);'
800         print '        for (GLint unit = 0; unit < max_units; ++unit) {'
801         print '            GLenum texture = GL_TEXTURE0 + unit;'
802         print '            glActiveTexture(texture);'
803         for target, binding in texture_targets:
804             print '            writeTexture(json, %s, %s);' % (target, binding)
805         print '        }'
806         print '        glActiveTexture(active_texture);'
807         print '        json.endObject();'
808         print '        json.endMember(); // textures'
809         print '    }'
810         print
811
812     def dump_framebuffer(self):
813         print '    json.beginMember("framebuffer");'
814         print '    json.beginObject();'
815         # TODO: Handle real FBOs
816         print
817         print '    GLint boundDrawFbo = 0, boundReadFbo = 0;'
818         print '    glGetIntegerv(GL_DRAW_FRAMEBUFFER_BINDING, &boundDrawFbo);'
819         print '    glGetIntegerv(GL_READ_FRAMEBUFFER_BINDING, &boundReadFbo);'
820         print '    if (!boundDrawFbo) {'
821         print '        GLint depth_bits = 0;'
822         print '        glGetIntegerv(GL_DEPTH_BITS, &depth_bits);'
823         print '        GLint stencil_bits = 0;'
824         print '        glGetIntegerv(GL_STENCIL_BITS, &stencil_bits);'
825         print '        writeDrawBuffers(json, depth_bits, stencil_bits);'
826         print '    } else {'
827         print '        GLint colorRb, stencilRb, depthRb;'
828         print '        GLint boundRb;'
829         print '        glGetIntegerv(GL_RENDERBUFFER_BINDING, &boundRb);'
830         print '        GLint drawbuffer = glretrace::double_buffer ? GL_BACK : GL_FRONT;'
831         print '        glGetIntegerv(GL_DRAW_BUFFER, &drawbuffer);'
832         print
833         print '        glGetFramebufferAttachmentParameteriv(GL_FRAMEBUFFER,'
834         print '                                              drawbuffer,'
835         print '                                              GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME,'
836         print '                                              &colorRb);'
837         print '        glGetFramebufferAttachmentParameteriv(GL_FRAMEBUFFER,'
838         print '                                              GL_DEPTH_ATTACHMENT,'
839         print '                                              GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME,'
840         print '                                              &depthRb);'
841         print '        glGetFramebufferAttachmentParameteriv(GL_FRAMEBUFFER,'
842         print '                                              GL_STENCIL_ATTACHMENT,'
843         print '                                              GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME,'
844         print '                                              &stencilRb);'
845         print
846         print '        GLint colorSamples, depthSamples, stencilSamples;'
847         print '        GLuint rbs[3];'
848         print '        GLint numRbs = 0;'
849         print '        GLuint fboCopy = 0;'
850         print '        glBindRenderbuffer(GL_RENDERBUFFER, colorRb);'
851         print '        glGetRenderbufferParameteriv(GL_RENDERBUFFER,'
852         print '                                     GL_RENDERBUFFER_SAMPLES, &colorSamples);'
853         print '        glBindRenderbuffer(GL_RENDERBUFFER, depthRb);'
854         print '        glGetRenderbufferParameteriv(GL_RENDERBUFFER,'
855         print '                                     GL_RENDERBUFFER_SAMPLES, &depthSamples);'
856         print '        glBindRenderbuffer(GL_RENDERBUFFER, stencilRb);'
857         print '        glGetRenderbufferParameteriv(GL_RENDERBUFFER,'
858         print '                                     GL_RENDERBUFFER_SAMPLES, &stencilSamples);'
859         print '        glBindRenderbuffer(GL_RENDERBUFFER, boundRb);'
860         print
861         print '        if (colorSamples || depthSamples || stencilSamples) {'
862         print '            //glReadPixels doesnt support multisampled buffers so we need'
863         print '            // to blit the fbo to a temporary one'
864         print '            fboCopy = downsampledFramebuffer(boundDrawFbo, drawbuffer,'
865         print '                                             colorRb, depthRb, stencilRb,'
866         print '                                             rbs, &numRbs);'
867         print '        }'
868         print '        glDrawBuffer(drawbuffer);'
869         print '        glReadBuffer(drawbuffer);'
870         print
871         print '        writeDrawBuffers(json, depthRb, stencilRb);'
872         print
873         print '        if (fboCopy) {'
874         print '            glBindFramebuffer(GL_FRAMEBUFFER, boundDrawFbo);'
875         print '            glBindFramebuffer(GL_READ_FRAMEBUFFER, boundReadFbo);'
876         print '            glBindFramebuffer(GL_DRAW_FRAMEBUFFER, boundDrawFbo);'
877         print '            glBindRenderbuffer(GL_RENDERBUFFER_BINDING, boundRb);'
878         print '            glDeleteRenderbuffers(numRbs, rbs);'
879         print '            glDeleteFramebuffers(1, &fboCopy);'
880         print '        }'
881         print '    }'
882         print
883         print '    json.endObject();'
884         print '    json.endMember(); // framebuffer'
885         pass
886
887     def dump_atoms(self, getter, *args):
888         for function, type, count, name in parameters:
889             inflection = getter.inflector.radical + getter.suffix
890             if inflection not in function.split(','):
891                 continue
892             if type is X:
893                 continue
894             print '        // %s' % name
895             print '        {'
896             type, value = getter(*(args + (name,)))
897             print '            if (glGetError() != GL_NO_ERROR) {'
898             #print '                std::cerr << "warning: %s(%s) failed\\n";' % (inflection, name)
899             print '            } else {'
900             print '                json.beginMember("%s");' % name
901             JsonWriter().visit(type, value)
902             print '                json.endMember();'
903             print '            }'
904             print '        }'
905             print
906
907
908 if __name__ == '__main__':
909     StateDumper().dump()