]> git.cworth.org Git - apitrace/blob - glstate.py
Describe glGetProgram params.
[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 glGetProgram = StateGetter('glGetProgram', {I: 'iv'})
176 glGetProgramARB = StateGetter('glGetProgram', {I: 'iv', F: 'fv', S: 'Stringv'}, 'ARB')
177
178
179 class JsonWriter(Visitor):
180     '''Type visitor that will dump a value of the specified type through the
181     JSON writer.
182     
183     It expects a previously declared JSONWriter instance named "json".'''
184
185     def visit_literal(self, literal, instance):
186         if literal.format == 'Bool':
187             print '    json.writeBool(%s);' % instance
188         elif literal.format in ('SInt', 'Uint', 'Float', 'Double'):
189             print '    json.writeNumber(%s);' % instance
190         else:
191             raise NotImplementedError
192
193     def visit_string(self, string, instance):
194         assert string.length is None
195         print '    json.writeString((const char *)%s);' % instance
196
197     def visit_enum(self, enum, instance):
198         if enum.expr == 'GLenum':
199             print '    writeEnum(json, %s);' % instance
200         else:
201             print '    json.writeNumber(%s);' % instance
202
203     def visit_bitmask(self, bitmask, instance):
204         raise NotImplementedError
205
206     def visit_alias(self, alias, instance):
207         self.visit(alias.type, instance)
208
209     def visit_opaque(self, opaque, instance):
210         print '    json.writeNumber((size_t)%s);' % instance
211
212     __index = 0
213
214     def visit_array(self, array, instance):
215         index = '__i%u' % JsonWriter.__index
216         JsonWriter.__index += 1
217         print '    json.beginArray();'
218         print '    for (unsigned %s = 0; %s < %s; ++%s) {' % (index, index, array.length, index)
219         self.visit(array.type, '%s[%s]' % (instance, index))
220         print '    }'
221         print '    json.endArray();'
222
223
224
225 class StateDumper:
226     '''Class to generate code to dump all GL state in JSON format via
227     stdout.'''
228
229     def __init__(self):
230         pass
231
232     def dump(self):
233         print '#include <string.h>'
234         print '#include <iostream>'
235         print '#include <algorithm>'
236         print
237         print '#include "image.hpp"'
238         print '#include "json.hpp"'
239         print '#include "glimports.hpp"'
240         print '#include "glproc.hpp"'
241         print '#include "glsize.hpp"'
242         print '#include "glretrace.hpp"'
243         print
244
245         print 'static const char *'
246         print '_enum_string(GLenum pname)'
247         print '{'
248         print '    switch(pname) {'
249         for name in GLenum.values:
250             print '    case %s:' % name
251             print '        return "%s";' % name
252         print '    default:'
253         print '        return NULL;'
254         print '    }'
255         print '}'
256         print
257
258         print 'static const char *'
259         print 'enum_string(GLenum pname)'
260         print '{'
261         print '    const char *s = _enum_string(pname);'
262         print '    if (s) {'
263         print '        return s;'
264         print '    } else {'
265         print '        static char buf[16];'
266         print '        snprintf(buf, sizeof buf, "0x%04x", pname);'
267         print '        return buf;'
268         print '    }'
269         print '}'
270         print
271
272         print 'static inline void'
273         print 'writeEnum(JSONWriter &json, GLenum pname)'
274         print '{'
275         print '    const char *s = _enum_string(pname);'
276         print '    if (s) {'
277         print '        json.writeString(s);'
278         print '    } else {'
279         print '        json.writeNumber(pname);'
280         print '    }'
281         print '}'
282         print
283
284         # shaders
285         print '''
286 static void
287 writeShader(JSONWriter &json, GLuint shader)
288 {
289     if (!shader) {
290         return;
291     }
292
293     GLint shader_type = 0;
294     glGetShaderiv(shader, GL_SHADER_TYPE, &shader_type);
295     if (!shader_type) {
296         return;
297     }
298
299     GLint source_length = 0;
300     glGetShaderiv(shader, GL_SHADER_SOURCE_LENGTH, &source_length);
301     if (!source_length) {
302         return;
303     }
304
305     GLchar *source = new GLchar[source_length];
306     GLsizei length = 0;
307     source[0] = 0;
308     glGetShaderSource(shader, source_length, &length, source);
309
310     json.beginMember(enum_string(shader_type));
311     json.writeString(source);
312     json.endMember();
313
314     delete [] source;
315 }
316
317 static inline void
318 writeCurrentProgram(JSONWriter &json)
319 {
320     GLint program = 0;
321     glGetIntegerv(GL_CURRENT_PROGRAM, &program);
322     if (!program) {
323         return;
324     }
325
326     GLint attached_shaders = 0;
327     glGetProgramiv(program, GL_ATTACHED_SHADERS, &attached_shaders);
328     if (!attached_shaders) {
329         return;
330     }
331
332     GLuint *shaders = new GLuint[attached_shaders];
333     GLsizei count = 0;
334     glGetAttachedShaders(program, attached_shaders, &count, shaders);
335     for (GLsizei i = 0; i < count; ++ i) {
336        writeShader(json, shaders[i]);
337     }
338     delete [] shaders;
339 }
340
341 static inline void
342 writeArbProgram(JSONWriter &json, GLenum target)
343 {
344     if (!glIsEnabled(target)) {
345         return;
346     }
347
348     GLint program_length = 0;
349     glGetProgramivARB(target, GL_PROGRAM_LENGTH_ARB, &program_length);
350     if (!program_length) {
351         return;
352     }
353
354     GLchar *source = new GLchar[program_length + 1];
355     source[0] = 0;
356     glGetProgramStringARB(target, GL_PROGRAM_STRING_ARB, source);
357     source[program_length] = 0;
358
359     json.beginMember(enum_string(target));
360     json.writeString(source);
361     json.endMember();
362
363     delete [] source;
364 }
365 '''
366
367         # texture image
368         print '''
369 static inline void
370 writeTextureImage(JSONWriter &json, GLenum target, GLint level)
371 {
372     GLint width, height = 1, depth = 1;
373
374     width = 0;
375     glGetTexLevelParameteriv(target, level, GL_TEXTURE_WIDTH, &width);
376
377     if (target != GL_TEXTURE_1D) {
378         height = 0;
379         glGetTexLevelParameteriv(target, level, GL_TEXTURE_HEIGHT, &height);
380         if (target == GL_TEXTURE_3D) {
381             depth = 0;
382             glGetTexLevelParameteriv(target, level, GL_TEXTURE_DEPTH, &depth);
383         }
384     }
385
386     if (width <= 0 || height <= 0 || depth <= 0) {
387         return;
388     } else {
389         char label[512];
390
391         GLint active_texture = GL_TEXTURE0;
392         glGetIntegerv(GL_ACTIVE_TEXTURE, &active_texture);
393         snprintf(label, sizeof label, "%s, %s, level = %i", _enum_string(active_texture), _enum_string(target), level);
394
395         json.beginMember(label);
396
397         json.beginObject();
398
399         // Tell the GUI this is no ordinary object, but an image
400         json.writeStringMember("__class__", "image");
401
402         json.writeNumberMember("__width__", width);
403         json.writeNumberMember("__height__", height);
404         json.writeNumberMember("__depth__", depth);
405
406         // Hardcoded for now, but we could chose types more adequate to the
407         // texture internal format
408         json.writeStringMember("__type__", "uint8");
409         json.writeBoolMember("__normalized__", true);
410         json.writeNumberMember("__channels__", 4);
411         
412         GLubyte *pixels = new GLubyte[depth*width*height*4];
413
414         glGetTexImage(target, level, GL_RGBA, GL_UNSIGNED_BYTE, pixels);
415
416         json.beginMember("__data__");
417         char *pngBuffer;
418         int pngBufferSize;
419         Image::writePixelsToBuffer(pixels, width, height, 4, false, &pngBuffer, &pngBufferSize);
420         json.writeBase64(pngBuffer, pngBufferSize);
421         free(pngBuffer);
422         json.endMember(); // __data__
423
424         delete [] pixels;
425         json.endObject();
426     }
427 }
428
429 static inline void
430 writeDrawBufferImage(JSONWriter &json, GLenum format)
431 {
432     GLint width  = glretrace::window_width;
433     GLint height = glretrace::window_height;
434
435     GLint channels = __gl_format_channels(format);
436
437     if (!width || !height) {
438         json.writeNull();
439     } else {
440         json.beginObject();
441
442         // Tell the GUI this is no ordinary object, but an image
443         json.writeStringMember("__class__", "image");
444
445         json.writeNumberMember("__width__", width);
446         json.writeNumberMember("__height__", height);
447         json.writeNumberMember("__depth__", 1);
448
449         // Hardcoded for now, but we could chose types more adequate to the
450         // texture internal format
451         json.writeStringMember("__type__", "uint8");
452         json.writeBoolMember("__normalized__", true);
453         json.writeNumberMember("__channels__", channels);
454
455         GLubyte *pixels = new GLubyte[width*height*channels];
456         
457         GLint drawbuffer = glretrace::double_buffer ? GL_BACK : GL_FRONT;
458         GLint readbuffer = glretrace::double_buffer ? GL_BACK : GL_FRONT;
459         glGetIntegerv(GL_DRAW_BUFFER, &drawbuffer);
460         glGetIntegerv(GL_READ_BUFFER, &readbuffer);
461         glReadBuffer(drawbuffer);
462
463         glPushClientAttrib(GL_CLIENT_PIXEL_STORE_BIT);
464         glPixelStorei(GL_PACK_ALIGNMENT, 1);
465
466         glReadPixels(0, 0, width, height, format, GL_UNSIGNED_BYTE, pixels);
467
468         glPopClientAttrib();
469         glReadBuffer(readbuffer);
470
471         json.beginMember("__data__");
472         char *pngBuffer;
473         int pngBufferSize;
474         Image::writePixelsToBuffer(pixels, width, height, channels, false, &pngBuffer, &pngBufferSize);
475         //std::cerr <<" Before = "<<(width * height * channels * sizeof *pixels)
476         //          <<", after = "<<pngBufferSize << ", ratio = " << double(width * height * channels * sizeof *pixels)/pngBufferSize;
477         json.writeBase64(pngBuffer, pngBufferSize);
478         free(pngBuffer);
479         json.endMember(); // __data__
480
481         delete [] pixels;
482         json.endObject();
483     }
484 }
485
486 static inline GLuint
487 downsampledFramebuffer(GLuint oldFbo, GLint drawbuffer,
488                        GLint colorRb, GLint depthRb, GLint stencilRb,
489                        GLuint *rbs, GLint *numRbs)
490 {
491     GLuint fbo;
492     GLint format;
493     GLint w, h;
494
495     *numRbs = 0;
496
497     glGenFramebuffers(1, &fbo);
498     glBindFramebuffer(GL_FRAMEBUFFER, fbo);
499
500     glBindRenderbuffer(GL_RENDERBUFFER, colorRb);
501     glGetRenderbufferParameteriv(GL_RENDERBUFFER,
502                                  GL_RENDERBUFFER_WIDTH, &w);
503     glGetRenderbufferParameteriv(GL_RENDERBUFFER,
504                                  GL_RENDERBUFFER_HEIGHT, &h);
505     glGetRenderbufferParameteriv(GL_RENDERBUFFER,
506                                  GL_RENDERBUFFER_INTERNAL_FORMAT, &format);
507
508     glGenRenderbuffers(1, &rbs[*numRbs]);
509     glBindRenderbuffer(GL_RENDERBUFFER, rbs[*numRbs]);
510     glRenderbufferStorage(GL_RENDERBUFFER, format, w, h);
511     glFramebufferRenderbuffer(GL_FRAMEBUFFER, drawbuffer,
512                               GL_RENDERBUFFER, rbs[*numRbs]);
513
514     glBindFramebuffer(GL_READ_FRAMEBUFFER, oldFbo);
515     glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbo);
516     glDrawBuffer(drawbuffer);
517     glReadBuffer(drawbuffer);
518     glBlitFramebuffer(0, 0, w, h, 0, 0, w, h,
519                       GL_COLOR_BUFFER_BIT, GL_NEAREST);
520     glBindFramebuffer(GL_FRAMEBUFFER, fbo);
521     ++*numRbs;
522
523     if (stencilRb == depthRb && stencilRb) {
524         //combined depth and stencil buffer
525         glBindRenderbuffer(GL_RENDERBUFFER, depthRb);
526         glGetRenderbufferParameteriv(GL_RENDERBUFFER,
527                                      GL_RENDERBUFFER_WIDTH, &w);
528         glGetRenderbufferParameteriv(GL_RENDERBUFFER,
529                                      GL_RENDERBUFFER_HEIGHT, &h);
530         glGetRenderbufferParameteriv(GL_RENDERBUFFER,
531                                      GL_RENDERBUFFER_INTERNAL_FORMAT, &format);
532
533         glGenRenderbuffers(1, &rbs[*numRbs]);
534         glBindRenderbuffer(GL_RENDERBUFFER, rbs[*numRbs]);
535         glRenderbufferStorage(GL_RENDERBUFFER, format, w, h);
536         glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT,
537                                   GL_RENDERBUFFER, rbs[*numRbs]);
538         glBindFramebuffer(GL_READ_FRAMEBUFFER, oldFbo);
539         glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbo);
540         glBlitFramebuffer(0, 0, w, h, 0, 0, w, h,
541                           GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT, GL_NEAREST);
542         glBindFramebuffer(GL_FRAMEBUFFER, fbo);
543         ++*numRbs;
544     } else {
545         if (depthRb) {
546             glBindRenderbuffer(GL_RENDERBUFFER, depthRb);
547             glGetRenderbufferParameteriv(GL_RENDERBUFFER,
548                                          GL_RENDERBUFFER_WIDTH, &w);
549             glGetRenderbufferParameteriv(GL_RENDERBUFFER,
550                                          GL_RENDERBUFFER_HEIGHT, &h);
551             glGetRenderbufferParameteriv(GL_RENDERBUFFER,
552                                          GL_RENDERBUFFER_INTERNAL_FORMAT, &format);
553
554             glGenRenderbuffers(1, &rbs[*numRbs]);
555             glBindRenderbuffer(GL_RENDERBUFFER, rbs[*numRbs]);
556             glRenderbufferStorage(GL_RENDERBUFFER, format, w, h);
557             glFramebufferRenderbuffer(GL_FRAMEBUFFER,
558                                       GL_DEPTH_ATTACHMENT,
559                                       GL_RENDERBUFFER, rbs[*numRbs]);
560             glBindFramebuffer(GL_READ_FRAMEBUFFER, oldFbo);
561             glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbo);
562             glDrawBuffer(GL_DEPTH_ATTACHMENT);
563             glReadBuffer(GL_DEPTH_ATTACHMENT);
564             glBlitFramebuffer(0, 0, w, h, 0, 0, w, h,
565                               GL_DEPTH_BUFFER_BIT, GL_NEAREST);
566             ++*numRbs;
567         }
568         if (stencilRb) {
569             glBindRenderbuffer(GL_RENDERBUFFER, stencilRb);
570             glGetRenderbufferParameteriv(GL_RENDERBUFFER,
571                                          GL_RENDERBUFFER_WIDTH, &w);
572             glGetRenderbufferParameteriv(GL_RENDERBUFFER,
573                                          GL_RENDERBUFFER_HEIGHT, &h);
574             glGetRenderbufferParameteriv(GL_RENDERBUFFER,
575                                      GL_RENDERBUFFER_INTERNAL_FORMAT, &format);
576
577             glGenRenderbuffers(1, &rbs[*numRbs]);
578             glBindRenderbuffer(GL_RENDERBUFFER, rbs[*numRbs]);
579             glRenderbufferStorage(GL_RENDERBUFFER, format, w, h);
580             glFramebufferRenderbuffer(GL_FRAMEBUFFER,
581                                       GL_STENCIL_ATTACHMENT,
582                                       GL_RENDERBUFFER, rbs[*numRbs]);
583             glBindFramebuffer(GL_READ_FRAMEBUFFER, oldFbo);
584             glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbo);
585             glDrawBuffer(GL_STENCIL_ATTACHMENT);
586             glReadBuffer(GL_STENCIL_ATTACHMENT);
587             glBlitFramebuffer(0, 0, w, h, 0, 0, w, h,
588                               GL_STENCIL_BUFFER_BIT, GL_NEAREST);
589             ++*numRbs;
590         }
591     }
592
593     return fbo;
594 }
595
596 static void
597 writeDrawBuffers(JSONWriter &json, GLboolean writeDepth, GLboolean writeStencil)
598 {
599     json.beginMember("GL_RGBA");
600     writeDrawBufferImage(json, GL_RGBA);
601     json.endMember();
602
603     if (writeDepth) {
604         json.beginMember("GL_DEPTH_COMPONENT");
605         writeDrawBufferImage(json, GL_DEPTH_COMPONENT);
606         json.endMember();
607     }
608
609     if (writeStencil) {
610         json.beginMember("GL_STENCIL_INDEX");
611         writeDrawBufferImage(json, GL_STENCIL_INDEX);
612         json.endMember();
613     }
614 }
615
616 '''
617
618         # textures
619         print 'static inline void'
620         print 'writeTexture(JSONWriter &json, GLenum target, GLenum binding)'
621         print '{'
622         print '    GLint texture_binding = 0;'
623         print '    glGetIntegerv(binding, &texture_binding);'
624         print '    if (!glIsEnabled(target) && !texture_binding) {'
625         print '        return;'
626         print '    }'
627         print
628         print '    GLint level = 0;'
629         print '    do {'
630         print '        GLint width = 0, height = 0;'
631         print '        glGetTexLevelParameteriv(target, level, GL_TEXTURE_WIDTH, &width);'
632         print '        glGetTexLevelParameteriv(target, level, GL_TEXTURE_HEIGHT, &height);'
633         print '        if (!width || !height) {'
634         print '            break;'
635         print '        }'
636         print
637         print '        if (target == GL_TEXTURE_CUBE_MAP) {'
638         print '            for (int face = 0; face < 6; ++face) {'
639         print '                writeTextureImage(json, GL_TEXTURE_CUBE_MAP_POSITIVE_X + face, level);'
640         print '            }'
641         print '        } else {'
642         print '            writeTextureImage(json, target, level);'
643         print '        }'
644         print
645         print '        ++level;'
646         print '    } while(true);'
647         print '}'
648         print
649
650         print 'void glretrace::state_dump(std::ostream &os)'
651         print '{'
652         print '    JSONWriter json(os);'
653         self.dump_parameters()
654         self.dump_current_program()
655         self.dump_textures()
656         self.dump_framebuffer()
657         print '}'
658         print
659
660     def dump_parameters(self):
661         print '    json.beginMember("parameters");'
662         print '    json.beginObject();'
663         
664         self.dump_atoms(glGet)
665         
666         self.dump_material_params()
667         self.dump_light_params()
668         self.dump_vertex_attribs()
669         self.dump_texenv_params()
670         self.dump_program_params()
671         self.dump_texture_parameters()
672
673         print '    json.endObject();'
674         print '    json.endMember(); // parameters'
675         print
676
677     def dump_material_params(self):
678         for face in ['GL_FRONT', 'GL_BACK']:
679             print '    json.beginMember("%s");' % face
680             print '    json.beginObject();'
681             self.dump_atoms(glGetMaterial, face)
682             print '    json.endObject();'
683         print
684
685     def dump_light_params(self):
686         print '    GLint max_lights = 0;'
687         print '    __glGetIntegerv(GL_MAX_LIGHTS, &max_lights);'
688         print '    for (GLint index = 0; index < max_lights; ++index) {'
689         print '        GLenum light = GL_LIGHT0 + index;'
690         print '        if (glIsEnabled(light)) {'
691         print '            char name[32];'
692         print '            snprintf(name, sizeof name, "GL_LIGHT%i", index);'
693         print '            json.beginMember(name);'
694         print '            json.beginObject();'
695         self.dump_atoms(glGetLight, '    GL_LIGHT0 + index')
696         print '            json.endObject();'
697         print '            json.endMember(); // GL_LIGHTi'
698         print '        }'
699         print '    }'
700         print
701
702     def dump_texenv_params(self):
703         for target in ['GL_TEXTURE_ENV', 'GL_TEXTURE_FILTER_CONTROL', 'GL_POINT_SPRITE']:
704             if target != 'GL_TEXTURE_FILTER_CONTROL':
705                 print '    if (glIsEnabled(%s)) {' % target
706             else:
707                 print '    {'
708             print '        json.beginMember("%s");' % target
709             print '        json.beginObject();'
710             self.dump_atoms(glGetTexEnv, target)
711             print '        json.endObject();'
712             print '    }'
713
714     def dump_vertex_attribs(self):
715         print '    GLint max_vertex_attribs = 0;'
716         print '    __glGetIntegerv(GL_MAX_VERTEX_ATTRIBS, &max_vertex_attribs);'
717         print '    for (GLint index = 0; index < max_vertex_attribs; ++index) {'
718         print '        char name[32];'
719         print '        snprintf(name, sizeof name, "GL_VERTEX_ATTRIB_ARRAY%i", index);'
720         print '        json.beginMember(name);'
721         print '        json.beginObject();'
722         self.dump_atoms(glGetVertexAttrib, 'index')
723         print '        json.endObject();'
724         print '        json.endMember(); // GL_VERTEX_ATTRIB_ARRAYi'
725         print '    }'
726         print
727
728     program_targets = [
729         'GL_FRAGMENT_PROGRAM_ARB',
730         'GL_VERTEX_PROGRAM_ARB',
731     ]
732
733     def dump_program_params(self):
734         for target in self.program_targets:
735             print '    if (glIsEnabled(%s)) {' % target
736             print '        json.beginMember("%s");' % target
737             print '        json.beginObject();'
738             self.dump_atoms(glGetProgramARB, target)
739             print '        json.endObject();'
740             print '    }'
741
742     def dump_texture_parameters(self):
743         print '    {'
744         print '        GLint active_texture = GL_TEXTURE0;'
745         print '        glGetIntegerv(GL_ACTIVE_TEXTURE, &active_texture);'
746         print '        GLint max_texture_coords = 0;'
747         print '        glGetIntegerv(GL_MAX_TEXTURE_COORDS, &max_texture_coords);'
748         print '        GLint max_combined_texture_image_units = 0;'
749         print '        glGetIntegerv(GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS, &max_combined_texture_image_units);'
750         print '        GLint max_units = std::max(max_combined_texture_image_units, max_texture_coords);'
751         print '        for (GLint unit = 0; unit < max_units; ++unit) {'
752         print '            char name[32];'
753         print '            snprintf(name, sizeof name, "GL_TEXTURE%i", unit);'
754         print '            json.beginMember(name);'
755         print '            glActiveTexture(GL_TEXTURE0 + unit);'
756         print '            json.beginObject();'
757         print '            GLint texture;'
758         print
759         for target, binding in texture_targets:
760             print '            // %s' % target
761             print '            texture = 0;'
762             print '            glGetIntegerv(%s, &texture);' % binding
763             print '            if (glIsEnabled(%s) || texture) {' % target
764             print '                json.beginMember("%s");' % target
765             print '                json.beginObject();'
766             self.dump_atoms(glGetTexParameter, target)
767             # We only dump the first level parameters
768             self.dump_atoms(glGetTexLevelParameter, target, "0")
769             print '                json.endObject();'
770             print '                json.endMember(); // %s' % target
771             print '            }'
772             print
773         print '            json.endObject();'
774         print '            json.endMember(); // GL_TEXTUREi'
775         print '        }'
776         print '        glActiveTexture(active_texture);'
777         print '    }'
778         print
779
780     def dump_current_program(self):
781         print '    json.beginMember("shaders");'
782         print '    json.beginObject();'
783         print '    writeCurrentProgram(json);'
784         for target in self.program_targets:
785             print '    writeArbProgram(json, %s);' % target
786         print '    json.endObject();'
787         print '    json.endMember(); //shaders'
788         print
789
790     def dump_textures(self):
791         print '    {'
792         print '        json.beginMember("textures");'
793         print '        json.beginObject();'
794         print '        GLint active_texture = GL_TEXTURE0;'
795         print '        glGetIntegerv(GL_ACTIVE_TEXTURE, &active_texture);'
796         print '        GLint max_texture_coords = 0;'
797         print '        glGetIntegerv(GL_MAX_TEXTURE_COORDS, &max_texture_coords);'
798         print '        GLint max_combined_texture_image_units = 0;'
799         print '        glGetIntegerv(GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS, &max_combined_texture_image_units);'
800         print '        GLint max_units = std::max(max_combined_texture_image_units, max_texture_coords);'
801         print '        for (GLint unit = 0; unit < max_units; ++unit) {'
802         print '            GLenum texture = GL_TEXTURE0 + unit;'
803         print '            glActiveTexture(texture);'
804         for target, binding in texture_targets:
805             print '            writeTexture(json, %s, %s);' % (target, binding)
806         print '        }'
807         print '        glActiveTexture(active_texture);'
808         print '        json.endObject();'
809         print '        json.endMember(); // textures'
810         print '    }'
811         print
812
813     def dump_framebuffer(self):
814         print '    json.beginMember("framebuffer");'
815         print '    json.beginObject();'
816         # TODO: Handle real FBOs
817         print
818         print '    GLint boundDrawFbo = 0, boundReadFbo = 0;'
819         print '    glGetIntegerv(GL_DRAW_FRAMEBUFFER_BINDING, &boundDrawFbo);'
820         print '    glGetIntegerv(GL_READ_FRAMEBUFFER_BINDING, &boundReadFbo);'
821         print '    if (!boundDrawFbo) {'
822         print '        GLint depth_bits = 0;'
823         print '        glGetIntegerv(GL_DEPTH_BITS, &depth_bits);'
824         print '        GLint stencil_bits = 0;'
825         print '        glGetIntegerv(GL_STENCIL_BITS, &stencil_bits);'
826         print '        writeDrawBuffers(json, depth_bits, stencil_bits);'
827         print '    } else {'
828         print '        GLint colorRb, stencilRb, depthRb;'
829         print '        GLint boundRb;'
830         print '        glGetIntegerv(GL_RENDERBUFFER_BINDING, &boundRb);'
831         print '        GLint drawbuffer = glretrace::double_buffer ? GL_BACK : GL_FRONT;'
832         print '        glGetIntegerv(GL_DRAW_BUFFER, &drawbuffer);'
833         print
834         print '        glGetFramebufferAttachmentParameteriv(GL_FRAMEBUFFER,'
835         print '                                              drawbuffer,'
836         print '                                              GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME,'
837         print '                                              &colorRb);'
838         print '        glGetFramebufferAttachmentParameteriv(GL_FRAMEBUFFER,'
839         print '                                              GL_DEPTH_ATTACHMENT,'
840         print '                                              GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME,'
841         print '                                              &depthRb);'
842         print '        glGetFramebufferAttachmentParameteriv(GL_FRAMEBUFFER,'
843         print '                                              GL_STENCIL_ATTACHMENT,'
844         print '                                              GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME,'
845         print '                                              &stencilRb);'
846         print
847         print '        GLint colorSamples, depthSamples, stencilSamples;'
848         print '        GLuint rbs[3];'
849         print '        GLint numRbs = 0;'
850         print '        GLuint fboCopy = 0;'
851         print '        glBindRenderbuffer(GL_RENDERBUFFER, colorRb);'
852         print '        glGetRenderbufferParameteriv(GL_RENDERBUFFER,'
853         print '                                     GL_RENDERBUFFER_SAMPLES, &colorSamples);'
854         print '        glBindRenderbuffer(GL_RENDERBUFFER, depthRb);'
855         print '        glGetRenderbufferParameteriv(GL_RENDERBUFFER,'
856         print '                                     GL_RENDERBUFFER_SAMPLES, &depthSamples);'
857         print '        glBindRenderbuffer(GL_RENDERBUFFER, stencilRb);'
858         print '        glGetRenderbufferParameteriv(GL_RENDERBUFFER,'
859         print '                                     GL_RENDERBUFFER_SAMPLES, &stencilSamples);'
860         print '        glBindRenderbuffer(GL_RENDERBUFFER, boundRb);'
861         print
862         print '        if (colorSamples || depthSamples || stencilSamples) {'
863         print '            //glReadPixels doesnt support multisampled buffers so we need'
864         print '            // to blit the fbo to a temporary one'
865         print '            fboCopy = downsampledFramebuffer(boundDrawFbo, drawbuffer,'
866         print '                                             colorRb, depthRb, stencilRb,'
867         print '                                             rbs, &numRbs);'
868         print '        }'
869         print '        glDrawBuffer(drawbuffer);'
870         print '        glReadBuffer(drawbuffer);'
871         print
872         print '        writeDrawBuffers(json, depthRb, stencilRb);'
873         print
874         print '        if (fboCopy) {'
875         print '            glBindFramebuffer(GL_FRAMEBUFFER, boundDrawFbo);'
876         print '            glBindFramebuffer(GL_READ_FRAMEBUFFER, boundReadFbo);'
877         print '            glBindFramebuffer(GL_DRAW_FRAMEBUFFER, boundDrawFbo);'
878         print '            glBindRenderbuffer(GL_RENDERBUFFER_BINDING, boundRb);'
879         print '            glDeleteRenderbuffers(numRbs, rbs);'
880         print '            glDeleteFramebuffers(1, &fboCopy);'
881         print '        }'
882         print '    }'
883         print
884         print '    json.endObject();'
885         print '    json.endMember(); // framebuffer'
886         pass
887
888     def dump_atoms(self, getter, *args):
889         for function, type, count, name in parameters:
890             inflection = getter.inflector.radical + getter.suffix
891             if inflection not in function.split(','):
892                 continue
893             if type is X:
894                 continue
895             print '        // %s' % name
896             print '        {'
897             type, value = getter(*(args + (name,)))
898             print '            if (glGetError() != GL_NO_ERROR) {'
899             #print '                std::cerr << "warning: %s(%s) failed\\n";' % (inflection, name)
900             print '            } else {'
901             print '                json.beginMember("%s");' % name
902             JsonWriter().visit(type, value)
903             print '                json.endMember();'
904             print '            }'
905             print '        }'
906             print
907
908
909 if __name__ == '__main__':
910     StateDumper().dump()