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