1 ##########################################################################
3 # Copyright 2011 Jose Fonseca
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:
13 # The above copyright notice and this permission notice shall be included in
14 # all copies or substantial portions of the Software.
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
24 ##########################################################################/
27 '''Generate code to dump most GL state into JSON.'''
30 from specs.stdapi import *
32 from specs.gltypes import *
33 from specs.glparams import *
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')
44 framebuffer_targets = [
45 ('GL_DRAW_FRAMEBUFFER', 'GL_DRAW_FRAMEBUFFER_BINDING'),
46 ('GL_READ_FRAMEBUFFER', 'GL_READ_FRAMEBUFFER_BINDING'),
50 '''Objects that describes how to inflect.'''
58 def __init__(self, radical, inflections, suffix = ''):
59 self.radical = radical
60 self.inflections = inflections
63 def reduced_type(self, type):
64 if type in self.inflections:
66 if type in self.reduced_types:
67 return self.reduced_type(self.reduced_types[type])
68 raise NotImplementedError
70 def inflect(self, type):
71 return self.radical + self.inflection(type) + self.suffix
73 def inflection(self, type):
74 type = self.reduced_type(type)
75 assert type in self.inflections
76 return self.inflections[type]
79 return self.radical + self.suffix
82 class StateGetter(Visitor):
83 '''Type visitor that is able to extract the state via one of the glGet*
86 It will declare any temporary variable
89 def __init__(self, radical, inflections, suffix=''):
90 self.inflector = GetInflector(radical, inflections)
94 for function, type, count, name in parameters:
95 inflection = self.inflector.radical + self.suffix
96 if inflection not in function.split(','):
100 yield type, count, name
102 def __call__(self, *args):
105 for type, count, name in self.iter():
108 type = Array(type, str(count))
110 return type, self.visit(type, args)
112 raise NotImplementedError
114 def temp_name(self, args):
115 '''Return the name of a temporary variable to hold the state.'''
118 return pname[3:].lower()
120 def visitConst(self, const, args):
121 return self.visit(const.type, args)
123 def visitScalar(self, type, args):
124 temp_name = self.temp_name(args)
125 elem_type = self.inflector.reduced_type(type)
126 inflection = self.inflector.inflect(type)
127 if inflection.endswith('v'):
128 print ' %s %s = 0;' % (elem_type, temp_name)
129 print ' %s(%s, &%s);' % (inflection + self.suffix, ', '.join(args), temp_name)
131 print ' %s %s = %s(%s);' % (elem_type, temp_name, inflection + self.suffix, ', '.join(args))
134 def visitString(self, string, args):
135 temp_name = self.temp_name(args)
136 inflection = self.inflector.inflect(string)
137 assert not inflection.endswith('v')
138 print ' %s %s = (%s)%s(%s);' % (string, temp_name, string, inflection + self.suffix, ', '.join(args))
141 def visitAlias(self, alias, args):
142 return self.visitScalar(alias, args)
144 def visitEnum(self, enum, args):
145 return self.visit(GLint, args)
147 def visitBitmask(self, bitmask, args):
148 return self.visit(GLint, args)
150 def visitArray(self, array, args):
151 temp_name = self.temp_name(args)
152 if array.length == '1':
153 return self.visit(array.type)
154 elem_type = self.inflector.reduced_type(array.type)
155 inflection = self.inflector.inflect(array.type)
156 assert inflection.endswith('v')
157 print ' %s %s[%s + 1];' % (elem_type, temp_name, array.length)
158 print ' memset(%s, 0, %s * sizeof *%s);' % (temp_name, array.length, temp_name)
159 print ' %s[%s] = (%s)0xdeadc0de;' % (temp_name, array.length, elem_type)
160 print ' %s(%s, %s);' % (inflection + self.suffix, ', '.join(args), temp_name)
161 # Simple buffer overflow detection
162 print ' assert(%s[%s] == (%s)0xdeadc0de);' % (temp_name, array.length, elem_type)
165 def visitOpaque(self, pointer, args):
166 temp_name = self.temp_name(args)
167 inflection = self.inflector.inflect(pointer)
168 assert inflection.endswith('v')
169 print ' GLvoid *%s;' % temp_name
170 print ' %s(%s, &%s);' % (inflection + self.suffix, ', '.join(args), temp_name)
174 glGet = StateGetter('glGet', {
183 glGetMaterial = StateGetter('glGetMaterial', {I: 'iv', F: 'fv'})
184 glGetLight = StateGetter('glGetLight', {I: 'iv', F: 'fv'})
185 glGetVertexAttrib = StateGetter('glGetVertexAttrib', {I: 'iv', F: 'fv', D: 'dv', P: 'Pointerv'})
186 glGetTexParameter = StateGetter('glGetTexParameter', {I: 'iv', F: 'fv'})
187 glGetTexEnv = StateGetter('glGetTexEnv', {I: 'iv', F: 'fv'})
188 glGetTexLevelParameter = StateGetter('glGetTexLevelParameter', {I: 'iv', F: 'fv'})
189 glGetShader = StateGetter('glGetShaderiv', {I: 'iv'})
190 glGetProgram = StateGetter('glGetProgram', {I: 'iv'})
191 glGetProgramARB = StateGetter('glGetProgram', {I: 'iv', F: 'fv', S: 'Stringv'}, 'ARB')
192 glGetFramebufferAttachmentParameter = StateGetter('glGetFramebufferAttachmentParameter', {I: 'iv'})
195 class JsonWriter(Visitor):
196 '''Type visitor that will dump a value of the specified type through the
199 It expects a previously declared JSONWriter instance named "json".'''
201 def visitLiteral(self, literal, instance):
202 if literal.kind == 'Bool':
203 print ' json.writeBool(%s);' % instance
204 elif literal.kind in ('SInt', 'Uint', 'Float', 'Double'):
205 print ' json.writeNumber(%s);' % instance
207 raise NotImplementedError
209 def visitString(self, string, instance):
210 assert string.length is None
211 print ' json.writeString((const char *)%s);' % instance
213 def visitEnum(self, enum, instance):
214 if enum.expr == 'GLenum':
215 print ' dumpEnum(json, %s);' % instance
217 print ' json.writeNumber(%s);' % instance
219 def visitBitmask(self, bitmask, instance):
220 raise NotImplementedError
222 def visitAlias(self, alias, instance):
223 self.visit(alias.type, instance)
225 def visitOpaque(self, opaque, instance):
226 print ' json.writeNumber((size_t)%s);' % instance
230 def visitArray(self, array, instance):
231 index = '__i%u' % JsonWriter.__index
232 JsonWriter.__index += 1
233 print ' json.beginArray();'
234 print ' for (unsigned %s = 0; %s < %s; ++%s) {' % (index, index, array.length, index)
235 self.visit(array.type, '%s[%s]' % (instance, index))
237 print ' json.endArray();'
242 '''Class to generate code to dump all GL state in JSON format via
249 print '#include <string.h>'
251 print '#include "json.hpp"'
252 print '#include "glproc.hpp"'
253 print '#include "glsize.hpp"'
254 print '#include "glstate.hpp"'
255 print '#include "glstate_internal.hpp"'
257 print 'namespace glstate {'
261 print 'enumToString(GLenum pname)'
263 print ' switch (pname) {'
264 for name in GLenum.values:
265 print ' case %s:' % name
266 print ' return "%s";' % name
268 print ' return NULL;'
274 print 'dumpFramebufferAttachementParameters(JSONWriter &json, GLenum target, GLenum attachment)'
276 self.dump_attachment_parameters('target', 'attachment')
281 print 'dumpEnum(JSONWriter &json, GLenum pname)'
283 print ' const char *s = enumToString(pname);'
285 print ' json.writeString(s);'
287 print ' json.writeNumber(pname);'
292 print 'void dumpParameters(JSONWriter &json, Context &context)'
294 print ' json.beginMember("parameters");'
295 print ' json.beginObject();'
297 self.dump_atoms(glGet)
299 self.dump_material_params()
300 self.dump_light_params()
301 self.dump_vertex_attribs()
302 self.dump_program_params()
303 self.dump_texture_parameters()
304 self.dump_framebuffer_parameters()
306 print ' json.endObject();'
307 print ' json.endMember(); // parameters'
311 print '} /*namespace glstate */'
313 def dump_material_params(self):
314 print ' if (!context.ES) {'
315 for face in ['GL_FRONT', 'GL_BACK']:
316 print ' json.beginMember("%s");' % face
317 print ' json.beginObject();'
318 self.dump_atoms(glGetMaterial, face)
319 print ' json.endObject();'
323 def dump_light_params(self):
324 print ' GLint max_lights = 0;'
325 print ' __glGetIntegerv(GL_MAX_LIGHTS, &max_lights);'
326 print ' for (GLint index = 0; index < max_lights; ++index) {'
327 print ' GLenum light = GL_LIGHT0 + index;'
328 print ' if (glIsEnabled(light)) {'
329 print ' char name[32];'
330 print ' snprintf(name, sizeof name, "GL_LIGHT%i", index);'
331 print ' json.beginMember(name);'
332 print ' json.beginObject();'
333 self.dump_atoms(glGetLight, ' GL_LIGHT0 + index')
334 print ' json.endObject();'
335 print ' json.endMember(); // GL_LIGHTi'
340 def texenv_param_target(self, name):
341 if name == 'GL_TEXTURE_LOD_BIAS':
342 return 'GL_TEXTURE_FILTER_CONTROL'
343 elif name == 'GL_COORD_REPLACE':
344 return 'GL_POINT_SPRITE'
346 return 'GL_TEXTURE_ENV'
348 def dump_texenv_params(self):
349 for target in ['GL_TEXTURE_ENV', 'GL_TEXTURE_FILTER_CONTROL', 'GL_POINT_SPRITE']:
350 print ' if (!context.ES) {'
351 print ' json.beginMember("%s");' % target
352 print ' json.beginObject();'
353 for _, _, name in glGetTexEnv.iter():
354 if self.texenv_param_target(name) == target:
355 self.dump_atom(glGetTexEnv, target, name)
356 print ' json.endObject();'
359 def dump_vertex_attribs(self):
360 print ' GLint max_vertex_attribs = 0;'
361 print ' __glGetIntegerv(GL_MAX_VERTEX_ATTRIBS, &max_vertex_attribs);'
362 print ' for (GLint index = 0; index < max_vertex_attribs; ++index) {'
363 print ' char name[32];'
364 print ' snprintf(name, sizeof name, "GL_VERTEX_ATTRIB_ARRAY%i", index);'
365 print ' json.beginMember(name);'
366 print ' json.beginObject();'
367 self.dump_atoms(glGetVertexAttrib, 'index')
368 print ' json.endObject();'
369 print ' json.endMember(); // GL_VERTEX_ATTRIB_ARRAYi'
374 'GL_FRAGMENT_PROGRAM_ARB',
375 'GL_VERTEX_PROGRAM_ARB',
378 def dump_program_params(self):
379 for target in self.program_targets:
380 print ' if (glIsEnabled(%s)) {' % target
381 print ' json.beginMember("%s");' % target
382 print ' json.beginObject();'
383 self.dump_atoms(glGetProgramARB, target)
384 print ' json.endObject();'
387 def dump_texture_parameters(self):
389 print ' GLint active_texture = GL_TEXTURE0;'
390 print ' glGetIntegerv(GL_ACTIVE_TEXTURE, &active_texture);'
391 print ' GLint max_texture_coords = 0;'
392 print ' glGetIntegerv(GL_MAX_TEXTURE_COORDS, &max_texture_coords);'
393 print ' GLint max_combined_texture_image_units = 0;'
394 print ' glGetIntegerv(GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS, &max_combined_texture_image_units);'
395 print ' GLint max_units = std::max(max_combined_texture_image_units, max_texture_coords);'
396 print ' for (GLint unit = 0; unit < max_units; ++unit) {'
397 print ' char name[32];'
398 print ' snprintf(name, sizeof name, "GL_TEXTURE%i", unit);'
399 print ' json.beginMember(name);'
400 print ' glActiveTexture(GL_TEXTURE0 + unit);'
401 print ' json.beginObject();'
402 print ' GLboolean enabled;'
403 print ' GLint binding;'
405 for target, binding in texture_targets:
406 print ' // %s' % target
407 print ' enabled = GL_FALSE;'
408 print ' glGetBooleanv(%s, &enabled);' % target
409 print ' json.writeBoolMember("%s", enabled);' % target
410 print ' binding = 0;'
411 print ' glGetIntegerv(%s, &binding);' % binding
412 print ' json.writeNumberMember("%s", binding);' % binding
413 print ' if (enabled || binding) {'
414 print ' json.beginMember("%s");' % target
415 print ' json.beginObject();'
416 self.dump_atoms(glGetTexParameter, target)
417 print ' if (!context.ES) {'
418 # We only dump the first level parameters
419 self.dump_atoms(glGetTexLevelParameter, target, "0")
421 print ' json.endObject();'
422 print ' json.endMember(); // %s' % target
425 print ' if (unit < max_texture_coords) {'
426 self.dump_texenv_params()
428 print ' json.endObject();'
429 print ' json.endMember(); // GL_TEXTUREi'
431 print ' glActiveTexture(active_texture);'
435 def dump_framebuffer_parameters(self):
437 print ' GLint max_color_attachments = 0;'
438 print ' glGetIntegerv(GL_MAX_COLOR_ATTACHMENTS, &max_color_attachments);'
439 print ' GLint framebuffer;'
440 for target, binding in framebuffer_targets:
441 print ' // %s' % target
442 print ' framebuffer = 0;'
443 print ' glGetIntegerv(%s, &framebuffer);' % binding
444 print ' if (framebuffer) {'
445 print ' json.beginMember("%s");' % target
446 print ' json.beginObject();'
447 print ' for (GLint i = 0; i < max_color_attachments; ++i) {'
448 print ' GLint color_attachment = GL_COLOR_ATTACHMENT0 + i;'
449 print ' dumpFramebufferAttachementParameters(json, %s, color_attachment);' % target
451 print ' dumpFramebufferAttachementParameters(json, %s, GL_DEPTH_ATTACHMENT);' % target
452 print ' dumpFramebufferAttachementParameters(json, %s, GL_STENCIL_ATTACHMENT);' % target
453 print ' json.endObject();'
454 print ' json.endMember(); // %s' % target
460 def dump_attachment_parameters(self, target, attachment):
462 print ' GLint object_type = GL_NONE;'
463 print ' glGetFramebufferAttachmentParameteriv(%s, %s, GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE, &object_type);' % (target, attachment)
464 print ' if (object_type != GL_NONE) {'
465 print ' json.beginMember(enumToString(%s));' % attachment
466 print ' json.beginObject();'
467 self.dump_atoms(glGetFramebufferAttachmentParameter, target, attachment)
468 print ' json.endObject();'
469 print ' json.endMember(); // GL_x_ATTACHMENT'
473 def dump_atoms(self, getter, *args):
474 for _, _, name in getter.iter():
475 self.dump_atom(getter, *(args + (name,)))
477 def dump_atom(self, getter, *args):
480 # Avoid crash on MacOSX
481 # XXX: The right fix would be to look at the support extensions..
483 if name == 'GL_SAMPLER_BINDING' and platform.system() == 'Darwin':
486 print ' // %s' % name
488 #print ' assert(glGetError() == GL_NO_ERROR);'
489 type, value = getter(*args)
490 print ' if (glGetError() != GL_NO_ERROR) {'
491 #print ' std::cerr << "warning: %s(%s) failed\\n";' % (inflection, name)
492 print ' while (glGetError() != GL_NO_ERROR) {}'
494 print ' json.beginMember("%s");' % name
495 JsonWriter().visit(type, value)
496 print ' json.endMember();'
502 if __name__ == '__main__':