]> git.cworth.org Git - apitrace/blob - retrace/glretrace.py
Merge remote-tracking branch 'github/master' into profile-gui
[apitrace] / retrace / glretrace.py
1 ##########################################################################
2 #
3 # Copyright 2010 VMware, Inc.
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 """GL retracer generator."""
28
29
30 from retrace import Retracer
31 import specs.stdapi as stdapi
32 import specs.glapi as glapi
33 import specs.glesapi as glesapi
34
35
36 class GlRetracer(Retracer):
37
38     table_name = 'glretrace::gl_callbacks'
39
40     def retraceFunction(self, function):
41         Retracer.retraceFunction(self, function)
42
43     array_pointer_function_names = set((
44         "glVertexPointer",
45         "glNormalPointer",
46         "glColorPointer",
47         "glIndexPointer",
48         "glTexCoordPointer",
49         "glEdgeFlagPointer",
50         "glFogCoordPointer",
51         "glSecondaryColorPointer",
52
53         "glInterleavedArrays",
54
55         "glVertexPointerEXT",
56         "glNormalPointerEXT",
57         "glColorPointerEXT",
58         "glIndexPointerEXT",
59         "glTexCoordPointerEXT",
60         "glEdgeFlagPointerEXT",
61         "glFogCoordPointerEXT",
62         "glSecondaryColorPointerEXT",
63
64         "glVertexAttribPointer",
65         "glVertexAttribPointerARB",
66         "glVertexAttribPointerNV",
67         "glVertexAttribIPointer",
68         "glVertexAttribIPointerEXT",
69         "glVertexAttribLPointer",
70         "glVertexAttribLPointerEXT",
71         
72         #"glMatrixIndexPointerARB",
73     ))
74
75     draw_array_function_names = set([
76         "glDrawArrays",
77         "glDrawArraysEXT",
78         "glDrawArraysIndirect",
79         "glDrawArraysInstanced",
80         "glDrawArraysInstancedARB",
81         "glDrawArraysInstancedEXT",
82         "glDrawArraysInstancedBaseInstance",
83         "glDrawMeshArraysSUN",
84         "glMultiDrawArrays",
85         "glMultiDrawArraysEXT",
86         "glMultiModeDrawArraysIBM",
87     ])
88
89     draw_elements_function_names = set([
90         "glDrawElements",
91         "glDrawElementsBaseVertex",
92         "glDrawElementsIndirect",
93         "glDrawElementsInstanced",
94         "glDrawElementsInstancedARB",
95         "glDrawElementsInstancedEXT",
96         "glDrawElementsInstancedBaseVertex",
97         "glDrawElementsInstancedBaseInstance",
98         "glDrawElementsInstancedBaseVertexBaseInstance",
99         "glDrawRangeElements",
100         "glDrawRangeElementsEXT",
101         "glDrawRangeElementsBaseVertex",
102         "glMultiDrawElements",
103         "glMultiDrawElementsBaseVertex",
104         "glMultiDrawElementsEXT",
105         "glMultiModeDrawElementsIBM",
106     ])
107
108     draw_indirect_function_names = set([
109         "glDrawArraysIndirect",
110         "glDrawElementsIndirect",
111     ])
112
113     misc_draw_function_names = set([
114         "glCallList",
115         "glCallLists",
116         "glClear",
117         "glEnd",
118         "glDrawPixels",
119         "glBlitFramebuffer",
120         "glBlitFramebufferEXT",
121     ])
122
123     bind_framebuffer_function_names = set([
124         "glBindFramebuffer",
125         "glBindFramebufferEXT",
126         "glBindFramebufferOES",
127     ])
128
129     # Names of the functions that can pack into the current pixel buffer
130     # object.  See also the ARB_pixel_buffer_object specification.
131     pack_function_names = set([
132         'glGetCompressedTexImage',
133         'glGetConvolutionFilter',
134         'glGetHistogram',
135         'glGetMinmax',
136         'glGetPixelMapfv',
137         'glGetPixelMapuiv',
138         'glGetPixelMapusv',
139         'glGetPolygonStipple',
140         'glGetSeparableFilter',
141         'glGetTexImage',
142         'glReadPixels',
143         'glGetnCompressedTexImageARB',
144         'glGetnConvolutionFilterARB',
145         'glGetnHistogramARB',
146         'glGetnMinmaxARB',
147         'glGetnPixelMapfvARB',
148         'glGetnPixelMapuivARB',
149         'glGetnPixelMapusvARB',
150         'glGetnPolygonStippleARB',
151         'glGetnSeparableFilterARB',
152         'glGetnTexImageARB',
153         'glReadnPixelsARB',
154     ])
155
156     map_function_names = set([
157         'glMapBuffer',
158         'glMapBufferARB',
159         'glMapBufferOES',
160         'glMapBufferRange',
161         'glMapNamedBufferEXT',
162         'glMapNamedBufferRangeEXT',
163         'glMapObjectBufferATI',
164     ])
165
166     unmap_function_names = set([
167         'glUnmapBuffer',
168         'glUnmapBufferARB',
169         'glUnmapBufferOES',
170         'glUnmapNamedBufferEXT',
171         'glUnmapObjectBufferATI',
172     ])
173
174     def retraceFunctionBody(self, function):
175         is_array_pointer = function.name in self.array_pointer_function_names
176         is_draw_array = function.name in self.draw_array_function_names
177         is_draw_elements = function.name in self.draw_elements_function_names
178         is_misc_draw = function.name in self.misc_draw_function_names
179
180         if is_array_pointer or is_draw_array or is_draw_elements:
181             print '    if (retrace::parser.version < 1) {'
182
183             if is_array_pointer or is_draw_array:
184                 print '        GLint _array_buffer = 0;'
185                 print '        glGetIntegerv(GL_ARRAY_BUFFER_BINDING, &_array_buffer);'
186                 print '        if (!_array_buffer) {'
187                 self.failFunction(function)
188                 print '        }'
189
190             if is_draw_elements:
191                 print '        GLint _element_array_buffer = 0;'
192                 print '        glGetIntegerv(GL_ELEMENT_ARRAY_BUFFER_BINDING, &_element_array_buffer);'
193                 print '        if (!_element_array_buffer) {'
194                 self.failFunction(function)
195                 print '        }'
196             
197             print '    }'
198
199         # When no pack buffer object is bound, the pack functions are no-ops.
200         if function.name in self.pack_function_names:
201             print '    GLint _pack_buffer = 0;'
202             print '    glGetIntegerv(GL_PIXEL_PACK_BUFFER_BINDING, &_pack_buffer);'
203             print '    if (!_pack_buffer) {'
204             print '        return;'
205             print '    }'
206
207         # Pre-snapshots
208         if function.name in self.bind_framebuffer_function_names:
209             print '    assert(call.flags & trace::CALL_FLAG_SWAP_RENDERTARGET);'
210         if function.name == 'glFrameTerminatorGREMEDY':
211             print '    glretrace::frame_complete(call);'
212             return
213
214         Retracer.retraceFunctionBody(self, function)
215
216         # Post-snapshots
217         if function.name in ('glFlush', 'glFinish'):
218             print '    if (!retrace::doubleBuffer) {'
219             print '        glretrace::frame_complete(call);'
220             print '    }'
221         if is_draw_array or is_draw_elements or is_misc_draw:
222             print '    assert(call.flags & trace::CALL_FLAG_RENDER);'
223
224
225     def invokeFunction(self, function):
226         # Infer the drawable size from GL calls
227         if function.name == "glViewport":
228             print '    glretrace::updateDrawable(x + width, y + height);'
229         if function.name == "glViewportArray":
230             # We are concerned about drawables so only care for the first viewport
231             print '    if (first == 0 && count > 0) {'
232             print '        GLfloat x = v[0], y = v[1], w = v[2], h = v[3];'
233             print '        glretrace::updateDrawable(x + w, y + h);'
234             print '    }'
235         if function.name == "glViewportIndexedf":
236             print '    if (index == 0) {'
237             print '        glretrace::updateDrawable(x + w, y + h);'
238             print '    }'
239         if function.name == "glViewportIndexedfv":
240             print '    if (index == 0) {'
241             print '        GLfloat x = v[0], y = v[1], w = v[2], h = v[3];'
242             print '        glretrace::updateDrawable(x + w, y + h);'
243             print '    }'
244         if function.name in ('glBlitFramebuffer', 'glBlitFramebufferEXT'):
245             # Some applications do all their rendering in a framebuffer, and
246             # then just blit to the drawable without ever calling glViewport.
247             print '    glretrace::updateDrawable(std::max(dstX0, dstX1), std::max(dstY0, dstY1));'
248
249         if function.name == "glEnd":
250             print '    glretrace::insideGlBeginEnd = false;'
251
252         if function.name.startswith('gl') and not function.name.startswith('glX'):
253             print r'    if (retrace::debug && !glretrace::currentContext) {'
254             print r'        retrace::warning(call) << "no current context\n";'
255             print r'    }'
256
257         if function.name == 'memcpy':
258             print '    if (!dest || !src || !n) return;'
259
260         # Skip glEnable/Disable(GL_DEBUG_OUTPUT_SYNCHRONOUS_ARB) as we don't
261         # faithfully set the CONTEXT_DEBUG_BIT_ARB flags on context creation.
262         if function.name in ('glEnable', 'glDisable'):
263             print '    if (cap == GL_DEBUG_OUTPUT_SYNCHRONOUS_ARB) return;'
264
265         # Destroy the buffer mapping
266         if function.name in self.unmap_function_names:
267             print r'        GLvoid *ptr = NULL;'
268             if function.name == 'glUnmapBuffer':
269                 print r'            glGetBufferPointerv(target, GL_BUFFER_MAP_POINTER, &ptr);'
270             elif function.name == 'glUnmapBufferARB':
271                 print r'            glGetBufferPointervARB(target, GL_BUFFER_MAP_POINTER_ARB, &ptr);'
272             elif function.name == 'glUnmapBufferOES':
273                 print r'            glGetBufferPointervOES(target, GL_BUFFER_MAP_POINTER_OES, &ptr);'
274             elif function.name == 'glUnmapNamedBufferEXT':
275                 print r'            glGetNamedBufferPointervEXT(buffer, GL_BUFFER_MAP_POINTER, &ptr);'
276             elif function.name == 'glUnmapObjectBufferATI':
277                 # TODO
278                 pass
279             else:
280                 assert False
281             print r'        if (ptr) {'
282             print r'            retrace::delRegionByPointer(ptr);'
283             print r'        } else {'
284             print r'            retrace::warning(call) << "no current context\n";'
285             print r'        }'
286
287         if function.name in ('glBindProgramPipeline', 'glBindProgramPipelineEXT'):
288             # Note if glBindProgramPipeline has ever been called
289             print r'    if (pipeline) {'
290             print r'        _pipelineHasBeenBound = true;'
291             print r'    }'
292
293         profileDraw = (
294             function.name in self.draw_array_function_names or
295             function.name in self.draw_elements_function_names or
296             function.name in self.draw_indirect_function_names or
297             function.name in self.misc_draw_function_names or
298             function.name == 'glBegin'
299         )
300
301         if function.name in ('glUseProgram', 'glUseProgramObjectARB'):
302             print r'    if (glretrace::currentContext) {'
303             print r'        glretrace::currentContext->activeProgram = call.arg(0).toUInt();'
304             print r'    }'
305
306         # Only profile if not inside a list as the queries get inserted into list
307         if function.name == 'glNewList':
308             print r'    glretrace::insideList = true;'
309
310         if function.name == 'glEndList':
311             print r'    glretrace::insideList = false;'
312
313         if profileDraw and function.name != 'glEnd':
314             print r'    if (!glretrace::insideList && !glretrace::insideGlBeginEnd && retrace::profiling) {'
315             print r'        glretrace::beginProfile(call);'
316             print r'    }'
317
318         if function.name == 'glCreateShaderProgramv':
319             # When dumping state, break down glCreateShaderProgramv so that the
320             # shader source can be recovered.
321             print r'    if (retrace::dumpingState) {'
322             print r'        GLuint _shader = glCreateShader(type);'
323             print r'        if (_shader) {'
324             print r'            glShaderSource(_shader, count, strings, NULL);'
325             print r'            glCompileShader(_shader);'
326             print r'            const GLuint _program = glCreateProgram();'
327             print r'            if (_program) {'
328             print r'                GLint compiled = GL_FALSE;'
329             print r'                glGetShaderiv(_shader, GL_COMPILE_STATUS, &compiled);'
330             print r'                glProgramParameteri(_program, GL_PROGRAM_SEPARABLE, GL_TRUE);'
331             print r'                if (compiled) {'
332             print r'                    glAttachShader(_program, _shader);'
333             print r'                    glLinkProgram(_program);'
334             print r'                    //glDetachShader(_program, _shader);'
335             print r'                }'
336             print r'                //append-shader-info-log-to-program-info-log'
337             print r'            }'
338             print r'            //glDeleteShader(_shader);'
339             print r'            _result = _program;'
340             print r'        } else {'
341             print r'            _result = 0;'
342             print r'        }'
343             print r'    } else {'
344             Retracer.invokeFunction(self, function)
345             print r'    }'
346         else:
347             Retracer.invokeFunction(self, function)
348
349         if function.name == "glBegin":
350             print '    glretrace::insideGlBeginEnd = true;'
351
352         if profileDraw or function.name == 'glEnd':
353             print r'    if (!glretrace::insideList && !glretrace::insideGlBeginEnd && retrace::profiling) {'
354             print r'        glretrace::endProfile(call);'
355             print r'    }'
356
357         # Error checking
358         if function.name.startswith('gl'):
359             # glGetError is not allowed inside glBegin/glEnd
360             print '    if (retrace::debug && !glretrace::insideGlBeginEnd) {'
361             print '        glretrace::checkGlError(call);'
362             if function.name in ('glProgramStringARB', 'glProgramStringNV'):
363                 print r'        GLint error_position = -1;'
364                 print r'        glGetIntegerv(GL_PROGRAM_ERROR_POSITION_ARB, &error_position);'
365                 print r'        if (error_position != -1) {'
366                 print r'            const char *error_string = (const char *)glGetString(GL_PROGRAM_ERROR_STRING_ARB);'
367                 print r'            retrace::warning(call) << error_string << "\n";'
368                 print r'        }'
369             if function.name == 'glCompileShader':
370                 print r'        GLint compile_status = 0;'
371                 print r'        glGetShaderiv(shader, GL_COMPILE_STATUS, &compile_status);'
372                 print r'        if (!compile_status) {'
373                 print r'             GLint info_log_length = 0;'
374                 print r'             glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &info_log_length);'
375                 print r'             GLchar *infoLog = new GLchar[info_log_length];'
376                 print r'             glGetShaderInfoLog(shader, info_log_length, NULL, infoLog);'
377                 print r'             retrace::warning(call) << infoLog << "\n";'
378                 print r'             delete [] infoLog;'
379                 print r'        }'
380             if function.name in ('glLinkProgram', 'glCreateShaderProgramv', 'glCreateShaderProgramEXT'):
381                 if function.name != 'glLinkProgram':
382                     print r'        GLuint program = _result;'
383                 print r'        GLint link_status = 0;'
384                 print r'        glGetProgramiv(program, GL_LINK_STATUS, &link_status);'
385                 print r'        if (!link_status) {'
386                 print r'             GLint info_log_length = 0;'
387                 print r'             glGetProgramiv(program, GL_INFO_LOG_LENGTH, &info_log_length);'
388                 print r'             GLchar *infoLog = new GLchar[info_log_length];'
389                 print r'             glGetProgramInfoLog(program, info_log_length, NULL, infoLog);'
390                 print r'             retrace::warning(call) << infoLog << "\n";'
391                 print r'             delete [] infoLog;'
392                 print r'        }'
393             if function.name == 'glCompileShaderARB':
394                 print r'        GLint compile_status = 0;'
395                 print r'        glGetObjectParameterivARB(shaderObj, GL_OBJECT_COMPILE_STATUS_ARB, &compile_status);'
396                 print r'        if (!compile_status) {'
397                 print r'             GLint info_log_length = 0;'
398                 print r'             glGetObjectParameterivARB(shaderObj, GL_OBJECT_INFO_LOG_LENGTH_ARB, &info_log_length);'
399                 print r'             GLchar *infoLog = new GLchar[info_log_length];'
400                 print r'             glGetInfoLogARB(shaderObj, info_log_length, NULL, infoLog);'
401                 print r'             retrace::warning(call) << infoLog << "\n";'
402                 print r'             delete [] infoLog;'
403                 print r'        }'
404             if function.name == 'glLinkProgramARB':
405                 print r'        GLint link_status = 0;'
406                 print r'        glGetObjectParameterivARB(programObj, GL_OBJECT_LINK_STATUS_ARB, &link_status);'
407                 print r'        if (!link_status) {'
408                 print r'             GLint info_log_length = 0;'
409                 print r'             glGetObjectParameterivARB(programObj, GL_OBJECT_INFO_LOG_LENGTH_ARB, &info_log_length);'
410                 print r'             GLchar *infoLog = new GLchar[info_log_length];'
411                 print r'             glGetInfoLogARB(programObj, info_log_length, NULL, infoLog);'
412                 print r'             retrace::warning(call) << infoLog << "\n";'
413                 print r'             delete [] infoLog;'
414                 print r'        }'
415             if function.name in self.map_function_names:
416                 print r'        if (!_result) {'
417                 print r'             retrace::warning(call) << "failed to map buffer\n";'
418                 print r'        }'
419             if function.name in self.unmap_function_names and function.type is not stdapi.Void:
420                 print r'        if (!_result) {'
421                 print r'             retrace::warning(call) << "failed to unmap buffer\n";'
422                 print r'        }'
423             if function.name in ('glGetAttribLocation', 'glGetAttribLocationARB'):
424                 print r'    GLint _origResult = call.ret->toSInt();'
425                 print r'    if (_result != _origResult) {'
426                 print r'        retrace::warning(call) << "vertex attrib location mismatch " << _origResult << " -> " << _result << "\n";'
427                 print r'    }'
428             if function.name in ('glCheckFramebufferStatus', 'glCheckFramebufferStatusEXT', 'glCheckNamedFramebufferStatusEXT'):
429                 print r'    GLint _origResult = call.ret->toSInt();'
430                 print r'    if (_origResult == GL_FRAMEBUFFER_COMPLETE &&'
431                 print r'        _result != GL_FRAMEBUFFER_COMPLETE) {'
432                 print r'        retrace::warning(call) << "incomplete framebuffer (" << glstate::enumToString(_result) << ")\n";'
433                 print r'    }'
434             print '    }'
435
436         # Query the buffer length for whole buffer mappings
437         if function.name in self.map_function_names:
438             if 'length' in function.argNames():
439                 assert 'BufferRange' in function.name
440             else:
441                 assert 'BufferRange' not in function.name
442                 print r'    GLint length = 0;'
443                 if function.name in ('glMapBuffer', 'glMapBufferOES'):
444                     print r'    glGetBufferParameteriv(target, GL_BUFFER_SIZE, &length);'
445                 elif function.name == 'glMapBufferARB':
446                     print r'    glGetBufferParameterivARB(target, GL_BUFFER_SIZE_ARB, &length);'
447                 elif function.name == 'glMapNamedBufferEXT':
448                     print r'    glGetNamedBufferParameterivEXT(buffer, GL_BUFFER_SIZE, &length);'
449                 elif function.name == 'glMapObjectBufferATI':
450                     print r'    glGetObjectBufferivATI(buffer, GL_OBJECT_BUFFER_SIZE_ATI, &length);'
451                 else:
452                     assert False
453
454     def extractArg(self, function, arg, arg_type, lvalue, rvalue):
455         if function.name in self.array_pointer_function_names and arg.name == 'pointer':
456             print '    %s = static_cast<%s>(retrace::toPointer(%s, true));' % (lvalue, arg_type, rvalue)
457             return
458
459         if function.name in self.draw_elements_function_names and arg.name == 'indices' or\
460            function.name in self.draw_indirect_function_names and arg.name == 'indirect':
461             self.extractOpaqueArg(function, arg, arg_type, lvalue, rvalue)
462             return
463
464         # Handle pointer with offsets into the current pack pixel buffer
465         # object.
466         if function.name in self.pack_function_names and arg.output:
467             assert isinstance(arg_type, (stdapi.Pointer, stdapi.Array, stdapi.Blob, stdapi.Opaque))
468             print '    %s = static_cast<%s>((%s).toPointer());' % (lvalue, arg_type, rvalue)
469             return
470
471         if arg.type is glapi.GLlocation \
472            and 'program' not in function.argNames():
473             # Determine the active program for uniforms swizzling
474             print '    GLint program = -1;'
475             print '    GLint pipeline = 0;'
476             print '    if (_pipelineHasBeenBound) {'
477             print '        glGetIntegerv(GL_PROGRAM_PIPELINE_BINDING, &pipeline);'
478             print '    }'
479             print '    if (pipeline) {'
480             print '        glGetProgramPipelineiv(pipeline, GL_ACTIVE_PROGRAM, &program);'
481             print '    } else {'
482             print '        glGetIntegerv(GL_CURRENT_PROGRAM, &program);'
483             print '    }'
484             print
485
486         if arg.type is glapi.GLlocationARB \
487            and 'programObj' not in function.argNames():
488             print '    GLhandleARB programObj = glGetHandleARB(GL_PROGRAM_OBJECT_ARB);'
489
490         Retracer.extractArg(self, function, arg, arg_type, lvalue, rvalue)
491
492         # Don't try to use more samples than the implementation supports
493         if arg.name == 'samples':
494             assert arg.type is glapi.GLsizei
495             print '    GLint max_samples = 0;'
496             print '    glGetIntegerv(GL_MAX_SAMPLES, &max_samples);'
497             print '    if (samples > max_samples) {'
498             print '        samples = max_samples;'
499             print '    }'
500
501         # These parameters are referred beyond the call life-time
502         # TODO: Replace ad-hoc solution for bindable parameters with general one
503         if function.name in ('glFeedbackBuffer', 'glSelectBuffer') and arg.output:
504             print '    _allocator.bind(%s);' % arg.name
505
506
507
508 if __name__ == '__main__':
509     print r'''
510 #include <string.h>
511
512 #include "glproc.hpp"
513 #include "glretrace.hpp"
514 #include "glstate.hpp"
515
516
517 static bool _pipelineHasBeenBound = false;
518 '''
519     api = glapi.glapi
520     api.addApi(glesapi.glesapi)
521     retracer = GlRetracer()
522     retracer.retraceApi(api)