]> git.cworth.org Git - apitrace/blob - retrace/glstate_params.py
glstate: Dump parameters for array and multisample texture targets.
[apitrace] / retrace / glstate_params.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 import retrace # to adjust sys.path
31
32 from specs.stdapi import *
33
34 from specs.gltypes import *
35 from specs.glparams import *
36
37
38 texture_targets = [
39     ('GL_TEXTURE_1D', 'GL_TEXTURE_BINDING_1D'),
40     ('GL_TEXTURE_1D_ARRAY', 'GL_TEXTURE_BINDING_1D_ARRAY'),
41     ('GL_TEXTURE_2D', 'GL_TEXTURE_BINDING_2D'),
42     ('GL_TEXTURE_2D_ARRAY', 'GL_TEXTURE_BINDING_2D_ARRAY'),
43     ('GL_TEXTURE_2D_MULTISAMPLE', 'GL_TEXTURE_BINDING_2D_MULTISAMPLE'),
44     ('GL_TEXTURE_2D_MULTISAMPLE_ARRAY', 'GL_TEXTURE_BINDING_2D_MULTISAMPLE_ARRAY'),
45     ('GL_TEXTURE_3D', 'GL_TEXTURE_BINDING_3D'),
46     ('GL_TEXTURE_RECTANGLE', 'GL_TEXTURE_BINDING_RECTANGLE'),
47     ('GL_TEXTURE_CUBE_MAP', 'GL_TEXTURE_BINDING_CUBE_MAP'),
48     ('GL_TEXTURE_CUBE_MAP_ARRAY', 'GL_TEXTURE_BINDING_CUBE_MAP_ARRAY'),
49 ]
50
51 framebuffer_targets = [
52     ('GL_DRAW_FRAMEBUFFER', 'GL_DRAW_FRAMEBUFFER_BINDING'),
53     ('GL_READ_FRAMEBUFFER', 'GL_READ_FRAMEBUFFER_BINDING'),
54 ]
55
56 class GetInflector:
57     '''Objects that describes how to inflect.'''
58
59     reduced_types = {
60         B: I,
61         E: I,
62         I: F,
63     }
64
65     def __init__(self, radical, inflections, suffix = ''):
66         self.radical = radical
67         self.inflections = inflections
68         self.suffix = suffix
69
70     def reduced_type(self, type):
71         if type in self.inflections:
72             return type
73         if type in self.reduced_types:
74             return self.reduced_type(self.reduced_types[type])
75         raise NotImplementedError
76
77     def inflect(self, type):
78         return self.radical + self.inflection(type) + self.suffix
79
80     def inflection(self, type):
81         type = self.reduced_type(type)
82         assert type in self.inflections
83         return self.inflections[type]
84
85     def __str__(self):
86         return self.radical + self.suffix
87
88
89 class StateGetter(Visitor):
90     '''Type visitor that is able to extract the state via one of the glGet*
91     functions.
92
93     It will declare any temporary variable
94     '''
95
96     def __init__(self, radical, inflections, suffix=''):
97         self.inflector = GetInflector(radical, inflections)
98         self.suffix = suffix
99
100     def iter(self):
101         for function, type, count, name in parameters:
102             inflection = self.inflector.radical + self.suffix
103             if inflection not in function.split(','):
104                 continue
105             if type is X:
106                 continue
107             yield type, count, name
108
109     def __call__(self, *args):
110         pname = args[-1]
111
112         for type, count, name in self.iter():
113             if name == pname:
114                 if count != 1:
115                     type = Array(type, str(count))
116
117                 return type, self.visit(type, args)
118
119         raise NotImplementedError
120
121     def temp_name(self, args):
122         '''Return the name of a temporary variable to hold the state.'''
123         pname = args[-1]
124
125         return pname[3:].lower()
126
127     def visitConst(self, const, args):
128         return self.visit(const.type, args)
129
130     def visitScalar(self, type, args):
131         temp_name = self.temp_name(args)
132         elem_type = self.inflector.reduced_type(type)
133         inflection = self.inflector.inflect(type)
134         if inflection.endswith('v'):
135             print '    %s %s = 0;' % (elem_type, temp_name)
136             print '    %s(%s, &%s);' % (inflection + self.suffix, ', '.join(args), temp_name)
137         else:
138             print '    %s %s = %s(%s);' % (elem_type, temp_name, inflection + self.suffix, ', '.join(args))
139         return temp_name
140
141     def visitString(self, string, args):
142         temp_name = self.temp_name(args)
143         inflection = self.inflector.inflect(string)
144         assert not inflection.endswith('v')
145         print '    %s %s = (%s)%s(%s);' % (string, temp_name, string, inflection + self.suffix, ', '.join(args))
146         return temp_name
147
148     def visitAlias(self, alias, args):
149         return self.visitScalar(alias, args)
150
151     def visitEnum(self, enum, args):
152         return self.visitScalar(enum, args)
153
154     def visitBitmask(self, bitmask, args):
155         return self.visit(GLint, args)
156
157     def visitArray(self, array, args):
158         temp_name = self.temp_name(args)
159         if array.length == '1':
160             return self.visit(array.type)
161         elem_type = self.inflector.reduced_type(array.type)
162         inflection = self.inflector.inflect(array.type)
163         assert inflection.endswith('v')
164         array_length = array.length
165         if array_length.isdigit():
166             # Static integer length
167             print '    %s %s[%s + 1];' % (elem_type, temp_name, array_length)
168         else:
169             # Put the length in a variable to avoid recomputing it every time
170             print '    size_t _%s_length = %s;' % (temp_name, array_length)
171             array_length = '_%s_length' % temp_name
172             # Allocate a dynamic sized array
173             print '    %s *%s = _allocator.alloc<%s>(%s + 1);' % (elem_type, temp_name, elem_type, array_length)
174         print '    memset(%s, 0, %s * sizeof *%s);' % (temp_name, array_length, temp_name)
175         print '    %s[%s] = (%s)0xdeadc0de;' % (temp_name, array_length, elem_type)
176         print '    %s(%s, %s);' % (inflection + self.suffix, ', '.join(args), temp_name)
177         # Simple buffer overflow detection
178         print '    assert(%s[%s] == (%s)0xdeadc0de);' % (temp_name, array_length, elem_type)
179         return temp_name
180
181     def visitOpaque(self, pointer, args):
182         temp_name = self.temp_name(args)
183         inflection = self.inflector.inflect(pointer)
184         assert inflection.endswith('v')
185         print '    GLvoid *%s;' % temp_name
186         print '    %s(%s, &%s);' % (inflection + self.suffix, ', '.join(args), temp_name)
187         return temp_name
188
189
190 glGet = StateGetter('glGet', {
191     B: 'Booleanv',
192     I: 'Integerv',
193     F: 'Floatv',
194     D: 'Doublev',
195     S: 'String',
196     P: 'Pointerv',
197 })
198
199 glGetMaterial = StateGetter('glGetMaterial', {I: 'iv', F: 'fv'})
200 glGetLight = StateGetter('glGetLight', {I: 'iv', F: 'fv'})
201 glGetVertexAttrib = StateGetter('glGetVertexAttrib', {I: 'iv', F: 'fv', D: 'dv', P: 'Pointerv'})
202 glGetTexParameter = StateGetter('glGetTexParameter', {I: 'iv', F: 'fv'})
203 glGetTexEnv = StateGetter('glGetTexEnv', {I: 'iv', F: 'fv'})
204 glGetTexLevelParameter = StateGetter('glGetTexLevelParameter', {I: 'iv', F: 'fv'})
205 glGetShader = StateGetter('glGetShaderiv', {I: 'iv'})
206 glGetProgram = StateGetter('glGetProgram', {I: 'iv'})
207 glGetProgramARB = StateGetter('glGetProgram', {I: 'iv', F: 'fv', S: 'Stringv'}, 'ARB')
208 glGetFramebufferAttachmentParameter = StateGetter('glGetFramebufferAttachmentParameter', {I: 'iv'})
209
210
211 class JsonWriter(Visitor):
212     '''Type visitor that will dump a value of the specified type through the
213     JSON writer.
214     
215     It expects a previously declared JSONWriter instance named "json".'''
216
217     def visitLiteral(self, literal, instance):
218         if literal.kind == 'Bool':
219             print '    json.writeBool(%s);' % instance
220         elif literal.kind in ('SInt', 'Uint'):
221             print '    json.writeInt(%s);' % instance
222         elif literal.kind in ('Float', 'Double'):
223             print '    json.writeFloat(%s);' % instance
224         else:
225             raise NotImplementedError
226
227     def visitString(self, string, instance):
228         assert string.length is None
229         print '    json.writeString((const char *)%s);' % instance
230
231     def visitEnum(self, enum, instance):
232         if enum is GLboolean:
233             print '    dumpBoolean(json, %s);' % instance
234         elif enum is GLenum:
235             print '    dumpEnum(json, %s);' % instance
236         else:
237             assert False
238             print '    json.writeInt(%s);' % instance
239
240     def visitBitmask(self, bitmask, instance):
241         raise NotImplementedError
242
243     def visitAlias(self, alias, instance):
244         self.visit(alias.type, instance)
245
246     def visitOpaque(self, opaque, instance):
247         print '    json.writeInt((size_t)%s);' % instance
248
249     __index = 0
250
251     def visitArray(self, array, instance):
252         index = '_i%u' % JsonWriter.__index
253         JsonWriter.__index += 1
254         print '    json.beginArray();'
255         print '    for (unsigned %s = 0; %s < %s; ++%s) {' % (index, index, array.length, index)
256         self.visit(array.type, '%s[%s]' % (instance, index))
257         print '    }'
258         print '    json.endArray();'
259
260
261
262 class StateDumper:
263     '''Class to generate code to dump all GL state in JSON format via
264     stdout.'''
265
266     def __init__(self):
267         pass
268
269     def dump(self):
270         print '#include <assert.h>'
271         print '#include <string.h>'
272         print
273         print '#include "json.hpp"'
274         print '#include "scoped_allocator.hpp"'
275         print '#include "glproc.hpp"'
276         print '#include "glsize.hpp"'
277         print '#include "glstate.hpp"'
278         print '#include "glstate_internal.hpp"'
279         print
280         print 'namespace glstate {'
281         print
282
283         print 'void'
284         print 'dumpBoolean(JSONWriter &json, GLboolean value)'
285         print '{'
286         print '    switch (value) {'
287         print '    case GL_FALSE:'
288         print '        json.writeString("GL_FALSE");'
289         print '        break;'
290         print '    case GL_TRUE:'
291         print '        json.writeString("GL_TRUE");'
292         print '        break;'
293         print '    default:'
294         print '        json.writeInt(static_cast<GLint>(value));'
295         print '        break;'
296         print '    }'
297         print '}'
298         print
299
300         print 'const char *'
301         print 'enumToString(GLenum pname)'
302         print '{'
303         print '    switch (pname) {'
304         for name in GLenum.values:
305             print '    case %s:' % name
306             print '        return "%s";' % name
307         print '    default:'
308         print '        return NULL;'
309         print '    }'
310         print '}'
311         print
312
313         print 'void'
314         print 'dumpEnum(JSONWriter &json, GLenum pname)'
315         print '{'
316         print '    const char *s = enumToString(pname);'
317         print '    if (s) {'
318         print '        json.writeString(s);'
319         print '    } else {'
320         print '        json.writeInt(pname);'
321         print '    }'
322         print '}'
323         print
324
325         print 'static void'
326         print 'dumpFramebufferAttachementParameters(JSONWriter &json, GLenum target, GLenum attachment)'
327         print '{'
328         self.dump_attachment_parameters('target', 'attachment')
329         print '}'
330         print
331
332         print 'void dumpParameters(JSONWriter &json, Context &context)'
333         print '{'
334         print '    ScopedAllocator _allocator;'
335         print '    (void)_allocator;'
336         print
337         print '    json.beginMember("parameters");'
338         print '    json.beginObject();'
339         
340         self.dump_atoms(glGet)
341         
342         self.dump_material_params()
343         self.dump_light_params()
344         self.dump_vertex_attribs()
345         self.dump_program_params()
346         self.dump_texture_parameters()
347         self.dump_framebuffer_parameters()
348
349         print '    json.endObject();'
350         print '    json.endMember(); // parameters'
351         print '}'
352         print
353         
354         print '} /*namespace glstate */'
355
356     def dump_material_params(self):
357         print '    if (!context.ES) {'
358         for face in ['GL_FRONT', 'GL_BACK']:
359             print '    json.beginMember("%s");' % face
360             print '    json.beginObject();'
361             self.dump_atoms(glGetMaterial, face)
362             print '    json.endObject();'
363         print '    }'
364         print
365
366     def dump_light_params(self):
367         print '    GLint max_lights = 0;'
368         print '    _glGetIntegerv(GL_MAX_LIGHTS, &max_lights);'
369         print '    for (GLint index = 0; index < max_lights; ++index) {'
370         print '        GLenum light = GL_LIGHT0 + index;'
371         print '        if (glIsEnabled(light)) {'
372         print '            char name[32];'
373         print '            snprintf(name, sizeof name, "GL_LIGHT%i", index);'
374         print '            json.beginMember(name);'
375         print '            json.beginObject();'
376         self.dump_atoms(glGetLight, '    GL_LIGHT0 + index')
377         print '            json.endObject();'
378         print '            json.endMember(); // GL_LIGHTi'
379         print '        }'
380         print '    }'
381         print
382
383     def texenv_param_target(self, name):
384         if name == 'GL_TEXTURE_LOD_BIAS':
385            return 'GL_TEXTURE_FILTER_CONTROL'
386         elif name == 'GL_COORD_REPLACE':
387            return 'GL_POINT_SPRITE'
388         else:
389            return 'GL_TEXTURE_ENV'
390
391     def dump_texenv_params(self):
392         for target in ['GL_TEXTURE_ENV', 'GL_TEXTURE_FILTER_CONTROL', 'GL_POINT_SPRITE']:
393             print '    if (!context.ES) {'
394             print '        json.beginMember("%s");' % target
395             print '        json.beginObject();'
396             for _, _, name in glGetTexEnv.iter():
397                 if self.texenv_param_target(name) == target:
398                     self.dump_atom(glGetTexEnv, target, name) 
399             print '        json.endObject();'
400             print '    }'
401
402     def dump_vertex_attribs(self):
403         print '    GLint max_vertex_attribs = 0;'
404         print '    _glGetIntegerv(GL_MAX_VERTEX_ATTRIBS, &max_vertex_attribs);'
405         print '    for (GLint index = 0; index < max_vertex_attribs; ++index) {'
406         print '        char name[32];'
407         print '        snprintf(name, sizeof name, "GL_VERTEX_ATTRIB_ARRAY%i", index);'
408         print '        json.beginMember(name);'
409         print '        json.beginObject();'
410         self.dump_atoms(glGetVertexAttrib, 'index')
411         print '        json.endObject();'
412         print '        json.endMember(); // GL_VERTEX_ATTRIB_ARRAYi'
413         print '    }'
414         print
415
416     program_targets = [
417         'GL_FRAGMENT_PROGRAM_ARB',
418         'GL_VERTEX_PROGRAM_ARB',
419     ]
420
421     def dump_program_params(self):
422         for target in self.program_targets:
423             print '    if (glIsEnabled(%s)) {' % target
424             print '        json.beginMember("%s");' % target
425             print '        json.beginObject();'
426             self.dump_atoms(glGetProgramARB, target)
427             print '        json.endObject();'
428             print '    }'
429
430     def dump_texture_parameters(self):
431         print '    {'
432         print '        GLint active_texture = GL_TEXTURE0;'
433         print '        glGetIntegerv(GL_ACTIVE_TEXTURE, &active_texture);'
434         print '        GLint max_texture_coords = 0;'
435         print '        glGetIntegerv(GL_MAX_TEXTURE_COORDS, &max_texture_coords);'
436         print '        GLint max_combined_texture_image_units = 0;'
437         print '        glGetIntegerv(GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS, &max_combined_texture_image_units);'
438         print '        GLint max_units = std::max(std::max(max_combined_texture_image_units, max_texture_coords), 2);'
439         print '        for (GLint unit = 0; unit < max_units; ++unit) {'
440         print '            char name[32];'
441         print '            snprintf(name, sizeof name, "GL_TEXTURE%i", unit);'
442         print '            json.beginMember(name);'
443         print '            glActiveTexture(GL_TEXTURE0 + unit);'
444         print '            json.beginObject();'
445         print '            GLboolean enabled;'
446         print '            GLint binding;'
447         print
448         for target, binding in texture_targets:
449             print '            // %s' % target
450             print '            enabled = GL_FALSE;'
451             print '            glGetBooleanv(%s, &enabled);' % target
452             print '            json.beginMember("%s");' % target
453             print '            dumpBoolean(json, enabled);'
454             print '            json.endMember();'
455             print '            binding = 0;'
456             print '            glGetIntegerv(%s, &binding);' % binding
457             print '            json.writeIntMember("%s", binding);' % binding
458             print '            if (enabled || binding) {'
459             print '                json.beginMember("%s");' % target
460             print '                json.beginObject();'
461             self.dump_atoms(glGetTexParameter, target)
462             print '                if (!context.ES) {'
463             if target.startswith('GL_TEXTURE_CUBE_MAP'):
464                 # Must pick a face
465                 levelTarget = 'GL_TEXTURE_CUBE_MAP_POSITIVE_X'
466             else:
467                 levelTarget = target
468             # We only dump the first level parameters
469             self.dump_atoms(glGetTexLevelParameter, levelTarget, "0")
470             print '                }'
471             print '                json.endObject();'
472             print '                json.endMember(); // %s' % target
473             print '            }'
474             print
475         print '            if (unit < max_texture_coords) {'
476         self.dump_texenv_params()
477         print '            }'
478         print '            json.endObject();'
479         print '            json.endMember(); // GL_TEXTUREi'
480         print '        }'
481         print '        glActiveTexture(active_texture);'
482         print '    }'
483         print
484
485     def dump_framebuffer_parameters(self):
486         print '    {'
487         print '        GLint max_color_attachments = 0;'
488         print '        glGetIntegerv(GL_MAX_COLOR_ATTACHMENTS, &max_color_attachments);'
489         print '        GLint framebuffer;'
490         for target, binding in framebuffer_targets:
491             print '            // %s' % target
492             print '            framebuffer = 0;'
493             print '            glGetIntegerv(%s, &framebuffer);' % binding
494             print '            if (framebuffer) {'
495             print '                json.beginMember("%s");' % target
496             print '                json.beginObject();'
497             print '                for (GLint i = 0; i < max_color_attachments; ++i) {'
498             print '                    GLint color_attachment = GL_COLOR_ATTACHMENT0 + i;'
499             print '                    dumpFramebufferAttachementParameters(json, %s, color_attachment);' % target
500             print '                }'
501             print '                dumpFramebufferAttachementParameters(json, %s, GL_DEPTH_ATTACHMENT);' % target
502             print '                dumpFramebufferAttachementParameters(json, %s, GL_STENCIL_ATTACHMENT);' % target
503             print '                json.endObject();'
504             print '                json.endMember(); // %s' % target
505             print '            }'
506             print
507         print '    }'
508         print
509
510     def dump_attachment_parameters(self, target, attachment):
511         print '            {'
512         print '                GLint object_type = GL_NONE;'
513         print '                glGetFramebufferAttachmentParameteriv(%s, %s, GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE, &object_type);' % (target, attachment)
514         print '                if (object_type != GL_NONE) {'
515         print '                    json.beginMember(enumToString(%s));' % attachment
516         print '                    json.beginObject();'
517         self.dump_atoms(glGetFramebufferAttachmentParameter, target, attachment)
518         print '                    json.endObject();'
519         print '                    json.endMember(); // GL_x_ATTACHMENT'
520         print '                }'
521         print '            }'
522
523     def dump_atoms(self, getter, *args):
524         for _, _, name in getter.iter():
525             self.dump_atom(getter, *(args + (name,))) 
526
527     def dump_atom(self, getter, *args):
528         name = args[-1]
529
530         # Avoid crash on MacOSX
531         # XXX: The right fix would be to look at the support extensions..
532         import platform
533         if name == 'GL_SAMPLER_BINDING' and platform.system() == 'Darwin':
534             return
535
536         print '        // %s' % name
537         print '        {'
538         print '            while (glGetError() != GL_NO_ERROR) {}'
539         type, value = getter(*args)
540         print '            if (glGetError() != GL_NO_ERROR) {'
541         #print '                std::cerr << "warning: %s(%s) failed\\n";' % (inflection, name)
542         print '                while (glGetError() != GL_NO_ERROR) {}'
543         print '            } else {'
544         print '                json.beginMember("%s");' % name
545         JsonWriter().visit(type, value)
546         print '                json.endMember();'
547         print '            }'
548         print '        }'
549         print
550
551
552 if __name__ == '__main__':
553     StateDumper().dump()