]> git.cworth.org Git - apitrace/blob - retrace/glstate_params.py
9e4fab0fdaed5281c5065b082ece32e4800581cc
[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 'dumpTextureTargetParameters(JSONWriter &json, Context &context, GLenum target, GLenum binding_param)'
327         print '{'
328         print '    GLboolean enabled = GL_FALSE;'
329         print '    GLint binding = 0;'
330         print '    glGetBooleanv(target, &enabled);'
331         print '    json.beginMember(enumToString(target));'
332         print '    dumpBoolean(json, enabled);'
333         print '    json.endMember();'
334         print '    glGetIntegerv(binding_param, &binding);'
335         print '    json.writeIntMember(enumToString(binding_param), binding);'
336         print '    if (enabled || binding) {'
337         print '        json.beginMember(enumToString(target));'
338         print '        json.beginObject();'
339         self.dump_atoms(glGetTexParameter, 'target')
340         print '        if (!context.ES) {'
341         print '            GLenum levelTarget;'
342         print '            if (target == GL_TEXTURE_CUBE_MAP ||'
343         print '                target == GL_TEXTURE_CUBE_MAP_ARRAY) {'
344         print '                // Must pick a face'
345         print '                levelTarget = GL_TEXTURE_CUBE_MAP_POSITIVE_X;'
346         print '            } else {'
347         print '                levelTarget = target;'
348         print '            }'
349         self.dump_atoms(glGetTexLevelParameter, 'levelTarget', '0')
350         print '        }'
351         print '        json.endObject();'
352         print '        json.endMember(); // target'
353         print '    }'
354         print '}'
355         print
356
357         print 'static void'
358         print 'dumpFramebufferAttachementParameters(JSONWriter &json, GLenum target, GLenum attachment)'
359         print '{'
360         self.dump_attachment_parameters('target', 'attachment')
361         print '}'
362         print
363
364         print 'void dumpParameters(JSONWriter &json, Context &context)'
365         print '{'
366         print '    ScopedAllocator _allocator;'
367         print '    (void)_allocator;'
368         print
369         print '    json.beginMember("parameters");'
370         print '    json.beginObject();'
371         
372         self.dump_atoms(glGet)
373         
374         self.dump_material_params()
375         self.dump_light_params()
376         self.dump_vertex_attribs()
377         self.dump_program_params()
378         self.dump_texture_parameters()
379         self.dump_framebuffer_parameters()
380
381         print '    json.endObject();'
382         print '    json.endMember(); // parameters'
383         print '}'
384         print
385         
386         print '} /*namespace glstate */'
387
388     def dump_material_params(self):
389         print '    if (!context.ES) {'
390         for face in ['GL_FRONT', 'GL_BACK']:
391             print '    json.beginMember("%s");' % face
392             print '    json.beginObject();'
393             self.dump_atoms(glGetMaterial, face)
394             print '    json.endObject();'
395         print '    }'
396         print
397
398     def dump_light_params(self):
399         print '    GLint max_lights = 0;'
400         print '    _glGetIntegerv(GL_MAX_LIGHTS, &max_lights);'
401         print '    for (GLint index = 0; index < max_lights; ++index) {'
402         print '        GLenum light = GL_LIGHT0 + index;'
403         print '        if (glIsEnabled(light)) {'
404         print '            char name[32];'
405         print '            snprintf(name, sizeof name, "GL_LIGHT%i", index);'
406         print '            json.beginMember(name);'
407         print '            json.beginObject();'
408         self.dump_atoms(glGetLight, '    GL_LIGHT0 + index')
409         print '            json.endObject();'
410         print '            json.endMember(); // GL_LIGHTi'
411         print '        }'
412         print '    }'
413         print
414
415     def texenv_param_target(self, name):
416         if name == 'GL_TEXTURE_LOD_BIAS':
417            return 'GL_TEXTURE_FILTER_CONTROL'
418         elif name == 'GL_COORD_REPLACE':
419            return 'GL_POINT_SPRITE'
420         else:
421            return 'GL_TEXTURE_ENV'
422
423     def dump_texenv_params(self):
424         for target in ['GL_TEXTURE_ENV', 'GL_TEXTURE_FILTER_CONTROL', 'GL_POINT_SPRITE']:
425             print '    if (!context.ES) {'
426             print '        json.beginMember("%s");' % target
427             print '        json.beginObject();'
428             for _, _, name in glGetTexEnv.iter():
429                 if self.texenv_param_target(name) == target:
430                     self.dump_atom(glGetTexEnv, target, name) 
431             print '        json.endObject();'
432             print '    }'
433
434     def dump_vertex_attribs(self):
435         print '    GLint max_vertex_attribs = 0;'
436         print '    _glGetIntegerv(GL_MAX_VERTEX_ATTRIBS, &max_vertex_attribs);'
437         print '    for (GLint index = 0; index < max_vertex_attribs; ++index) {'
438         print '        char name[32];'
439         print '        snprintf(name, sizeof name, "GL_VERTEX_ATTRIB_ARRAY%i", index);'
440         print '        json.beginMember(name);'
441         print '        json.beginObject();'
442         self.dump_atoms(glGetVertexAttrib, 'index')
443         print '        json.endObject();'
444         print '        json.endMember(); // GL_VERTEX_ATTRIB_ARRAYi'
445         print '    }'
446         print
447
448     program_targets = [
449         'GL_FRAGMENT_PROGRAM_ARB',
450         'GL_VERTEX_PROGRAM_ARB',
451     ]
452
453     def dump_program_params(self):
454         for target in self.program_targets:
455             print '    if (glIsEnabled(%s)) {' % target
456             print '        json.beginMember("%s");' % target
457             print '        json.beginObject();'
458             self.dump_atoms(glGetProgramARB, target)
459             print '        json.endObject();'
460             print '    }'
461
462     def dump_texture_parameters(self):
463         print '    {'
464         print '        GLint active_texture = GL_TEXTURE0;'
465         print '        glGetIntegerv(GL_ACTIVE_TEXTURE, &active_texture);'
466         print '        GLint max_texture_coords = 0;'
467         print '        glGetIntegerv(GL_MAX_TEXTURE_COORDS, &max_texture_coords);'
468         print '        GLint max_combined_texture_image_units = 0;'
469         print '        glGetIntegerv(GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS, &max_combined_texture_image_units);'
470         print '        GLint max_units = std::max(std::max(max_combined_texture_image_units, max_texture_coords), 2);'
471         print '        for (GLint unit = 0; unit < max_units; ++unit) {'
472         print '            char name[32];'
473         print '            snprintf(name, sizeof name, "GL_TEXTURE%i", unit);'
474         print '            json.beginMember(name);'
475         print '            glActiveTexture(GL_TEXTURE0 + unit);'
476         print '            json.beginObject();'
477         print
478         for target, binding in texture_targets:
479             print '            dumpTextureTargetParameters(json, context, %s, %s);' % (target, binding)
480         print '            if (unit < max_texture_coords) {'
481         self.dump_texenv_params()
482         print '            }'
483         print '            json.endObject();'
484         print '            json.endMember(); // GL_TEXTUREi'
485         print '        }'
486         print '        glActiveTexture(active_texture);'
487         print '    }'
488         print
489
490     def dump_framebuffer_parameters(self):
491         print '    {'
492         print '        GLint max_color_attachments = 0;'
493         print '        glGetIntegerv(GL_MAX_COLOR_ATTACHMENTS, &max_color_attachments);'
494         print '        GLint framebuffer;'
495         for target, binding in framebuffer_targets:
496             print '            // %s' % target
497             print '            framebuffer = 0;'
498             print '            glGetIntegerv(%s, &framebuffer);' % binding
499             print '            if (framebuffer) {'
500             print '                json.beginMember("%s");' % target
501             print '                json.beginObject();'
502             print '                for (GLint i = 0; i < max_color_attachments; ++i) {'
503             print '                    GLint color_attachment = GL_COLOR_ATTACHMENT0 + i;'
504             print '                    dumpFramebufferAttachementParameters(json, %s, color_attachment);' % target
505             print '                }'
506             print '                dumpFramebufferAttachementParameters(json, %s, GL_DEPTH_ATTACHMENT);' % target
507             print '                dumpFramebufferAttachementParameters(json, %s, GL_STENCIL_ATTACHMENT);' % target
508             print '                json.endObject();'
509             print '                json.endMember(); // %s' % target
510             print '            }'
511             print
512         print '    }'
513         print
514
515     def dump_attachment_parameters(self, target, attachment):
516         print '            {'
517         print '                GLint object_type = GL_NONE;'
518         print '                glGetFramebufferAttachmentParameteriv(%s, %s, GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE, &object_type);' % (target, attachment)
519         print '                if (object_type != GL_NONE) {'
520         print '                    json.beginMember(enumToString(%s));' % attachment
521         print '                    json.beginObject();'
522         self.dump_atoms(glGetFramebufferAttachmentParameter, target, attachment)
523         print '                    json.endObject();'
524         print '                    json.endMember(); // GL_x_ATTACHMENT'
525         print '                }'
526         print '            }'
527
528     def dump_atoms(self, getter, *args):
529         for _, _, name in getter.iter():
530             self.dump_atom(getter, *(args + (name,))) 
531
532     def dump_atom(self, getter, *args):
533         name = args[-1]
534
535         # Avoid crash on MacOSX
536         # XXX: The right fix would be to look at the support extensions..
537         import platform
538         if name == 'GL_SAMPLER_BINDING' and platform.system() == 'Darwin':
539             return
540
541         print '        // %s' % name
542         print '        {'
543         print '            while (glGetError() != GL_NO_ERROR) {}'
544         type, value = getter(*args)
545         print '            if (glGetError() != GL_NO_ERROR) {'
546         #print '                std::cerr << "warning: %s(%s) failed\\n";' % (inflection, name)
547         print '                while (glGetError() != GL_NO_ERROR) {}'
548         print '            } else {'
549         print '                json.beginMember("%s");' % name
550         JsonWriter().visit(type, value)
551         print '                json.endMember();'
552         print '            }'
553         print '        }'
554         print
555
556
557 if __name__ == '__main__':
558     StateDumper().dump()