2 # Copyright (c) 2012 The Chromium Authors. All rights reserved.
3 # Use of this source code is governed by a BSD-style license that can be
4 # found in the LICENSE file.
6 """code generator for GLES2 command buffers."""
13 from optparse
import OptionParser
16 _SIZE_OF_COMMAND_HEADER
= 4
17 _FIRST_SPECIFIC_COMMAND_ID
= 256
19 _LICENSE
= """// Copyright (c) 2012 The Chromium Authors. All rights reserved.
20 // Use of this source code is governed by a BSD-style license that can be
21 // found in the LICENSE file.
25 _DO_NOT_EDIT_WARNING
= """// This file is auto-generated from
26 // gpu/command_buffer/build_gles2_cmd_buffer.py
31 # This string is copied directly out of the gl2.h file from GLES2.0
35 # *) Any argument that is a resourceID has been changed to GLid<Type>.
36 # (not pointer arguments) and if it's allowed to be zero it's GLidZero<Type>
37 # If it's allowed to not exist it's GLidBind<Type>
39 # *) All GLenums have been changed to GLenumTypeOfEnum
42 'GLenum': 'unsigned int',
43 'GLboolean': 'unsigned char',
44 'GLbitfield': 'unsigned int',
45 'GLbyte': 'signed char',
49 'GLubyte': 'unsigned char',
50 'GLushort': 'unsigned short',
51 'GLuint': 'unsigned int',
60 'GLintptr': 'long int',
61 'GLsizeiptr': 'long int'
65 'GLintptr': 'long long int',
66 'GLsizeiptr': 'long long int'
69 # Capabilites selected with glEnable
72 {'name': 'cull_face'},
73 {'name': 'depth_test', 'state_flag': 'framebuffer_state_.clear_state_dirty'},
74 {'name': 'dither', 'default': True},
75 {'name': 'polygon_offset_fill'},
76 {'name': 'sample_alpha_to_coverage'},
77 {'name': 'sample_coverage'},
78 {'name': 'scissor_test',
79 'state_flag': 'framebuffer_state_.clear_state_dirty'},
80 {'name': 'stencil_test',
81 'state_flag': 'framebuffer_state_.clear_state_dirty'},
88 'enum': 'GL_COLOR_CLEAR_VALUE',
90 {'name': 'color_clear_red', 'type': 'GLfloat', 'default': '0.0f'},
91 {'name': 'color_clear_green', 'type': 'GLfloat', 'default': '0.0f'},
92 {'name': 'color_clear_blue', 'type': 'GLfloat', 'default': '0.0f'},
93 {'name': 'color_clear_alpha', 'type': 'GLfloat', 'default': '0.0f'},
99 'enum': 'GL_DEPTH_CLEAR_VALUE',
101 {'name': 'depth_clear', 'type': 'GLclampf', 'default': '1.0f'},
107 'enum': 'GL_COLOR_WRITEMASK',
109 {'name': 'color_mask_red', 'type': 'GLboolean', 'default': 'true'},
110 {'name': 'color_mask_green', 'type': 'GLboolean', 'default': 'true'},
111 {'name': 'color_mask_blue', 'type': 'GLboolean', 'default': 'true'},
112 {'name': 'color_mask_alpha', 'type': 'GLboolean', 'default': 'true'},
114 'state_flag': 'framebuffer_state_.clear_state_dirty',
118 'func': 'ClearStencil',
119 'enum': 'GL_STENCIL_CLEAR_VALUE',
121 {'name': 'stencil_clear', 'type': 'GLint', 'default': '0'},
126 'func': 'BlendColor',
127 'enum': 'GL_BLEND_COLOR',
129 {'name': 'blend_color_red', 'type': 'GLfloat', 'default': '0.0f'},
130 {'name': 'blend_color_green', 'type': 'GLfloat', 'default': '0.0f'},
131 {'name': 'blend_color_blue', 'type': 'GLfloat', 'default': '0.0f'},
132 {'name': 'blend_color_alpha', 'type': 'GLfloat', 'default': '0.0f'},
137 'func': 'BlendEquationSeparate',
140 'name': 'blend_equation_rgb',
142 'enum': 'GL_BLEND_EQUATION_RGB',
143 'default': 'GL_FUNC_ADD',
146 'name': 'blend_equation_alpha',
148 'enum': 'GL_BLEND_EQUATION_ALPHA',
149 'default': 'GL_FUNC_ADD',
155 'func': 'BlendFuncSeparate',
158 'name': 'blend_source_rgb',
160 'enum': 'GL_BLEND_SRC_RGB',
164 'name': 'blend_dest_rgb',
166 'enum': 'GL_BLEND_DST_RGB',
167 'default': 'GL_ZERO',
170 'name': 'blend_source_alpha',
172 'enum': 'GL_BLEND_SRC_ALPHA',
176 'name': 'blend_dest_alpha',
178 'enum': 'GL_BLEND_DST_ALPHA',
179 'default': 'GL_ZERO',
185 'func': 'PolygonOffset',
188 'name': 'polygon_offset_factor',
190 'enum': 'GL_POLYGON_OFFSET_FACTOR',
194 'name': 'polygon_offset_units',
196 'enum': 'GL_POLYGON_OFFSET_UNITS',
204 'enum': 'GL_CULL_FACE_MODE',
209 'default': 'GL_BACK',
216 'enum': 'GL_FRONT_FACE',
217 'states': [{'name': 'front_face', 'type': 'GLenum', 'default': 'GL_CCW'}],
222 'enum': 'GL_DEPTH_FUNC',
223 'states': [{'name': 'depth_func', 'type': 'GLenum', 'default': 'GL_LESS'}],
227 'func': 'DepthRange',
228 'enum': 'GL_DEPTH_RANGE',
230 {'name': 'z_near', 'type': 'GLclampf', 'default': '0.0f'},
231 {'name': 'z_far', 'type': 'GLclampf', 'default': '1.0f'},
236 'func': 'SampleCoverage',
239 'name': 'sample_coverage_value',
241 'enum': 'GL_SAMPLE_COVERAGE_VALUE',
245 'name': 'sample_coverage_invert',
247 'enum': 'GL_SAMPLE_COVERAGE_INVERT',
254 'func': 'StencilMaskSeparate',
255 'state_flag': 'framebuffer_state_.clear_state_dirty',
258 'name': 'stencil_front_writemask',
260 'enum': 'GL_STENCIL_WRITEMASK',
261 'default': '0xFFFFFFFFU',
264 'name': 'stencil_back_writemask',
266 'enum': 'GL_STENCIL_BACK_WRITEMASK',
267 'default': '0xFFFFFFFFU',
273 'func': 'StencilOpSeparate',
276 'name': 'stencil_front_fail_op',
278 'enum': 'GL_STENCIL_FAIL',
279 'default': 'GL_KEEP',
282 'name': 'stencil_front_z_fail_op',
284 'enum': 'GL_STENCIL_PASS_DEPTH_FAIL',
285 'default': 'GL_KEEP',
288 'name': 'stencil_front_z_pass_op',
290 'enum': 'GL_STENCIL_PASS_DEPTH_PASS',
291 'default': 'GL_KEEP',
294 'name': 'stencil_back_fail_op',
296 'enum': 'GL_STENCIL_BACK_FAIL',
297 'default': 'GL_KEEP',
300 'name': 'stencil_back_z_fail_op',
302 'enum': 'GL_STENCIL_BACK_PASS_DEPTH_FAIL',
303 'default': 'GL_KEEP',
306 'name': 'stencil_back_z_pass_op',
308 'enum': 'GL_STENCIL_BACK_PASS_DEPTH_PASS',
309 'default': 'GL_KEEP',
315 'func': 'StencilFuncSeparate',
318 'name': 'stencil_front_func',
320 'enum': 'GL_STENCIL_FUNC',
321 'default': 'GL_ALWAYS',
324 'name': 'stencil_front_ref',
326 'enum': 'GL_STENCIL_REF',
330 'name': 'stencil_front_mask',
332 'enum': 'GL_STENCIL_VALUE_MASK',
333 'default': '0xFFFFFFFFU',
336 'name': 'stencil_back_func',
338 'enum': 'GL_STENCIL_BACK_FUNC',
339 'default': 'GL_ALWAYS',
342 'name': 'stencil_back_ref',
344 'enum': 'GL_STENCIL_BACK_REF',
348 'name': 'stencil_back_mask',
350 'enum': 'GL_STENCIL_BACK_VALUE_MASK',
351 'default': '0xFFFFFFFFU',
356 'type': 'NamedParameter',
360 'name': 'hint_generate_mipmap',
362 'enum': 'GL_GENERATE_MIPMAP_HINT',
363 'default': 'GL_DONT_CARE'
366 'name': 'hint_fragment_shader_derivative',
368 'enum': 'GL_FRAGMENT_SHADER_DERIVATIVE_HINT_OES',
369 'default': 'GL_DONT_CARE',
370 'extension_flag': 'oes_standard_derivatives'
375 'type': 'NamedParameter',
376 'func': 'PixelStorei',
379 'name': 'pack_alignment',
381 'enum': 'GL_PACK_ALIGNMENT',
385 'name': 'unpack_alignment',
387 'enum': 'GL_UNPACK_ALIGNMENT',
392 # TODO: Consider implemenenting these states
397 'enum': 'GL_LINE_WIDTH',
400 'name': 'line_width',
403 'range_checks': [{'check': "<= 0.0f", 'test_value': "0.0f"}],
409 'enum': 'GL_DEPTH_WRITEMASK',
411 {'name': 'depth_mask', 'type': 'GLboolean', 'default': 'true'},
413 'state_flag': 'framebuffer_state_.clear_state_dirty',
418 'enum': 'GL_SCISSOR_BOX',
420 # NOTE: These defaults reset at GLES2DecoderImpl::Initialization.
425 'expected': 'kViewportX',
431 'expected': 'kViewportY',
434 'name': 'scissor_width',
437 'expected': 'kViewportWidth',
440 'name': 'scissor_height',
443 'expected': 'kViewportHeight',
450 'enum': 'GL_VIEWPORT',
452 # NOTE: These defaults reset at GLES2DecoderImpl::Initialization.
454 'name': 'viewport_x',
457 'expected': 'kViewportX',
460 'name': 'viewport_y',
463 'expected': 'kViewportY',
466 'name': 'viewport_width',
469 'expected': 'kViewportWidth',
472 'name': 'viewport_height',
475 'expected': 'kViewportHeight',
481 # This is a list of enum names and their valid values. It is used to map
482 # GLenum arguments to a specific set of valid values.
491 'GL_LINEAR_MIPMAP_LINEAR',
494 'FrameBufferTarget': {
500 'GL_DRAW_FRAMEBUFFER' ,
501 'GL_READ_FRAMEBUFFER' ,
504 'RenderBufferTarget': {
517 'GL_ELEMENT_ARRAY_BUFFER',
534 'CompressedTextureFormat': {
542 # NOTE: State an Capability entries added later.
544 'GL_ALIASED_LINE_WIDTH_RANGE',
545 'GL_ALIASED_POINT_SIZE_RANGE',
547 'GL_ARRAY_BUFFER_BINDING',
549 'GL_COMPRESSED_TEXTURE_FORMATS',
550 'GL_CURRENT_PROGRAM',
553 'GL_ELEMENT_ARRAY_BUFFER_BINDING',
554 'GL_FRAMEBUFFER_BINDING',
555 'GL_GENERATE_MIPMAP_HINT',
557 'GL_IMPLEMENTATION_COLOR_READ_FORMAT',
558 'GL_IMPLEMENTATION_COLOR_READ_TYPE',
559 'GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS',
560 'GL_MAX_CUBE_MAP_TEXTURE_SIZE',
561 'GL_MAX_FRAGMENT_UNIFORM_VECTORS',
562 'GL_MAX_RENDERBUFFER_SIZE',
563 'GL_MAX_TEXTURE_IMAGE_UNITS',
564 'GL_MAX_TEXTURE_SIZE',
565 'GL_MAX_VARYING_VECTORS',
566 'GL_MAX_VERTEX_ATTRIBS',
567 'GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS',
568 'GL_MAX_VERTEX_UNIFORM_VECTORS',
569 'GL_MAX_VIEWPORT_DIMS',
570 'GL_NUM_COMPRESSED_TEXTURE_FORMATS',
571 'GL_NUM_SHADER_BINARY_FORMATS',
574 'GL_RENDERBUFFER_BINDING',
576 'GL_SAMPLE_COVERAGE_INVERT',
577 'GL_SAMPLE_COVERAGE_VALUE',
580 'GL_SHADER_BINARY_FORMATS',
581 'GL_SHADER_COMPILER',
584 'GL_TEXTURE_BINDING_2D',
585 'GL_TEXTURE_BINDING_CUBE_MAP',
586 'GL_UNPACK_ALIGNMENT',
587 'GL_UNPACK_FLIP_Y_CHROMIUM',
588 'GL_UNPACK_PREMULTIPLY_ALPHA_CHROMIUM',
589 'GL_UNPACK_UNPREMULTIPLY_ALPHA_CHROMIUM',
590 # we can add this because we emulate it if the driver does not support it.
591 'GL_VERTEX_ARRAY_BINDING_OES',
598 'GetTexParamTarget': {
602 'GL_TEXTURE_CUBE_MAP',
605 'GL_PROXY_TEXTURE_CUBE_MAP',
612 'GL_TEXTURE_CUBE_MAP_POSITIVE_X',
613 'GL_TEXTURE_CUBE_MAP_NEGATIVE_X',
614 'GL_TEXTURE_CUBE_MAP_POSITIVE_Y',
615 'GL_TEXTURE_CUBE_MAP_NEGATIVE_Y',
616 'GL_TEXTURE_CUBE_MAP_POSITIVE_Z',
617 'GL_TEXTURE_CUBE_MAP_NEGATIVE_Z',
620 'GL_PROXY_TEXTURE_CUBE_MAP',
623 'TextureBindTarget': {
627 'GL_TEXTURE_CUBE_MAP',
638 'GL_FRAGMENT_SHADER',
641 'GL_GEOMETRY_SHADER',
677 'GL_FUNC_REVERSE_SUBTRACT',
690 'GL_ONE_MINUS_SRC_COLOR',
692 'GL_ONE_MINUS_DST_COLOR',
694 'GL_ONE_MINUS_SRC_ALPHA',
696 'GL_ONE_MINUS_DST_ALPHA',
698 'GL_ONE_MINUS_CONSTANT_COLOR',
700 'GL_ONE_MINUS_CONSTANT_ALPHA',
701 'GL_SRC_ALPHA_SATURATE',
710 'GL_ONE_MINUS_SRC_COLOR',
712 'GL_ONE_MINUS_DST_COLOR',
714 'GL_ONE_MINUS_SRC_ALPHA',
716 'GL_ONE_MINUS_DST_ALPHA',
718 'GL_ONE_MINUS_CONSTANT_COLOR',
720 'GL_ONE_MINUS_CONSTANT_ALPHA',
725 'valid': ["GL_%s" % cap
['name'].upper() for cap
in _CAPABILITY_FLAGS
],
772 'GL_COLOR_ATTACHMENT0',
773 'GL_DEPTH_ATTACHMENT',
774 'GL_STENCIL_ATTACHMENT',
777 'BackbufferAttachment': {
792 'GL_PIXEL_PACK_BUFFER',
795 'FrameBufferParameter': {
798 'GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE',
799 'GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME',
800 'GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL',
801 'GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE',
804 'ProgramParameter': {
809 'GL_VALIDATE_STATUS',
810 'GL_INFO_LOG_LENGTH',
811 'GL_ATTACHED_SHADERS',
812 'GL_ACTIVE_ATTRIBUTES',
813 'GL_ACTIVE_ATTRIBUTE_MAX_LENGTH',
814 'GL_ACTIVE_UNIFORMS',
815 'GL_ACTIVE_UNIFORM_MAX_LENGTH',
818 'QueryObjectParameter': {
821 'GL_QUERY_RESULT_EXT',
822 'GL_QUERY_RESULT_AVAILABLE_EXT',
828 'GL_CURRENT_QUERY_EXT',
834 'GL_ANY_SAMPLES_PASSED_EXT',
835 'GL_ANY_SAMPLES_PASSED_CONSERVATIVE_EXT',
836 'GL_COMMANDS_ISSUED_CHROMIUM',
837 'GL_LATENCY_QUERY_CHROMIUM',
838 'GL_ASYNC_PIXEL_UNPACK_COMPLETED_CHROMIUM',
839 'GL_ASYNC_PIXEL_PACK_COMPLETED_CHROMIUM',
842 'RenderBufferParameter': {
845 'GL_RENDERBUFFER_RED_SIZE',
846 'GL_RENDERBUFFER_GREEN_SIZE',
847 'GL_RENDERBUFFER_BLUE_SIZE',
848 'GL_RENDERBUFFER_ALPHA_SIZE',
849 'GL_RENDERBUFFER_DEPTH_SIZE',
850 'GL_RENDERBUFFER_STENCIL_SIZE',
851 'GL_RENDERBUFFER_WIDTH',
852 'GL_RENDERBUFFER_HEIGHT',
853 'GL_RENDERBUFFER_INTERNAL_FORMAT',
862 'GL_INFO_LOG_LENGTH',
863 'GL_SHADER_SOURCE_LENGTH',
864 'GL_TRANSLATED_SHADER_SOURCE_LENGTH_ANGLE',
884 'GL_SHADING_LANGUAGE_VERSION',
888 'TextureParameter': {
891 'GL_TEXTURE_MAG_FILTER',
892 'GL_TEXTURE_MIN_FILTER',
893 'GL_TEXTURE_POOL_CHROMIUM',
898 'GL_GENERATE_MIPMAP',
904 'GL_TEXTURE_POOL_MANAGED_CHROMIUM',
905 'GL_TEXTURE_POOL_UNMANAGED_CHROMIUM',
912 'GL_MIRRORED_REPEAT',
916 'TextureMinFilterMode': {
921 'GL_NEAREST_MIPMAP_NEAREST',
922 'GL_LINEAR_MIPMAP_NEAREST',
923 'GL_NEAREST_MIPMAP_LINEAR',
924 'GL_LINEAR_MIPMAP_LINEAR',
927 'TextureMagFilterMode': {
938 'GL_FRAMEBUFFER_ATTACHMENT_ANGLE',
944 # some enum that the decoder actually passes through to GL needs
945 # to be the first listed here since it's used in unit tests.
946 'GL_VERTEX_ATTRIB_ARRAY_NORMALIZED',
947 'GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING',
948 'GL_VERTEX_ATTRIB_ARRAY_ENABLED',
949 'GL_VERTEX_ATTRIB_ARRAY_SIZE',
950 'GL_VERTEX_ATTRIB_ARRAY_STRIDE',
951 'GL_VERTEX_ATTRIB_ARRAY_TYPE',
952 'GL_CURRENT_VERTEX_ATTRIB',
958 'GL_VERTEX_ATTRIB_ARRAY_POINTER',
964 'GL_GENERATE_MIPMAP_HINT',
967 'GL_PERSPECTIVE_CORRECTION_HINT',
982 'GL_UNPACK_ALIGNMENT',
983 'GL_UNPACK_FLIP_Y_CHROMIUM',
984 'GL_UNPACK_PREMULTIPLY_ALPHA_CHROMIUM',
985 'GL_UNPACK_UNPREMULTIPLY_ALPHA_CHROMIUM',
988 'GL_PACK_SWAP_BYTES',
989 'GL_UNPACK_SWAP_BYTES',
992 'PixelStoreAlignment': {
1005 'ReadPixelFormat': {
1017 'GL_UNSIGNED_SHORT_5_6_5',
1018 'GL_UNSIGNED_SHORT_4_4_4_4',
1019 'GL_UNSIGNED_SHORT_5_5_5_1',
1030 'GL_UNSIGNED_SHORT_5_6_5',
1031 'GL_UNSIGNED_SHORT_4_4_4_4',
1032 'GL_UNSIGNED_SHORT_5_5_5_1',
1039 'RenderBufferFormat': {
1045 'GL_DEPTH_COMPONENT16',
1046 'GL_STENCIL_INDEX8',
1049 'ShaderBinaryFormat': {
1072 'GL_LUMINANCE_ALPHA',
1081 'TextureInternalFormat': {
1086 'GL_LUMINANCE_ALPHA',
1095 'TextureInternalFormatStorage': {
1102 'GL_LUMINANCE8_EXT',
1103 'GL_LUMINANCE8_ALPHA8_EXT',
1108 'VertexAttribType': {
1114 'GL_UNSIGNED_SHORT',
1115 # 'GL_FIXED', // This is not available on Desktop GL.
1131 'VertexAttribSize': {
1154 'type': 'GLboolean',
1165 'GL_GUILTY_CONTEXT_RESET_ARB',
1166 'GL_INNOCENT_CONTEXT_RESET_ARB',
1167 'GL_UNKNOWN_CONTEXT_RESET_ARB',
1172 # This table specifies the different pepper interfaces that are supported for
1173 # GL commands. 'dev' is true if it's a dev interface.
1174 _PEPPER_INTERFACES
= [
1175 {'name': '', 'dev': False},
1176 {'name': 'InstancedArrays', 'dev': False},
1177 {'name': 'FramebufferBlit', 'dev': False},
1178 {'name': 'FramebufferMultisample', 'dev': False},
1179 {'name': 'ChromiumEnableFeature', 'dev': False},
1180 {'name': 'ChromiumMapSub', 'dev': False},
1181 {'name': 'Query', 'dev': False},
1184 # This table specifies types and other special data for the commands that
1185 # will be generated.
1187 # Must match function names specified in "cmd_buffer_functions.txt".
1189 # cmd_comment: A comment added to the cmd format.
1190 # type: defines which handler will be used to generate code.
1191 # decoder_func: defines which function to call in the decoder to execute the
1192 # corresponding GL command. If not specified the GL command will
1193 # be called directly.
1194 # gl_test_func: GL function that is expected to be called when testing.
1195 # cmd_args: The arguments to use for the command. This overrides generating
1196 # them based on the GL function arguments.
1197 # a NonImmediate type is a type that stays a pointer even in
1198 # and immediate version of acommand.
1199 # gen_cmd: Whether or not this function geneates a command. Default = True.
1200 # immediate: Whether or not to generate an immediate command for the GL
1201 # function. The default is if there is exactly 1 pointer argument
1202 # in the GL function an immediate command is generated.
1203 # bucket: True to generate a bucket version of the command.
1204 # impl_func: Whether or not to generate the GLES2Implementation part of this
1206 # impl_decl: Whether or not to generate the GLES2Implementation declaration
1208 # needs_size: If true a data_size field is added to the command.
1209 # data_type: The type of data the command uses. For PUTn or PUT types.
1210 # count: The number of units per element. For PUTn or PUT types.
1211 # unit_test: If False no service side unit test will be generated.
1212 # client_test: If False no client side unit test will be generated.
1213 # expectation: If False the unit test will have no expected calls.
1214 # gen_func: Name of function that generates GL resource for corresponding
1216 # states: array of states that get set by this function corresponding to
1217 # the given arguments
1218 # state_flag: name of flag that is set to true when function is called.
1219 # no_gl: no GL function is called.
1220 # valid_args: A dictionary of argument indices to args to use in unit tests
1221 # when they can not be automatically determined.
1222 # pepper_interface: The pepper interface that is used for this extension
1223 # pepper_args: A string representing the argument list (what would appear in
1224 # C/C++ between the parentheses for the function declaration)
1225 # that the Pepper API expects for this function. Use this only if
1226 # the stable Pepper API differs from the GLES2 argument list.
1227 # invalid_test: False if no invalid test needed.
1228 # shadowed: True = the value is shadowed so no glGetXXX call will be made.
1229 # first_element_only: For PUT types, True if only the first element of an
1230 # array is used and we end up calling the single value
1231 # corresponding function. eg. TexParameteriv -> TexParameteri
1235 'decoder_func': 'DoActiveTexture',
1238 'client_test': False,
1240 'AttachShader': {'decoder_func': 'DoAttachShader'},
1241 'BindAttribLocation': {
1249 'decoder_func': 'DoBindBuffer',
1250 'gen_func': 'GenBuffersARB',
1252 'BindFramebuffer': {
1254 'decoder_func': 'DoBindFramebuffer',
1255 'gl_test_func': 'glBindFramebufferEXT',
1256 'gen_func': 'GenFramebuffersEXT',
1258 'BindRenderbuffer': {
1260 'decoder_func': 'DoBindRenderbuffer',
1261 'gl_test_func': 'glBindRenderbufferEXT',
1262 'gen_func': 'GenRenderbuffersEXT',
1266 'decoder_func': 'DoBindTexture',
1267 'gen_func': 'GenTextures',
1268 # TODO(gman): remove this once client side caching works.
1269 'client_test': False,
1271 'BlitFramebufferCHROMIUM': {
1272 'decoder_func': 'DoBlitFramebufferCHROMIUM',
1275 'pepper_interface': 'FramebufferBlit',
1276 'defer_reads': True,
1277 'defer_draws': True,
1282 'client_test': False,
1286 'client_test': False,
1287 'decoder_func': 'DoBufferSubData',
1290 'CheckFramebufferStatus': {
1292 'decoder_func': 'DoCheckFramebufferStatus',
1293 'gl_test_func': 'glCheckFramebufferStatusEXT',
1294 'error_value': 'GL_FRAMEBUFFER_UNSUPPORTED',
1295 'result': ['GLenum'],
1298 'decoder_func': 'DoClear',
1299 'defer_draws': True,
1303 'state': 'ClearColor',
1307 'state': 'ClearDepthf',
1308 'decoder_func': 'glClearDepth',
1309 'gl_test_func': 'glClearDepth',
1316 'state': 'ColorMask',
1318 'expectation': False,
1320 'ConsumeTextureCHROMIUM': {
1321 'decoder_func': 'DoConsumeTextureCHROMIUM',
1323 'data_type': 'GLbyte',
1331 'state': 'ClearStencil',
1333 'EnableFeatureCHROMIUM': {
1336 'decoder_func': 'DoEnableFeatureCHROMIUM',
1337 'expectation': False,
1338 'cmd_args': 'GLuint bucket_id, GLint* result',
1339 'result': ['GLint'],
1342 'pepper_interface': 'ChromiumEnableFeature',
1344 'CompileShader': {'decoder_func': 'DoCompileShader', 'unit_test': False},
1345 'CompressedTexImage2D': {
1350 'CompressedTexSubImage2D': {
1353 'decoder_func': 'DoCompressedTexSubImage2D',
1357 'decoder_func': 'DoCopyTexImage2D',
1359 'defer_reads': True,
1361 'CopyTexSubImage2D': {
1362 'decoder_func': 'DoCopyTexSubImage2D',
1363 'defer_reads': True,
1365 'CreateImageCHROMIUM': {
1367 'cmd_args': 'GLsizei width, GLsizei height, GLenum internalformat',
1368 'result': ['GLuint'],
1369 'client_test': False,
1371 'expectation': False,
1375 'DestroyImageCHROMIUM': {
1378 'client_test': False,
1383 'GetImageParameterivCHROMIUM': {
1385 'client_test': False,
1387 'expectation': False,
1393 'client_test': False,
1397 'client_test': False,
1401 'state': 'BlendColor',
1404 'type': 'StateSetRGBAlpha',
1405 'state': 'BlendEquation',
1407 '0': 'GL_FUNC_SUBTRACT'
1410 'BlendEquationSeparate': {
1412 'state': 'BlendEquation',
1414 '0': 'GL_FUNC_SUBTRACT'
1418 'type': 'StateSetRGBAlpha',
1419 'state': 'BlendFunc',
1421 'BlendFuncSeparate': {
1423 'state': 'BlendFunc',
1425 'SampleCoverage': {'decoder_func': 'DoSampleCoverage'},
1427 'type': 'StateSetFrontBack',
1428 'state': 'StencilFunc',
1430 'StencilFuncSeparate': {
1431 'type': 'StateSetFrontBackSeparate',
1432 'state': 'StencilFunc',
1435 'type': 'StateSetFrontBack',
1436 'state': 'StencilOp',
1441 'StencilOpSeparate': {
1442 'type': 'StateSetFrontBackSeparate',
1443 'state': 'StencilOp',
1449 'type': 'StateSetNamedParameter',
1452 'CullFace': {'type': 'StateSet', 'state': 'CullFace'},
1453 'FrontFace': {'type': 'StateSet', 'state': 'FrontFace'},
1454 'DepthFunc': {'type': 'StateSet', 'state': 'DepthFunc'},
1457 'state': 'LineWidth',
1464 'state': 'PolygonOffset',
1468 'gl_test_func': 'glDeleteBuffersARB',
1469 'resource_type': 'Buffer',
1470 'resource_types': 'Buffers',
1472 'DeleteFramebuffers': {
1474 'gl_test_func': 'glDeleteFramebuffersEXT',
1475 'resource_type': 'Framebuffer',
1476 'resource_types': 'Framebuffers',
1478 'DeleteProgram': {'type': 'Delete', 'decoder_func': 'DoDeleteProgram'},
1479 'DeleteRenderbuffers': {
1481 'gl_test_func': 'glDeleteRenderbuffersEXT',
1482 'resource_type': 'Renderbuffer',
1483 'resource_types': 'Renderbuffers',
1485 'DeleteShader': {'type': 'Delete', 'decoder_func': 'DoDeleteShader'},
1486 'DeleteSharedIdsCHROMIUM': {
1488 'decoder_func': 'DoDeleteSharedIdsCHROMIUM',
1490 'expectation': False,
1497 'resource_type': 'Texture',
1498 'resource_types': 'Textures',
1501 'decoder_func': 'DoDepthRangef',
1502 'gl_test_func': 'glDepthRange',
1506 'state': 'DepthMask',
1508 'expectation': False,
1510 'DetachShader': {'decoder_func': 'DoDetachShader'},
1512 'decoder_func': 'DoDisable',
1514 'client_test': False,
1516 'DisableVertexAttribArray': {
1517 'decoder_func': 'DoDisableVertexAttribArray',
1522 'cmd_args': 'GLenumDrawMode mode, GLint first, GLsizei count',
1523 'defer_draws': True,
1527 'cmd_args': 'GLenumDrawMode mode, GLsizei count, '
1528 'GLenumIndexType type, GLuint index_offset',
1529 'client_test': False,
1530 'defer_draws': True,
1533 'decoder_func': 'DoEnable',
1535 'client_test': False,
1537 'EnableVertexAttribArray': {
1538 'decoder_func': 'DoEnableVertexAttribArray',
1543 'client_test': False,
1544 'decoder_func': 'DoFinish',
1545 'defer_reads': True,
1549 'decoder_func': 'DoFlush',
1551 'FramebufferRenderbuffer': {
1552 'decoder_func': 'DoFramebufferRenderbuffer',
1553 'gl_test_func': 'glFramebufferRenderbufferEXT',
1555 'FramebufferTexture2D': {
1556 'decoder_func': 'DoFramebufferTexture2D',
1557 'gl_test_func': 'glFramebufferTexture2DEXT',
1559 'FramebufferTexture2DMultisampleEXT': {
1560 'decoder_func': 'DoFramebufferTexture2DMultisample',
1561 'gl_test_func': 'glFramebufferTexture2DMultisampleEXT',
1562 'expectation': False,
1567 'decoder_func': 'DoGenerateMipmap',
1568 'gl_test_func': 'glGenerateMipmapEXT',
1572 'gl_test_func': 'glGenBuffersARB',
1573 'resource_type': 'Buffer',
1574 'resource_types': 'Buffers',
1576 'GenMailboxCHROMIUM': {
1577 'type': 'HandWritten',
1583 'GenFramebuffers': {
1585 'gl_test_func': 'glGenFramebuffersEXT',
1586 'resource_type': 'Framebuffer',
1587 'resource_types': 'Framebuffers',
1589 'GenRenderbuffers': {
1590 'type': 'GENn', 'gl_test_func': 'glGenRenderbuffersEXT',
1591 'resource_type': 'Renderbuffer',
1592 'resource_types': 'Renderbuffers',
1596 'gl_test_func': 'glGenTextures',
1597 'resource_type': 'Texture',
1598 'resource_types': 'Textures',
1600 'GenSharedIdsCHROMIUM': {
1602 'decoder_func': 'DoGenSharedIdsCHROMIUM',
1604 'expectation': False,
1609 'GetActiveAttrib': {
1613 'GLidProgram program, GLuint index, uint32 name_bucket_id, '
1621 'GetActiveUniform': {
1625 'GLidProgram program, GLuint index, uint32 name_bucket_id, '
1633 'GetAttachedShaders': {
1636 'cmd_args': 'GLidProgram program, void* result, uint32 result_size',
1637 'result': ['SizedResult<GLuint>'],
1639 'GetAttribLocation': {
1640 'type': 'HandWritten',
1645 'GLidProgram program, const char* name, NonImmediate GLint* location',
1646 'result': ['GLint'],
1647 'error_return': -1, # http://www.opengl.org/sdk/docs/man/xhtml/glGetAttribLocation.xml
1651 'result': ['SizedResult<GLboolean>'],
1652 'decoder_func': 'DoGetBooleanv',
1653 'gl_test_func': 'glGetBooleanv',
1655 'GetBufferParameteriv': {
1657 'result': ['SizedResult<GLint>'],
1658 'decoder_func': 'DoGetBufferParameteriv',
1659 'expectation': False,
1664 'decoder_func': 'GetErrorState()->GetGLError',
1666 'result': ['GLenum'],
1667 'client_test': False,
1671 'result': ['SizedResult<GLfloat>'],
1672 'decoder_func': 'DoGetFloatv',
1673 'gl_test_func': 'glGetFloatv',
1675 'GetFramebufferAttachmentParameteriv': {
1677 'decoder_func': 'DoGetFramebufferAttachmentParameteriv',
1678 'gl_test_func': 'glGetFramebufferAttachmentParameterivEXT',
1679 'result': ['SizedResult<GLint>'],
1683 'result': ['SizedResult<GLint>'],
1684 'decoder_func': 'DoGetIntegerv',
1685 'client_test': False,
1687 'GetMaxValueInBufferCHROMIUM': {
1689 'decoder_func': 'DoGetMaxValueInBufferCHROMIUM',
1690 'result': ['GLuint'],
1692 'client_test': False,
1697 'GetMultipleIntegervCHROMIUM': {
1700 'expectation': False,
1703 'client_test': False,
1707 'decoder_func': 'DoGetProgramiv',
1708 'result': ['SizedResult<GLint>'],
1709 'expectation': False,
1711 'GetProgramInfoCHROMIUM': {
1714 'expectation': False,
1718 'client_test': False,
1719 'cmd_args': 'GLidProgram program, uint32 bucket_id',
1721 'uint32 link_status',
1722 'uint32 num_attribs',
1723 'uint32 num_uniforms',
1726 'GetProgramInfoLog': {
1728 'expectation': False,
1730 'GetRenderbufferParameteriv': {
1732 'decoder_func': 'DoGetRenderbufferParameteriv',
1733 'gl_test_func': 'glGetRenderbufferParameterivEXT',
1734 'result': ['SizedResult<GLint>'],
1738 'decoder_func': 'DoGetShaderiv',
1739 'result': ['SizedResult<GLint>'],
1741 'GetShaderInfoLog': {
1743 'get_len_func': 'glGetShaderiv',
1744 'get_len_enum': 'GL_INFO_LOG_LENGTH',
1747 'GetShaderPrecisionFormat': {
1751 'GLenumShaderType shadertype, GLenumShaderPrecision precisiontype, '
1760 'GetShaderSource': {
1762 'get_len_func': 'DoGetShaderiv',
1763 'get_len_enum': 'GL_SHADER_SOURCE_LENGTH',
1765 'client_test': False,
1769 'client_test': False,
1770 'cmd_args': 'GLenumStringType name, uint32 bucket_id',
1772 'GetTexParameterfv': {'type': 'GETn', 'result': ['SizedResult<GLfloat>']},
1773 'GetTexParameteriv': {'type': 'GETn', 'result': ['SizedResult<GLint>']},
1774 'GetTranslatedShaderSourceANGLE': {
1776 'get_len_func': 'DoGetShaderiv',
1777 'get_len_enum': 'GL_TRANSLATED_SHADER_SOURCE_LENGTH_ANGLE',
1784 'result': ['SizedResult<GLfloat>'],
1789 'result': ['SizedResult<GLint>'],
1791 'GetUniformLocation': {
1792 'type': 'HandWritten',
1797 'GLidProgram program, const char* name, NonImmediate GLint* location',
1798 'result': ['GLint'],
1799 'error_return': -1, # http://www.opengl.org/sdk/docs/man/xhtml/glGetUniformLocation.xml
1801 'GetVertexAttribfv': {
1803 'result': ['SizedResult<GLfloat>'],
1805 'decoder_func': 'DoGetVertexAttribfv',
1806 'expectation': False,
1807 'client_test': False,
1809 'GetVertexAttribiv': {
1811 'result': ['SizedResult<GLint>'],
1813 'decoder_func': 'DoGetVertexAttribiv',
1814 'expectation': False,
1815 'client_test': False,
1817 'GetVertexAttribPointerv': {
1820 'result': ['SizedResult<GLuint>'],
1821 'client_test': False,
1825 'decoder_func': 'DoIsBuffer',
1826 'expectation': False,
1830 'decoder_func': 'DoIsEnabled',
1832 'expectation': False,
1836 'decoder_func': 'DoIsFramebuffer',
1837 'expectation': False,
1841 'decoder_func': 'DoIsProgram',
1842 'expectation': False,
1846 'decoder_func': 'DoIsRenderbuffer',
1847 'expectation': False,
1851 'decoder_func': 'DoIsShader',
1852 'expectation': False,
1856 'decoder_func': 'DoIsTexture',
1857 'expectation': False,
1860 'decoder_func': 'DoLinkProgram',
1863 'MapBufferCHROMIUM': {
1867 'client_test': False,
1869 'MapBufferSubDataCHROMIUM': {
1873 'client_test': False,
1874 'pepper_interface': 'ChromiumMapSub',
1876 'MapImageCHROMIUM': {
1880 'client_test': False,
1882 'MapTexSubImage2DCHROMIUM': {
1886 'client_test': False,
1887 'pepper_interface': 'ChromiumMapSub',
1889 'PixelStorei': {'type': 'Manual'},
1890 'PostSubBufferCHROMIUM': {
1894 'client_test': False,
1898 'ProduceTextureCHROMIUM': {
1899 'decoder_func': 'DoProduceTextureCHROMIUM',
1901 'data_type': 'GLbyte',
1907 'RenderbufferStorage': {
1908 'decoder_func': 'DoRenderbufferStorage',
1909 'gl_test_func': 'glRenderbufferStorageEXT',
1910 'expectation': False,
1912 'RenderbufferStorageMultisampleCHROMIUM': {
1914 '// GL_CHROMIUM_framebuffer_multisample\n',
1915 'decoder_func': 'DoRenderbufferStorageMultisampleCHROMIUM',
1916 'gl_test_func': 'glRenderbufferStorageMultisampleCHROMIUM',
1917 'expectation': False,
1920 'pepper_interface': 'FramebufferMultisample',
1922 'RenderbufferStorageMultisampleEXT': {
1924 '// GL_EXT_multisampled_render_to_texture\n',
1925 'decoder_func': 'DoRenderbufferStorageMultisampleEXT',
1926 'gl_test_func': 'glRenderbufferStorageMultisampleEXT',
1927 'expectation': False,
1933 '// ReadPixels has the result separated from the pixel buffer so that\n'
1934 '// it is easier to specify the result going to some specific place\n'
1935 '// that exactly fits the rectangle of pixels.\n',
1939 'client_test': False,
1941 'GLint x, GLint y, GLsizei width, GLsizei height, '
1942 'GLenumReadPixelFormat format, GLenumReadPixelType type, '
1943 'uint32 pixels_shm_id, uint32 pixels_shm_offset, '
1944 'uint32 result_shm_id, uint32 result_shm_offset, '
1946 'result': ['uint32'],
1947 'defer_reads': True,
1949 'RegisterSharedIdsCHROMIUM': {
1951 'decoder_func': 'DoRegisterSharedIdsCHROMIUM',
1953 'expectation': False,
1958 'ReleaseShaderCompiler': {
1959 'decoder_func': 'DoReleaseShaderCompiler',
1964 'client_test': False,
1971 'client_test': False,
1973 'GLuint shader, const char* data',
1975 'GLuint shader, GLsizei count, const char** str, const GLint* length',
1978 'type': 'StateSetFrontBack',
1979 'state': 'StencilMask',
1981 'expectation': False,
1983 'StencilMaskSeparate': {
1984 'type': 'StateSetFrontBackSeparate',
1985 'state': 'StencilMask',
1987 'expectation': False,
1991 'decoder_func': 'DoSwapBuffers',
1993 'client_test': False,
1999 'client_test': False,
2002 'decoder_func': 'DoTexParameterf',
2003 'gl_test_func': 'glTexParameteri',
2009 'decoder_func': 'DoTexParameteri',
2016 'data_type': 'GLfloat',
2017 'data_value': 'GL_NEAREST',
2019 'decoder_func': 'DoTexParameterfv',
2020 'gl_test_func': 'glTexParameteri',
2021 'first_element_only': True,
2025 'data_type': 'GLint',
2026 'data_value': 'GL_NEAREST',
2028 'decoder_func': 'DoTexParameteriv',
2029 'gl_test_func': 'glTexParameteri',
2030 'first_element_only': True,
2035 'client_test': False,
2036 'cmd_args': 'GLenumTextureTarget target, GLint level, '
2037 'GLint xoffset, GLint yoffset, '
2038 'GLsizei width, GLsizei height, '
2039 'GLenumTextureFormat format, GLenumPixelType type, '
2040 'const void* pixels, GLboolean internal'
2042 'Uniform1f': {'type': 'PUTXn', 'data_type': 'GLfloat', 'count': 1},
2045 'data_type': 'GLfloat',
2047 'decoder_func': 'DoUniform1fv',
2049 'Uniform1i': {'decoder_func': 'DoUniform1i', 'unit_test': False},
2052 'data_type': 'GLint',
2054 'decoder_func': 'DoUniform1iv',
2057 'Uniform2i': {'type': 'PUTXn', 'data_type': 'GLint', 'count': 2},
2058 'Uniform2f': {'type': 'PUTXn', 'data_type': 'GLfloat', 'count': 2},
2061 'data_type': 'GLfloat',
2063 'decoder_func': 'DoUniform2fv',
2067 'data_type': 'GLint',
2069 'decoder_func': 'DoUniform2iv',
2071 'Uniform3i': {'type': 'PUTXn', 'data_type': 'GLint', 'count': 3},
2072 'Uniform3f': {'type': 'PUTXn', 'data_type': 'GLfloat', 'count': 3},
2075 'data_type': 'GLfloat',
2077 'decoder_func': 'DoUniform3fv',
2081 'data_type': 'GLint',
2083 'decoder_func': 'DoUniform3iv',
2085 'Uniform4i': {'type': 'PUTXn', 'data_type': 'GLint', 'count': 4},
2086 'Uniform4f': {'type': 'PUTXn', 'data_type': 'GLfloat', 'count': 4},
2089 'data_type': 'GLfloat',
2091 'decoder_func': 'DoUniform4fv',
2095 'data_type': 'GLint',
2097 'decoder_func': 'DoUniform4iv',
2099 'UniformMatrix2fv': {
2101 'data_type': 'GLfloat',
2103 'decoder_func': 'DoUniformMatrix2fv',
2105 'UniformMatrix3fv': {
2107 'data_type': 'GLfloat',
2109 'decoder_func': 'DoUniformMatrix3fv',
2111 'UniformMatrix4fv': {
2113 'data_type': 'GLfloat',
2115 'decoder_func': 'DoUniformMatrix4fv',
2117 'UnmapBufferCHROMIUM': {
2121 'client_test': False,
2123 'UnmapBufferSubDataCHROMIUM': {
2127 'client_test': False,
2128 'pepper_interface': 'ChromiumMapSub',
2130 'UnmapImageCHROMIUM': {
2134 'client_test': False,
2136 'UnmapTexSubImage2DCHROMIUM': {
2140 'client_test': False,
2141 'pepper_interface': 'ChromiumMapSub',
2144 'decoder_func': 'DoUseProgram',
2148 'ValidateProgram': {'decoder_func': 'DoValidateProgram'},
2149 'VertexAttrib1f': {'decoder_func': 'DoVertexAttrib1f'},
2150 'VertexAttrib1fv': {
2152 'data_type': 'GLfloat',
2154 'decoder_func': 'DoVertexAttrib1fv',
2156 'VertexAttrib2f': {'decoder_func': 'DoVertexAttrib2f'},
2157 'VertexAttrib2fv': {
2159 'data_type': 'GLfloat',
2161 'decoder_func': 'DoVertexAttrib2fv',
2163 'VertexAttrib3f': {'decoder_func': 'DoVertexAttrib3f'},
2164 'VertexAttrib3fv': {
2166 'data_type': 'GLfloat',
2168 'decoder_func': 'DoVertexAttrib3fv',
2170 'VertexAttrib4f': {'decoder_func': 'DoVertexAttrib4f'},
2171 'VertexAttrib4fv': {
2173 'data_type': 'GLfloat',
2175 'decoder_func': 'DoVertexAttrib4fv',
2177 'VertexAttribPointer': {
2179 'cmd_args': 'GLuint indx, GLintVertexAttribSize size, '
2180 'GLenumVertexAttribType type, GLboolean normalized, '
2181 'GLsizei stride, GLuint offset',
2182 'client_test': False,
2189 'decoder_func': 'DoViewport',
2198 'GetRequestableExtensionsCHROMIUM': {
2202 'cmd_args': 'uint32 bucket_id',
2206 'RequestExtensionCHROMIUM': {
2210 'client_test': False,
2211 'cmd_args': 'uint32 bucket_id',
2215 'RateLimitOffscreenContextCHROMIUM': {
2219 'client_test': False,
2221 'CreateStreamTextureCHROMIUM': {
2223 'cmd_args': 'GLuint client_id, void* result',
2224 'result': ['GLuint'],
2227 'expectation': False,
2230 'client_test': False,
2232 'DestroyStreamTextureCHROMIUM': {
2235 'expectation': False,
2239 'TexImageIOSurface2DCHROMIUM': {
2240 'decoder_func': 'DoTexImageIOSurface2DCHROMIUM',
2245 'CopyTextureCHROMIUM': {
2246 'decoder_func': 'DoCopyTextureCHROMIUM',
2251 'TexStorage2DEXT': {
2254 'decoder_func': 'DoTexStorage2DEXT',
2256 'DrawArraysInstancedANGLE': {
2258 'cmd_args': 'GLenumDrawMode mode, GLint first, GLsizei count, '
2259 'GLsizei primcount',
2262 'pepper_interface': 'InstancedArrays',
2263 'defer_draws': True,
2267 'decoder_func': 'DoDrawBuffersEXT',
2268 'data_type': 'GLenum',
2270 'client_test': False,
2274 'DrawElementsInstancedANGLE': {
2276 'cmd_args': 'GLenumDrawMode mode, GLsizei count, '
2277 'GLenumIndexType type, GLuint index_offset, GLsizei primcount',
2280 'client_test': False,
2281 'pepper_interface': 'InstancedArrays',
2282 'defer_draws': True,
2284 'VertexAttribDivisorANGLE': {
2286 'cmd_args': 'GLuint index, GLuint divisor',
2289 'pepper_interface': 'InstancedArrays',
2293 'gl_test_func': 'glGenQueriesARB',
2294 'resource_type': 'Query',
2295 'resource_types': 'Queries',
2297 'pepper_interface': 'Query',
2299 'DeleteQueriesEXT': {
2301 'gl_test_func': 'glDeleteQueriesARB',
2302 'resource_type': 'Query',
2303 'resource_types': 'Queries',
2305 'pepper_interface': 'Query',
2309 'client_test': False,
2310 'pepper_interface': 'Query',
2314 'cmd_args': 'GLenumQueryTarget target, GLidQuery id, void* sync_data',
2316 'gl_test_func': 'glBeginQuery',
2317 'pepper_interface': 'Query',
2321 'cmd_args': 'GLenumQueryTarget target, GLuint submit_count',
2322 'gl_test_func': 'glEndnQuery',
2323 'client_test': False,
2324 'pepper_interface': 'Query',
2328 'client_test': False,
2329 'gl_test_func': 'glGetQueryiv',
2330 'pepper_interface': 'Query',
2332 'GetQueryObjectuivEXT': {
2334 'client_test': False,
2335 'gl_test_func': 'glGetQueryObjectuiv',
2336 'pepper_interface': 'Query',
2338 'BindUniformLocationCHROMIUM': {
2343 'gl_test_func': 'DoBindUniformLocationCHROMIUM',
2346 'InsertEventMarkerEXT': {
2348 'decoder_func': 'DoInsertEventMarkerEXT',
2349 'expectation': False,
2352 'PushGroupMarkerEXT': {
2354 'decoder_func': 'DoPushGroupMarkerEXT',
2355 'expectation': False,
2358 'PopGroupMarkerEXT': {
2359 'decoder_func': 'DoPopGroupMarkerEXT',
2360 'expectation': False,
2365 'GenVertexArraysOES': {
2368 'gl_test_func': 'glGenVertexArraysOES',
2369 'resource_type': 'VertexArray',
2370 'resource_types': 'VertexArrays',
2373 'BindVertexArrayOES': {
2376 'gl_test_func': 'glBindVertexArrayOES',
2377 'decoder_func': 'DoBindVertexArrayOES',
2378 'gen_func': 'GenVertexArraysOES',
2380 'client_test': False,
2382 'DeleteVertexArraysOES': {
2385 'gl_test_func': 'glDeleteVertexArraysOES',
2386 'resource_type': 'VertexArray',
2387 'resource_types': 'VertexArrays',
2390 'IsVertexArrayOES': {
2393 'gl_test_func': 'glIsVertexArrayOES',
2394 'decoder_func': 'DoIsVertexArrayOES',
2395 'expectation': False,
2398 'BindTexImage2DCHROMIUM': {
2399 'decoder_func': 'DoBindTexImage2DCHROMIUM',
2404 'ReleaseTexImage2DCHROMIUM': {
2405 'decoder_func': 'DoReleaseTexImage2DCHROMIUM',
2410 'ShallowFinishCHROMIUM': {
2415 'client_test': False,
2417 'ShallowFlushCHROMIUM': {
2422 'client_test': False,
2424 'TraceBeginCHROMIUM': {
2428 'client_test': False,
2429 'cmd_args': 'GLuint bucket_id',
2433 'TraceEndCHROMIUM': {
2436 'client_test': False,
2437 'decoder_func': 'DoTraceEndCHROMIUM',
2442 'AsyncTexImage2DCHROMIUM': {
2445 'client_test': False,
2449 'AsyncTexSubImage2DCHROMIUM': {
2452 'client_test': False,
2456 'WaitAsyncTexImage2DCHROMIUM': {
2459 'client_test': False,
2463 'DiscardFramebufferEXT': {
2466 'data_type': 'GLenum',
2467 'cmd_args': 'GLenum target, GLsizei count, '
2468 'const GLenum* attachments',
2469 'decoder_func': 'DoDiscardFramebufferEXT',
2471 'client_test': False,
2474 'LoseContextCHROMIUM': {
2480 'InsertSyncPointCHROMIUM': {
2481 'type': 'HandWritten',
2486 'WaitSyncPointCHROMIUM': {
2492 'DiscardBackbufferCHROMIUM': {
2501 def Grouper(n
, iterable
, fillvalue
=None):
2502 """Collect data into fixed-length chunks or blocks"""
2503 args
= [iter(iterable
)] * n
2504 return itertools
.izip_longest(fillvalue
=fillvalue
, *args
)
2507 def SplitWords(input_string
):
2508 """Transforms a input_string into a list of lower-case components.
2511 input_string: the input string.
2514 a list of lower-case words.
2516 if input_string
.find('_') > -1:
2517 # 'some_TEXT_' -> 'some text'
2518 return input_string
.replace('_', ' ').strip().lower().split()
2520 if re
.search('[A-Z]', input_string
) and re
.search('[a-z]', input_string
):
2522 # look for capitalization to cut input_strings
2523 # 'SomeText' -> 'Some Text'
2524 input_string
= re
.sub('([A-Z])', r
' \1', input_string
).strip()
2525 # 'Vector3' -> 'Vector 3'
2526 input_string
= re
.sub('([^0-9])([0-9])', r
'\1 \2', input_string
)
2527 return input_string
.lower().split()
2531 """Makes a lower-case identifier from words.
2534 words: a list of lower-case words.
2537 the lower-case identifier.
2539 return '_'.join(words
)
2542 def ToUnderscore(input_string
):
2543 """converts CamelCase to camel_case."""
2544 words
= SplitWords(input_string
)
2548 class CWriter(object):
2549 """Writes to a file formatting it for Google's style guidelines."""
2551 def __init__(self
, filename
):
2552 self
.filename
= filename
2556 def SetFileNum(self
, num
):
2557 """Used to help write number files and tests."""
2560 def Write(self
, string
):
2561 """Writes a string to a file spliting if it's > 80 characters."""
2562 lines
= string
.splitlines()
2563 num_lines
= len(lines
)
2564 for ii
in range(0, num_lines
):
2565 self
.__WriteLine
(lines
[ii
], ii
< (num_lines
- 1) or string
[-1] == '\n')
2567 def __FindSplit(self
, string
):
2568 """Finds a place to split a string."""
2569 splitter
= string
.find('=')
2570 if splitter
>= 1 and not string
[splitter
+ 1] == '=' and splitter
< 80:
2572 # parts = string.split('(')
2573 parts
= re
.split("(?<=[^\"])\((?!\")", string
)
2574 fptr
= re
.compile('\*\w*\)')
2576 splitter
= len(parts
[0])
2577 for ii
in range(1, len(parts
)):
2578 # Don't split on the dot in "if (.condition)".
2579 if (not parts
[ii
- 1][-3:] == "if " and
2580 # Don't split "(.)" or "(.*fptr)".
2581 (len(parts
[ii
]) > 0 and
2582 not parts
[ii
][0] == ")" and not fptr
.match(parts
[ii
]))
2585 splitter
+= len(parts
[ii
]) + 1
2590 splitter
= string
[0:end
].rfind(',')
2591 if splitter
< 0 or (splitter
> 0 and string
[splitter
- 1] == '"'):
2592 return last_splitter
2593 elif splitter
>= 80:
2598 def __WriteLine(self
, line
, ends_with_eol
):
2599 """Given a signle line, writes it to a file, splitting if it's > 80 chars"""
2601 i
= self
.__FindSplit
(line
)
2603 line1
= line
[0:i
+ 1]
2604 if line1
[-1] == ' ':
2611 nolint
= ' // NOLINT'
2612 self
.__AddLine
(line1
+ nolint
+ lineend
+ '\n')
2613 match
= re
.match("( +)", line1
)
2616 indent
= match
.group(1)
2618 if not splitter
== ',':
2619 indent
= " " + indent
2620 self
.__WriteLine
(indent
+ line
[i
+ 1:].lstrip(), True)
2624 nolint
= ' // NOLINT'
2625 self
.__AddLine
(line
+ nolint
)
2627 self
.__AddLine
('\n')
2629 def __AddLine(self
, line
):
2630 self
.content
.append(line
)
2633 """Close the file."""
2634 content
= "".join(self
.content
)
2636 if os
.path
.exists(self
.filename
):
2637 old_file
= open(self
.filename
, "rb");
2638 old_content
= old_file
.read()
2640 if content
== old_content
:
2643 file = open(self
.filename
, "wb")
2648 class CHeaderWriter(CWriter
):
2649 """Writes a C Header file."""
2651 _non_alnum_re
= re
.compile(r
'[^a-zA-Z0-9]')
2653 def __init__(self
, filename
, file_comment
= None):
2654 CWriter
.__init
__(self
, filename
)
2656 base
= os
.path
.abspath(filename
)
2657 while os
.path
.basename(base
) != 'src':
2658 new_base
= os
.path
.dirname(base
)
2659 assert new_base
!= base
# Prevent infinite loop.
2662 hpath
= os
.path
.relpath(filename
, base
)
2663 self
.guard
= self
._non
_alnum
_re
.sub('_', hpath
).upper() + '_'
2665 self
.Write(_LICENSE
)
2666 self
.Write(_DO_NOT_EDIT_WARNING
)
2667 if not file_comment
== None:
2668 self
.Write(file_comment
)
2669 self
.Write("#ifndef %s\n" % self
.guard
)
2670 self
.Write("#define %s\n\n" % self
.guard
)
2673 self
.Write("#endif // %s\n\n" % self
.guard
)
2676 class TypeHandler(object):
2677 """This class emits code for a particular type of function."""
2679 _remove_expected_call_re
= re
.compile(r
' EXPECT_CALL.*?;\n', re
.S
)
2684 def InitFunction(self
, func
):
2685 """Add or adjust anything type specific for this function."""
2686 if func
.GetInfo('needs_size') and not func
.name
.endswith('Bucket'):
2687 func
.AddCmdArg(DataSizeArgument('data_size'))
2689 def AddImmediateFunction(self
, generator
, func
):
2690 """Adds an immediate version of a function."""
2691 # Generate an immediate command if there is only 1 pointer arg.
2692 immediate
= func
.GetInfo('immediate') # can be True, False or None
2693 if immediate
== True or immediate
== None:
2694 if func
.num_pointer_args
== 1 or immediate
:
2695 generator
.AddFunction(ImmediateFunction(func
))
2697 def AddBucketFunction(self
, generator
, func
):
2698 """Adds a bucket version of a function."""
2699 # Generate an immediate command if there is only 1 pointer arg.
2700 bucket
= func
.GetInfo('bucket') # can be True, False or None
2702 generator
.AddFunction(BucketFunction(func
))
2704 def WriteStruct(self
, func
, file):
2705 """Writes a structure that matches the arguments to a function."""
2706 comment
= func
.GetInfo('cmd_comment')
2707 if not comment
== None:
2709 file.Write("struct %s {\n" % func
.name
)
2710 file.Write(" typedef %s ValueType;\n" % func
.name
)
2711 file.Write(" static const CommandId kCmdId = k%s;\n" % func
.name
)
2712 func
.WriteCmdArgFlag(file)
2714 result
= func
.GetInfo('result')
2715 if not result
== None:
2716 if len(result
) == 1:
2717 file.Write(" typedef %s Result;\n\n" % result
[0])
2719 file.Write(" struct Result {\n")
2721 file.Write(" %s;\n" % line
)
2722 file.Write(" };\n\n")
2724 func
.WriteCmdComputeSize(file)
2725 func
.WriteCmdSetHeader(file)
2726 func
.WriteCmdInit(file)
2727 func
.WriteCmdSet(file)
2729 file.Write(" gpu::CommandHeader header;\n")
2730 args
= func
.GetCmdArgs()
2732 file.Write(" %s %s;\n" % (arg
.cmd_type
, arg
.name
))
2736 size
= len(args
) * _SIZE_OF_UINT32
+ _SIZE_OF_COMMAND_HEADER
2737 file.Write("COMPILE_ASSERT(sizeof(%s) == %d,\n" % (func
.name
, size
))
2738 file.Write(" Sizeof_%s_is_not_%d);\n" % (func
.name
, size
))
2739 file.Write("COMPILE_ASSERT(offsetof(%s, header) == 0,\n" % func
.name
)
2740 file.Write(" OffsetOf_%s_header_not_0);\n" % func
.name
)
2741 offset
= _SIZE_OF_COMMAND_HEADER
2743 file.Write("COMPILE_ASSERT(offsetof(%s, %s) == %d,\n" %
2744 (func
.name
, arg
.name
, offset
))
2745 file.Write(" OffsetOf_%s_%s_not_%d);\n" %
2746 (func
.name
, arg
.name
, offset
))
2747 offset
+= _SIZE_OF_UINT32
2748 if not result
== None and len(result
) > 1:
2751 parts
= line
.split()
2754 COMPILE_ASSERT(offsetof(%(cmd_name)s::Result, %(field_name)s) == %(offset)d,
2755 OffsetOf_%(cmd_name)s_Result_%(field_name)s_not_%(offset)d);
2757 file.Write((check
.strip() + "\n") % {
2758 'cmd_name': func
.name
,
2762 offset
+= _SIZE_OF_UINT32
2765 def WriteHandlerImplementation(self
, func
, file):
2766 """Writes the handler implementation for this command."""
2767 file.Write(" %s(%s);\n" %
2768 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
2770 def WriteCmdSizeTest(self
, func
, file):
2771 """Writes the size test for a command."""
2772 file.Write(" EXPECT_EQ(sizeof(cmd), cmd.header.size * 4u);\n")
2774 def WriteFormatTest(self
, func
, file):
2775 """Writes a format test for a command."""
2776 file.Write("TEST_F(GLES2FormatTest, %s) {\n" % func
.name
)
2777 file.Write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
2778 (func
.name
, func
.name
))
2779 file.Write(" void* next_cmd = cmd.Set(\n")
2781 args
= func
.GetCmdArgs()
2782 for value
, arg
in enumerate(args
):
2783 file.Write(",\n static_cast<%s>(%d)" % (arg
.type, value
+ 11))
2785 file.Write(" EXPECT_EQ(static_cast<uint32>(cmds::%s::kCmdId),\n" %
2787 file.Write(" cmd.header.command);\n")
2788 func
.type_handler
.WriteCmdSizeTest(func
, file)
2789 for value
, arg
in enumerate(args
):
2790 file.Write(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);\n" %
2791 (arg
.type, value
+ 11, arg
.name
))
2792 file.Write(" CheckBytesWrittenMatchesExpectedSize(\n")
2793 file.Write(" next_cmd, sizeof(cmd));\n")
2797 def WriteImmediateFormatTest(self
, func
, file):
2798 """Writes a format test for an immediate version of a command."""
2801 def WriteBucketFormatTest(self
, func
, file):
2802 """Writes a format test for a bucket version of a command."""
2805 def WriteGetDataSizeCode(self
, func
, file):
2806 """Writes the code to set data_size used in validation"""
2809 def WriteImmediateCmdSizeTest(self
, func
, file):
2810 """Writes a size test for an immediate version of a command."""
2811 file.Write(" // TODO(gman): Compute correct size.\n")
2812 file.Write(" EXPECT_EQ(sizeof(cmd), cmd.header.size * 4u);\n")
2814 def WriteImmediateHandlerImplementation (self
, func
, file):
2815 """Writes the handler impl for the immediate version of a command."""
2816 file.Write(" %s(%s);\n" %
2817 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
2819 def WriteBucketHandlerImplementation (self
, func
, file):
2820 """Writes the handler impl for the bucket version of a command."""
2821 file.Write(" %s(%s);\n" %
2822 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
2824 def WriteServiceImplementation(self
, func
, file):
2825 """Writes the service implementation for a command."""
2827 "error::Error GLES2DecoderImpl::Handle%s(\n" % func
.name
)
2829 " uint32 immediate_data_size, const gles2::cmds::%s& c) {\n" %
2831 self
.WriteHandlerDeferReadWrite(func
, file);
2832 if len(func
.GetOriginalArgs()) > 0:
2833 last_arg
= func
.GetLastOriginalArg()
2834 all_but_last_arg
= func
.GetOriginalArgs()[:-1]
2835 for arg
in all_but_last_arg
:
2836 arg
.WriteGetCode(file)
2837 self
.WriteGetDataSizeCode(func
, file)
2838 last_arg
.WriteGetCode(file)
2839 func
.WriteHandlerValidation(file)
2840 func
.WriteHandlerImplementation(file)
2841 file.Write(" return error::kNoError;\n")
2845 def WriteImmediateServiceImplementation(self
, func
, file):
2846 """Writes the service implementation for an immediate version of command."""
2848 "error::Error GLES2DecoderImpl::Handle%s(\n" % func
.name
)
2850 " uint32 immediate_data_size, const gles2::cmds::%s& c) {\n" %
2852 self
.WriteHandlerDeferReadWrite(func
, file);
2853 last_arg
= func
.GetLastOriginalArg()
2854 all_but_last_arg
= func
.GetOriginalArgs()[:-1]
2855 for arg
in all_but_last_arg
:
2856 arg
.WriteGetCode(file)
2857 self
.WriteGetDataSizeCode(func
, file)
2858 last_arg
.WriteGetCode(file)
2859 func
.WriteHandlerValidation(file)
2860 func
.WriteHandlerImplementation(file)
2861 file.Write(" return error::kNoError;\n")
2865 def WriteBucketServiceImplementation(self
, func
, file):
2866 """Writes the service implementation for a bucket version of command."""
2868 "error::Error GLES2DecoderImpl::Handle%s(\n" % func
.name
)
2870 " uint32 immediate_data_size, const gles2::cmds::%s& c) {\n" %
2872 self
.WriteHandlerDeferReadWrite(func
, file);
2873 last_arg
= func
.GetLastOriginalArg()
2874 all_but_last_arg
= func
.GetOriginalArgs()[:-1]
2875 for arg
in all_but_last_arg
:
2876 arg
.WriteGetCode(file)
2877 self
.WriteGetDataSizeCode(func
, file)
2878 last_arg
.WriteGetCode(file)
2879 func
.WriteHandlerValidation(file)
2880 func
.WriteHandlerImplementation(file)
2881 file.Write(" return error::kNoError;\n")
2885 def WriteHandlerDeferReadWrite(self
, func
, file):
2886 """Writes the code to handle deferring reads or writes."""
2887 defer_draws
= func
.GetInfo('defer_draws')
2888 defer_reads
= func
.GetInfo('defer_reads')
2889 if defer_draws
or defer_reads
:
2890 file.Write(" error::Error error;\n")
2892 file.Write(" error = WillAccessBoundFramebufferForDraw();\n")
2893 file.Write(" if (error != error::kNoError)\n")
2894 file.Write(" return error;\n")
2896 file.Write(" error = WillAccessBoundFramebufferForRead();\n")
2897 file.Write(" if (error != error::kNoError)\n")
2898 file.Write(" return error;\n")
2900 def WriteValidUnitTest(self
, func
, file, test
, extra
= {}):
2901 """Writes a valid unit test."""
2902 if func
.GetInfo('expectation') == False:
2903 test
= self
._remove
_expected
_call
_re
.sub('', test
)
2906 for count
, arg
in enumerate(func
.GetOriginalArgs()):
2907 arg_strings
.append(arg
.GetValidArg(func
, count
, 0))
2909 for count
, arg
in enumerate(func
.GetOriginalArgs()):
2910 gl_arg_strings
.append(arg
.GetValidGLArg(func
, count
, 0))
2911 gl_func_name
= func
.GetGLTestFunctionName()
2913 'test_name': 'GLES2DecoderTest%d' % file.file_num
,
2915 'gl_func_name': gl_func_name
,
2916 'args': ", ".join(arg_strings
),
2917 'gl_args': ", ".join(gl_arg_strings
),
2921 while (old_test
!= test
):
2924 file.Write(test
% vars)
2926 def WriteInvalidUnitTest(self
, func
, file, test
, extra
= {}):
2927 """Writes a invalid unit test."""
2928 for arg_index
, arg
in enumerate(func
.GetOriginalArgs()):
2929 num_invalid_values
= arg
.GetNumInvalidValues(func
)
2930 for value_index
in range(0, num_invalid_values
):
2932 parse_result
= "kNoError"
2934 for count
, arg
in enumerate(func
.GetOriginalArgs()):
2935 if count
== arg_index
:
2936 (arg_string
, parse_result
, gl_error
) = arg
.GetInvalidArg(
2939 arg_string
= arg
.GetValidArg(func
, count
, 0)
2940 arg_strings
.append(arg_string
)
2942 for arg
in func
.GetOriginalArgs():
2943 gl_arg_strings
.append("_")
2944 gl_func_name
= func
.GetGLTestFunctionName()
2946 if not gl_error
== None:
2947 gl_error_test
= '\n EXPECT_EQ(%s, GetGLError());' % gl_error
2950 'test_name': 'GLES2DecoderTest%d' % file.file_num
,
2952 'arg_index': arg_index
,
2953 'value_index': value_index
,
2954 'gl_func_name': gl_func_name
,
2955 'args': ", ".join(arg_strings
),
2956 'all_but_last_args': ", ".join(arg_strings
[:-1]),
2957 'gl_args': ", ".join(gl_arg_strings
),
2958 'parse_result': parse_result
,
2959 'gl_error_test': gl_error_test
,
2962 file.Write(test
% vars)
2964 def WriteServiceUnitTest(self
, func
, file):
2965 """Writes the service unit test for a command."""
2967 TEST_F(%(test_name)s, %(name)sValidArgs) {
2968 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
2969 SpecializedSetup<cmds::%(name)s, 0>(true);
2972 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
2973 EXPECT_EQ(GL_NO_ERROR, GetGLError());
2976 self
.WriteValidUnitTest(func
, file, valid_test
)
2979 TEST_F(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
2980 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
2981 SpecializedSetup<cmds::%(name)s, 0>(false);
2984 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
2987 self
.WriteInvalidUnitTest(func
, file, invalid_test
)
2989 def WriteImmediateServiceUnitTest(self
, func
, file):
2990 """Writes the service unit test for an immediate command."""
2991 file.Write("// TODO(gman): %s\n" % func
.name
)
2993 def WriteImmediateValidationCode(self
, func
, file):
2994 """Writes the validation code for an immediate version of a command."""
2997 def WriteBucketServiceUnitTest(self
, func
, file):
2998 """Writes the service unit test for a bucket command."""
2999 file.Write("// TODO(gman): %s\n" % func
.name
)
3001 def WriteBucketValidationCode(self
, func
, file):
3002 """Writes the validation code for a bucket version of a command."""
3003 file.Write("// TODO(gman): %s\n" % func
.name
)
3005 def WriteGLES2ImplementationDeclaration(self
, func
, file):
3006 """Writes the GLES2 Implemention declaration."""
3007 impl_decl
= func
.GetInfo('impl_decl')
3008 if impl_decl
== None or impl_decl
== True:
3009 file.Write("virtual %s %s(%s) OVERRIDE;\n" %
3010 (func
.return_type
, func
.original_name
,
3011 func
.MakeTypedOriginalArgString("")))
3014 def WriteGLES2CLibImplementation(self
, func
, file):
3015 file.Write("%s GLES2%s(%s) {\n" %
3016 (func
.return_type
, func
.name
,
3017 func
.MakeTypedOriginalArgString("")))
3018 result_string
= "return "
3019 if func
.return_type
== "void":
3021 file.Write(" %sgles2::GetGLContext()->%s(%s);\n" %
3022 (result_string
, func
.original_name
,
3023 func
.MakeOriginalArgString("")))
3026 def WriteGLES2Header(self
, func
, file):
3027 """Writes a re-write macro for GLES"""
3028 file.Write("#define gl%s GLES2_GET_FUN(%s)\n" %(func
.name
, func
.name
))
3030 def WriteClientGLCallLog(self
, func
, file):
3031 """Writes a logging macro for the client side code."""
3033 if len(func
.GetOriginalArgs()):
3036 ' GPU_CLIENT_LOG("[" << GetLogPrefix() << "] gl%s("%s%s << ")");\n' %
3037 (func
.original_name
, comma
, func
.MakeLogArgString()))
3039 def WriteClientGLReturnLog(self
, func
, file):
3040 """Writes the return value logging code."""
3041 if func
.return_type
!= "void":
3042 file.Write(' GPU_CLIENT_LOG("return:" << result)\n')
3044 def WriteGLES2ImplementationHeader(self
, func
, file):
3045 """Writes the GLES2 Implemention."""
3046 self
.WriteGLES2ImplementationDeclaration(func
, file)
3048 def WriteGLES2TraceImplementationHeader(self
, func
, file):
3049 """Writes the GLES2 Trace Implemention header."""
3050 file.Write("virtual %s %s(%s) OVERRIDE;\n" %
3051 (func
.return_type
, func
.original_name
,
3052 func
.MakeTypedOriginalArgString("")))
3054 def WriteGLES2TraceImplementation(self
, func
, file):
3055 """Writes the GLES2 Trace Implemention."""
3056 file.Write("%s GLES2TraceImplementation::%s(%s) {\n" %
3057 (func
.return_type
, func
.original_name
,
3058 func
.MakeTypedOriginalArgString("")))
3059 result_string
= "return "
3060 if func
.return_type
== "void":
3062 file.Write(' TRACE_EVENT_BINARY_EFFICIENT0("gpu", "GLES2Trace::%s");\n' %
3064 file.Write(" %sgl_->%s(%s);\n" %
3065 (result_string
, func
.name
, func
.MakeOriginalArgString("")))
3069 def WriteGLES2Implementation(self
, func
, file):
3070 """Writes the GLES2 Implemention."""
3071 impl_func
= func
.GetInfo('impl_func')
3072 impl_decl
= func
.GetInfo('impl_decl')
3073 gen_cmd
= func
.GetInfo('gen_cmd')
3074 if (func
.can_auto_generate
and
3075 (impl_func
== None or impl_func
== True) and
3076 (impl_decl
== None or impl_decl
== True) and
3077 (gen_cmd
== None or gen_cmd
== True)):
3078 file.Write("%s GLES2Implementation::%s(%s) {\n" %
3079 (func
.return_type
, func
.original_name
,
3080 func
.MakeTypedOriginalArgString("")))
3081 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
3082 self
.WriteClientGLCallLog(func
, file)
3083 func
.WriteDestinationInitalizationValidation(file)
3084 for arg
in func
.GetOriginalArgs():
3085 arg
.WriteClientSideValidationCode(file, func
)
3086 file.Write(" helper_->%s(%s);\n" %
3087 (func
.name
, func
.MakeOriginalArgString("")))
3088 file.Write(" CheckGLError();\n")
3089 self
.WriteClientGLReturnLog(func
, file)
3093 def WriteGLES2InterfaceHeader(self
, func
, file):
3094 """Writes the GLES2 Interface."""
3095 file.Write("virtual %s %s(%s) = 0;\n" %
3096 (func
.return_type
, func
.original_name
,
3097 func
.MakeTypedOriginalArgString("")))
3099 def WriteGLES2InterfaceStub(self
, func
, file):
3100 """Writes the GLES2 Interface stub declaration."""
3101 file.Write("virtual %s %s(%s) OVERRIDE;\n" %
3102 (func
.return_type
, func
.original_name
,
3103 func
.MakeTypedOriginalArgString("")))
3105 def WriteGLES2InterfaceStubImpl(self
, func
, file):
3106 """Writes the GLES2 Interface stub declaration."""
3107 args
= func
.GetOriginalArgs()
3108 arg_string
= ", ".join(
3109 ["%s /* %s */" % (arg
.type, arg
.name
) for arg
in args
])
3110 file.Write("%s GLES2InterfaceStub::%s(%s) {\n" %
3111 (func
.return_type
, func
.original_name
, arg_string
))
3112 if func
.return_type
!= "void":
3113 file.Write(" return 0;\n")
3116 def WriteGLES2ImplementationUnitTest(self
, func
, file):
3117 """Writes the GLES2 Implemention unit test."""
3118 client_test
= func
.GetInfo('client_test')
3119 if (func
.can_auto_generate
and
3120 (client_test
== None or client_test
== True)):
3122 TEST_F(GLES2ImplementationTest, %(name)s) {
3127 expected.cmd.Init(%(cmd_args)s);
3129 gl_->%(name)s(%(args)s);
3130 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
3133 cmd_arg_strings
= []
3134 for count
, arg
in enumerate(func
.GetCmdArgs()):
3135 cmd_arg_strings
.append(arg
.GetValidClientSideCmdArg(func
, count
, 0))
3138 for count
, arg
in enumerate(func
.GetOriginalArgs()):
3139 gl_arg_strings
.append(arg
.GetValidClientSideArg(func
, count
, 0))
3142 'args': ", ".join(gl_arg_strings
),
3143 'cmd_args': ", ".join(cmd_arg_strings
),
3146 if client_test
!= False:
3147 file.Write("// TODO: Implement unit test for %s\n" % func
.name
)
3149 def WriteDestinationInitalizationValidation(self
, func
, file):
3150 """Writes the client side destintion initialization validation."""
3151 for arg
in func
.GetOriginalArgs():
3152 arg
.WriteDestinationInitalizationValidation(file, func
)
3154 def WriteTraceEvent(self
, func
, file):
3155 file.Write(' TRACE_EVENT0("gpu", "GLES2Implementation::%s");\n' %
3158 def WriteImmediateCmdComputeSize(self
, func
, file):
3159 """Writes the size computation code for the immediate version of a cmd."""
3160 file.Write(" static uint32 ComputeSize(uint32 size_in_bytes) {\n")
3161 file.Write(" return static_cast<uint32>(\n")
3162 file.Write(" sizeof(ValueType) + // NOLINT\n")
3163 file.Write(" RoundSizeToMultipleOfEntries(size_in_bytes));\n")
3167 def WriteImmediateCmdSetHeader(self
, func
, file):
3168 """Writes the SetHeader function for the immediate version of a cmd."""
3169 file.Write(" void SetHeader(uint32 size_in_bytes) {\n")
3170 file.Write(" header.SetCmdByTotalSize<ValueType>(size_in_bytes);\n")
3174 def WriteImmediateCmdInit(self
, func
, file):
3175 """Writes the Init function for the immediate version of a command."""
3176 raise NotImplementedError(func
.name
)
3178 def WriteImmediateCmdSet(self
, func
, file):
3179 """Writes the Set function for the immediate version of a command."""
3180 raise NotImplementedError(func
.name
)
3182 def WriteCmdHelper(self
, func
, file):
3183 """Writes the cmd helper definition for a cmd."""
3184 code
= """ void %(name)s(%(typed_args)s) {
3185 gles2::cmds::%(name)s* c = GetCmdSpace<gles2::cmds::%(name)s>();
3194 "typed_args": func
.MakeTypedCmdArgString(""),
3195 "args": func
.MakeCmdArgString(""),
3198 def WriteImmediateCmdHelper(self
, func
, file):
3199 """Writes the cmd helper definition for the immediate version of a cmd."""
3200 code
= """ void %(name)s(%(typed_args)s) {
3201 const uint32 s = 0; // TODO(gman): compute correct size
3202 gles2::cmds::%(name)s* c =
3203 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(s);
3212 "typed_args": func
.MakeTypedCmdArgString(""),
3213 "args": func
.MakeCmdArgString(""),
3217 class StateSetHandler(TypeHandler
):
3218 """Handler for commands that simply set state."""
3221 TypeHandler
.__init
__(self
)
3223 def WriteHandlerImplementation(self
, func
, file):
3224 """Overrriden from TypeHandler."""
3225 state_name
= func
.GetInfo('state')
3226 state
= _STATES
[state_name
]
3227 states
= state
['states']
3228 args
= func
.GetOriginalArgs()
3230 for ndx
,item
in enumerate(states
):
3231 if 'range_checks' in item
:
3232 for range_check
in item
['range_checks']:
3233 code
.append("%s %s" % (args
[ndx
].name
, range_check
['check']))
3235 file.Write(" if (%s) {\n" % " ||\n ".join(code
))
3237 ' LOCAL_SET_GL_ERROR(GL_INVALID_VALUE,'
3238 ' "%s", "%s out of range");\n' %
3239 (func
.name
, args
[ndx
].name
))
3240 file.Write(" return error::kNoError;\n")
3243 for ndx
,item
in enumerate(states
):
3244 code
.append("state_.%s != %s" % (item
['name'], args
[ndx
].name
))
3245 file.Write(" if (%s) {\n" % " ||\n ".join(code
))
3246 for ndx
,item
in enumerate(states
):
3247 file.Write(" state_.%s = %s;\n" % (item
['name'], args
[ndx
].name
))
3248 if 'state_flag' in state
:
3249 file.Write(" %s = true;\n" % state
['state_flag'])
3250 if not func
.GetInfo("no_gl"):
3251 file.Write(" %s(%s);\n" %
3252 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
3255 def WriteServiceUnitTest(self
, func
, file):
3256 """Overrriden from TypeHandler."""
3257 TypeHandler
.WriteServiceUnitTest(self
, func
, file)
3258 state_name
= func
.GetInfo('state')
3259 state
= _STATES
[state_name
]
3260 states
= state
['states']
3261 for ndx
,item
in enumerate(states
):
3262 if 'range_checks' in item
:
3263 for check_ndx
, range_check
in enumerate(item
['range_checks']):
3265 TEST_F(%(test_name)s, %(name)sInvalidValue%(ndx)d_%(check_ndx)d) {
3266 SpecializedSetup<cmds::%(name)s, 0>(false);
3269 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
3270 EXPECT_EQ(GL_INVALID_VALUE, GetGLError());
3275 for count
, arg
in enumerate(func
.GetOriginalArgs()):
3276 arg_strings
.append(arg
.GetValidArg(func
, count
, 0))
3277 arg_strings
[ndx
] = range_check
['test_value']
3279 'test_name': 'GLES2DecoderTest%d' % file.file_num
,
3282 'check_ndx': check_ndx
,
3283 'args': ", ".join(arg_strings
),
3285 file.Write(valid_test
% vars)
3288 class StateSetRGBAlphaHandler(TypeHandler
):
3289 """Handler for commands that simply set state that have rgb/alpha."""
3292 TypeHandler
.__init
__(self
)
3294 def WriteHandlerImplementation(self
, func
, file):
3295 """Overrriden from TypeHandler."""
3296 state_name
= func
.GetInfo('state')
3297 state
= _STATES
[state_name
]
3298 states
= state
['states']
3299 args
= func
.GetOriginalArgs()
3300 num_args
= len(args
)
3302 for ndx
,item
in enumerate(states
):
3303 code
.append("state_.%s != %s" % (item
['name'], args
[ndx
% num_args
].name
))
3304 file.Write(" if (%s) {\n" % " ||\n ".join(code
))
3305 for ndx
, item
in enumerate(states
):
3306 file.Write(" state_.%s = %s;\n" %
3307 (item
['name'], args
[ndx
% num_args
].name
))
3308 if 'state_flag' in state
:
3309 file.Write(" %s = true;\n" % state
['state_flag'])
3310 if not func
.GetInfo("no_gl"):
3311 file.Write(" %s(%s);\n" %
3312 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
3316 class StateSetFrontBackSeparateHandler(TypeHandler
):
3317 """Handler for commands that simply set state that have front/back."""
3320 TypeHandler
.__init
__(self
)
3322 def WriteHandlerImplementation(self
, func
, file):
3323 """Overrriden from TypeHandler."""
3324 state_name
= func
.GetInfo('state')
3325 state
= _STATES
[state_name
]
3326 states
= state
['states']
3327 args
= func
.GetOriginalArgs()
3329 num_args
= len(args
)
3330 file.Write(" bool changed = false;\n")
3331 for group_ndx
, group
in enumerate(Grouper(num_args
- 1, states
)):
3332 file.Write(" if (%s == %s || %s == GL_FRONT_AND_BACK) {\n" %
3333 (face
, ('GL_FRONT', 'GL_BACK')[group_ndx
], face
))
3335 for ndx
, item
in enumerate(group
):
3336 code
.append("state_.%s != %s" % (item
['name'], args
[ndx
+ 1].name
))
3337 file.Write(" changed |= %s;\n" % " ||\n ".join(code
))
3339 file.Write(" if (changed) {\n")
3340 for group_ndx
, group
in enumerate(Grouper(num_args
- 1, states
)):
3341 file.Write(" if (%s == %s || %s == GL_FRONT_AND_BACK) {\n" %
3342 (face
, ('GL_FRONT', 'GL_BACK')[group_ndx
], face
))
3343 for ndx
, item
in enumerate(group
):
3344 file.Write(" state_.%s = %s;\n" %
3345 (item
['name'], args
[ndx
+ 1].name
))
3347 if 'state_flag' in state
:
3348 file.Write(" %s = true;\n" % state
['state_flag'])
3349 if not func
.GetInfo("no_gl"):
3350 file.Write(" %s(%s);\n" %
3351 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
3355 class StateSetFrontBackHandler(TypeHandler
):
3356 """Handler for commands that simply set state that set both front/back."""
3359 TypeHandler
.__init
__(self
)
3361 def WriteHandlerImplementation(self
, func
, file):
3362 """Overrriden from TypeHandler."""
3363 state_name
= func
.GetInfo('state')
3364 state
= _STATES
[state_name
]
3365 states
= state
['states']
3366 args
= func
.GetOriginalArgs()
3367 num_args
= len(args
)
3369 for group_ndx
, group
in enumerate(Grouper(num_args
, states
)):
3370 for ndx
, item
in enumerate(group
):
3371 code
.append("state_.%s != %s" % (item
['name'], args
[ndx
].name
))
3372 file.Write(" if (%s) {\n" % " ||\n ".join(code
))
3373 for group_ndx
, group
in enumerate(Grouper(num_args
, states
)):
3374 for ndx
, item
in enumerate(group
):
3375 file.Write(" state_.%s = %s;\n" % (item
['name'], args
[ndx
].name
))
3376 if 'state_flag' in state
:
3377 file.Write(" %s = true;\n" % state
['state_flag'])
3378 if not func
.GetInfo("no_gl"):
3379 file.Write(" %s(%s);\n" %
3380 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
3384 class StateSetNamedParameter(TypeHandler
):
3385 """Handler for commands that set a state chosen with an enum parameter."""
3388 TypeHandler
.__init
__(self
)
3390 def WriteHandlerImplementation(self
, func
, file):
3391 """Overridden from TypeHandler."""
3392 state_name
= func
.GetInfo('state')
3393 state
= _STATES
[state_name
]
3394 states
= state
['states']
3395 args
= func
.GetOriginalArgs()
3396 num_args
= len(args
)
3397 assert num_args
== 2
3398 file.Write(" switch (%s) {\n" % args
[0].name
)
3399 for state
in states
:
3400 file.Write(" case %s:\n" % state
['enum'])
3401 file.Write(" if (state_.%s != %s) {\n" %
3402 (state
['name'], args
[1].name
))
3403 file.Write(" state_.%s = %s;\n" % (state
['name'], args
[1].name
))
3404 if not func
.GetInfo("no_gl"):
3405 file.Write(" %s(%s);\n" %
3406 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
3408 file.Write(" break;\n")
3409 file.Write(" default:\n")
3410 file.Write(" NOTREACHED();\n")
3414 class CustomHandler(TypeHandler
):
3415 """Handler for commands that are auto-generated but require minor tweaks."""
3418 TypeHandler
.__init
__(self
)
3420 def WriteServiceImplementation(self
, func
, file):
3421 """Overrriden from TypeHandler."""
3424 def WriteImmediateServiceImplementation(self
, func
, file):
3425 """Overrriden from TypeHandler."""
3428 def WriteBucketServiceImplementation(self
, func
, file):
3429 """Overrriden from TypeHandler."""
3432 def WriteServiceUnitTest(self
, func
, file):
3433 """Overrriden from TypeHandler."""
3434 file.Write("// TODO(gman): %s\n\n" % func
.name
)
3436 def WriteImmediateServiceUnitTest(self
, func
, file):
3437 """Overrriden from TypeHandler."""
3438 file.Write("// TODO(gman): %s\n\n" % func
.name
)
3440 def WriteImmediateCmdGetTotalSize(self
, func
, file):
3441 """Overrriden from TypeHandler."""
3442 file.Write(" uint32 total_size = 0; // TODO(gman): get correct size.\n")
3444 def WriteImmediateCmdInit(self
, func
, file):
3445 """Overrriden from TypeHandler."""
3446 file.Write(" void Init(%s) {\n" % func
.MakeTypedCmdArgString("_"))
3447 self
.WriteImmediateCmdGetTotalSize(func
, file)
3448 file.Write(" SetHeader(total_size);\n")
3449 args
= func
.GetCmdArgs()
3451 file.Write(" %s = _%s;\n" % (arg
.name
, arg
.name
))
3455 def WriteImmediateCmdSet(self
, func
, file):
3456 """Overrriden from TypeHandler."""
3457 copy_args
= func
.MakeCmdArgString("_", False)
3458 file.Write(" void* Set(void* cmd%s) {\n" %
3459 func
.MakeTypedCmdArgString("_", True))
3460 self
.WriteImmediateCmdGetTotalSize(func
, file)
3461 file.Write(" static_cast<ValueType*>(cmd)->Init(%s);\n" % copy_args
)
3462 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
3463 "cmd, total_size);\n")
3468 class TodoHandler(CustomHandler
):
3469 """Handle for commands that are not yet implemented."""
3471 def AddImmediateFunction(self
, generator
, func
):
3472 """Overrriden from TypeHandler."""
3475 def WriteImmediateFormatTest(self
, func
, file):
3476 """Overrriden from TypeHandler."""
3479 def WriteGLES2ImplementationUnitTest(self
, func
, file):
3480 """Overrriden from TypeHandler."""
3483 def WriteGLES2Implementation(self
, func
, file):
3484 """Overrriden from TypeHandler."""
3485 file.Write("%s GLES2Implementation::%s(%s) {\n" %
3486 (func
.return_type
, func
.original_name
,
3487 func
.MakeTypedOriginalArgString("")))
3488 file.Write(" // TODO: for now this is a no-op\n")
3491 "GL_INVALID_OPERATION, \"gl%s\", \"not implemented\");\n" %
3493 if func
.return_type
!= "void":
3494 file.Write(" return 0;\n")
3498 def WriteServiceImplementation(self
, func
, file):
3499 """Overrriden from TypeHandler."""
3501 "error::Error GLES2DecoderImpl::Handle%s(\n" % func
.name
)
3503 " uint32 immediate_data_size, const gles2::cmds::%s& c) {\n" %
3505 file.Write(" // TODO: for now this is a no-op\n")
3507 " LOCAL_SET_GL_ERROR("
3508 "GL_INVALID_OPERATION, \"gl%s\", \"not implemented\");\n" %
3510 file.Write(" return error::kNoError;\n")
3515 class HandWrittenHandler(CustomHandler
):
3516 """Handler for comands where everything must be written by hand."""
3518 def InitFunction(self
, func
):
3519 """Add or adjust anything type specific for this function."""
3520 CustomHandler
.InitFunction(self
, func
)
3521 func
.can_auto_generate
= False
3523 def WriteStruct(self
, func
, file):
3524 """Overrriden from TypeHandler."""
3527 def WriteDocs(self
, func
, file):
3528 """Overrriden from TypeHandler."""
3531 def WriteServiceUnitTest(self
, func
, file):
3532 """Overrriden from TypeHandler."""
3533 file.Write("// TODO(gman): %s\n\n" % func
.name
)
3535 def WriteImmediateServiceUnitTest(self
, func
, file):
3536 """Overrriden from TypeHandler."""
3537 file.Write("// TODO(gman): %s\n\n" % func
.name
)
3539 def WriteBucketServiceUnitTest(self
, func
, file):
3540 """Overrriden from TypeHandler."""
3541 file.Write("// TODO(gman): %s\n\n" % func
.name
)
3543 def WriteServiceImplementation(self
, func
, file):
3544 """Overrriden from TypeHandler."""
3547 def WriteImmediateServiceImplementation(self
, func
, file):
3548 """Overrriden from TypeHandler."""
3551 def WriteBucketServiceImplementation(self
, func
, file):
3552 """Overrriden from TypeHandler."""
3555 def WriteImmediateCmdHelper(self
, func
, file):
3556 """Overrriden from TypeHandler."""
3559 def WriteBucketCmdHelper(self
, func
, file):
3560 """Overrriden from TypeHandler."""
3563 def WriteCmdHelper(self
, func
, file):
3564 """Overrriden from TypeHandler."""
3567 def WriteFormatTest(self
, func
, file):
3568 """Overrriden from TypeHandler."""
3569 file.Write("// TODO(gman): Write test for %s\n" % func
.name
)
3571 def WriteImmediateFormatTest(self
, func
, file):
3572 """Overrriden from TypeHandler."""
3573 file.Write("// TODO(gman): Write test for %s\n" % func
.name
)
3575 def WriteBucketFormatTest(self
, func
, file):
3576 """Overrriden from TypeHandler."""
3577 file.Write("// TODO(gman): Write test for %s\n" % func
.name
)
3581 class ManualHandler(CustomHandler
):
3582 """Handler for commands who's handlers must be written by hand."""
3585 CustomHandler
.__init
__(self
)
3587 def InitFunction(self
, func
):
3588 """Overrriden from TypeHandler."""
3589 if (func
.name
== 'CompressedTexImage2DBucket'):
3590 func
.cmd_args
= func
.cmd_args
[:-1]
3591 func
.AddCmdArg(Argument('bucket_id', 'GLuint'))
3593 CustomHandler
.InitFunction(self
, func
)
3595 def WriteServiceImplementation(self
, func
, file):
3596 """Overrriden from TypeHandler."""
3599 def WriteBucketServiceImplementation(self
, func
, file):
3600 """Overrriden from TypeHandler."""
3603 def WriteServiceUnitTest(self
, func
, file):
3604 """Overrriden from TypeHandler."""
3605 file.Write("// TODO(gman): %s\n\n" % func
.name
)
3607 def WriteImmediateServiceUnitTest(self
, func
, file):
3608 """Overrriden from TypeHandler."""
3609 file.Write("// TODO(gman): %s\n\n" % func
.name
)
3611 def WriteImmediateServiceImplementation(self
, func
, file):
3612 """Overrriden from TypeHandler."""
3615 def WriteImmediateFormatTest(self
, func
, file):
3616 """Overrriden from TypeHandler."""
3617 file.Write("// TODO(gman): Implement test for %s\n" % func
.name
)
3619 def WriteGLES2Implementation(self
, func
, file):
3620 """Overrriden from TypeHandler."""
3621 if func
.GetInfo('impl_func'):
3622 super(ManualHandler
, self
).WriteGLES2Implementation(func
, file)
3624 def WriteGLES2ImplementationHeader(self
, func
, file):
3625 """Overrriden from TypeHandler."""
3626 file.Write("virtual %s %s(%s) OVERRIDE;\n" %
3627 (func
.return_type
, func
.original_name
,
3628 func
.MakeTypedOriginalArgString("")))
3631 def WriteImmediateCmdGetTotalSize(self
, func
, file):
3632 """Overrriden from TypeHandler."""
3633 # TODO(gman): Move this data to _FUNCTION_INFO?
3634 CustomHandler
.WriteImmediateCmdGetTotalSize(self
, func
, file)
3637 class DataHandler(TypeHandler
):
3638 """Handler for glBufferData, glBufferSubData, glTexImage2D, glTexSubImage2D,
3639 glCompressedTexImage2D, glCompressedTexImageSub2D."""
3641 TypeHandler
.__init
__(self
)
3643 def InitFunction(self
, func
):
3644 """Overrriden from TypeHandler."""
3645 if func
.name
== 'CompressedTexSubImage2DBucket':
3646 func
.cmd_args
= func
.cmd_args
[:-1]
3647 func
.AddCmdArg(Argument('bucket_id', 'GLuint'))
3649 def WriteGetDataSizeCode(self
, func
, file):
3650 """Overrriden from TypeHandler."""
3651 # TODO(gman): Move this data to _FUNCTION_INFO?
3653 if name
.endswith("Immediate"):
3655 if name
== 'BufferData' or name
== 'BufferSubData':
3656 file.Write(" uint32 data_size = size;\n")
3657 elif (name
== 'CompressedTexImage2D' or
3658 name
== 'CompressedTexSubImage2D'):
3659 file.Write(" uint32 data_size = imageSize;\n")
3660 elif (name
== 'CompressedTexSubImage2DBucket'):
3661 file.Write(" Bucket* bucket = GetBucket(c.bucket_id);\n")
3662 file.Write(" uint32 data_size = bucket->size();\n")
3663 file.Write(" GLsizei imageSize = data_size;\n")
3664 elif name
== 'TexImage2D' or name
== 'TexSubImage2D':
3665 code
= """ uint32 data_size;
3666 if (!GLES2Util::ComputeImageDataSize(
3667 width, height, format, type, unpack_alignment_, &data_size)) {
3668 return error::kOutOfBounds;
3673 file.Write("// uint32 data_size = 0; // TODO(gman): get correct size!\n")
3675 def WriteImmediateCmdGetTotalSize(self
, func
, file):
3676 """Overrriden from TypeHandler."""
3679 def WriteImmediateCmdSizeTest(self
, func
, file):
3680 """Overrriden from TypeHandler."""
3681 file.Write(" EXPECT_EQ(sizeof(cmd), total_size);\n")
3683 def WriteImmediateCmdInit(self
, func
, file):
3684 """Overrriden from TypeHandler."""
3685 file.Write(" void Init(%s) {\n" % func
.MakeTypedCmdArgString("_"))
3686 self
.WriteImmediateCmdGetTotalSize(func
, file)
3687 file.Write(" SetHeader(total_size);\n")
3688 args
= func
.GetCmdArgs()
3690 file.Write(" %s = _%s;\n" % (arg
.name
, arg
.name
))
3694 def WriteImmediateCmdSet(self
, func
, file):
3695 """Overrriden from TypeHandler."""
3696 copy_args
= func
.MakeCmdArgString("_", False)
3697 file.Write(" void* Set(void* cmd%s) {\n" %
3698 func
.MakeTypedCmdArgString("_", True))
3699 self
.WriteImmediateCmdGetTotalSize(func
, file)
3700 file.Write(" static_cast<ValueType*>(cmd)->Init(%s);\n" % copy_args
)
3701 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
3702 "cmd, total_size);\n")
3706 def WriteImmediateFormatTest(self
, func
, file):
3707 """Overrriden from TypeHandler."""
3708 # TODO(gman): Remove this exception.
3709 file.Write("// TODO(gman): Implement test for %s\n" % func
.name
)
3712 def WriteServiceUnitTest(self
, func
, file):
3713 """Overrriden from TypeHandler."""
3714 file.Write("// TODO(gman): %s\n\n" % func
.name
)
3716 def WriteImmediateServiceUnitTest(self
, func
, file):
3717 """Overrriden from TypeHandler."""
3718 file.Write("// TODO(gman): %s\n\n" % func
.name
)
3720 def WriteBucketServiceImplementation(self
, func
, file):
3721 """Overrriden from TypeHandler."""
3722 if not func
.name
== 'CompressedTexSubImage2DBucket':
3723 TypeHandler
.WriteBucketServiceImplemenation(self
, func
, file)
3726 class BindHandler(TypeHandler
):
3727 """Handler for glBind___ type functions."""
3730 TypeHandler
.__init
__(self
)
3732 def WriteServiceUnitTest(self
, func
, file):
3733 """Overrriden from TypeHandler."""
3735 if len(func
.GetOriginalArgs()) == 1:
3737 TEST_F(%(test_name)s, %(name)sValidArgs) {
3738 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
3739 SpecializedSetup<cmds::%(name)s, 0>(true);
3742 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
3743 EXPECT_EQ(GL_NO_ERROR, GetGLError());
3746 TEST_F(%(test_name)s, %(name)sValidArgsNewId) {
3747 EXPECT_CALL(*gl_, %(gl_func_name)s(kNewServiceId));
3748 EXPECT_CALL(*gl_, %(gl_gen_func_name)s(1, _))
3749 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
3750 SpecializedSetup<cmds::%(name)s, 0>(true);
3752 cmd.Init(kNewClientId);
3753 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
3754 EXPECT_EQ(GL_NO_ERROR, GetGLError());
3755 EXPECT_TRUE(Get%(resource_type)s(kNewClientId) != NULL);
3760 self
.WriteValidUnitTest(func
, file, valid_test
, {
3761 'resource_type': func
.GetOriginalArgs()[0].resource_type
,
3762 'gl_gen_func_name': func
.GetInfo("gen_func"),
3766 TEST_F(%(test_name)s, %(name)sValidArgs) {
3767 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
3768 SpecializedSetup<cmds::%(name)s, 0>(true);
3771 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
3772 EXPECT_EQ(GL_NO_ERROR, GetGLError());
3775 TEST_F(%(test_name)s, %(name)sValidArgsNewId) {
3776 EXPECT_CALL(*gl_, %(gl_func_name)s(%(first_gl_arg)s, kNewServiceId));
3777 EXPECT_CALL(*gl_, %(gl_gen_func_name)s(1, _))
3778 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
3779 SpecializedSetup<cmds::%(name)s, 0>(true);
3781 cmd.Init(%(first_arg)s, kNewClientId);
3782 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
3783 EXPECT_EQ(GL_NO_ERROR, GetGLError());
3784 EXPECT_TRUE(Get%(resource_type)s(kNewClientId) != NULL);
3789 self
.WriteValidUnitTest(func
, file, valid_test
, {
3790 'first_arg': func
.GetOriginalArgs()[0].GetValidArg(func
, 0, 0),
3791 'first_gl_arg': func
.GetOriginalArgs()[0].GetValidGLArg(func
, 0, 0),
3792 'resource_type': func
.GetOriginalArgs()[1].resource_type
,
3793 'gl_gen_func_name': func
.GetInfo("gen_func"),
3797 TEST_F(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
3798 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
3799 SpecializedSetup<cmds::%(name)s, 0>(false);
3802 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
3805 self
.WriteInvalidUnitTest(func
, file, invalid_test
)
3807 def WriteGLES2Implementation(self
, func
, file):
3808 """Writes the GLES2 Implemention."""
3810 impl_func
= func
.GetInfo('impl_func')
3811 impl_decl
= func
.GetInfo('impl_decl')
3813 if (func
.can_auto_generate
and
3814 (impl_func
== None or impl_func
== True) and
3815 (impl_decl
== None or impl_decl
== True)):
3817 file.Write("%s GLES2Implementation::%s(%s) {\n" %
3818 (func
.return_type
, func
.original_name
,
3819 func
.MakeTypedOriginalArgString("")))
3820 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
3821 func
.WriteDestinationInitalizationValidation(file)
3822 self
.WriteClientGLCallLog(func
, file)
3823 for arg
in func
.GetOriginalArgs():
3824 arg
.WriteClientSideValidationCode(file, func
)
3826 code
= """ if (Is%(type)sReservedId(%(id)s)) {
3827 SetGLError(GL_INVALID_OPERATION, "%(name)s\", \"%(id)s reserved id");
3830 if (Bind%(type)sHelper(%(arg_string)s)) {
3831 helper_->%(name)s(%(arg_string)s);
3838 if len(func
.GetOriginalArgs()) == 1:
3839 # Bind functions that have no target (like BindVertexArrayOES)
3840 name_arg
= func
.GetOriginalArgs()[0]
3842 # Bind functions that have both a target and a name (like BindTexture)
3843 name_arg
= func
.GetOriginalArgs()[1]
3847 'arg_string': func
.MakeOriginalArgString(""),
3848 'id': name_arg
.name
,
3849 'type': name_arg
.resource_type
,
3850 'lc_type': name_arg
.resource_type
.lower(),
3853 def WriteGLES2ImplementationUnitTest(self
, func
, file):
3854 """Overrriden from TypeHandler."""
3855 client_test
= func
.GetInfo('client_test')
3856 if client_test
== False:
3859 TEST_F(GLES2ImplementationTest, %(name)s) {
3864 expected.cmd.Init(%(cmd_args)s);
3866 gl_->%(name)s(%(args)s);
3867 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
3869 gl_->%(name)s(%(args)s);
3870 EXPECT_TRUE(NoCommandsWritten());
3873 cmd_arg_strings
= []
3874 for count
, arg
in enumerate(func
.GetCmdArgs()):
3875 cmd_arg_strings
.append(arg
.GetValidClientSideCmdArg(func
, count
, 0))
3878 for count
, arg
in enumerate(func
.GetOriginalArgs()):
3879 gl_arg_strings
.append(arg
.GetValidClientSideArg(func
, count
, 0))
3882 'args': ", ".join(gl_arg_strings
),
3883 'cmd_args': ", ".join(cmd_arg_strings
),
3887 class GENnHandler(TypeHandler
):
3888 """Handler for glGen___ type functions."""
3891 TypeHandler
.__init
__(self
)
3893 def InitFunction(self
, func
):
3894 """Overrriden from TypeHandler."""
3897 def WriteGetDataSizeCode(self
, func
, file):
3898 """Overrriden from TypeHandler."""
3899 code
= """ uint32 data_size;
3900 if (!SafeMultiplyUint32(n, sizeof(GLuint), &data_size)) {
3901 return error::kOutOfBounds;
3906 def WriteHandlerImplementation (self
, func
, file):
3907 """Overrriden from TypeHandler."""
3908 file.Write(" if (!%sHelper(n, %s)) {\n"
3909 " return error::kInvalidArguments;\n"
3911 (func
.name
, func
.GetLastOriginalArg().name
))
3913 def WriteImmediateHandlerImplementation(self
, func
, file):
3914 """Overrriden from TypeHandler."""
3915 file.Write(" if (!%sHelper(n, %s)) {\n"
3916 " return error::kInvalidArguments;\n"
3918 (func
.original_name
, func
.GetLastOriginalArg().name
))
3920 def WriteGLES2Implementation(self
, func
, file):
3921 """Overrriden from TypeHandler."""
3922 log_code
= (""" GPU_CLIENT_LOG_CODE_BLOCK({
3923 for (GLsizei i = 0; i < n; ++i) {
3924 GPU_CLIENT_LOG(" " << i << ": " << %s[i]);
3926 });""" % func
.GetOriginalArgs()[1].name
)
3928 'log_code': log_code
,
3929 'return_type': func
.return_type
,
3930 'name': func
.original_name
,
3931 'typed_args': func
.MakeTypedOriginalArgString(""),
3932 'args': func
.MakeOriginalArgString(""),
3933 'resource_types': func
.GetInfo('resource_types'),
3934 'count_name': func
.GetOriginalArgs()[0].name
,
3937 "%(return_type)s GLES2Implementation::%(name)s(%(typed_args)s) {\n" %
3939 func
.WriteDestinationInitalizationValidation(file)
3940 self
.WriteClientGLCallLog(func
, file)
3941 for arg
in func
.GetOriginalArgs():
3942 arg
.WriteClientSideValidationCode(file, func
)
3943 code
= """ GPU_CLIENT_SINGLE_THREAD_CHECK();
3944 GetIdHandler(id_namespaces::k%(resource_types)s)->
3945 MakeIds(this, 0, %(args)s);
3946 %(name)sHelper(%(args)s);
3947 helper_->%(name)sImmediate(%(args)s);
3948 helper_->CommandBufferHelper::Flush();
3954 file.Write(code
% args
)
3956 def WriteGLES2ImplementationUnitTest(self
, func
, file):
3957 """Overrriden from TypeHandler."""
3959 TEST_F(GLES2ImplementationTest, %(name)s) {
3960 GLuint ids[2] = { 0, };
3962 cmds::%(name)sImmediate gen;
3966 expected.gen.Init(arraysize(ids), &ids[0]);
3967 expected.data[0] = k%(types)sStartId;
3968 expected.data[1] = k%(types)sStartId + 1;
3969 gl_->%(name)s(arraysize(ids), &ids[0]);
3970 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
3971 EXPECT_EQ(k%(types)sStartId, ids[0]);
3972 EXPECT_EQ(k%(types)sStartId + 1, ids[1]);
3977 'types': func
.GetInfo('resource_types'),
3980 def WriteServiceUnitTest(self
, func
, file):
3981 """Overrriden from TypeHandler."""
3983 TEST_F(%(test_name)s, %(name)sValidArgs) {
3984 EXPECT_CALL(*gl_, %(gl_func_name)s(1, _))
3985 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
3986 GetSharedMemoryAs<GLuint*>()[0] = kNewClientId;
3987 SpecializedSetup<cmds::%(name)s, 0>(true);
3990 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
3991 EXPECT_EQ(GL_NO_ERROR, GetGLError());
3992 EXPECT_TRUE(Get%(resource_name)s(kNewClientId) != NULL);
3995 self
.WriteValidUnitTest(func
, file, valid_test
, {
3996 'resource_name': func
.GetInfo('resource_type'),
3999 TEST_F(%(test_name)s, %(name)sInvalidArgs) {
4000 EXPECT_CALL(*gl_, %(gl_func_name)s(_, _)).Times(0);
4001 GetSharedMemoryAs<GLuint*>()[0] = client_%(resource_name)s_id_;
4002 SpecializedSetup<cmds::%(name)s, 0>(false);
4005 EXPECT_EQ(error::kInvalidArguments, ExecuteCmd(cmd));
4008 self
.WriteValidUnitTest(func
, file, invalid_test
, {
4009 'resource_name': func
.GetInfo('resource_type').lower(),
4012 def WriteImmediateServiceUnitTest(self
, func
, file):
4013 """Overrriden from TypeHandler."""
4015 TEST_F(%(test_name)s, %(name)sValidArgs) {
4016 EXPECT_CALL(*gl_, %(gl_func_name)s(1, _))
4017 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
4018 cmds::%(name)s* cmd = GetImmediateAs<cmds::%(name)s>();
4019 GLuint temp = kNewClientId;
4020 SpecializedSetup<cmds::%(name)s, 0>(true);
4021 cmd->Init(1, &temp);
4022 EXPECT_EQ(error::kNoError,
4023 ExecuteImmediateCmd(*cmd, sizeof(temp)));
4024 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4025 EXPECT_TRUE(Get%(resource_name)s(kNewClientId) != NULL);
4028 self
.WriteValidUnitTest(func
, file, valid_test
, {
4029 'resource_name': func
.GetInfo('resource_type'),
4032 TEST_F(%(test_name)s, %(name)sInvalidArgs) {
4033 EXPECT_CALL(*gl_, %(gl_func_name)s(_, _)).Times(0);
4034 cmds::%(name)s* cmd = GetImmediateAs<cmds::%(name)s>();
4035 SpecializedSetup<cmds::%(name)s, 0>(false);
4036 cmd->Init(1, &client_%(resource_name)s_id_);
4037 EXPECT_EQ(error::kInvalidArguments,
4038 ExecuteImmediateCmd(*cmd, sizeof(&client_%(resource_name)s_id_)));
4041 self
.WriteValidUnitTest(func
, file, invalid_test
, {
4042 'resource_name': func
.GetInfo('resource_type').lower(),
4045 def WriteImmediateCmdComputeSize(self
, func
, file):
4046 """Overrriden from TypeHandler."""
4047 file.Write(" static uint32 ComputeDataSize(GLsizei n) {\n")
4049 " return static_cast<uint32>(sizeof(GLuint) * n); // NOLINT\n")
4052 file.Write(" static uint32 ComputeSize(GLsizei n) {\n")
4053 file.Write(" return static_cast<uint32>(\n")
4054 file.Write(" sizeof(ValueType) + ComputeDataSize(n)); // NOLINT\n")
4058 def WriteImmediateCmdSetHeader(self
, func
, file):
4059 """Overrriden from TypeHandler."""
4060 file.Write(" void SetHeader(GLsizei n) {\n")
4061 file.Write(" header.SetCmdByTotalSize<ValueType>(ComputeSize(n));\n")
4065 def WriteImmediateCmdInit(self
, func
, file):
4066 """Overrriden from TypeHandler."""
4067 last_arg
= func
.GetLastOriginalArg()
4068 file.Write(" void Init(%s, %s _%s) {\n" %
4069 (func
.MakeTypedCmdArgString("_"),
4070 last_arg
.type, last_arg
.name
))
4071 file.Write(" SetHeader(_n);\n")
4072 args
= func
.GetCmdArgs()
4074 file.Write(" %s = _%s;\n" % (arg
.name
, arg
.name
))
4075 file.Write(" memcpy(ImmediateDataAddress(this),\n")
4076 file.Write(" _%s, ComputeDataSize(_n));\n" % last_arg
.name
)
4080 def WriteImmediateCmdSet(self
, func
, file):
4081 """Overrriden from TypeHandler."""
4082 last_arg
= func
.GetLastOriginalArg()
4083 copy_args
= func
.MakeCmdArgString("_", False)
4084 file.Write(" void* Set(void* cmd%s, %s _%s) {\n" %
4085 (func
.MakeTypedCmdArgString("_", True),
4086 last_arg
.type, last_arg
.name
))
4087 file.Write(" static_cast<ValueType*>(cmd)->Init(%s, _%s);\n" %
4088 (copy_args
, last_arg
.name
))
4089 file.Write(" const uint32 size = ComputeSize(_n);\n")
4090 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
4095 def WriteImmediateCmdHelper(self
, func
, file):
4096 """Overrriden from TypeHandler."""
4097 code
= """ void %(name)s(%(typed_args)s) {
4098 const uint32 size = gles2::cmds::%(name)s::ComputeSize(n);
4099 gles2::cmds::%(name)s* c =
4100 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
4109 "typed_args": func
.MakeTypedOriginalArgString(""),
4110 "args": func
.MakeOriginalArgString(""),
4113 def WriteImmediateFormatTest(self
, func
, file):
4114 """Overrriden from TypeHandler."""
4115 file.Write("TEST_F(GLES2FormatTest, %s) {\n" % func
.name
)
4116 file.Write(" static GLuint ids[] = { 12, 23, 34, };\n")
4117 file.Write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
4118 (func
.name
, func
.name
))
4119 file.Write(" void* next_cmd = cmd.Set(\n")
4120 file.Write(" &cmd, static_cast<GLsizei>(arraysize(ids)), ids);\n")
4121 file.Write(" EXPECT_EQ(static_cast<uint32>(cmds::%s::kCmdId),\n" %
4123 file.Write(" cmd.header.command);\n")
4124 file.Write(" EXPECT_EQ(sizeof(cmd) +\n")
4125 file.Write(" RoundSizeToMultipleOfEntries(cmd.n * 4u),\n")
4126 file.Write(" cmd.header.size * 4u);\n")
4127 file.Write(" EXPECT_EQ(static_cast<GLsizei>(arraysize(ids)), cmd.n);\n");
4128 file.Write(" CheckBytesWrittenMatchesExpectedSize(\n")
4129 file.Write(" next_cmd, sizeof(cmd) +\n")
4130 file.Write(" RoundSizeToMultipleOfEntries(arraysize(ids) * 4u));\n")
4131 file.Write(" // TODO(gman): Check that ids were inserted;\n")
4136 class CreateHandler(TypeHandler
):
4137 """Handler for glCreate___ type functions."""
4140 TypeHandler
.__init
__(self
)
4142 def InitFunction(self
, func
):
4143 """Overrriden from TypeHandler."""
4144 func
.AddCmdArg(Argument("client_id", 'uint32'))
4146 def WriteServiceUnitTest(self
, func
, file):
4147 """Overrriden from TypeHandler."""
4149 TEST_F(%(test_name)s, %(name)sValidArgs) {
4150 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s))
4151 .WillOnce(Return(kNewServiceId));
4152 SpecializedSetup<cmds::%(name)s, 0>(true);
4154 cmd.Init(%(args)s%(comma)skNewClientId);
4155 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4156 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4157 EXPECT_TRUE(Get%(resource_type)s(kNewClientId) != NULL);
4161 if len(func
.GetOriginalArgs()):
4163 self
.WriteValidUnitTest(func
, file, valid_test
, {
4165 'resource_type': func
.name
[6:],
4168 TEST_F(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
4169 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
4170 SpecializedSetup<cmds::%(name)s, 0>(false);
4172 cmd.Init(%(args)s%(comma)skNewClientId);
4173 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));%(gl_error_test)s
4176 self
.WriteInvalidUnitTest(func
, file, invalid_test
, {
4180 def WriteHandlerImplementation (self
, func
, file):
4181 """Overrriden from TypeHandler."""
4182 file.Write(" uint32 client_id = c.client_id;\n")
4183 file.Write(" if (!%sHelper(%s)) {\n" %
4184 (func
.name
, func
.MakeCmdArgString("")))
4185 file.Write(" return error::kInvalidArguments;\n")
4188 def WriteGLES2Implementation(self
, func
, file):
4189 """Overrriden from TypeHandler."""
4190 file.Write("%s GLES2Implementation::%s(%s) {\n" %
4191 (func
.return_type
, func
.original_name
,
4192 func
.MakeTypedOriginalArgString("")))
4193 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
4194 func
.WriteDestinationInitalizationValidation(file)
4195 self
.WriteClientGLCallLog(func
, file)
4196 for arg
in func
.GetOriginalArgs():
4197 arg
.WriteClientSideValidationCode(file, func
)
4198 file.Write(" GLuint client_id;\n")
4200 " GetIdHandler(id_namespaces::kProgramsAndShaders)->\n")
4201 file.Write(" MakeIds(this, 0, 1, &client_id);\n")
4202 file.Write(" helper_->%s(%s);\n" %
4203 (func
.name
, func
.MakeCmdArgString("")))
4204 file.Write(' GPU_CLIENT_LOG("returned " << client_id);\n')
4205 file.Write(" CheckGLError();\n")
4206 file.Write(" return client_id;\n")
4211 class DeleteHandler(TypeHandler
):
4212 """Handler for glDelete___ single resource type functions."""
4215 TypeHandler
.__init
__(self
)
4217 def WriteServiceImplementation(self
, func
, file):
4218 """Overrriden from TypeHandler."""
4221 def WriteGLES2Implementation(self
, func
, file):
4222 """Overrriden from TypeHandler."""
4223 file.Write("%s GLES2Implementation::%s(%s) {\n" %
4224 (func
.return_type
, func
.original_name
,
4225 func
.MakeTypedOriginalArgString("")))
4226 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
4227 func
.WriteDestinationInitalizationValidation(file)
4228 self
.WriteClientGLCallLog(func
, file)
4229 for arg
in func
.GetOriginalArgs():
4230 arg
.WriteClientSideValidationCode(file, func
)
4232 " GPU_CLIENT_DCHECK(%s != 0);\n" % func
.GetOriginalArgs()[-1].name
)
4233 file.Write(" %sHelper(%s);\n" %
4234 (func
.original_name
, func
.GetOriginalArgs()[-1].name
))
4235 file.Write(" CheckGLError();\n")
4240 class DELnHandler(TypeHandler
):
4241 """Handler for glDelete___ type functions."""
4244 TypeHandler
.__init
__(self
)
4246 def WriteGetDataSizeCode(self
, func
, file):
4247 """Overrriden from TypeHandler."""
4248 code
= """ uint32 data_size;
4249 if (!SafeMultiplyUint32(n, sizeof(GLuint), &data_size)) {
4250 return error::kOutOfBounds;
4255 def WriteGLES2ImplementationUnitTest(self
, func
, file):
4256 """Overrriden from TypeHandler."""
4258 TEST_F(GLES2ImplementationTest, %(name)s) {
4259 GLuint ids[2] = { k%(types)sStartId, k%(types)sStartId + 1 };
4261 cmds::%(name)sImmediate del;
4265 expected.del.Init(arraysize(ids), &ids[0]);
4266 expected.data[0] = k%(types)sStartId;
4267 expected.data[1] = k%(types)sStartId + 1;
4268 gl_->%(name)s(arraysize(ids), &ids[0]);
4269 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
4274 'types': func
.GetInfo('resource_types'),
4277 def WriteServiceUnitTest(self
, func
, file):
4278 """Overrriden from TypeHandler."""
4280 TEST_F(%(test_name)s, %(name)sValidArgs) {
4283 %(gl_func_name)s(1, Pointee(kService%(upper_resource_name)sId)))
4285 GetSharedMemoryAs<GLuint*>()[0] = client_%(resource_name)s_id_;
4286 SpecializedSetup<cmds::%(name)s, 0>(true);
4289 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4290 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4292 Get%(upper_resource_name)s(client_%(resource_name)s_id_) == NULL);
4295 self
.WriteValidUnitTest(func
, file, valid_test
, {
4296 'resource_name': func
.GetInfo('resource_type').lower(),
4297 'upper_resource_name': func
.GetInfo('resource_type'),
4300 TEST_F(%(test_name)s, %(name)sInvalidArgs) {
4301 GetSharedMemoryAs<GLuint*>()[0] = kInvalidClientId;
4302 SpecializedSetup<cmds::%(name)s, 0>(false);
4305 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4308 self
.WriteValidUnitTest(func
, file, invalid_test
)
4310 def WriteImmediateServiceUnitTest(self
, func
, file):
4311 """Overrriden from TypeHandler."""
4313 TEST_F(%(test_name)s, %(name)sValidArgs) {
4316 %(gl_func_name)s(1, Pointee(kService%(upper_resource_name)sId)))
4318 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
4319 SpecializedSetup<cmds::%(name)s, 0>(true);
4320 cmd.Init(1, &client_%(resource_name)s_id_);
4321 EXPECT_EQ(error::kNoError,
4322 ExecuteImmediateCmd(cmd, sizeof(client_%(resource_name)s_id_)));
4323 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4325 Get%(upper_resource_name)s(client_%(resource_name)s_id_) == NULL);
4328 self
.WriteValidUnitTest(func
, file, valid_test
, {
4329 'resource_name': func
.GetInfo('resource_type').lower(),
4330 'upper_resource_name': func
.GetInfo('resource_type'),
4333 TEST_F(%(test_name)s, %(name)sInvalidArgs) {
4334 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
4335 SpecializedSetup<cmds::%(name)s, 0>(false);
4336 GLuint temp = kInvalidClientId;
4338 EXPECT_EQ(error::kNoError,
4339 ExecuteImmediateCmd(cmd, sizeof(temp)));
4342 self
.WriteValidUnitTest(func
, file, invalid_test
)
4344 def WriteHandlerImplementation (self
, func
, file):
4345 """Overrriden from TypeHandler."""
4346 file.Write(" %sHelper(n, %s);\n" %
4347 (func
.name
, func
.GetLastOriginalArg().name
))
4349 def WriteImmediateHandlerImplementation (self
, func
, file):
4350 """Overrriden from TypeHandler."""
4351 file.Write(" %sHelper(n, %s);\n" %
4352 (func
.original_name
, func
.GetLastOriginalArg().name
))
4354 def WriteGLES2Implementation(self
, func
, file):
4355 """Overrriden from TypeHandler."""
4356 impl_decl
= func
.GetInfo('impl_decl')
4357 if impl_decl
== None or impl_decl
== True:
4359 'return_type': func
.return_type
,
4360 'name': func
.original_name
,
4361 'typed_args': func
.MakeTypedOriginalArgString(""),
4362 'args': func
.MakeOriginalArgString(""),
4363 'resource_type': func
.GetInfo('resource_type').lower(),
4364 'count_name': func
.GetOriginalArgs()[0].name
,
4367 "%(return_type)s GLES2Implementation::%(name)s(%(typed_args)s) {\n" %
4369 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
4370 func
.WriteDestinationInitalizationValidation(file)
4371 self
.WriteClientGLCallLog(func
, file)
4372 file.Write(""" GPU_CLIENT_LOG_CODE_BLOCK({
4373 for (GLsizei i = 0; i < n; ++i) {
4374 GPU_CLIENT_LOG(" " << i << ": " << %s[i]);
4377 """ % func
.GetOriginalArgs()[1].name
)
4378 file.Write(""" GPU_CLIENT_DCHECK_CODE_BLOCK({
4379 for (GLsizei i = 0; i < n; ++i) {
4383 """ % func
.GetOriginalArgs()[1].name
)
4384 for arg
in func
.GetOriginalArgs():
4385 arg
.WriteClientSideValidationCode(file, func
)
4386 code
= """ %(name)sHelper(%(args)s);
4391 file.Write(code
% args
)
4393 def WriteImmediateCmdComputeSize(self
, func
, file):
4394 """Overrriden from TypeHandler."""
4395 file.Write(" static uint32 ComputeDataSize(GLsizei n) {\n")
4397 " return static_cast<uint32>(sizeof(GLuint) * n); // NOLINT\n")
4400 file.Write(" static uint32 ComputeSize(GLsizei n) {\n")
4401 file.Write(" return static_cast<uint32>(\n")
4402 file.Write(" sizeof(ValueType) + ComputeDataSize(n)); // NOLINT\n")
4406 def WriteImmediateCmdSetHeader(self
, func
, file):
4407 """Overrriden from TypeHandler."""
4408 file.Write(" void SetHeader(GLsizei n) {\n")
4409 file.Write(" header.SetCmdByTotalSize<ValueType>(ComputeSize(n));\n")
4413 def WriteImmediateCmdInit(self
, func
, file):
4414 """Overrriden from TypeHandler."""
4415 last_arg
= func
.GetLastOriginalArg()
4416 file.Write(" void Init(%s, %s _%s) {\n" %
4417 (func
.MakeTypedCmdArgString("_"),
4418 last_arg
.type, last_arg
.name
))
4419 file.Write(" SetHeader(_n);\n")
4420 args
= func
.GetCmdArgs()
4422 file.Write(" %s = _%s;\n" % (arg
.name
, arg
.name
))
4423 file.Write(" memcpy(ImmediateDataAddress(this),\n")
4424 file.Write(" _%s, ComputeDataSize(_n));\n" % last_arg
.name
)
4428 def WriteImmediateCmdSet(self
, func
, file):
4429 """Overrriden from TypeHandler."""
4430 last_arg
= func
.GetLastOriginalArg()
4431 copy_args
= func
.MakeCmdArgString("_", False)
4432 file.Write(" void* Set(void* cmd%s, %s _%s) {\n" %
4433 (func
.MakeTypedCmdArgString("_", True),
4434 last_arg
.type, last_arg
.name
))
4435 file.Write(" static_cast<ValueType*>(cmd)->Init(%s, _%s);\n" %
4436 (copy_args
, last_arg
.name
))
4437 file.Write(" const uint32 size = ComputeSize(_n);\n")
4438 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
4443 def WriteImmediateCmdHelper(self
, func
, file):
4444 """Overrriden from TypeHandler."""
4445 code
= """ void %(name)s(%(typed_args)s) {
4446 const uint32 size = gles2::cmds::%(name)s::ComputeSize(n);
4447 gles2::cmds::%(name)s* c =
4448 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
4457 "typed_args": func
.MakeTypedOriginalArgString(""),
4458 "args": func
.MakeOriginalArgString(""),
4461 def WriteImmediateFormatTest(self
, func
, file):
4462 """Overrriden from TypeHandler."""
4463 file.Write("TEST_F(GLES2FormatTest, %s) {\n" % func
.name
)
4464 file.Write(" static GLuint ids[] = { 12, 23, 34, };\n")
4465 file.Write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
4466 (func
.name
, func
.name
))
4467 file.Write(" void* next_cmd = cmd.Set(\n")
4468 file.Write(" &cmd, static_cast<GLsizei>(arraysize(ids)), ids);\n")
4469 file.Write(" EXPECT_EQ(static_cast<uint32>(cmds::%s::kCmdId),\n" %
4471 file.Write(" cmd.header.command);\n")
4472 file.Write(" EXPECT_EQ(sizeof(cmd) +\n")
4473 file.Write(" RoundSizeToMultipleOfEntries(cmd.n * 4u),\n")
4474 file.Write(" cmd.header.size * 4u);\n")
4475 file.Write(" EXPECT_EQ(static_cast<GLsizei>(arraysize(ids)), cmd.n);\n");
4476 file.Write(" CheckBytesWrittenMatchesExpectedSize(\n")
4477 file.Write(" next_cmd, sizeof(cmd) +\n")
4478 file.Write(" RoundSizeToMultipleOfEntries(arraysize(ids) * 4u));\n")
4479 file.Write(" // TODO(gman): Check that ids were inserted;\n")
4484 class GETnHandler(TypeHandler
):
4485 """Handler for GETn for glGetBooleanv, glGetFloatv, ... type functions."""
4488 TypeHandler
.__init
__(self
)
4490 def AddImmediateFunction(self
, generator
, func
):
4491 """Overrriden from TypeHandler."""
4494 def WriteServiceImplementation(self
, func
, file):
4495 """Overrriden from TypeHandler."""
4497 "error::Error GLES2DecoderImpl::Handle%s(\n" % func
.name
)
4499 " uint32 immediate_data_size, const gles2::cmds::%s& c) {\n" %
4501 last_arg
= func
.GetLastOriginalArg()
4503 all_but_last_args
= func
.GetOriginalArgs()[:-1]
4504 for arg
in all_but_last_args
:
4505 arg
.WriteGetCode(file)
4507 code
= """ typedef cmds::%(func_name)s::Result Result;
4508 GLsizei num_values = 0;
4509 GetNumValuesReturnedForGLGet(pname, &num_values);
4510 Result* result = GetSharedMemoryAs<Result*>(
4511 c.params_shm_id, c.params_shm_offset, Result::ComputeSize(num_values));
4512 %(last_arg_type)s params = result ? result->GetData() : NULL;
4515 'last_arg_type': last_arg
.type,
4516 'func_name': func
.name
,
4518 func
.WriteHandlerValidation(file)
4519 code
= """ // Check that the client initialized the result.
4520 if (result->size != 0) {
4521 return error::kInvalidArguments;
4524 shadowed
= func
.GetInfo('shadowed')
4526 file.Write(' LOCAL_COPY_REAL_GL_ERRORS_TO_WRAPPER("%s");\n' % func
.name
)
4528 func
.WriteHandlerImplementation(file)
4530 code
= """ result->SetNumResults(num_values);
4531 return error::kNoError;
4535 code
= """ GLenum error = glGetError();
4536 if (error == GL_NO_ERROR) {
4537 result->SetNumResults(num_values);
4539 LOCAL_SET_GL_ERROR(error, "%(func_name)s", "");
4541 return error::kNoError;
4545 file.Write(code
% {'func_name': func
.name
})
4547 def WriteGLES2Implementation(self
, func
, file):
4548 """Overrriden from TypeHandler."""
4549 impl_decl
= func
.GetInfo('impl_decl')
4550 if impl_decl
== None or impl_decl
== True:
4551 file.Write("%s GLES2Implementation::%s(%s) {\n" %
4552 (func
.return_type
, func
.original_name
,
4553 func
.MakeTypedOriginalArgString("")))
4554 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
4555 func
.WriteDestinationInitalizationValidation(file)
4556 self
.WriteClientGLCallLog(func
, file)
4557 for arg
in func
.GetOriginalArgs():
4558 arg
.WriteClientSideValidationCode(file, func
)
4559 all_but_last_args
= func
.GetOriginalArgs()[:-1]
4561 ", ".join(["%s" % arg
.name
for arg
in all_but_last_args
]))
4563 ", ".join(["%s" % arg
.name
for arg
in func
.GetOriginalArgs()]))
4564 self
.WriteTraceEvent(func
, file)
4565 code
= """ if (%(func_name)sHelper(%(all_arg_string)s)) {
4568 typedef cmds::%(func_name)s::Result Result;
4569 Result* result = GetResultAs<Result*>();
4573 result->SetNumResults(0);
4574 helper_->%(func_name)s(%(arg_string)s,
4575 GetResultShmId(), GetResultShmOffset());
4577 result->CopyResult(params);
4578 GPU_CLIENT_LOG_CODE_BLOCK({
4579 for (int32 i = 0; i < result->GetNumResults(); ++i) {
4580 GPU_CLIENT_LOG(" " << i << ": " << result->GetData()[i]);
4587 'func_name': func
.name
,
4588 'arg_string': arg_string
,
4589 'all_arg_string': all_arg_string
,
4592 def WriteGLES2ImplementationUnitTest(self
, func
, file):
4593 """Writes the GLES2 Implemention unit test."""
4595 TEST_F(GLES2ImplementationTest, %(name)s) {
4599 typedef cmds::%(name)s::Result Result;
4600 Result::Type result = 0;
4602 ExpectedMemoryInfo result1 = GetExpectedResultMemory(4);
4603 expected.cmd.Init(%(cmd_args)s, result1.id, result1.offset);
4604 EXPECT_CALL(*command_buffer(), OnFlush())
4605 .WillOnce(SetMemory(result1.ptr, SizedResultHelper<Result::Type>(1)))
4606 .RetiresOnSaturation();
4607 gl_->%(name)s(%(args)s, &result);
4608 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
4609 EXPECT_EQ(static_cast<Result::Type>(1), result);
4612 cmd_arg_strings
= []
4613 for count
, arg
in enumerate(func
.GetCmdArgs()[0:-2]):
4614 cmd_arg_strings
.append(arg
.GetValidClientSideCmdArg(func
, count
, 0))
4615 cmd_arg_strings
[0] = '123'
4617 for count
, arg
in enumerate(func
.GetOriginalArgs()[0:-1]):
4618 gl_arg_strings
.append(arg
.GetValidClientSideArg(func
, count
, 0))
4619 gl_arg_strings
[0] = '123'
4622 'args': ", ".join(gl_arg_strings
),
4623 'cmd_args': ", ".join(cmd_arg_strings
),
4626 def WriteServiceUnitTest(self
, func
, file):
4627 """Overrriden from TypeHandler."""
4629 TEST_F(%(test_name)s, %(name)sValidArgs) {
4630 EXPECT_CALL(*gl_, GetError())
4631 .WillOnce(Return(GL_NO_ERROR))
4632 .WillOnce(Return(GL_NO_ERROR))
4633 .RetiresOnSaturation();
4634 SpecializedSetup<cmds::%(name)s, 0>(true);
4635 typedef cmds::%(name)s::Result Result;
4636 Result* result = static_cast<Result*>(shared_memory_address_);
4637 EXPECT_CALL(*gl_, %(gl_func_name)s(%(local_gl_args)s));
4641 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4642 EXPECT_EQ(decoder_->GetGLES2Util()->GLGetNumValuesReturned(
4644 result->GetNumResults());
4645 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4650 for count
, arg
in enumerate(func
.GetOriginalArgs()[:-1]):
4651 arg_value
= arg
.GetValidGLArg(func
, count
, 0)
4652 gl_arg_strings
.append(arg_value
)
4653 if arg
.name
== 'pname':
4654 valid_pname
= arg_value
4655 if func
.GetInfo('gl_test_func') == 'glGetIntegerv':
4656 gl_arg_strings
.append("_")
4658 gl_arg_strings
.append("result->GetData()")
4660 self
.WriteValidUnitTest(func
, file, valid_test
, {
4661 'local_gl_args': ", ".join(gl_arg_strings
),
4662 'valid_pname': valid_pname
,
4666 TEST_F(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
4667 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
4668 SpecializedSetup<cmds::%(name)s, 0>(false);
4669 cmds::%(name)s::Result* result =
4670 static_cast<cmds::%(name)s::Result*>(shared_memory_address_);
4674 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));
4675 EXPECT_EQ(0u, result->size);%(gl_error_test)s
4678 self
.WriteInvalidUnitTest(func
, file, invalid_test
)
4681 class PUTHandler(TypeHandler
):
4682 """Handler for glTexParameter_v, glVertexAttrib_v functions."""
4685 TypeHandler
.__init
__(self
)
4687 def WriteServiceUnitTest(self
, func
, file):
4688 """Writes the service unit test for a command."""
4689 expected_call
= "EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));"
4690 if func
.GetInfo("first_element_only"):
4692 for count
, arg
in enumerate(func
.GetOriginalArgs()):
4693 gl_arg_strings
.append(arg
.GetValidGLArg(func
, count
, 0))
4694 gl_arg_strings
[-1] = "*" + gl_arg_strings
[-1]
4695 expected_call
= ("EXPECT_CALL(*gl_, %%(gl_func_name)s(%s));" %
4696 ", ".join(gl_arg_strings
))
4698 TEST_F(%(test_name)s, %(name)sValidArgs) {
4699 SpecializedSetup<cmds::%(name)s, 0>(true);
4702 GetSharedMemoryAs<%(data_type)s*>()[0] = %(data_value)s;
4704 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4705 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4709 'data_type': func
.GetInfo('data_type'),
4710 'data_value': func
.GetInfo('data_value') or '0',
4711 'expected_call': expected_call
,
4713 self
.WriteValidUnitTest(func
, file, valid_test
, extra
)
4716 TEST_F(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
4717 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
4718 SpecializedSetup<cmds::%(name)s, 0>(false);
4721 GetSharedMemoryAs<%(data_type)s*>()[0] = %(data_value)s;
4722 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
4725 self
.WriteInvalidUnitTest(func
, file, invalid_test
, extra
)
4727 def WriteImmediateServiceUnitTest(self
, func
, file):
4728 """Writes the service unit test for a command."""
4730 TEST_F(%(test_name)s, %(name)sValidArgs) {
4731 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
4732 SpecializedSetup<cmds::%(name)s, 0>(true);
4733 %(data_type)s temp[%(data_count)s] = { %(data_value)s, };
4734 cmd.Init(%(gl_args)s, &temp[0]);
4737 %(gl_func_name)s(%(gl_args)s, %(data_ref)sreinterpret_cast<
4738 %(data_type)s*>(ImmediateDataAddress(&cmd))));
4739 EXPECT_EQ(error::kNoError,
4740 ExecuteImmediateCmd(cmd, sizeof(temp)));
4741 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4746 for count
, arg
in enumerate(func
.GetOriginalArgs()[0:-1]):
4747 gl_arg_strings
.append(arg
.GetValidGLArg(func
, count
, 0))
4748 gl_any_strings
.append("_")
4750 'data_ref': ("*" if func
.GetInfo('first_element_only') else ""),
4751 'data_type': func
.GetInfo('data_type'),
4752 'data_count': func
.GetInfo('count'),
4753 'data_value': func
.GetInfo('data_value') or '0',
4754 'gl_args': ", ".join(gl_arg_strings
),
4755 'gl_any_args': ", ".join(gl_any_strings
),
4757 self
.WriteValidUnitTest(func
, file, valid_test
, extra
)
4760 TEST_F(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
4761 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
4762 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_any_args)s, _)).Times(0);
4763 SpecializedSetup<cmds::%(name)s, 0>(false);
4764 %(data_type)s temp[%(data_count)s] = { %(data_value)s, };
4765 cmd.Init(%(all_but_last_args)s, &temp[0]);
4766 EXPECT_EQ(error::%(parse_result)s,
4767 ExecuteImmediateCmd(cmd, sizeof(temp)));%(gl_error_test)s
4770 self
.WriteInvalidUnitTest(func
, file, invalid_test
, extra
)
4772 def WriteGetDataSizeCode(self
, func
, file):
4773 """Overrriden from TypeHandler."""
4774 code
= """ uint32 data_size;
4775 if (!ComputeDataSize(1, sizeof(%s), %d, &data_size)) {
4776 return error::kOutOfBounds;
4779 file.Write(code
% (func
.info
.data_type
, func
.info
.count
))
4780 if func
.is_immediate
:
4781 file.Write(" if (data_size > immediate_data_size) {\n")
4782 file.Write(" return error::kOutOfBounds;\n")
4785 def WriteGLES2Implementation(self
, func
, file):
4786 """Overrriden from TypeHandler."""
4787 file.Write("%s GLES2Implementation::%s(%s) {\n" %
4788 (func
.return_type
, func
.original_name
,
4789 func
.MakeTypedOriginalArgString("")))
4790 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
4791 func
.WriteDestinationInitalizationValidation(file)
4792 self
.WriteClientGLCallLog(func
, file)
4793 last_arg_name
= func
.GetLastOriginalArg().name
4794 values_str
= ' << ", " << '.join(
4795 ["%s[%d]" % (last_arg_name
, ndx
) for ndx
in range(0, func
.info
.count
)])
4796 file.Write(' GPU_CLIENT_LOG("values: " << %s);\n' % values_str
)
4797 for arg
in func
.GetOriginalArgs():
4798 arg
.WriteClientSideValidationCode(file, func
)
4799 file.Write(" helper_->%sImmediate(%s);\n" %
4800 (func
.name
, func
.MakeOriginalArgString("")))
4801 file.Write(" CheckGLError();\n")
4805 def WriteGLES2ImplementationUnitTest(self
, func
, file):
4806 """Writes the GLES2 Implemention unit test."""
4808 TEST_F(GLES2ImplementationTest, %(name)s) {
4809 %(type)s data[%(count)d] = {0};
4811 cmds::%(name)sImmediate cmd;
4812 %(type)s data[%(count)d];
4815 for (int jj = 0; jj < %(count)d; ++jj) {
4816 data[jj] = static_cast<%(type)s>(jj);
4819 expected.cmd.Init(%(cmd_args)s, &data[0]);
4820 gl_->%(name)s(%(args)s, &data[0]);
4821 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
4824 cmd_arg_strings
= []
4825 for count
, arg
in enumerate(func
.GetCmdArgs()[0:-2]):
4826 cmd_arg_strings
.append(arg
.GetValidClientSideCmdArg(func
, count
, 0))
4828 for count
, arg
in enumerate(func
.GetOriginalArgs()[0:-1]):
4829 gl_arg_strings
.append(arg
.GetValidClientSideArg(func
, count
, 0))
4832 'type': func
.GetInfo('data_type'),
4833 'count': func
.GetInfo('count'),
4834 'args': ", ".join(gl_arg_strings
),
4835 'cmd_args': ", ".join(cmd_arg_strings
),
4838 def WriteImmediateCmdComputeSize(self
, func
, file):
4839 """Overrriden from TypeHandler."""
4840 file.Write(" static uint32 ComputeDataSize() {\n")
4841 file.Write(" return static_cast<uint32>(\n")
4842 file.Write(" sizeof(%s) * %d); // NOLINT\n" %
4843 (func
.info
.data_type
, func
.info
.count
))
4846 file.Write(" static uint32 ComputeSize() {\n")
4847 file.Write(" return static_cast<uint32>(\n")
4849 " sizeof(ValueType) + ComputeDataSize()); // NOLINT\n")
4853 def WriteImmediateCmdSetHeader(self
, func
, file):
4854 """Overrriden from TypeHandler."""
4855 file.Write(" void SetHeader() {\n")
4857 " header.SetCmdByTotalSize<ValueType>(ComputeSize());\n")
4861 def WriteImmediateCmdInit(self
, func
, file):
4862 """Overrriden from TypeHandler."""
4863 last_arg
= func
.GetLastOriginalArg()
4864 file.Write(" void Init(%s, %s _%s) {\n" %
4865 (func
.MakeTypedCmdArgString("_"),
4866 last_arg
.type, last_arg
.name
))
4867 file.Write(" SetHeader();\n")
4868 args
= func
.GetCmdArgs()
4870 file.Write(" %s = _%s;\n" % (arg
.name
, arg
.name
))
4871 file.Write(" memcpy(ImmediateDataAddress(this),\n")
4872 file.Write(" _%s, ComputeDataSize());\n" % last_arg
.name
)
4876 def WriteImmediateCmdSet(self
, func
, file):
4877 """Overrriden from TypeHandler."""
4878 last_arg
= func
.GetLastOriginalArg()
4879 copy_args
= func
.MakeCmdArgString("_", False)
4880 file.Write(" void* Set(void* cmd%s, %s _%s) {\n" %
4881 (func
.MakeTypedCmdArgString("_", True),
4882 last_arg
.type, last_arg
.name
))
4883 file.Write(" static_cast<ValueType*>(cmd)->Init(%s, _%s);\n" %
4884 (copy_args
, last_arg
.name
))
4885 file.Write(" const uint32 size = ComputeSize();\n")
4886 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
4891 def WriteImmediateCmdHelper(self
, func
, file):
4892 """Overrriden from TypeHandler."""
4893 code
= """ void %(name)s(%(typed_args)s) {
4894 const uint32 size = gles2::cmds::%(name)s::ComputeSize();
4895 gles2::cmds::%(name)s* c =
4896 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
4905 "typed_args": func
.MakeTypedOriginalArgString(""),
4906 "args": func
.MakeOriginalArgString(""),
4909 def WriteImmediateFormatTest(self
, func
, file):
4910 """Overrriden from TypeHandler."""
4911 file.Write("TEST_F(GLES2FormatTest, %s) {\n" % func
.name
)
4912 file.Write(" const int kSomeBaseValueToTestWith = 51;\n")
4913 file.Write(" static %s data[] = {\n" % func
.info
.data_type
)
4914 for v
in range(0, func
.info
.count
):
4915 file.Write(" static_cast<%s>(kSomeBaseValueToTestWith + %d),\n" %
4916 (func
.info
.data_type
, v
))
4918 file.Write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
4919 (func
.name
, func
.name
))
4920 file.Write(" void* next_cmd = cmd.Set(\n")
4922 args
= func
.GetCmdArgs()
4923 for value
, arg
in enumerate(args
):
4924 file.Write(",\n static_cast<%s>(%d)" % (arg
.type, value
+ 11))
4925 file.Write(",\n data);\n")
4926 args
= func
.GetCmdArgs()
4927 file.Write(" EXPECT_EQ(static_cast<uint32>(cmds::%s::kCmdId),\n"
4929 file.Write(" cmd.header.command);\n")
4930 file.Write(" EXPECT_EQ(sizeof(cmd) +\n")
4931 file.Write(" RoundSizeToMultipleOfEntries(sizeof(data)),\n")
4932 file.Write(" cmd.header.size * 4u);\n")
4933 for value
, arg
in enumerate(args
):
4934 file.Write(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);\n" %
4935 (arg
.type, value
+ 11, arg
.name
))
4936 file.Write(" CheckBytesWrittenMatchesExpectedSize(\n")
4937 file.Write(" next_cmd, sizeof(cmd) +\n")
4938 file.Write(" RoundSizeToMultipleOfEntries(sizeof(data)));\n")
4939 file.Write(" // TODO(gman): Check that data was inserted;\n")
4944 class PUTnHandler(TypeHandler
):
4945 """Handler for PUTn 'glUniform__v' type functions."""
4948 TypeHandler
.__init
__(self
)
4950 def WriteServiceUnitTest(self
, func
, file):
4951 """Overridden from TypeHandler."""
4952 TypeHandler
.WriteServiceUnitTest(self
, func
, file)
4955 TEST_F(%(test_name)s, %(name)sValidArgsCountTooLarge) {
4956 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
4957 SpecializedSetup<cmds::%(name)s, 0>(true);
4960 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4961 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4966 for count
, arg
in enumerate(func
.GetOriginalArgs()):
4967 # hardcoded to match unit tests.
4969 # the location of the second element of the 2nd uniform.
4970 # defined in GLES2DecoderBase::SetupShaderForUniform
4971 gl_arg_strings
.append("3")
4972 arg_strings
.append("ProgramManager::MakeFakeLocation(1, 1)")
4974 # the number of elements that gl will be called with.
4975 gl_arg_strings
.append("3")
4976 # the number of elements requested in the command.
4977 arg_strings
.append("5")
4979 gl_arg_strings
.append(arg
.GetValidGLArg(func
, count
, 0))
4980 arg_strings
.append(arg
.GetValidArg(func
, count
, 0))
4982 'gl_args': ", ".join(gl_arg_strings
),
4983 'args': ", ".join(arg_strings
),
4985 self
.WriteValidUnitTest(func
, file, valid_test
, extra
)
4987 def WriteImmediateServiceUnitTest(self
, func
, file):
4988 """Overridden from TypeHandler."""
4990 TEST_F(%(test_name)s, %(name)sValidArgs) {
4991 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
4994 %(gl_func_name)s(%(gl_args)s,
4995 reinterpret_cast<%(data_type)s*>(ImmediateDataAddress(&cmd))));
4996 SpecializedSetup<cmds::%(name)s, 0>(true);
4997 %(data_type)s temp[%(data_count)s * 2] = { 0, };
4998 cmd.Init(%(args)s, &temp[0]);
4999 EXPECT_EQ(error::kNoError,
5000 ExecuteImmediateCmd(cmd, sizeof(temp)));
5001 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5007 for count
, arg
in enumerate(func
.GetOriginalArgs()[0:-1]):
5008 gl_arg_strings
.append(arg
.GetValidGLArg(func
, count
, 0))
5009 gl_any_strings
.append("_")
5010 arg_strings
.append(arg
.GetValidArg(func
, count
, 0))
5012 'data_type': func
.GetInfo('data_type'),
5013 'data_count': func
.GetInfo('count'),
5014 'args': ", ".join(arg_strings
),
5015 'gl_args': ", ".join(gl_arg_strings
),
5016 'gl_any_args': ", ".join(gl_any_strings
),
5018 self
.WriteValidUnitTest(func
, file, valid_test
, extra
)
5021 TEST_F(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
5022 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
5023 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_any_args)s, _)).Times(0);
5024 SpecializedSetup<cmds::%(name)s, 0>(false);
5025 %(data_type)s temp[%(data_count)s * 2] = { 0, };
5026 cmd.Init(%(all_but_last_args)s, &temp[0]);
5027 EXPECT_EQ(error::%(parse_result)s,
5028 ExecuteImmediateCmd(cmd, sizeof(temp)));%(gl_error_test)s
5031 self
.WriteInvalidUnitTest(func
, file, invalid_test
, extra
)
5033 def WriteGetDataSizeCode(self
, func
, file):
5034 """Overrriden from TypeHandler."""
5035 code
= """ uint32 data_size;
5036 if (!ComputeDataSize(count, sizeof(%s), %d, &data_size)) {
5037 return error::kOutOfBounds;
5040 file.Write(code
% (func
.info
.data_type
, func
.info
.count
))
5041 if func
.is_immediate
:
5042 file.Write(" if (data_size > immediate_data_size) {\n")
5043 file.Write(" return error::kOutOfBounds;\n")
5046 def WriteGLES2Implementation(self
, func
, file):
5047 """Overrriden from TypeHandler."""
5048 file.Write("%s GLES2Implementation::%s(%s) {\n" %
5049 (func
.return_type
, func
.original_name
,
5050 func
.MakeTypedOriginalArgString("")))
5051 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
5052 func
.WriteDestinationInitalizationValidation(file)
5053 self
.WriteClientGLCallLog(func
, file)
5054 last_arg_name
= func
.GetLastOriginalArg().name
5055 file.Write(""" GPU_CLIENT_LOG_CODE_BLOCK({
5056 for (GLsizei i = 0; i < count; ++i) {
5058 values_str
= ' << ", " << '.join(
5059 ["%s[%d + i * %d]" % (
5060 last_arg_name
, ndx
, func
.info
.count
) for ndx
in range(
5061 0, func
.info
.count
)])
5062 file.Write(' GPU_CLIENT_LOG(" " << i << ": " << %s);\n' % values_str
)
5063 file.Write(" }\n });\n")
5064 for arg
in func
.GetOriginalArgs():
5065 arg
.WriteClientSideValidationCode(file, func
)
5066 file.Write(" helper_->%sImmediate(%s);\n" %
5067 (func
.name
, func
.MakeOriginalArgString("")))
5068 file.Write(" CheckGLError();\n")
5072 def WriteGLES2ImplementationUnitTest(self
, func
, file):
5073 """Writes the GLES2 Implemention unit test."""
5075 TEST_F(GLES2ImplementationTest, %(name)s) {
5076 %(type)s data[%(count_param)d][%(count)d] = {{0}};
5078 cmds::%(name)sImmediate cmd;
5079 %(type)s data[%(count_param)d][%(count)d];
5083 for (int ii = 0; ii < %(count_param)d; ++ii) {
5084 for (int jj = 0; jj < %(count)d; ++jj) {
5085 data[ii][jj] = static_cast<%(type)s>(ii * %(count)d + jj);
5088 expected.cmd.Init(%(cmd_args)s, &data[0][0]);
5089 gl_->%(name)s(%(args)s, &data[0][0]);
5090 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
5093 cmd_arg_strings
= []
5094 for count
, arg
in enumerate(func
.GetCmdArgs()[0:-2]):
5095 cmd_arg_strings
.append(arg
.GetValidClientSideCmdArg(func
, count
, 0))
5098 for count
, arg
in enumerate(func
.GetOriginalArgs()[0:-1]):
5099 gl_arg_strings
.append(arg
.GetValidClientSideArg(func
, count
, 0))
5100 if arg
.name
== "count":
5101 count_param
= int(arg
.GetValidClientSideArg(func
, count
, 0))
5104 'type': func
.GetInfo('data_type'),
5105 'count': func
.GetInfo('count'),
5106 'args': ", ".join(gl_arg_strings
),
5107 'cmd_args': ", ".join(cmd_arg_strings
),
5108 'count_param': count_param
,
5111 def WriteImmediateCmdComputeSize(self
, func
, file):
5112 """Overrriden from TypeHandler."""
5113 file.Write(" static uint32 ComputeDataSize(GLsizei count) {\n")
5114 file.Write(" return static_cast<uint32>(\n")
5115 file.Write(" sizeof(%s) * %d * count); // NOLINT\n" %
5116 (func
.info
.data_type
, func
.info
.count
))
5119 file.Write(" static uint32 ComputeSize(GLsizei count) {\n")
5120 file.Write(" return static_cast<uint32>(\n")
5122 " sizeof(ValueType) + ComputeDataSize(count)); // NOLINT\n")
5126 def WriteImmediateCmdSetHeader(self
, func
, file):
5127 """Overrriden from TypeHandler."""
5128 file.Write(" void SetHeader(GLsizei count) {\n")
5130 " header.SetCmdByTotalSize<ValueType>(ComputeSize(count));\n")
5134 def WriteImmediateCmdInit(self
, func
, file):
5135 """Overrriden from TypeHandler."""
5136 last_arg
= func
.GetLastOriginalArg()
5137 file.Write(" void Init(%s, %s _%s) {\n" %
5138 (func
.MakeTypedCmdArgString("_"),
5139 last_arg
.type, last_arg
.name
))
5140 file.Write(" SetHeader(_count);\n")
5141 args
= func
.GetCmdArgs()
5143 file.Write(" %s = _%s;\n" % (arg
.name
, arg
.name
))
5144 file.Write(" memcpy(ImmediateDataAddress(this),\n")
5145 file.Write(" _%s, ComputeDataSize(_count));\n" % last_arg
.name
)
5149 def WriteImmediateCmdSet(self
, func
, file):
5150 """Overrriden from TypeHandler."""
5151 last_arg
= func
.GetLastOriginalArg()
5152 copy_args
= func
.MakeCmdArgString("_", False)
5153 file.Write(" void* Set(void* cmd%s, %s _%s) {\n" %
5154 (func
.MakeTypedCmdArgString("_", True),
5155 last_arg
.type, last_arg
.name
))
5156 file.Write(" static_cast<ValueType*>(cmd)->Init(%s, _%s);\n" %
5157 (copy_args
, last_arg
.name
))
5158 file.Write(" const uint32 size = ComputeSize(_count);\n")
5159 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
5164 def WriteImmediateCmdHelper(self
, func
, file):
5165 """Overrriden from TypeHandler."""
5166 code
= """ void %(name)s(%(typed_args)s) {
5167 const uint32 size = gles2::cmds::%(name)s::ComputeSize(count);
5168 gles2::cmds::%(name)s* c =
5169 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
5178 "typed_args": func
.MakeTypedOriginalArgString(""),
5179 "args": func
.MakeOriginalArgString(""),
5182 def WriteImmediateFormatTest(self
, func
, file):
5183 """Overrriden from TypeHandler."""
5184 args
= func
.GetCmdArgs()
5186 for value
, arg
in enumerate(args
):
5187 if arg
.name
== "count":
5188 count_param
= int(arg
.GetValidClientSideArg(func
, value
, 0))
5189 file.Write("TEST_F(GLES2FormatTest, %s) {\n" % func
.name
)
5190 file.Write(" const int kSomeBaseValueToTestWith = 51;\n")
5191 file.Write(" static %s data[] = {\n" % func
.info
.data_type
)
5192 for v
in range(0, func
.info
.count
* count_param
):
5193 file.Write(" static_cast<%s>(kSomeBaseValueToTestWith + %d),\n" %
5194 (func
.info
.data_type
, v
))
5196 file.Write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
5197 (func
.name
, func
.name
))
5198 file.Write(" const GLsizei kNumElements = %d;\n" % count_param
)
5199 file.Write(" const size_t kExpectedCmdSize =\n")
5200 file.Write(" sizeof(cmd) + kNumElements * sizeof(%s) * %d;\n" %
5201 (func
.info
.data_type
, func
.info
.count
))
5202 file.Write(" void* next_cmd = cmd.Set(\n")
5204 for value
, arg
in enumerate(args
):
5205 file.Write(",\n static_cast<%s>(%d)" % (arg
.type, value
+ 1))
5206 file.Write(",\n data);\n")
5207 file.Write(" EXPECT_EQ(static_cast<uint32>(cmds::%s::kCmdId),\n" %
5209 file.Write(" cmd.header.command);\n")
5210 file.Write(" EXPECT_EQ(kExpectedCmdSize, cmd.header.size * 4u);\n")
5211 for value
, arg
in enumerate(args
):
5212 file.Write(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);\n" %
5213 (arg
.type, value
+ 1, arg
.name
))
5214 file.Write(" CheckBytesWrittenMatchesExpectedSize(\n")
5215 file.Write(" next_cmd, sizeof(cmd) +\n")
5216 file.Write(" RoundSizeToMultipleOfEntries(sizeof(data)));\n")
5217 file.Write(" // TODO(gman): Check that data was inserted;\n")
5222 class PUTXnHandler(TypeHandler
):
5223 """Handler for glUniform?f functions."""
5225 TypeHandler
.__init
__(self
)
5227 def WriteHandlerImplementation(self
, func
, file):
5228 """Overrriden from TypeHandler."""
5229 code
= """ %(type)s temp[%(count)s] = { %(values)s};
5230 Do%(name)sv(%(location)s, 1, &temp[0]);
5233 args
= func
.GetOriginalArgs()
5234 count
= int(func
.GetInfo('count'))
5235 num_args
= len(args
)
5236 for ii
in range(count
):
5237 values
+= "%s, " % args
[len(args
) - count
+ ii
].name
5241 'count': func
.GetInfo('count'),
5242 'type': func
.GetInfo('data_type'),
5243 'location': args
[0].name
,
5244 'args': func
.MakeOriginalArgString(""),
5248 def WriteServiceUnitTest(self
, func
, file):
5249 """Overrriden from TypeHandler."""
5251 TEST_F(%(test_name)s, %(name)sValidArgs) {
5252 EXPECT_CALL(*gl_, %(name)sv(%(local_args)s));
5253 SpecializedSetup<cmds::%(name)s, 0>(true);
5256 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5257 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5260 args
= func
.GetOriginalArgs()
5261 local_args
= "%s, 1, _" % args
[0].GetValidGLArg(func
, 0, 0)
5262 self
.WriteValidUnitTest(func
, file, valid_test
, {
5264 'count': func
.GetInfo('count'),
5265 'local_args': local_args
,
5269 TEST_F(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
5270 EXPECT_CALL(*gl_, %(name)sv(_, _, _).Times(0);
5271 SpecializedSetup<cmds::%(name)s, 0>(false);
5274 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
5277 self
.WriteInvalidUnitTest(func
, file, invalid_test
, {
5278 'name': func
.GetInfo('name'),
5279 'count': func
.GetInfo('count'),
5283 class GLcharHandler(CustomHandler
):
5284 """Handler for functions that pass a single string ."""
5287 CustomHandler
.__init
__(self
)
5289 def WriteImmediateCmdComputeSize(self
, func
, file):
5290 """Overrriden from TypeHandler."""
5291 file.Write(" static uint32 ComputeSize(uint32 data_size) {\n")
5292 file.Write(" return static_cast<uint32>(\n")
5293 file.Write(" sizeof(ValueType) + data_size); // NOLINT\n")
5296 def WriteImmediateCmdSetHeader(self
, func
, file):
5297 """Overrriden from TypeHandler."""
5299 void SetHeader(uint32 data_size) {
5300 header.SetCmdBySize<ValueType>(data_size);
5305 def WriteImmediateCmdInit(self
, func
, file):
5306 """Overrriden from TypeHandler."""
5307 last_arg
= func
.GetLastOriginalArg()
5308 args
= func
.GetCmdArgs()
5311 set_code
.append(" %s = _%s;" % (arg
.name
, arg
.name
))
5313 void Init(%(typed_args)s, uint32 _data_size) {
5314 SetHeader(_data_size);
5316 memcpy(ImmediateDataAddress(this), _%(last_arg)s, _data_size);
5321 "typed_args": func
.MakeTypedOriginalArgString("_"),
5322 "set_code": "\n".join(set_code
),
5323 "last_arg": last_arg
.name
5326 def WriteImmediateCmdSet(self
, func
, file):
5327 """Overrriden from TypeHandler."""
5328 last_arg
= func
.GetLastOriginalArg()
5329 file.Write(" void* Set(void* cmd%s, uint32 _data_size) {\n" %
5330 func
.MakeTypedOriginalArgString("_", True))
5331 file.Write(" static_cast<ValueType*>(cmd)->Init(%s, _data_size);\n" %
5332 func
.MakeOriginalArgString("_"))
5333 file.Write(" return NextImmediateCmdAddress<ValueType>("
5334 "cmd, _data_size);\n")
5338 def WriteImmediateCmdHelper(self
, func
, file):
5339 """Overrriden from TypeHandler."""
5340 code
= """ void %(name)s(%(typed_args)s) {
5341 const uint32 data_size = strlen(name);
5342 gles2::cmds::%(name)s* c =
5343 GetImmediateCmdSpace<gles2::cmds::%(name)s>(data_size);
5345 c->Init(%(args)s, data_size);
5352 "typed_args": func
.MakeTypedOriginalArgString(""),
5353 "args": func
.MakeOriginalArgString(""),
5357 def WriteImmediateFormatTest(self
, func
, file):
5358 """Overrriden from TypeHandler."""
5361 all_but_last_arg
= func
.GetCmdArgs()[:-1]
5362 for value
, arg
in enumerate(all_but_last_arg
):
5363 init_code
.append(" static_cast<%s>(%d)," % (arg
.type, value
+ 11))
5364 for value
, arg
in enumerate(all_but_last_arg
):
5365 check_code
.append(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);" %
5366 (arg
.type, value
+ 11, arg
.name
))
5368 TEST_F(GLES2FormatTest, %(func_name)s) {
5369 cmds::%(func_name)s& cmd = *GetBufferAs<cmds::%(func_name)s>();
5370 static const char* const test_str = \"test string\";
5371 void* next_cmd = cmd.Set(
5376 EXPECT_EQ(static_cast<uint32>(cmds::%(func_name)s::kCmdId),
5377 cmd.header.command);
5378 EXPECT_EQ(sizeof(cmd) +
5379 RoundSizeToMultipleOfEntries(strlen(test_str)),
5380 cmd.header.size * 4u);
5381 EXPECT_EQ(static_cast<char*>(next_cmd),
5382 reinterpret_cast<char*>(&cmd) + sizeof(cmd) +
5383 RoundSizeToMultipleOfEntries(strlen(test_str)));
5385 EXPECT_EQ(static_cast<uint32>(strlen(test_str)), cmd.data_size);
5386 EXPECT_EQ(0, memcmp(test_str, ImmediateDataAddress(&cmd), strlen(test_str)));
5389 sizeof(cmd) + RoundSizeToMultipleOfEntries(strlen(test_str)),
5390 sizeof(cmd) + strlen(test_str));
5395 'func_name': func
.name
,
5396 'init_code': "\n".join(init_code
),
5397 'check_code': "\n".join(check_code
),
5401 class GLcharNHandler(CustomHandler
):
5402 """Handler for functions that pass a single string with an optional len."""
5405 CustomHandler
.__init
__(self
)
5407 def InitFunction(self
, func
):
5408 """Overrriden from TypeHandler."""
5410 func
.AddCmdArg(Argument('bucket_id', 'GLuint'))
5412 def AddImmediateFunction(self
, generator
, func
):
5413 """Overrriden from TypeHandler."""
5416 def AddBucketFunction(self
, generator
, func
):
5417 """Overrriden from TypeHandler."""
5420 def WriteServiceImplementation(self
, func
, file):
5421 """Overrriden from TypeHandler."""
5422 file.Write("""error::Error GLES2DecoderImpl::Handle%(name)s(
5423 uint32 immediate_data_size, const gles2::cmds::%(name)s& c) {
5424 GLuint bucket_id = static_cast<GLuint>(c.%(bucket_id)s);
5425 Bucket* bucket = GetBucket(bucket_id);
5426 if (!bucket || bucket->size() == 0) {
5427 return error::kInvalidArguments;
5430 if (!bucket->GetAsString(&str)) {
5431 return error::kInvalidArguments;
5433 %(gl_func_name)s(0, str.c_str());
5434 return error::kNoError;
5439 'gl_func_name': func
.GetGLFunctionName(),
5440 'bucket_id': func
.cmd_args
[0].name
,
5444 class IsHandler(TypeHandler
):
5445 """Handler for glIs____ type and glGetError functions."""
5448 TypeHandler
.__init
__(self
)
5450 def InitFunction(self
, func
):
5451 """Overrriden from TypeHandler."""
5452 func
.AddCmdArg(Argument("result_shm_id", 'uint32'))
5453 func
.AddCmdArg(Argument("result_shm_offset", 'uint32'))
5454 if func
.GetInfo('result') == None:
5455 func
.AddInfo('result', ['uint32'])
5457 def WriteServiceUnitTest(self
, func
, file):
5458 """Overrriden from TypeHandler."""
5460 TEST_F(%(test_name)s, %(name)sValidArgs) {
5461 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
5462 SpecializedSetup<cmds::%(name)s, 0>(true);
5464 cmd.Init(%(args)s%(comma)sshared_memory_id_, shared_memory_offset_);
5465 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5466 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5470 if len(func
.GetOriginalArgs()):
5472 self
.WriteValidUnitTest(func
, file, valid_test
, {
5477 TEST_F(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
5478 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
5479 SpecializedSetup<cmds::%(name)s, 0>(false);
5481 cmd.Init(%(args)s%(comma)sshared_memory_id_, shared_memory_offset_);
5482 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
5485 self
.WriteInvalidUnitTest(func
, file, invalid_test
, {
5490 TEST_F(%(test_name)s, %(name)sInvalidArgsBadSharedMemoryId) {
5491 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
5492 SpecializedSetup<cmds::%(name)s, 0>(false);
5494 cmd.Init(%(args)s%(comma)skInvalidSharedMemoryId, shared_memory_offset_);
5495 EXPECT_EQ(error::kOutOfBounds, ExecuteCmd(cmd));
5496 cmd.Init(%(args)s%(comma)sshared_memory_id_, kInvalidSharedMemoryOffset);
5497 EXPECT_EQ(error::kOutOfBounds, ExecuteCmd(cmd));
5500 self
.WriteValidUnitTest(func
, file, invalid_test
, {
5504 def WriteServiceImplementation(self
, func
, file):
5505 """Overrriden from TypeHandler."""
5507 "error::Error GLES2DecoderImpl::Handle%s(\n" % func
.name
)
5509 " uint32 immediate_data_size, const gles2::cmds::%s& c) {\n" %
5511 args
= func
.GetOriginalArgs()
5513 arg
.WriteGetCode(file)
5515 code
= """ typedef cmds::%(func_name)s::Result Result;
5516 Result* result_dst = GetSharedMemoryAs<Result*>(
5517 c.result_shm_id, c.result_shm_offset, sizeof(*result_dst));
5519 return error::kOutOfBounds;
5522 file.Write(code
% {'func_name': func
.name
})
5523 func
.WriteHandlerValidation(file)
5524 file.Write(" *result_dst = %s(%s);\n" %
5525 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
5526 file.Write(" return error::kNoError;\n")
5530 def WriteGLES2Implementation(self
, func
, file):
5531 """Overrriden from TypeHandler."""
5532 impl_func
= func
.GetInfo('impl_func')
5533 if impl_func
== None or impl_func
== True:
5534 error_value
= func
.GetInfo("error_value") or "GL_FALSE"
5535 file.Write("%s GLES2Implementation::%s(%s) {\n" %
5536 (func
.return_type
, func
.original_name
,
5537 func
.MakeTypedOriginalArgString("")))
5538 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
5539 self
.WriteTraceEvent(func
, file)
5540 func
.WriteDestinationInitalizationValidation(file)
5541 self
.WriteClientGLCallLog(func
, file)
5542 file.Write(" typedef cmds::%s::Result Result;\n" % func
.name
)
5543 file.Write(" Result* result = GetResultAs<Result*>();\n")
5544 file.Write(" if (!result) {\n")
5545 file.Write(" return %s;\n" % error_value
)
5547 file.Write(" *result = 0;\n")
5548 arg_string
= func
.MakeOriginalArgString("")
5550 if len(arg_string
) > 0:
5553 " helper_->%s(%s%sGetResultShmId(), GetResultShmOffset());\n" %
5554 (func
.name
, arg_string
, comma
))
5555 file.Write(" WaitForCmd();\n")
5556 file.Write(" %s result_value = *result;\n" % func
.return_type
)
5557 file.Write(' GPU_CLIENT_LOG("returned " << result_value);\n')
5558 file.Write(" CheckGLError();\n")
5559 file.Write(" return result_value;\n")
5563 def WriteGLES2ImplementationUnitTest(self
, func
, file):
5564 """Overrriden from TypeHandler."""
5565 client_test
= func
.GetInfo('client_test')
5566 if client_test
== None or client_test
== True:
5568 TEST_F(GLES2ImplementationTest, %(name)s) {
5573 typedef cmds::%(name)s::Result Result;
5575 ExpectedMemoryInfo result1 =
5576 GetExpectedResultMemory(sizeof(cmds::%(name)s::Result));
5577 expected.cmd.Init(1, result1.id, result1.offset);
5579 EXPECT_CALL(*command_buffer(), OnFlush())
5580 .WillOnce(SetMemory(result1.ptr, uint32(1)))
5581 .RetiresOnSaturation();
5583 GLboolean result = gl_->%(name)s(1);
5584 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
5585 EXPECT_TRUE(result);
5593 class STRnHandler(TypeHandler
):
5594 """Handler for GetProgramInfoLog, GetShaderInfoLog, GetShaderSource, and
5595 GetTranslatedShaderSourceANGLE."""
5598 TypeHandler
.__init
__(self
)
5600 def InitFunction(self
, func
):
5601 """Overrriden from TypeHandler."""
5602 # remove all but the first cmd args.
5603 cmd_args
= func
.GetCmdArgs()
5605 func
.AddCmdArg(cmd_args
[0])
5606 # add on a bucket id.
5607 func
.AddCmdArg(Argument('bucket_id', 'uint32'))
5609 def WriteGLES2Implementation(self
, func
, file):
5610 """Overrriden from TypeHandler."""
5611 code_1
= """%(return_type)s GLES2Implementation::%(func_name)s(%(args)s) {
5612 GPU_CLIENT_SINGLE_THREAD_CHECK();
5614 code_2
= """ GPU_CLIENT_LOG("[" << GetLogPrefix()
5615 << "] gl%(func_name)s" << "("
5618 << static_cast<void*>(%(arg2)s) << ", "
5619 << static_cast<void*>(%(arg3)s) << ")");
5620 helper_->SetBucketSize(kResultBucketId, 0);
5621 helper_->%(func_name)s(%(id_name)s, kResultBucketId);
5623 GLsizei max_size = 0;
5624 if (GetBucketAsString(kResultBucketId, &str)) {
5627 std::min(static_cast<size_t>(%(bufsize_name)s) - 1, str.size());
5628 memcpy(%(dest_name)s, str.c_str(), max_size);
5629 %(dest_name)s[max_size] = '\\0';
5630 GPU_CLIENT_LOG("------\\n" << %(dest_name)s << "\\n------");
5633 if (%(length_name)s != NULL) {
5634 *%(length_name)s = max_size;
5639 args
= func
.GetOriginalArgs()
5641 'return_type': func
.return_type
,
5642 'func_name': func
.original_name
,
5643 'args': func
.MakeTypedOriginalArgString(""),
5644 'id_name': args
[0].name
,
5645 'bufsize_name': args
[1].name
,
5646 'length_name': args
[2].name
,
5647 'dest_name': args
[3].name
,
5648 'arg0': args
[0].name
,
5649 'arg1': args
[1].name
,
5650 'arg2': args
[2].name
,
5651 'arg3': args
[3].name
,
5653 file.Write(code_1
% str_args
)
5654 func
.WriteDestinationInitalizationValidation(file)
5655 file.Write(code_2
% str_args
)
5657 def WriteServiceUnitTest(self
, func
, file):
5658 """Overrriden from TypeHandler."""
5660 TEST_F(%(test_name)s, %(name)sValidArgs) {
5661 const char* kInfo = "hello";
5662 const uint32 kBucketId = 123;
5663 SpecializedSetup<cmds::%(name)s, 0>(true);
5665 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s))
5666 .WillOnce(DoAll(SetArgumentPointee<2>(strlen(kInfo)),
5667 SetArrayArgument<3>(kInfo, kInfo + strlen(kInfo) + 1)));
5670 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5671 CommonDecoder::Bucket* bucket = decoder_->GetBucket(kBucketId);
5672 ASSERT_TRUE(bucket != NULL);
5673 EXPECT_EQ(strlen(kInfo) + 1, bucket->size());
5674 EXPECT_EQ(0, memcmp(bucket->GetData(0, bucket->size()), kInfo,
5676 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5679 args
= func
.GetOriginalArgs()
5680 id_name
= args
[0].GetValidGLArg(func
, 0, 0)
5681 get_len_func
= func
.GetInfo('get_len_func')
5682 get_len_enum
= func
.GetInfo('get_len_enum')
5685 'get_len_func': get_len_func
,
5686 'get_len_enum': get_len_enum
,
5687 'gl_args': '%s, strlen(kInfo) + 1, _, _' %
5688 args
[0].GetValidGLArg(func
, 0, 0),
5689 'args': '%s, kBucketId' % args
[0].GetValidArg(func
, 0, 0),
5690 'expect_len_code': '',
5692 if get_len_func
and get_len_func
[0:2] == 'gl':
5693 sub
['expect_len_code'] = (
5694 " EXPECT_CALL(*gl_, %s(%s, %s, _))\n"
5695 " .WillOnce(SetArgumentPointee<2>(strlen(kInfo) + 1));") % (
5696 get_len_func
[2:], id_name
, get_len_enum
)
5697 self
.WriteValidUnitTest(func
, file, valid_test
, sub
)
5700 TEST_F(%(test_name)s, %(name)sInvalidArgs) {
5701 const uint32 kBucketId = 123;
5702 EXPECT_CALL(*gl_, %(gl_func_name)s(_, _, _, _))
5705 cmd.Init(kInvalidClientId, kBucketId);
5706 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5707 EXPECT_EQ(GL_INVALID_VALUE, GetGLError());
5710 self
.WriteValidUnitTest(func
, file, invalid_test
)
5712 def WriteServiceImplementation(self
, func
, file):
5713 """Overrriden from TypeHandler."""
5717 class FunctionInfo(object):
5718 """Holds info about a function."""
5720 def __init__(self
, info
, type_handler
):
5722 setattr(self
, key
, info
[key
])
5723 self
.type_handler
= type_handler
5724 if not 'type' in info
:
5728 class Argument(object):
5729 """A class that represents a function argument."""
5734 'GLintptr': 'int32',
5736 'GLsizeiptr': 'int32',
5738 'GLclampf': 'float',
5740 need_validation_
= ['GLsizei*', 'GLboolean*', 'GLenum*', 'GLint*']
5742 def __init__(self
, name
, type):
5744 self
.optional
= type.endswith("Optional*")
5746 type = type[:-9] + "*"
5749 if type in self
.cmd_type_map_
:
5750 self
.cmd_type
= self
.cmd_type_map_
[type]
5752 self
.cmd_type
= 'uint32'
5754 def IsPointer(self
):
5755 """Returns true if argument is a pointer."""
5758 def AddCmdArgs(self
, args
):
5759 """Adds command arguments for this argument to the given list."""
5760 return args
.append(self
)
5762 def AddInitArgs(self
, args
):
5763 """Adds init arguments for this argument to the given list."""
5764 return args
.append(self
)
5766 def GetValidArg(self
, func
, offset
, index
):
5767 """Gets a valid value for this argument."""
5768 valid_arg
= func
.GetValidArg(offset
)
5769 if valid_arg
!= None:
5771 return str(offset
+ 1)
5773 def GetValidClientSideArg(self
, func
, offset
, index
):
5774 """Gets a valid value for this argument."""
5775 return str(offset
+ 1)
5777 def GetValidClientSideCmdArg(self
, func
, offset
, index
):
5778 """Gets a valid value for this argument."""
5779 return str(offset
+ 1)
5781 def GetValidGLArg(self
, func
, offset
, index
):
5782 """Gets a valid GL value for this argument."""
5783 valid_arg
= func
.GetValidArg(offset
)
5784 if valid_arg
!= None:
5786 return str(offset
+ 1)
5788 def GetNumInvalidValues(self
, func
):
5789 """returns the number of invalid values to be tested."""
5792 def GetInvalidArg(self
, offset
, index
):
5793 """returns an invalid value and expected parse result by index."""
5794 return ("---ERROR0---", "---ERROR2---", None)
5796 def GetLogArg(self
):
5797 """Get argument appropriate for LOG macro."""
5798 if self
.type == 'GLboolean':
5799 return 'GLES2Util::GetStringBool(%s)' % self
.name
5800 if self
.type == 'GLenum':
5801 return 'GLES2Util::GetStringEnum(%s)' % self
.name
5804 def WriteGetCode(self
, file):
5805 """Writes the code to get an argument from a command structure."""
5806 file.Write(" %s %s = static_cast<%s>(c.%s);\n" %
5807 (self
.type, self
.name
, self
.type, self
.name
))
5809 def WriteValidationCode(self
, file, func
):
5810 """Writes the validation code for an argument."""
5813 def WriteClientSideValidationCode(self
, file, func
):
5814 """Writes the validation code for an argument."""
5817 def WriteDestinationInitalizationValidation(self
, file, func
):
5818 """Writes the client side destintion initialization validation."""
5821 def WriteDestinationInitalizationValidatationIfNeeded(self
, file, func
):
5822 """Writes the client side destintion initialization validation if needed."""
5823 parts
= self
.type.split(" ")
5826 if parts
[0] in self
.need_validation_
:
5828 " GPU_CLIENT_VALIDATE_DESTINATION_%sINITALIZATION(%s, %s);\n" %
5829 ("OPTIONAL_" if self
.optional
else "", self
.type[:-1], self
.name
))
5832 def WriteGetAddress(self
, file):
5833 """Writes the code to get the address this argument refers to."""
5836 def GetImmediateVersion(self
):
5837 """Gets the immediate version of this argument."""
5840 def GetBucketVersion(self
):
5841 """Gets the bucket version of this argument."""
5845 class BoolArgument(Argument
):
5846 """class for GLboolean"""
5848 def __init__(self
, name
, type):
5849 Argument
.__init
__(self
, name
, 'GLboolean')
5851 def GetValidArg(self
, func
, offset
, index
):
5852 """Gets a valid value for this argument."""
5855 def GetValidClientSideArg(self
, func
, offset
, index
):
5856 """Gets a valid value for this argument."""
5859 def GetValidClientSideCmdArg(self
, func
, offset
, index
):
5860 """Gets a valid value for this argument."""
5863 def GetValidGLArg(self
, func
, offset
, index
):
5864 """Gets a valid GL value for this argument."""
5868 class UniformLocationArgument(Argument
):
5869 """class for uniform locations."""
5871 def __init__(self
, name
):
5872 Argument
.__init
__(self
, name
, "GLint")
5874 def WriteGetCode(self
, file):
5875 """Writes the code to get an argument from a command structure."""
5876 code
= """ %s %s = static_cast<%s>(c.%s);
5878 file.Write(code
% (self
.type, self
.name
, self
.type, self
.name
))
5880 def GetValidArg(self
, func
, offset
, index
):
5881 """Gets a valid value for this argument."""
5882 return "%d" % (offset
+ 1)
5885 class DataSizeArgument(Argument
):
5886 """class for data_size which Bucket commands do not need."""
5888 def __init__(self
, name
):
5889 Argument
.__init
__(self
, name
, "uint32")
5891 def GetBucketVersion(self
):
5895 class SizeArgument(Argument
):
5896 """class for GLsizei and GLsizeiptr."""
5898 def __init__(self
, name
, type):
5899 Argument
.__init
__(self
, name
, type)
5901 def GetNumInvalidValues(self
, func
):
5902 """overridden from Argument."""
5903 if func
.is_immediate
:
5907 def GetInvalidArg(self
, offset
, index
):
5908 """overridden from Argument."""
5909 return ("-1", "kNoError", "GL_INVALID_VALUE")
5911 def WriteValidationCode(self
, file, func
):
5912 """overridden from Argument."""
5913 file.Write(" if (%s < 0) {\n" % self
.name
)
5915 " LOCAL_SET_GL_ERROR(GL_INVALID_VALUE, \"gl%s\", \"%s < 0\");\n" %
5916 (func
.original_name
, self
.name
))
5917 file.Write(" return error::kNoError;\n")
5920 def WriteClientSideValidationCode(self
, file, func
):
5921 """overridden from Argument."""
5922 file.Write(" if (%s < 0) {\n" % self
.name
)
5924 " SetGLError(GL_INVALID_VALUE, \"gl%s\", \"%s < 0\");\n" %
5925 (func
.original_name
, self
.name
))
5926 file.Write(" return;\n")
5930 class SizeNotNegativeArgument(SizeArgument
):
5931 """class for GLsizeiNotNegative. It's NEVER allowed to be negative"""
5933 def __init__(self
, name
, type, gl_type
):
5934 SizeArgument
.__init
__(self
, name
, gl_type
)
5936 def GetInvalidArg(self
, offset
, index
):
5937 """overridden from SizeArgument."""
5938 return ("-1", "kOutOfBounds", "GL_NO_ERROR")
5940 def WriteValidationCode(self
, file, func
):
5941 """overridden from SizeArgument."""
5945 class EnumBaseArgument(Argument
):
5946 """Base class for EnumArgument, IntArgument and ValidatedBoolArgument"""
5948 def __init__(self
, name
, gl_type
, type, gl_error
):
5949 Argument
.__init
__(self
, name
, gl_type
)
5951 self
.local_type
= type
5952 self
.gl_error
= gl_error
5953 name
= type[len(gl_type
):]
5954 self
.type_name
= name
5955 self
.enum_info
= _ENUM_LISTS
[name
]
5957 def WriteValidationCode(self
, file, func
):
5958 file.Write(" if (!validators_->%s.IsValid(%s)) {\n" %
5959 (ToUnderscore(self
.type_name
), self
.name
))
5960 if self
.gl_error
== "GL_INVALID_ENUM":
5962 " LOCAL_SET_GL_ERROR_INVALID_ENUM(\"gl%s\", %s, \"%s\");\n" %
5963 (func
.original_name
, self
.name
, self
.name
))
5966 " LOCAL_SET_GL_ERROR(%s, \"gl%s\", \"%s %s\");\n" %
5967 (self
.gl_error
, func
.original_name
, self
.name
, self
.gl_error
))
5968 file.Write(" return error::kNoError;\n")
5971 def GetValidArg(self
, func
, offset
, index
):
5972 valid_arg
= func
.GetValidArg(offset
)
5973 if valid_arg
!= None:
5975 if 'valid' in self
.enum_info
:
5976 valid
= self
.enum_info
['valid']
5977 num_valid
= len(valid
)
5978 if index
>= num_valid
:
5979 index
= num_valid
- 1
5981 return str(offset
+ 1)
5983 def GetValidClientSideArg(self
, func
, offset
, index
):
5984 """Gets a valid value for this argument."""
5985 return self
.GetValidArg(func
, offset
, index
)
5987 def GetValidClientSideCmdArg(self
, func
, offset
, index
):
5988 """Gets a valid value for this argument."""
5989 return self
.GetValidArg(func
, offset
, index
)
5991 def GetValidGLArg(self
, func
, offset
, index
):
5992 """Gets a valid value for this argument."""
5993 return self
.GetValidArg(func
, offset
, index
)
5995 def GetNumInvalidValues(self
, func
):
5996 """returns the number of invalid values to be tested."""
5997 if 'invalid' in self
.enum_info
:
5998 invalid
= self
.enum_info
['invalid']
6002 def GetInvalidArg(self
, offset
, index
):
6003 """returns an invalid value by index."""
6004 if 'invalid' in self
.enum_info
:
6005 invalid
= self
.enum_info
['invalid']
6006 num_invalid
= len(invalid
)
6007 if index
>= num_invalid
:
6008 index
= num_invalid
- 1
6009 return (invalid
[index
], "kNoError", self
.gl_error
)
6010 return ("---ERROR1---", "kNoError", self
.gl_error
)
6013 class EnumArgument(EnumBaseArgument
):
6014 """A class that represents a GLenum argument"""
6016 def __init__(self
, name
, type):
6017 EnumBaseArgument
.__init
__(self
, name
, "GLenum", type, "GL_INVALID_ENUM")
6019 def GetLogArg(self
):
6020 """Overridden from Argument."""
6021 return ("GLES2Util::GetString%s(%s)" %
6022 (self
.type_name
, self
.name
))
6025 class IntArgument(EnumBaseArgument
):
6026 """A class for a GLint argument that can only except specific values.
6028 For example glTexImage2D takes a GLint for its internalformat
6029 argument instead of a GLenum.
6032 def __init__(self
, name
, type):
6033 EnumBaseArgument
.__init
__(self
, name
, "GLint", type, "GL_INVALID_VALUE")
6036 class ValidatedBoolArgument(EnumBaseArgument
):
6037 """A class for a GLboolean argument that can only except specific values.
6039 For example glUniformMatrix takes a GLboolean for it's transpose but it
6043 def __init__(self
, name
, type):
6044 EnumBaseArgument
.__init
__(self
, name
, "GLboolean", type, "GL_INVALID_VALUE")
6046 def GetLogArg(self
):
6047 """Overridden from Argument."""
6048 return 'GLES2Util::GetStringBool(%s)' % self
.name
6051 class ImmediatePointerArgument(Argument
):
6052 """A class that represents an immediate argument to a function.
6054 An immediate argument is one where the data follows the command.
6057 def __init__(self
, name
, type):
6058 Argument
.__init
__(self
, name
, type)
6060 def AddCmdArgs(self
, args
):
6061 """Overridden from Argument."""
6064 def WriteGetCode(self
, file):
6065 """Overridden from Argument."""
6067 " %s %s = GetImmediateDataAs<%s>(\n" %
6068 (self
.type, self
.name
, self
.type))
6069 file.Write(" c, data_size, immediate_data_size);\n")
6071 def WriteValidationCode(self
, file, func
):
6072 """Overridden from Argument."""
6073 file.Write(" if (%s == NULL) {\n" % self
.name
)
6074 file.Write(" return error::kOutOfBounds;\n")
6077 def GetImmediateVersion(self
):
6078 """Overridden from Argument."""
6081 def WriteDestinationInitalizationValidation(self
, file, func
):
6082 """Overridden from Argument."""
6083 self
.WriteDestinationInitalizationValidatationIfNeeded(file, func
)
6085 def GetLogArg(self
):
6086 """Overridden from Argument."""
6087 return "static_cast<const void*>(%s)" % self
.name
6090 class BucketPointerArgument(Argument
):
6091 """A class that represents an bucket argument to a function."""
6093 def __init__(self
, name
, type):
6094 Argument
.__init
__(self
, name
, type)
6096 def AddCmdArgs(self
, args
):
6097 """Overridden from Argument."""
6100 def WriteGetCode(self
, file):
6101 """Overridden from Argument."""
6103 " %s %s = bucket->GetData(0, data_size);\n" %
6104 (self
.type, self
.name
))
6106 def WriteValidationCode(self
, file, func
):
6107 """Overridden from Argument."""
6110 def GetImmediateVersion(self
):
6111 """Overridden from Argument."""
6114 def WriteDestinationInitalizationValidation(self
, file, func
):
6115 """Overridden from Argument."""
6116 self
.WriteDestinationInitalizationValidatationIfNeeded(file, func
)
6118 def GetLogArg(self
):
6119 """Overridden from Argument."""
6120 return "static_cast<const void*>(%s)" % self
.name
6123 class PointerArgument(Argument
):
6124 """A class that represents a pointer argument to a function."""
6126 def __init__(self
, name
, type):
6127 Argument
.__init
__(self
, name
, type)
6129 def IsPointer(self
):
6130 """Returns true if argument is a pointer."""
6133 def GetValidArg(self
, func
, offset
, index
):
6134 """Overridden from Argument."""
6135 return "shared_memory_id_, shared_memory_offset_"
6137 def GetValidGLArg(self
, func
, offset
, index
):
6138 """Overridden from Argument."""
6139 return "reinterpret_cast<%s>(shared_memory_address_)" % self
.type
6141 def GetNumInvalidValues(self
, func
):
6142 """Overridden from Argument."""
6145 def GetInvalidArg(self
, offset
, index
):
6146 """Overridden from Argument."""
6148 return ("kInvalidSharedMemoryId, 0", "kOutOfBounds", None)
6150 return ("shared_memory_id_, kInvalidSharedMemoryOffset",
6151 "kOutOfBounds", None)
6153 def GetLogArg(self
):
6154 """Overridden from Argument."""
6155 return "static_cast<const void*>(%s)" % self
.name
6157 def AddCmdArgs(self
, args
):
6158 """Overridden from Argument."""
6159 args
.append(Argument("%s_shm_id" % self
.name
, 'uint32'))
6160 args
.append(Argument("%s_shm_offset" % self
.name
, 'uint32'))
6162 def WriteGetCode(self
, file):
6163 """Overridden from Argument."""
6165 " %s %s = GetSharedMemoryAs<%s>(\n" %
6166 (self
.type, self
.name
, self
.type))
6168 " c.%s_shm_id, c.%s_shm_offset, data_size);\n" %
6169 (self
.name
, self
.name
))
6171 def WriteGetAddress(self
, file):
6172 """Overridden from Argument."""
6174 " %s %s = GetSharedMemoryAs<%s>(\n" %
6175 (self
.type, self
.name
, self
.type))
6177 " %s_shm_id, %s_shm_offset, %s_size);\n" %
6178 (self
.name
, self
.name
, self
.name
))
6180 def WriteValidationCode(self
, file, func
):
6181 """Overridden from Argument."""
6182 file.Write(" if (%s == NULL) {\n" % self
.name
)
6183 file.Write(" return error::kOutOfBounds;\n")
6186 def GetImmediateVersion(self
):
6187 """Overridden from Argument."""
6188 return ImmediatePointerArgument(self
.name
, self
.type)
6190 def GetBucketVersion(self
):
6191 """Overridden from Argument."""
6192 if self
.type == "const char*":
6193 return InputStringBucketArgument(self
.name
, self
.type)
6194 return BucketPointerArgument(self
.name
, self
.type)
6196 def WriteDestinationInitalizationValidation(self
, file, func
):
6197 """Overridden from Argument."""
6198 self
.WriteDestinationInitalizationValidatationIfNeeded(file, func
)
6201 class InputStringBucketArgument(Argument
):
6202 """An string input argument where the string is passed in a bucket."""
6204 def __init__(self
, name
, type):
6205 Argument
.__init
__(self
, name
+ "_bucket_id", "uint32")
6207 def WriteGetCode(self
, file):
6208 """Overridden from Argument."""
6210 Bucket* %(name)s_bucket = GetBucket(c.%(name)s);
6211 if (!%(name)s_bucket) {
6212 return error::kInvalidArguments;
6214 std::string %(name)s_str;
6215 if (!%(name)s_bucket->GetAsString(&%(name)s_str)) {
6216 return error::kInvalidArguments;
6218 const char* %(name)s = %(name)s_str.c_str();
6224 def GetValidArg(self
, func
, offset
, index
):
6225 return "kNameBucketId"
6227 def GetValidGLArg(self
, func
, offset
, index
):
6231 class NonImmediatePointerArgument(PointerArgument
):
6232 """A pointer argument that stays a pointer even in an immediate cmd."""
6234 def __init__(self
, name
, type):
6235 PointerArgument
.__init
__(self
, name
, type)
6237 def IsPointer(self
):
6238 """Returns true if argument is a pointer."""
6241 def GetImmediateVersion(self
):
6242 """Overridden from Argument."""
6246 class ResourceIdArgument(Argument
):
6247 """A class that represents a resource id argument to a function."""
6249 def __init__(self
, name
, type):
6250 match
= re
.match("(GLid\w+)", type)
6251 self
.resource_type
= match
.group(1)[4:]
6252 type = type.replace(match
.group(1), "GLuint")
6253 Argument
.__init
__(self
, name
, type)
6255 def WriteGetCode(self
, file):
6256 """Overridden from Argument."""
6257 file.Write(" %s %s = c.%s;\n" % (self
.type, self
.name
, self
.name
))
6259 def GetValidArg(self
, func
, offset
, index
):
6260 return "client_%s_id_" % self
.resource_type
.lower()
6262 def GetValidGLArg(self
, func
, offset
, index
):
6263 return "kService%sId" % self
.resource_type
6266 class ResourceIdBindArgument(Argument
):
6267 """Represents a resource id argument to a bind function."""
6269 def __init__(self
, name
, type):
6270 match
= re
.match("(GLidBind\w+)", type)
6271 self
.resource_type
= match
.group(1)[8:]
6272 type = type.replace(match
.group(1), "GLuint")
6273 Argument
.__init
__(self
, name
, type)
6275 def WriteGetCode(self
, file):
6276 """Overridden from Argument."""
6277 code
= """ %(type)s %(name)s = c.%(name)s;
6279 file.Write(code
% {'type': self
.type, 'name': self
.name
})
6281 def GetValidArg(self
, func
, offset
, index
):
6282 return "client_%s_id_" % self
.resource_type
.lower()
6284 def GetValidGLArg(self
, func
, offset
, index
):
6285 return "kService%sId" % self
.resource_type
6288 class ResourceIdZeroArgument(Argument
):
6289 """Represents a resource id argument to a function that can be zero."""
6291 def __init__(self
, name
, type):
6292 match
= re
.match("(GLidZero\w+)", type)
6293 self
.resource_type
= match
.group(1)[8:]
6294 type = type.replace(match
.group(1), "GLuint")
6295 Argument
.__init
__(self
, name
, type)
6297 def WriteGetCode(self
, file):
6298 """Overridden from Argument."""
6299 file.Write(" %s %s = c.%s;\n" % (self
.type, self
.name
, self
.name
))
6301 def GetValidArg(self
, func
, offset
, index
):
6302 return "client_%s_id_" % self
.resource_type
.lower()
6304 def GetValidGLArg(self
, func
, offset
, index
):
6305 return "kService%sId" % self
.resource_type
6307 def GetNumInvalidValues(self
, func
):
6308 """returns the number of invalid values to be tested."""
6311 def GetInvalidArg(self
, offset
, index
):
6312 """returns an invalid value by index."""
6313 return ("kInvalidClientId", "kNoError", "GL_INVALID_VALUE")
6316 class Function(object):
6317 """A class that represents a function."""
6319 def __init__(self
, original_name
, name
, info
, return_type
, original_args
,
6320 args_for_cmds
, cmd_args
, init_args
, num_pointer_args
):
6322 self
.original_name
= original_name
6324 self
.type_handler
= info
.type_handler
6325 self
.return_type
= return_type
6326 self
.original_args
= original_args
6327 self
.num_pointer_args
= num_pointer_args
6328 self
.can_auto_generate
= num_pointer_args
== 0 and return_type
== "void"
6329 self
.cmd_args
= cmd_args
6330 self
.init_args
= init_args
6332 self
.args_for_cmds
= args_for_cmds
6333 self
.is_immediate
= False
6335 def IsType(self
, type_name
):
6336 """Returns true if function is a certain type."""
6337 return self
.info
.type == type_name
6339 def InitFunction(self
):
6340 """Calls the init function for the type handler."""
6341 self
.type_handler
.InitFunction(self
)
6343 def GetInfo(self
, name
):
6344 """Returns a value from the function info for this function."""
6345 if hasattr(self
.info
, name
):
6346 return getattr(self
.info
, name
)
6349 def GetValidArg(self
, index
):
6350 """Gets a valid arg from the function info if one exists."""
6351 valid_args
= self
.GetInfo('valid_args')
6352 if valid_args
and str(index
) in valid_args
:
6353 return valid_args
[str(index
)]
6356 def AddInfo(self
, name
, value
):
6358 setattr(self
.info
, name
, value
)
6360 def IsCoreGLFunction(self
):
6361 return (not self
.GetInfo('extension') and
6362 not self
.GetInfo('pepper_interface'))
6364 def InPepperInterface(self
, interface
):
6365 ext
= self
.GetInfo('pepper_interface')
6366 if not interface
.GetName():
6367 return self
.IsCoreGLFunction()
6368 return ext
== interface
.GetName()
6370 def InAnyPepperExtension(self
):
6371 return self
.IsCoreGLFunction() or self
.GetInfo('pepper_interface')
6373 def GetGLFunctionName(self
):
6374 """Gets the function to call to execute GL for this command."""
6375 if self
.GetInfo('decoder_func'):
6376 return self
.GetInfo('decoder_func')
6377 return "gl%s" % self
.original_name
6379 def GetGLTestFunctionName(self
):
6380 gl_func_name
= self
.GetInfo('gl_test_func')
6381 if gl_func_name
== None:
6382 gl_func_name
= self
.GetGLFunctionName()
6383 if gl_func_name
.startswith("gl"):
6384 gl_func_name
= gl_func_name
[2:]
6386 gl_func_name
= self
.original_name
6389 def AddCmdArg(self
, arg
):
6390 """Adds a cmd argument to this function."""
6391 self
.cmd_args
.append(arg
)
6393 def GetCmdArgs(self
):
6394 """Gets the command args for this function."""
6395 return self
.cmd_args
6397 def ClearCmdArgs(self
):
6398 """Clears the command args for this function."""
6401 def GetInitArgs(self
):
6402 """Gets the init args for this function."""
6403 return self
.init_args
6405 def GetOriginalArgs(self
):
6406 """Gets the original arguments to this function."""
6407 return self
.original_args
6409 def GetLastOriginalArg(self
):
6410 """Gets the last original argument to this function."""
6411 return self
.original_args
[len(self
.original_args
) - 1]
6413 def __MaybePrependComma(self
, arg_string
, add_comma
):
6414 """Adds a comma if arg_string is not empty and add_comma is true."""
6416 if add_comma
and len(arg_string
):
6418 return "%s%s" % (comma
, arg_string
)
6420 def MakeTypedOriginalArgString(self
, prefix
, add_comma
= False):
6421 """Gets a list of arguments as they are in GL."""
6422 args
= self
.GetOriginalArgs()
6423 arg_string
= ", ".join(
6424 ["%s %s%s" % (arg
.type, prefix
, arg
.name
) for arg
in args
])
6425 return self
.__MaybePrependComma
(arg_string
, add_comma
)
6427 def MakeOriginalArgString(self
, prefix
, add_comma
= False, separator
= ", "):
6428 """Gets the list of arguments as they are in GL."""
6429 args
= self
.GetOriginalArgs()
6430 arg_string
= separator
.join(
6431 ["%s%s" % (prefix
, arg
.name
) for arg
in args
])
6432 return self
.__MaybePrependComma
(arg_string
, add_comma
)
6434 def MakeTypedPepperArgString(self
, prefix
):
6435 """Gets a list of arguments as they need to be for Pepper."""
6436 if self
.GetInfo("pepper_args"):
6437 return self
.GetInfo("pepper_args")
6439 return self
.MakeTypedOriginalArgString(prefix
, False)
6441 def MakeTypedCmdArgString(self
, prefix
, add_comma
= False):
6442 """Gets a typed list of arguments as they need to be for command buffers."""
6443 args
= self
.GetCmdArgs()
6444 arg_string
= ", ".join(
6445 ["%s %s%s" % (arg
.type, prefix
, arg
.name
) for arg
in args
])
6446 return self
.__MaybePrependComma
(arg_string
, add_comma
)
6448 def MakeCmdArgString(self
, prefix
, add_comma
= False):
6449 """Gets the list of arguments as they need to be for command buffers."""
6450 args
= self
.GetCmdArgs()
6451 arg_string
= ", ".join(
6452 ["%s%s" % (prefix
, arg
.name
) for arg
in args
])
6453 return self
.__MaybePrependComma
(arg_string
, add_comma
)
6455 def MakeTypedInitString(self
, prefix
, add_comma
= False):
6456 """Gets a typed list of arguments as they need to be for cmd Init/Set."""
6457 args
= self
.GetInitArgs()
6458 arg_string
= ", ".join(
6459 ["%s %s%s" % (arg
.type, prefix
, arg
.name
) for arg
in args
])
6460 return self
.__MaybePrependComma
(arg_string
, add_comma
)
6462 def MakeInitString(self
, prefix
, add_comma
= False):
6463 """Gets the list of arguments as they need to be for cmd Init/Set."""
6464 args
= self
.GetInitArgs()
6465 arg_string
= ", ".join(
6466 ["%s%s" % (prefix
, arg
.name
) for arg
in args
])
6467 return self
.__MaybePrependComma
(arg_string
, add_comma
)
6469 def MakeLogArgString(self
):
6470 """Makes a string of the arguments for the LOG macros"""
6471 args
= self
.GetOriginalArgs()
6472 return ' << ", " << '.join([arg
.GetLogArg() for arg
in args
])
6474 def WriteCommandDescription(self
, file):
6475 """Writes a description of the command."""
6476 file.Write("//! Command that corresponds to gl%s.\n" % self
.original_name
)
6478 def WriteHandlerValidation(self
, file):
6479 """Writes validation code for the function."""
6480 for arg
in self
.GetOriginalArgs():
6481 arg
.WriteValidationCode(file, self
)
6482 self
.WriteValidationCode(file)
6484 def WriteHandlerImplementation(self
, file):
6485 """Writes the handler implementation for this command."""
6486 self
.type_handler
.WriteHandlerImplementation(self
, file)
6488 def WriteValidationCode(self
, file):
6489 """Writes the validation code for a command."""
6492 def WriteCmdArgFlag(self
, file):
6493 """Writes the cmd kArgFlags constant."""
6494 file.Write(" static const cmd::ArgFlags kArgFlags = cmd::kFixed;\n")
6496 def WriteCmdComputeSize(self
, file):
6497 """Writes the ComputeSize function for the command."""
6498 file.Write(" static uint32 ComputeSize() {\n")
6500 " return static_cast<uint32>(sizeof(ValueType)); // NOLINT\n")
6504 def WriteCmdSetHeader(self
, file):
6505 """Writes the cmd's SetHeader function."""
6506 file.Write(" void SetHeader() {\n")
6507 file.Write(" header.SetCmd<ValueType>();\n")
6511 def WriteCmdInit(self
, file):
6512 """Writes the cmd's Init function."""
6513 file.Write(" void Init(%s) {\n" % self
.MakeTypedCmdArgString("_"))
6514 file.Write(" SetHeader();\n")
6515 args
= self
.GetCmdArgs()
6517 file.Write(" %s = _%s;\n" % (arg
.name
, arg
.name
))
6521 def WriteCmdSet(self
, file):
6522 """Writes the cmd's Set function."""
6523 copy_args
= self
.MakeCmdArgString("_", False)
6524 file.Write(" void* Set(void* cmd%s) {\n" %
6525 self
.MakeTypedCmdArgString("_", True))
6526 file.Write(" static_cast<ValueType*>(cmd)->Init(%s);\n" % copy_args
)
6527 file.Write(" return NextCmdAddress<ValueType>(cmd);\n")
6531 def WriteStruct(self
, file):
6532 self
.type_handler
.WriteStruct(self
, file)
6534 def WriteDocs(self
, file):
6535 self
.type_handler
.WriteDocs(self
, file)
6537 def WriteCmdHelper(self
, file):
6538 """Writes the cmd's helper."""
6539 self
.type_handler
.WriteCmdHelper(self
, file)
6541 def WriteServiceImplementation(self
, file):
6542 """Writes the service implementation for a command."""
6543 self
.type_handler
.WriteServiceImplementation(self
, file)
6545 def WriteServiceUnitTest(self
, file):
6546 """Writes the service implementation for a command."""
6547 self
.type_handler
.WriteServiceUnitTest(self
, file)
6549 def WriteGLES2CLibImplementation(self
, file):
6550 """Writes the GLES2 C Lib Implemention."""
6551 self
.type_handler
.WriteGLES2CLibImplementation(self
, file)
6553 def WriteGLES2InterfaceHeader(self
, file):
6554 """Writes the GLES2 Interface declaration."""
6555 self
.type_handler
.WriteGLES2InterfaceHeader(self
, file)
6557 def WriteGLES2InterfaceStub(self
, file):
6558 """Writes the GLES2 Interface Stub declaration."""
6559 self
.type_handler
.WriteGLES2InterfaceStub(self
, file)
6561 def WriteGLES2InterfaceStubImpl(self
, file):
6562 """Writes the GLES2 Interface Stub declaration."""
6563 self
.type_handler
.WriteGLES2InterfaceStubImpl(self
, file)
6565 def WriteGLES2ImplementationHeader(self
, file):
6566 """Writes the GLES2 Implemention declaration."""
6567 self
.type_handler
.WriteGLES2ImplementationHeader(self
, file)
6569 def WriteGLES2Implementation(self
, file):
6570 """Writes the GLES2 Implemention definition."""
6571 self
.type_handler
.WriteGLES2Implementation(self
, file)
6573 def WriteGLES2TraceImplementationHeader(self
, file):
6574 """Writes the GLES2 Trace Implemention declaration."""
6575 self
.type_handler
.WriteGLES2TraceImplementationHeader(self
, file)
6577 def WriteGLES2TraceImplementation(self
, file):
6578 """Writes the GLES2 Trace Implemention definition."""
6579 self
.type_handler
.WriteGLES2TraceImplementation(self
, file)
6581 def WriteGLES2Header(self
, file):
6582 """Writes the GLES2 Implemention unit test."""
6583 self
.type_handler
.WriteGLES2Header(self
, file)
6585 def WriteGLES2ImplementationUnitTest(self
, file):
6586 """Writes the GLES2 Implemention unit test."""
6587 self
.type_handler
.WriteGLES2ImplementationUnitTest(self
, file)
6589 def WriteDestinationInitalizationValidation(self
, file):
6590 """Writes the client side destintion initialization validation."""
6591 self
.type_handler
.WriteDestinationInitalizationValidation(self
, file)
6593 def WriteFormatTest(self
, file):
6594 """Writes the cmd's format test."""
6595 self
.type_handler
.WriteFormatTest(self
, file)
6598 class PepperInterface(object):
6599 """A class that represents a function."""
6601 def __init__(self
, info
):
6602 self
.name
= info
["name"]
6603 self
.dev
= info
["dev"]
6608 def GetInterfaceName(self
):
6612 upperint
= "_" + self
.name
.upper()
6615 return "PPB_OPENGLES2%s%s_INTERFACE" % (upperint
, dev
)
6617 def GetInterfaceString(self
):
6621 return "PPB_OpenGLES2%s%s" % (self
.name
, dev
)
6623 def GetStructName(self
):
6627 return "PPB_OpenGLES2%s%s" % (self
.name
, dev
)
6630 class ImmediateFunction(Function
):
6631 """A class that represnets an immediate function command."""
6633 def __init__(self
, func
):
6635 for arg
in func
.GetOriginalArgs():
6636 new_arg
= arg
.GetImmediateVersion()
6638 new_args
.append(new_arg
)
6641 new_args_for_cmds
= []
6642 for arg
in func
.args_for_cmds
:
6643 new_arg
= arg
.GetImmediateVersion()
6645 new_args_for_cmds
.append(new_arg
)
6646 new_arg
.AddCmdArgs(cmd_args
)
6649 for arg
in new_args_for_cmds
:
6650 arg
.AddInitArgs(new_init_args
)
6655 "%sImmediate" % func
.name
,
6663 self
.is_immediate
= True
6665 def WriteCommandDescription(self
, file):
6666 """Overridden from Function"""
6667 file.Write("//! Immediate version of command that corresponds to gl%s.\n" %
6670 def WriteServiceImplementation(self
, file):
6671 """Overridden from Function"""
6672 self
.type_handler
.WriteImmediateServiceImplementation(self
, file)
6674 def WriteHandlerImplementation(self
, file):
6675 """Overridden from Function"""
6676 self
.type_handler
.WriteImmediateHandlerImplementation(self
, file)
6678 def WriteServiceUnitTest(self
, file):
6679 """Writes the service implementation for a command."""
6680 self
.type_handler
.WriteImmediateServiceUnitTest(self
, file)
6682 def WriteValidationCode(self
, file):
6683 """Overridden from Function"""
6684 self
.type_handler
.WriteImmediateValidationCode(self
, file)
6686 def WriteCmdArgFlag(self
, file):
6687 """Overridden from Function"""
6688 file.Write(" static const cmd::ArgFlags kArgFlags = cmd::kAtLeastN;\n")
6690 def WriteCmdComputeSize(self
, file):
6691 """Overridden from Function"""
6692 self
.type_handler
.WriteImmediateCmdComputeSize(self
, file)
6694 def WriteCmdSetHeader(self
, file):
6695 """Overridden from Function"""
6696 self
.type_handler
.WriteImmediateCmdSetHeader(self
, file)
6698 def WriteCmdInit(self
, file):
6699 """Overridden from Function"""
6700 self
.type_handler
.WriteImmediateCmdInit(self
, file)
6702 def WriteCmdSet(self
, file):
6703 """Overridden from Function"""
6704 self
.type_handler
.WriteImmediateCmdSet(self
, file)
6706 def WriteCmdHelper(self
, file):
6707 """Overridden from Function"""
6708 self
.type_handler
.WriteImmediateCmdHelper(self
, file)
6710 def WriteFormatTest(self
, file):
6711 """Overridden from Function"""
6712 self
.type_handler
.WriteImmediateFormatTest(self
, file)
6715 class BucketFunction(Function
):
6716 """A class that represnets a bucket version of a function command."""
6718 def __init__(self
, func
):
6720 for arg
in func
.GetOriginalArgs():
6721 new_arg
= arg
.GetBucketVersion()
6723 new_args
.append(new_arg
)
6726 new_args_for_cmds
= []
6727 for arg
in func
.args_for_cmds
:
6728 new_arg
= arg
.GetBucketVersion()
6730 new_args_for_cmds
.append(new_arg
)
6731 new_arg
.AddCmdArgs(cmd_args
)
6734 for arg
in new_args_for_cmds
:
6735 arg
.AddInitArgs(new_init_args
)
6740 "%sBucket" % func
.name
,
6749 # def InitFunction(self):
6750 # """Overridden from Function"""
6753 def WriteCommandDescription(self
, file):
6754 """Overridden from Function"""
6755 file.Write("//! Bucket version of command that corresponds to gl%s.\n" %
6758 def WriteServiceImplementation(self
, file):
6759 """Overridden from Function"""
6760 self
.type_handler
.WriteBucketServiceImplementation(self
, file)
6762 def WriteHandlerImplementation(self
, file):
6763 """Overridden from Function"""
6764 self
.type_handler
.WriteBucketHandlerImplementation(self
, file)
6766 def WriteServiceUnitTest(self
, file):
6767 """Writes the service implementation for a command."""
6768 self
.type_handler
.WriteBucketServiceUnitTest(self
, file)
6771 def CreateArg(arg_string
):
6772 """Creates an Argument."""
6773 arg_parts
= arg_string
.split()
6774 if len(arg_parts
) == 1 and arg_parts
[0] == 'void':
6776 # Is this a pointer argument?
6777 elif arg_string
.find('*') >= 0:
6778 if arg_parts
[0] == 'NonImmediate':
6779 return NonImmediatePointerArgument(
6781 " ".join(arg_parts
[1:-1]))
6783 return PointerArgument(
6785 " ".join(arg_parts
[0:-1]))
6786 # Is this a resource argument? Must come after pointer check.
6787 elif arg_parts
[0].startswith('GLidBind'):
6788 return ResourceIdBindArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
6789 elif arg_parts
[0].startswith('GLidZero'):
6790 return ResourceIdZeroArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
6791 elif arg_parts
[0].startswith('GLid'):
6792 return ResourceIdArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
6793 elif arg_parts
[0].startswith('GLenum') and len(arg_parts
[0]) > 6:
6794 return EnumArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
6795 elif arg_parts
[0].startswith('GLboolean') and len(arg_parts
[0]) > 9:
6796 return ValidatedBoolArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
6797 elif arg_parts
[0].startswith('GLboolean'):
6798 return BoolArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
6799 elif arg_parts
[0].startswith('GLintUniformLocation'):
6800 return UniformLocationArgument(arg_parts
[-1])
6801 elif (arg_parts
[0].startswith('GLint') and len(arg_parts
[0]) > 5 and
6802 not arg_parts
[0].startswith('GLintptr')):
6803 return IntArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
6804 elif (arg_parts
[0].startswith('GLsizeiNotNegative') or
6805 arg_parts
[0].startswith('GLintptrNotNegative')):
6806 return SizeNotNegativeArgument(arg_parts
[-1],
6807 " ".join(arg_parts
[0:-1]),
6808 arg_parts
[0][0:-11])
6809 elif arg_parts
[0].startswith('GLsize'):
6810 return SizeArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
6812 return Argument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
6815 class GLGenerator(object):
6816 """A class to generate GL command buffers."""
6818 _function_re
= re
.compile(r
'GL_APICALL(.*?)GL_APIENTRY (.*?) \((.*?)\);')
6820 def __init__(self
, verbose
):
6821 self
.original_functions
= []
6823 self
.verbose
= verbose
6825 self
._function
_info
= {}
6826 self
._empty
_type
_handler
= TypeHandler()
6827 self
._empty
_function
_info
= FunctionInfo({}, self
._empty
_type
_handler
)
6828 self
.pepper_interfaces
= []
6829 self
.interface_info
= {}
6831 self
._type
_handlers
= {
6832 'Bind': BindHandler(),
6833 'Create': CreateHandler(),
6834 'Custom': CustomHandler(),
6835 'Data': DataHandler(),
6836 'Delete': DeleteHandler(),
6837 'DELn': DELnHandler(),
6838 'GENn': GENnHandler(),
6839 'GETn': GETnHandler(),
6840 'GLchar': GLcharHandler(),
6841 'GLcharN': GLcharNHandler(),
6842 'HandWritten': HandWrittenHandler(),
6844 'Manual': ManualHandler(),
6845 'PUT': PUTHandler(),
6846 'PUTn': PUTnHandler(),
6847 'PUTXn': PUTXnHandler(),
6848 'StateSet': StateSetHandler(),
6849 'StateSetRGBAlpha': StateSetRGBAlphaHandler(),
6850 'StateSetFrontBack': StateSetFrontBackHandler(),
6851 'StateSetFrontBackSeparate': StateSetFrontBackSeparateHandler(),
6852 'StateSetNamedParameter': StateSetNamedParameter(),
6853 'STRn': STRnHandler(),
6854 'Todo': TodoHandler(),
6857 for func_name
in _FUNCTION_INFO
:
6858 info
= _FUNCTION_INFO
[func_name
]
6862 self
._function
_info
[func_name
] = FunctionInfo(info
,
6863 self
.GetTypeHandler(type))
6864 for interface
in _PEPPER_INTERFACES
:
6865 interface
= PepperInterface(interface
)
6866 self
.pepper_interfaces
.append(interface
)
6867 self
.interface_info
[interface
.GetName()] = interface
6869 def AddFunction(self
, func
):
6870 """Adds a function."""
6871 self
.functions
.append(func
)
6873 def GetTypeHandler(self
, name
):
6874 """Gets a type info for the given type."""
6876 if name
in self
._type
_handlers
:
6877 return self
._type
_handlers
[name
]
6879 raise KeyError("no such type handler: %s" % name
)
6880 return self
._empty
_type
_handler
6882 def GetFunctionInfo(self
, name
):
6883 """Gets a type info for the given function name."""
6884 if name
in self
._function
_info
:
6885 return self
._function
_info
[name
]
6886 return self
._empty
_function
_info
6889 """Prints something if verbose is true."""
6893 def Error(self
, msg
):
6894 """Prints an error."""
6895 print "Error: %s" % msg
6898 def WriteLicense(self
, file):
6899 """Writes the license."""
6900 file.Write(_LICENSE
)
6902 def WriteNamespaceOpen(self
, file):
6903 """Writes the code for the namespace."""
6904 file.Write("namespace gpu {\n")
6905 file.Write("namespace gles2 {\n")
6908 def WriteNamespaceClose(self
, file):
6909 """Writes the code to close the namespace."""
6910 file.Write("} // namespace gles2\n")
6911 file.Write("} // namespace gpu\n")
6914 def ParseArgs(self
, arg_string
):
6915 """Parses a function arg string."""
6917 num_pointer_args
= 0
6918 parts
= arg_string
.split(',')
6920 for arg_string
in parts
:
6921 if arg_string
.startswith('GLenum '):
6923 arg
= CreateArg(arg_string
)
6927 num_pointer_args
+= 1
6928 return (args
, num_pointer_args
, is_gl_enum
)
6930 def ParseGLH(self
, filename
):
6931 """Parses the cmd_buffer_functions.txt file and extracts the functions"""
6932 f
= open("gpu/command_buffer/cmd_buffer_functions.txt", "r")
6933 functions
= f
.read()
6935 for line
in functions
.splitlines():
6936 match
= self
._function
_re
.match(line
)
6938 func_name
= match
.group(2)[2:]
6939 func_info
= self
.GetFunctionInfo(func_name
)
6940 if func_info
.type != 'Noop':
6941 return_type
= match
.group(1).strip()
6942 arg_string
= match
.group(3)
6943 (args
, num_pointer_args
, is_gl_enum
) = self
.ParseArgs(arg_string
)
6944 # comment in to find out which functions use bare enums.
6946 # self.Log("%s uses bare GLenum" % func_name)
6947 args_for_cmds
= args
6948 if hasattr(func_info
, 'cmd_args'):
6949 (args_for_cmds
, num_pointer_args
, is_gl_enum
) = (
6950 self
.ParseArgs(getattr(func_info
, 'cmd_args')))
6952 for arg
in args_for_cmds
:
6953 arg
.AddCmdArgs(cmd_args
)
6955 for arg
in args_for_cmds
:
6956 arg
.AddInitArgs(init_args
)
6957 return_arg
= CreateArg(return_type
+ " result")
6959 init_args
.append(return_arg
)
6960 f
= Function(func_name
, func_name
, func_info
, return_type
, args
,
6961 args_for_cmds
, cmd_args
, init_args
, num_pointer_args
)
6962 self
.original_functions
.append(f
)
6963 gen_cmd
= f
.GetInfo('gen_cmd')
6964 if gen_cmd
== True or gen_cmd
== None:
6966 f
.type_handler
.AddImmediateFunction(self
, f
)
6967 f
.type_handler
.AddBucketFunction(self
, f
)
6969 self
.Log("Auto Generated Functions : %d" %
6970 len([f
for f
in self
.functions
if f
.can_auto_generate
or
6971 (not f
.IsType('') and not f
.IsType('Custom') and
6972 not f
.IsType('Todo'))]))
6974 funcs
= [f
for f
in self
.functions
if not f
.can_auto_generate
and
6975 (f
.IsType('') or f
.IsType('Custom') or f
.IsType('Todo'))]
6976 self
.Log("Non Auto Generated Functions: %d" % len(funcs
))
6979 self
.Log(" %-10s %-20s gl%s" % (f
.info
.type, f
.return_type
, f
.name
))
6981 def WriteCommandIds(self
, filename
):
6982 """Writes the command buffer format"""
6983 file = CHeaderWriter(filename
)
6984 file.Write("#define GLES2_COMMAND_LIST(OP) \\\n")
6986 for func
in self
.functions
:
6987 file.Write(" %-60s /* %d */ \\\n" %
6988 ("OP(%s)" % func
.name
, id))
6992 file.Write("enum CommandId {\n")
6993 file.Write(" kStartPoint = cmd::kLastCommonId, "
6994 "// All GLES2 commands start after this.\n")
6995 file.Write("#define GLES2_CMD_OP(name) k ## name,\n")
6996 file.Write(" GLES2_COMMAND_LIST(GLES2_CMD_OP)\n")
6997 file.Write("#undef GLES2_CMD_OP\n")
6998 file.Write(" kNumCommands\n")
7003 def WriteFormat(self
, filename
):
7004 """Writes the command buffer format"""
7005 file = CHeaderWriter(filename
)
7006 for func
in self
.functions
:
7008 #gen_cmd = func.GetInfo('gen_cmd')
7009 #if gen_cmd == True or gen_cmd == None:
7010 func
.WriteStruct(file)
7014 def WriteDocs(self
, filename
):
7015 """Writes the command buffer doc version of the commands"""
7016 file = CWriter(filename
)
7017 for func
in self
.functions
:
7019 #gen_cmd = func.GetInfo('gen_cmd')
7020 #if gen_cmd == True or gen_cmd == None:
7021 func
.WriteDocs(file)
7025 def WriteFormatTest(self
, filename
):
7026 """Writes the command buffer format test."""
7027 file = CHeaderWriter(
7029 "// This file contains unit tests for gles2 commmands\n"
7030 "// It is included by gles2_cmd_format_test.cc\n"
7033 for func
in self
.functions
:
7035 #gen_cmd = func.GetInfo('gen_cmd')
7036 #if gen_cmd == True or gen_cmd == None:
7037 func
.WriteFormatTest(file)
7041 def WriteCmdHelperHeader(self
, filename
):
7042 """Writes the gles2 command helper."""
7043 file = CHeaderWriter(filename
)
7045 for func
in self
.functions
:
7047 #gen_cmd = func.GetInfo('gen_cmd')
7048 #if gen_cmd == True or gen_cmd == None:
7049 func
.WriteCmdHelper(file)
7053 def WriteServiceContextStateHeader(self
, filename
):
7054 """Writes the service context state header."""
7055 file = CHeaderWriter(
7057 "// It is included by context_state.h\n")
7058 file.Write("struct EnableFlags {\n")
7059 file.Write(" EnableFlags();\n")
7060 for capability
in _CAPABILITY_FLAGS
:
7061 file.Write(" bool %s;\n" % capability
['name'])
7062 file.Write("};\n\n")
7064 for state_name
in sorted(_STATES
.keys()):
7065 state
= _STATES
[state_name
]
7066 for item
in state
['states']:
7067 file.Write("%s %s;\n" % (item
['type'], item
['name']))
7072 def WriteClientContextStateHeader(self
, filename
):
7073 """Writes the client context state header."""
7074 file = CHeaderWriter(
7076 "// It is included by client_context_state.h\n")
7077 file.Write("struct EnableFlags {\n")
7078 file.Write(" EnableFlags();\n")
7079 for capability
in _CAPABILITY_FLAGS
:
7080 file.Write(" bool %s;\n" % capability
['name'])
7081 file.Write("};\n\n")
7085 def WriteContextStateGetters(self
, file, class_name
):
7086 """Writes the state getters."""
7087 for gl_type
in ["GLint", "GLfloat"]:
7089 bool %s::GetStateAs%s(
7090 GLenum pname, %s* params, GLsizei* num_written) const {
7092 """ % (class_name
, gl_type
, gl_type
))
7093 for state_name
in sorted(_STATES
.keys()):
7094 state
= _STATES
[state_name
]
7096 file.Write(" case %s:\n" % state
['enum'])
7097 file.Write(" *num_written = %d;\n" % len(state
['states']))
7098 file.Write(" if (params) {\n")
7099 for ndx
,item
in enumerate(state
['states']):
7100 file.Write(" params[%d] = static_cast<%s>(%s);\n" %
7101 (ndx
, gl_type
, item
['name']))
7103 file.Write(" return true;\n")
7105 for item
in state
['states']:
7106 file.Write(" case %s:\n" % item
['enum'])
7107 file.Write(" *num_written = 1;\n")
7108 file.Write(" if (params) {\n")
7109 file.Write(" params[0] = static_cast<%s>(%s);\n" %
7110 (gl_type
, item
['name']))
7112 file.Write(" return true;\n")
7113 for capability
in _CAPABILITY_FLAGS
:
7114 file.Write(" case GL_%s:\n" % capability
['name'].upper())
7115 file.Write(" *num_written = 1;\n")
7116 file.Write(" if (params) {\n")
7118 " params[0] = static_cast<%s>(enable_flags.%s);\n" %
7119 (gl_type
, capability
['name']))
7121 file.Write(" return true;\n")
7122 file.Write(""" default:
7128 def WriteServiceContextStateImpl(self
, filename
):
7129 """Writes the context state service implementation."""
7130 file = CHeaderWriter(
7132 "// It is included by context_state.cc\n")
7134 for capability
in _CAPABILITY_FLAGS
:
7135 code
.append("%s(%s)" %
7136 (capability
['name'],
7137 ('false', 'true')['default' in capability
]))
7138 file.Write("ContextState::EnableFlags::EnableFlags()\n : %s {\n}\n" %
7142 file.Write("void ContextState::Initialize() {\n")
7143 for state_name
in sorted(_STATES
.keys()):
7144 state
= _STATES
[state_name
]
7145 for item
in state
['states']:
7146 file.Write(" %s = %s;\n" % (item
['name'], item
['default']))
7150 void ContextState::InitCapabilities() const {
7152 for capability
in _CAPABILITY_FLAGS
:
7153 file.Write(" EnableDisable(GL_%s, enable_flags.%s);\n" %
7154 (capability
['name'].upper(), capability
['name']))
7157 void ContextState::InitState() const {
7160 # We need to sort the keys so the expectations match
7161 for state_name
in sorted(_STATES
.keys()):
7162 state
= _STATES
[state_name
]
7163 if state
['type'] == 'FrontBack':
7164 num_states
= len(state
['states'])
7165 for ndx
, group
in enumerate(Grouper(num_states
/ 2, state
['states'])):
7168 args
.append('%s' % item
['name'])
7170 " gl%s(%s, %s);\n" %
7171 (state
['func'], ('GL_FRONT', 'GL_BACK')[ndx
], ", ".join(args
)))
7172 elif state
['type'] == 'NamedParameter':
7173 for item
in state
['states']:
7174 if 'extension_flag' in item
:
7175 file.Write(" if (feature_info_->feature_flags().%s)\n " %
7176 item
['extension_flag'])
7177 file.Write(" gl%s(%s, %s);\n" %
7178 (state
['func'], item
['enum'], item
['name']))
7181 for item
in state
['states']:
7182 args
.append('%s' % item
['name'])
7183 file.Write(" gl%s(%s);\n" % (state
['func'], ", ".join(args
)))
7186 file.Write("""bool ContextState::GetEnabled(GLenum cap) const {
7189 for capability
in _CAPABILITY_FLAGS
:
7190 file.Write(" case GL_%s:\n" % capability
['name'].upper())
7191 file.Write(" return enable_flags.%s;\n" % capability
['name'])
7192 file.Write(""" default:
7199 self
.WriteContextStateGetters(file, "ContextState")
7202 def WriteClientContextStateImpl(self
, filename
):
7203 """Writes the context state client side implementation."""
7204 file = CHeaderWriter(
7206 "// It is included by client_context_state.cc\n")
7208 for capability
in _CAPABILITY_FLAGS
:
7209 code
.append("%s(%s)" %
7210 (capability
['name'],
7211 ('false', 'true')['default' in capability
]))
7213 "ClientContextState::EnableFlags::EnableFlags()\n : %s {\n}\n" %
7218 bool ClientContextState::SetCapabilityState(
7219 GLenum cap, bool enabled, bool* changed) {
7223 for capability
in _CAPABILITY_FLAGS
:
7224 file.Write(" case GL_%s:\n" % capability
['name'].upper())
7225 file.Write(""" if (enable_flags.%(name)s != enabled) {
7227 enable_flags.%(name)s = enabled;
7231 file.Write(""" default:
7236 file.Write("""bool ClientContextState::GetEnabled(
7237 GLenum cap, bool* enabled) const {
7240 for capability
in _CAPABILITY_FLAGS
:
7241 file.Write(" case GL_%s:\n" % capability
['name'].upper())
7242 file.Write(" *enabled = enable_flags.%s;\n" % capability
['name'])
7243 file.Write(" return true;\n")
7244 file.Write(""" default:
7251 def WriteServiceImplementation(self
, filename
):
7252 """Writes the service decorder implementation."""
7253 file = CHeaderWriter(
7255 "// It is included by gles2_cmd_decoder.cc\n")
7257 for func
in self
.functions
:
7259 #gen_cmd = func.GetInfo('gen_cmd')
7260 #if gen_cmd == True or gen_cmd == None:
7261 func
.WriteServiceImplementation(file)
7264 bool GLES2DecoderImpl::SetCapabilityState(GLenum cap, bool enabled) {
7267 for capability
in _CAPABILITY_FLAGS
:
7268 file.Write(" case GL_%s:\n" % capability
['name'].upper())
7269 if 'state_flag' in capability
:
7270 file.Write(""" if (state_.enable_flags.%(name)s != enabled) {
7271 state_.enable_flags.%(name)s = enabled;
7272 %(state_flag)s = true;
7277 file.Write(""" state_.enable_flags.%(name)s = enabled;
7280 file.Write(""" default:
7288 def WriteServiceUnitTests(self
, filename
):
7289 """Writes the service decorder unit tests."""
7290 num_tests
= len(self
.functions
)
7291 FUNCTIONS_PER_FILE
= 98 # hard code this so it doesn't change.
7293 for test_num
in range(0, num_tests
, FUNCTIONS_PER_FILE
):
7295 name
= filename
% count
7296 file = CHeaderWriter(
7298 "// It is included by gles2_cmd_decoder_unittest_%d.cc\n" % count
)
7299 file.SetFileNum(count
)
7300 end
= test_num
+ FUNCTIONS_PER_FILE
7303 for idx
in range(test_num
, end
):
7304 func
= self
.functions
[idx
]
7306 #gen_cmd = func.GetInfo('gen_cmd')
7307 #if gen_cmd == True or gen_cmd == None:
7308 if func
.GetInfo('unit_test') == False:
7309 file.Write("// TODO(gman): %s\n" % func
.name
)
7311 func
.WriteServiceUnitTest(file)
7314 file = CHeaderWriter(
7316 "// It is included by gles2_cmd_decoder_unittest_base.cc\n")
7318 """void GLES2DecoderTestBase::SetupInitCapabilitiesExpectations() {
7320 for capability
in _CAPABILITY_FLAGS
:
7321 file.Write(" ExpectEnableDisable(GL_%s, %s);\n" %
7322 (capability
['name'].upper(),
7323 ('false', 'true')['default' in capability
]))
7326 void GLES2DecoderTestBase::SetupInitStateExpectations() {
7329 # We need to sort the keys so the expectations match
7330 for state_name
in sorted(_STATES
.keys()):
7331 state
= _STATES
[state_name
]
7332 if state
['type'] == 'FrontBack':
7333 num_states
= len(state
['states'])
7334 for ndx
, group
in enumerate(Grouper(num_states
/ 2, state
['states'])):
7337 if 'expected' in item
:
7338 args
.append(item
['expected'])
7340 args
.append(item
['default'])
7342 " EXPECT_CALL(*gl_, %s(%s, %s))\n" %
7343 (state
['func'], ('GL_FRONT', 'GL_BACK')[ndx
], ", ".join(args
)))
7344 file.Write(" .Times(1)\n")
7345 file.Write(" .RetiresOnSaturation();\n")
7346 elif state
['type'] == 'NamedParameter':
7347 for item
in state
['states']:
7348 if 'extension_flag' in item
:
7351 " EXPECT_CALL(*gl_, %s(%s, %s))\n" %
7352 (state
['func'], item
['enum'], item
['default']))
7353 file.Write(" .Times(1)\n")
7354 file.Write(" .RetiresOnSaturation();\n")
7357 for item
in state
['states']:
7358 if 'expected' in item
:
7359 args
.append(item
['expected'])
7361 args
.append(item
['default'])
7362 file.Write(" EXPECT_CALL(*gl_, %s(%s))\n" %
7363 (state
['func'], ", ".join(args
)))
7364 file.Write(" .Times(1)\n")
7365 file.Write(" .RetiresOnSaturation();\n")
7370 def WriteGLES2Header(self
, filename
):
7371 """Writes the GLES2 header."""
7372 file = CHeaderWriter(
7374 "// This file contains Chromium-specific GLES2 declarations.\n\n")
7376 for func
in self
.original_functions
:
7377 func
.WriteGLES2Header(file)
7382 def WriteGLES2CLibImplementation(self
, filename
):
7383 """Writes the GLES2 c lib implementation."""
7384 file = CHeaderWriter(
7386 "// These functions emulate GLES2 over command buffers.\n")
7388 for func
in self
.original_functions
:
7389 func
.WriteGLES2CLibImplementation(file)
7394 extern const NameToFunc g_gles2_function_table[] = {
7396 for func
in self
.original_functions
:
7398 ' { "gl%s", reinterpret_cast<GLES2FunctionPointer>(gl%s), },\n' %
7399 (func
.name
, func
.name
))
7400 file.Write(""" { NULL, NULL, },
7403 } // namespace gles2
7407 def WriteGLES2InterfaceHeader(self
, filename
):
7408 """Writes the GLES2 interface header."""
7409 file = CHeaderWriter(
7411 "// This file is included by gles2_interface.h to declare the\n"
7412 "// GL api functions.\n")
7413 for func
in self
.original_functions
:
7414 func
.WriteGLES2InterfaceHeader(file)
7417 def WriteGLES2InterfaceStub(self
, filename
):
7418 """Writes the GLES2 interface stub header."""
7419 file = CHeaderWriter(
7421 "// This file is included by gles2_interface_stub.h.\n")
7422 for func
in self
.original_functions
:
7423 func
.WriteGLES2InterfaceStub(file)
7426 def WriteGLES2InterfaceStubImpl(self
, filename
):
7427 """Writes the GLES2 interface header."""
7428 file = CHeaderWriter(
7430 "// This file is included by gles2_interface_stub.cc.\n")
7431 for func
in self
.original_functions
:
7432 func
.WriteGLES2InterfaceStubImpl(file)
7435 def WriteGLES2ImplementationHeader(self
, filename
):
7436 """Writes the GLES2 Implementation header."""
7437 file = CHeaderWriter(
7439 "// This file is included by gles2_implementation.h to declare the\n"
7440 "// GL api functions.\n")
7441 for func
in self
.original_functions
:
7442 func
.WriteGLES2ImplementationHeader(file)
7445 def WriteGLES2Implementation(self
, filename
):
7446 """Writes the GLES2 Implementation."""
7447 file = CHeaderWriter(
7449 "// This file is included by gles2_implementation.cc to define the\n"
7450 "// GL api functions.\n")
7451 for func
in self
.original_functions
:
7452 func
.WriteGLES2Implementation(file)
7455 def WriteGLES2TraceImplementationHeader(self
, filename
):
7456 """Writes the GLES2 Trace Implementation header."""
7457 file = CHeaderWriter(
7459 "// This file is included by gles2_trace_implementation.h\n")
7460 for func
in self
.original_functions
:
7461 func
.WriteGLES2TraceImplementationHeader(file)
7464 def WriteGLES2TraceImplementation(self
, filename
):
7465 """Writes the GLES2 Trace Implementation."""
7466 file = CHeaderWriter(
7468 "// This file is included by gles2_trace_implementation.cc\n")
7469 for func
in self
.original_functions
:
7470 func
.WriteGLES2TraceImplementation(file)
7473 def WriteGLES2ImplementationUnitTests(self
, filename
):
7474 """Writes the GLES2 helper header."""
7475 file = CHeaderWriter(
7477 "// This file is included by gles2_implementation.h to declare the\n"
7478 "// GL api functions.\n")
7479 for func
in self
.original_functions
:
7480 func
.WriteGLES2ImplementationUnitTest(file)
7483 def WriteServiceUtilsHeader(self
, filename
):
7484 """Writes the gles2 auto generated utility header."""
7485 file = CHeaderWriter(filename
)
7486 for enum
in sorted(_ENUM_LISTS
.keys()):
7487 file.Write("ValueValidator<%s> %s;\n" %
7488 (_ENUM_LISTS
[enum
]['type'], ToUnderscore(enum
)))
7492 def WriteServiceUtilsImplementation(self
, filename
):
7493 """Writes the gles2 auto generated utility implementation."""
7494 file = CHeaderWriter(filename
)
7495 enums
= sorted(_ENUM_LISTS
.keys())
7497 if len(_ENUM_LISTS
[enum
]['valid']) > 0:
7498 file.Write("static const %s valid_%s_table[] = {\n" %
7499 (_ENUM_LISTS
[enum
]['type'], ToUnderscore(enum
)))
7500 for value
in _ENUM_LISTS
[enum
]['valid']:
7501 file.Write(" %s,\n" % value
)
7504 file.Write("Validators::Validators()\n")
7507 for count
, enum
in enumerate(enums
):
7508 if count
+ 1 == len(enums
):
7510 if len(_ENUM_LISTS
[enum
]['valid']) > 0:
7511 code
= """ %(pre)s%(name)s(
7512 valid_%(name)s_table, arraysize(valid_%(name)s_table))%(post)s
7515 code
= """ %(pre)s%(name)s()%(post)s
7518 'name': ToUnderscore(enum
),
7523 file.Write("}\n\n");
7526 def WriteCommonUtilsHeader(self
, filename
):
7527 """Writes the gles2 common utility header."""
7528 file = CHeaderWriter(filename
)
7529 enums
= sorted(_ENUM_LISTS
.keys())
7531 if _ENUM_LISTS
[enum
]['type'] == 'GLenum':
7532 file.Write("static std::string GetString%s(uint32 value);\n" % enum
)
7536 def WriteCommonUtilsImpl(self
, filename
):
7537 """Writes the gles2 common utility header."""
7538 enum_re
= re
.compile(r
'\#define\s+(GL_[a-zA-Z0-9_]+)\s+([0-9A-Fa-fx]+)')
7540 for fname
in ['../../third_party/khronos/GLES2/gl2.h',
7541 '../../third_party/khronos/GLES2/gl2ext.h',
7542 '../../gpu/GLES2/gl2chromium.h',
7543 '../../gpu/GLES2/gl2extchromium.h']:
7544 lines
= open(fname
).readlines()
7546 m
= enum_re
.match(line
)
7550 if len(value
) <= 10 and not value
in dict:
7553 file = CHeaderWriter(filename
)
7554 file.Write("static const GLES2Util::EnumToString "
7555 "enum_to_string_table[] = {\n")
7557 file.Write(' { %s, "%s", },\n' % (value
, dict[value
]))
7560 const GLES2Util::EnumToString* const GLES2Util::enum_to_string_table_ =
7561 enum_to_string_table;
7562 const size_t GLES2Util::enum_to_string_table_len_ =
7563 sizeof(enum_to_string_table) / sizeof(enum_to_string_table[0]);
7567 enums
= sorted(_ENUM_LISTS
.keys())
7569 if _ENUM_LISTS
[enum
]['type'] == 'GLenum':
7570 file.Write("std::string GLES2Util::GetString%s(uint32 value) {\n" %
7572 if len(_ENUM_LISTS
[enum
]['valid']) > 0:
7573 file.Write(" static const EnumToString string_table[] = {\n")
7574 for value
in _ENUM_LISTS
[enum
]['valid']:
7575 file.Write(' { %s, "%s" },\n' % (value
, value
))
7577 return GLES2Util::GetQualifiedEnumString(
7578 string_table, arraysize(string_table), value);
7583 file.Write(""" return GLES2Util::GetQualifiedEnumString(
7590 def WritePepperGLES2Interface(self
, filename
, dev
):
7591 """Writes the Pepper OpenGLES interface definition."""
7592 file = CHeaderWriter(
7594 "// OpenGL ES interface.\n",
7597 file.Write("#include \"ppapi/c/pp_resource.h\"\n")
7599 file.Write("#include \"ppapi/c/ppb_opengles2.h\"\n\n")
7601 file.Write("\n#ifndef __gl2_h_\n")
7602 for (k
, v
) in _GL_TYPES
.iteritems():
7603 file.Write("typedef %s %s;\n" % (v
, k
))
7604 file.Write("#ifdef _WIN64\n")
7605 for (k
, v
) in _GL_TYPES_64
.iteritems():
7606 file.Write("typedef %s %s;\n" % (v
, k
))
7607 file.Write("#else\n")
7608 for (k
, v
) in _GL_TYPES_32
.iteritems():
7609 file.Write("typedef %s %s;\n" % (v
, k
))
7610 file.Write("#endif // _WIN64\n")
7611 file.Write("#endif // __gl2_h_\n\n")
7613 for interface
in self
.pepper_interfaces
:
7614 if interface
.dev
!= dev
:
7616 file.Write("#define %s_1_0 \"%s;1.0\"\n" %
7617 (interface
.GetInterfaceName(), interface
.GetInterfaceString()))
7618 file.Write("#define %s %s_1_0\n" %
7619 (interface
.GetInterfaceName(), interface
.GetInterfaceName()))
7621 file.Write("\nstruct %s {\n" % interface
.GetStructName())
7622 for func
in self
.original_functions
:
7623 if not func
.InPepperInterface(interface
):
7626 original_arg
= func
.MakeTypedPepperArgString("")
7627 context_arg
= "PP_Resource context"
7628 if len(original_arg
):
7629 arg
= context_arg
+ ", " + original_arg
7632 file.Write(" %s (*%s)(%s);\n" % (func
.return_type
, func
.name
, arg
))
7633 file.Write("};\n\n")
7638 def WritePepperGLES2Implementation(self
, filename
):
7639 """Writes the Pepper OpenGLES interface implementation."""
7641 file = CWriter(filename
)
7642 file.Write(_LICENSE
)
7643 file.Write(_DO_NOT_EDIT_WARNING
)
7645 file.Write("#include \"ppapi/shared_impl/ppb_opengles2_shared.h\"\n\n")
7646 file.Write("#include \"base/logging.h\"\n")
7647 file.Write("#include \"gpu/command_buffer/client/gles2_implementation.h\"\n")
7648 file.Write("#include \"ppapi/shared_impl/ppb_graphics_3d_shared.h\"\n")
7649 file.Write("#include \"ppapi/thunk/enter.h\"\n\n")
7651 file.Write("namespace ppapi {\n\n")
7652 file.Write("namespace {\n\n")
7654 file.Write("typedef thunk::EnterResource<thunk::PPB_Graphics3D_API>"
7657 file.Write("gpu::gles2::GLES2Implementation* ToGles2Impl(Enter3D*"
7659 file.Write(" DCHECK(enter);\n")
7660 file.Write(" DCHECK(enter->succeeded());\n")
7661 file.Write(" return static_cast<PPB_Graphics3D_Shared*>(enter->object())->"
7663 file.Write("}\n\n");
7665 for func
in self
.original_functions
:
7666 if not func
.InAnyPepperExtension():
7669 original_arg
= func
.MakeTypedPepperArgString("")
7670 context_arg
= "PP_Resource context_id"
7671 if len(original_arg
):
7672 arg
= context_arg
+ ", " + original_arg
7675 file.Write("%s %s(%s) {\n" % (func
.return_type
, func
.name
, arg
))
7676 file.Write(" Enter3D enter(context_id, true);\n")
7677 file.Write(" if (enter.succeeded()) {\n")
7679 return_str
= "" if func
.return_type
== "void" else "return "
7680 file.Write(" %sToGles2Impl(&enter)->%s(%s);\n" %
7681 (return_str
, func
.original_name
,
7682 func
.MakeOriginalArgString("")))
7684 if func
.return_type
== "void":
7687 file.Write(" else {\n")
7689 if func
.GetInfo("error_return"):
7690 error_return
= func
.GetInfo("error_return")
7691 elif func
.return_type
== "GLboolean":
7692 error_return
= "GL_FALSE"
7693 elif "*" in func
.return_type
:
7694 error_return
= "NULL"
7695 file.Write(" return %s;\n" % error_return
)
7699 file.Write("} // namespace\n")
7701 for interface
in self
.pepper_interfaces
:
7702 file.Write("const %s* PPB_OpenGLES2_Shared::Get%sInterface() {\n" %
7703 (interface
.GetStructName(), interface
.GetName()))
7704 file.Write(" static const struct %s "
7705 "ppb_opengles2 = {\n" % interface
.GetStructName())
7707 file.Write(",\n &".join(
7708 f
.name
for f
in self
.original_functions
7709 if f
.InPepperInterface(interface
)))
7713 file.Write(" return &ppb_opengles2;\n")
7716 file.Write("} // namespace ppapi\n")
7719 def WriteGLES2ToPPAPIBridge(self
, filename
):
7720 """Connects GLES2 helper library to PPB_OpenGLES2 interface"""
7722 file = CWriter(filename
)
7723 file.Write(_LICENSE
)
7724 file.Write(_DO_NOT_EDIT_WARNING
)
7726 file.Write("#ifndef GL_GLEXT_PROTOTYPES\n")
7727 file.Write("#define GL_GLEXT_PROTOTYPES\n")
7728 file.Write("#endif\n")
7729 file.Write("#include <GLES2/gl2.h>\n")
7730 file.Write("#include <GLES2/gl2ext.h>\n")
7731 file.Write("#include \"ppapi/lib/gl/gles2/gl2ext_ppapi.h\"\n\n")
7733 for func
in self
.original_functions
:
7734 if not func
.InAnyPepperExtension():
7737 interface
= self
.interface_info
[func
.GetInfo('pepper_interface') or '']
7739 file.Write("%s GL_APIENTRY gl%s(%s) {\n" %
7740 (func
.return_type
, func
.name
,
7741 func
.MakeTypedOriginalArgString("")))
7742 return_str
= "" if func
.return_type
== "void" else "return "
7743 interface_str
= "glGet%sInterfacePPAPI()" % interface
.GetName()
7744 original_arg
= func
.MakeOriginalArgString("")
7745 context_arg
= "glGetCurrentContextPPAPI()"
7746 if len(original_arg
):
7747 arg
= context_arg
+ ", " + original_arg
7750 if interface
.GetName():
7751 file.Write(" const struct %s* ext = %s;\n" %
7752 (interface
.GetStructName(), interface_str
))
7753 file.Write(" if (ext)\n")
7754 file.Write(" %sext->%s(%s);\n" %
7755 (return_str
, func
.name
, arg
))
7757 file.Write(" %s0;\n" % return_str
)
7759 file.Write(" %s%s->%s(%s);\n" %
7760 (return_str
, interface_str
, func
.name
, arg
))
7765 """This is the main function."""
7766 parser
= OptionParser()
7768 "-g", "--generate-implementation-templates", action
="store_true",
7769 help="generates files that are generally hand edited..")
7771 "--alternate-mode", type="choice",
7772 choices
=("ppapi", "chrome_ppapi", "chrome_ppapi_proxy", "nacl_ppapi"),
7773 help="generate files for other projects. \"ppapi\" will generate ppapi "
7774 "bindings. \"chrome_ppapi\" generate chrome implementation for ppapi. "
7775 "\"chrome_ppapi_proxy\" will generate the glue for the chrome IPC ppapi"
7776 "proxy. \"nacl_ppapi\" will generate NaCl implementation for ppapi")
7779 help="base directory for resulting files, under chrome/src. default is "
7780 "empty. Use this if you want the result stored under gen.")
7782 "-v", "--verbose", action
="store_true",
7783 help="prints more output.")
7785 (options
, args
) = parser
.parse_args(args
=argv
)
7787 # Add in states and capabilites to GLState
7788 for state_name
in sorted(_STATES
.keys()):
7789 state
= _STATES
[state_name
]
7791 _ENUM_LISTS
['GLState']['valid'].append(state
['enum'])
7793 for item
in state
['states']:
7794 if 'extension_flag' in item
:
7796 _ENUM_LISTS
['GLState']['valid'].append(item
['enum'])
7797 for capability
in _CAPABILITY_FLAGS
:
7798 _ENUM_LISTS
['GLState']['valid'].append("GL_%s" % capability
['name'].upper())
7800 # This script lives under gpu/command_buffer, cd to base directory.
7801 os
.chdir(os
.path
.dirname(__file__
) + "/../..")
7803 gen
= GLGenerator(options
.verbose
)
7804 gen
.ParseGLH("common/GLES2/gl2.h")
7806 # Support generating files under gen/
7807 if options
.output_dir
!= None:
7808 os
.chdir(options
.output_dir
)
7810 if options
.alternate_mode
== "ppapi":
7811 # To trigger this action, do "make ppapi_gles_bindings"
7813 gen
.WritePepperGLES2Interface("c/ppb_opengles2.h", False)
7814 gen
.WritePepperGLES2Interface("c/dev/ppb_opengles2ext_dev.h", True)
7815 gen
.WriteGLES2ToPPAPIBridge("lib/gl/gles2/gles2.c")
7817 elif options
.alternate_mode
== "chrome_ppapi":
7818 # To trigger this action, do "make ppapi_gles_implementation"
7819 gen
.WritePepperGLES2Implementation(
7820 "ppapi/shared_impl/ppb_opengles2_shared.cc")
7823 os
.chdir("gpu/command_buffer")
7824 gen
.WriteCommandIds("common/gles2_cmd_ids_autogen.h")
7825 gen
.WriteFormat("common/gles2_cmd_format_autogen.h")
7826 gen
.WriteFormatTest("common/gles2_cmd_format_test_autogen.h")
7827 gen
.WriteGLES2InterfaceHeader("client/gles2_interface_autogen.h")
7828 gen
.WriteGLES2InterfaceStub("client/gles2_interface_stub_autogen.h")
7829 gen
.WriteGLES2InterfaceStubImpl(
7830 "client/gles2_interface_stub_impl_autogen.h")
7831 gen
.WriteGLES2ImplementationHeader("client/gles2_implementation_autogen.h")
7832 gen
.WriteGLES2Implementation("client/gles2_implementation_impl_autogen.h")
7833 gen
.WriteGLES2ImplementationUnitTests(
7834 "client/gles2_implementation_unittest_autogen.h")
7835 gen
.WriteGLES2TraceImplementationHeader(
7836 "client/gles2_trace_implementation_autogen.h")
7837 gen
.WriteGLES2TraceImplementation(
7838 "client/gles2_trace_implementation_impl_autogen.h")
7839 gen
.WriteGLES2CLibImplementation("client/gles2_c_lib_autogen.h")
7840 gen
.WriteCmdHelperHeader("client/gles2_cmd_helper_autogen.h")
7841 gen
.WriteServiceImplementation("service/gles2_cmd_decoder_autogen.h")
7842 gen
.WriteServiceContextStateHeader("service/context_state_autogen.h")
7843 gen
.WriteServiceContextStateImpl("service/context_state_impl_autogen.h")
7844 gen
.WriteClientContextStateHeader("client/client_context_state_autogen.h")
7845 gen
.WriteClientContextStateImpl(
7846 "client/client_context_state_impl_autogen.h")
7847 gen
.WriteServiceUnitTests("service/gles2_cmd_decoder_unittest_%d_autogen.h")
7848 gen
.WriteServiceUtilsHeader("service/gles2_cmd_validation_autogen.h")
7849 gen
.WriteServiceUtilsImplementation(
7850 "service/gles2_cmd_validation_implementation_autogen.h")
7851 gen
.WriteCommonUtilsHeader("common/gles2_cmd_utils_autogen.h")
7852 gen
.WriteCommonUtilsImpl("common/gles2_cmd_utils_implementation_autogen.h")
7853 gen
.WriteGLES2Header("../GLES2/gl2chromium_autogen.h")
7856 print "%d errors" % gen
.errors
7861 if __name__
== '__main__':
7862 sys
.exit(main(sys
.argv
[1:]))