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 import retrace # to adjust sys.path
32 from specs.stdapi import *
34 from specs.gltypes import *
35 from specs.glparams import *
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'),
51 framebuffer_targets = [
52 ('GL_DRAW_FRAMEBUFFER', 'GL_DRAW_FRAMEBUFFER_BINDING'),
53 ('GL_READ_FRAMEBUFFER', 'GL_READ_FRAMEBUFFER_BINDING'),
57 '''Objects that describes how to inflect.'''
65 def __init__(self, radical, inflections, suffix = ''):
66 self.radical = radical
67 self.inflections = inflections
70 def reduced_type(self, type):
71 if type in self.inflections:
73 if type in self.reduced_types:
74 return self.reduced_type(self.reduced_types[type])
75 raise NotImplementedError
77 def inflect(self, type):
78 return self.radical + self.inflection(type) + self.suffix
80 def inflection(self, type):
81 type = self.reduced_type(type)
82 assert type in self.inflections
83 return self.inflections[type]
86 return self.radical + self.suffix
89 class StateGetter(Visitor):
90 '''Type visitor that is able to extract the state via one of the glGet*
93 It will declare any temporary variable
96 def __init__(self, radical, inflections, suffix=''):
97 self.inflector = GetInflector(radical, inflections)
101 for function, type, count, name in parameters:
102 inflection = self.inflector.radical + self.suffix
103 if inflection not in function.split(','):
107 yield type, count, name
109 def __call__(self, *args):
112 for type, count, name in self.iter():
115 type = Array(type, str(count))
117 return type, self.visit(type, args)
119 raise NotImplementedError
121 def temp_name(self, args):
122 '''Return the name of a temporary variable to hold the state.'''
125 return pname[3:].lower()
127 def visitConst(self, const, args):
128 return self.visit(const.type, args)
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)
138 print ' %s %s = %s(%s);' % (elem_type, temp_name, inflection + self.suffix, ', '.join(args))
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))
148 def visitAlias(self, alias, args):
149 return self.visitScalar(alias, args)
151 def visitEnum(self, enum, args):
152 return self.visitScalar(enum, args)
154 def visitBitmask(self, bitmask, args):
155 return self.visit(GLint, args)
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)
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)
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)
190 glGet = StateGetter('glGet', {
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'})
211 class JsonWriter(Visitor):
212 '''Type visitor that will dump a value of the specified type through the
215 It expects a previously declared JSONWriter instance named "json".'''
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
225 raise NotImplementedError
227 def visitString(self, string, instance):
228 assert string.length is None
229 print ' json.writeString((const char *)%s);' % instance
231 def visitEnum(self, enum, instance):
232 if enum is GLboolean:
233 print ' dumpBoolean(json, %s);' % instance
235 print ' dumpEnum(json, %s);' % instance
238 print ' json.writeInt(%s);' % instance
240 def visitBitmask(self, bitmask, instance):
241 raise NotImplementedError
243 def visitAlias(self, alias, instance):
244 self.visit(alias.type, instance)
246 def visitOpaque(self, opaque, instance):
247 print ' json.writeInt((size_t)%s);' % instance
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))
258 print ' json.endArray();'
263 '''Class to generate code to dump all GL state in JSON format via
270 print '#include <assert.h>'
271 print '#include <string.h>'
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"'
280 print 'namespace glstate {'
284 print 'dumpBoolean(JSONWriter &json, GLboolean value)'
286 print ' switch (value) {'
287 print ' case GL_FALSE:'
288 print ' json.writeString("GL_FALSE");'
290 print ' case GL_TRUE:'
291 print ' json.writeString("GL_TRUE");'
294 print ' json.writeInt(static_cast<GLint>(value));'
301 print 'enumToString(GLenum pname)'
303 print ' switch (pname) {'
304 for name in GLenum.values:
305 print ' case %s:' % name
306 print ' return "%s";' % name
308 print ' return NULL;'
314 print 'dumpEnum(JSONWriter &json, GLenum pname)'
316 print ' const char *s = enumToString(pname);'
318 print ' json.writeString(s);'
320 print ' json.writeInt(pname);'
326 print 'dumpTextureTargetParameters(JSONWriter &json, Context &context, GLenum target, GLenum binding_param)'
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;'
347 print ' levelTarget = target;'
349 self.dump_atoms(glGetTexLevelParameter, 'levelTarget', '0')
351 print ' json.endObject();'
352 print ' json.endMember(); // target'
358 print 'dumpFramebufferAttachementParameters(JSONWriter &json, GLenum target, GLenum attachment)'
360 self.dump_attachment_parameters('target', 'attachment')
364 print 'void dumpParameters(JSONWriter &json, Context &context)'
366 print ' ScopedAllocator _allocator;'
367 print ' (void)_allocator;'
369 print ' json.beginMember("parameters");'
370 print ' json.beginObject();'
372 self.dump_atoms(glGet)
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()
381 print ' json.endObject();'
382 print ' json.endMember(); // parameters'
386 print '} /*namespace glstate */'
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();'
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'
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'
421 return 'GL_TEXTURE_ENV'
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();'
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'
449 'GL_FRAGMENT_PROGRAM_ARB',
450 'GL_VERTEX_PROGRAM_ARB',
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();'
462 def dump_texture_parameters(self):
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();'
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()
483 print ' json.endObject();'
484 print ' json.endMember(); // GL_TEXTUREi'
486 print ' glActiveTexture(active_texture);'
490 def dump_framebuffer_parameters(self):
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
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
515 def dump_attachment_parameters(self, target, attachment):
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'
528 def dump_atoms(self, getter, *args):
529 for _, _, name in getter.iter():
530 self.dump_atom(getter, *(args + (name,)))
532 def dump_atom(self, getter, *args):
535 # Avoid crash on MacOSX
536 # XXX: The right fix would be to look at the support extensions..
538 if name == 'GL_SAMPLER_BINDING' and platform.system() == 'Darwin':
541 print ' // %s' % name
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) {}'
549 print ' json.beginMember("%s");' % name
550 JsonWriter().visit(type, value)
551 print ' json.endMember();'
557 if __name__ == '__main__':