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
14 from subprocess
import call
17 _SIZE_OF_COMMAND_HEADER
= 4
18 _FIRST_SPECIFIC_COMMAND_ID
= 256
20 _LICENSE
= """// Copyright (c) 2014 The Chromium Authors. All rights reserved.
21 // Use of this source code is governed by a BSD-style license that can be
22 // found in the LICENSE file.
26 _DO_NOT_EDIT_WARNING
= """// This file is auto-generated from
27 // gpu/command_buffer/build_gles2_cmd_buffer.py
28 // It's formatted by clang-format using chromium coding style:
29 // clang-format -i -style=chromium filename
34 # This string is copied directly out of the gl2.h file from GLES2.0
38 # *) Any argument that is a resourceID has been changed to GLid<Type>.
39 # (not pointer arguments) and if it's allowed to be zero it's GLidZero<Type>
40 # If it's allowed to not exist it's GLidBind<Type>
42 # *) All GLenums have been changed to GLenumTypeOfEnum
45 'GLenum': 'unsigned int',
46 'GLboolean': 'unsigned char',
47 'GLbitfield': 'unsigned int',
48 'GLbyte': 'signed char',
52 'GLubyte': 'unsigned char',
53 'GLushort': 'unsigned short',
54 'GLuint': 'unsigned int',
63 'GLintptr': 'long int',
64 'GLsizeiptr': 'long int'
68 'GLintptr': 'long long int',
69 'GLsizeiptr': 'long long int'
72 # Capabilites selected with glEnable
75 {'name': 'cull_face'},
76 {'name': 'depth_test', 'state_flag': 'framebuffer_state_.clear_state_dirty'},
77 {'name': 'dither', 'default': True},
78 {'name': 'polygon_offset_fill'},
79 {'name': 'sample_alpha_to_coverage'},
80 {'name': 'sample_coverage'},
81 {'name': 'scissor_test',
82 'state_flag': 'framebuffer_state_.clear_state_dirty'},
83 {'name': 'stencil_test',
84 'state_flag': 'framebuffer_state_.clear_state_dirty'},
91 'enum': 'GL_COLOR_CLEAR_VALUE',
93 {'name': 'color_clear_red', 'type': 'GLfloat', 'default': '0.0f'},
94 {'name': 'color_clear_green', 'type': 'GLfloat', 'default': '0.0f'},
95 {'name': 'color_clear_blue', 'type': 'GLfloat', 'default': '0.0f'},
96 {'name': 'color_clear_alpha', 'type': 'GLfloat', 'default': '0.0f'},
101 'func': 'ClearDepth',
102 'enum': 'GL_DEPTH_CLEAR_VALUE',
104 {'name': 'depth_clear', 'type': 'GLclampf', 'default': '1.0f'},
110 'enum': 'GL_COLOR_WRITEMASK',
112 {'name': 'color_mask_red', 'type': 'GLboolean', 'default': 'true'},
113 {'name': 'color_mask_green', 'type': 'GLboolean', 'default': 'true'},
114 {'name': 'color_mask_blue', 'type': 'GLboolean', 'default': 'true'},
115 {'name': 'color_mask_alpha', 'type': 'GLboolean', 'default': 'true'},
117 'state_flag': 'framebuffer_state_.clear_state_dirty',
121 'func': 'ClearStencil',
122 'enum': 'GL_STENCIL_CLEAR_VALUE',
124 {'name': 'stencil_clear', 'type': 'GLint', 'default': '0'},
129 'func': 'BlendColor',
130 'enum': 'GL_BLEND_COLOR',
132 {'name': 'blend_color_red', 'type': 'GLfloat', 'default': '0.0f'},
133 {'name': 'blend_color_green', 'type': 'GLfloat', 'default': '0.0f'},
134 {'name': 'blend_color_blue', 'type': 'GLfloat', 'default': '0.0f'},
135 {'name': 'blend_color_alpha', 'type': 'GLfloat', 'default': '0.0f'},
140 'func': 'BlendEquationSeparate',
143 'name': 'blend_equation_rgb',
145 'enum': 'GL_BLEND_EQUATION_RGB',
146 'default': 'GL_FUNC_ADD',
149 'name': 'blend_equation_alpha',
151 'enum': 'GL_BLEND_EQUATION_ALPHA',
152 'default': 'GL_FUNC_ADD',
158 'func': 'BlendFuncSeparate',
161 'name': 'blend_source_rgb',
163 'enum': 'GL_BLEND_SRC_RGB',
167 'name': 'blend_dest_rgb',
169 'enum': 'GL_BLEND_DST_RGB',
170 'default': 'GL_ZERO',
173 'name': 'blend_source_alpha',
175 'enum': 'GL_BLEND_SRC_ALPHA',
179 'name': 'blend_dest_alpha',
181 'enum': 'GL_BLEND_DST_ALPHA',
182 'default': 'GL_ZERO',
188 'func': 'PolygonOffset',
191 'name': 'polygon_offset_factor',
193 'enum': 'GL_POLYGON_OFFSET_FACTOR',
197 'name': 'polygon_offset_units',
199 'enum': 'GL_POLYGON_OFFSET_UNITS',
207 'enum': 'GL_CULL_FACE_MODE',
212 'default': 'GL_BACK',
219 'enum': 'GL_FRONT_FACE',
220 'states': [{'name': 'front_face', 'type': 'GLenum', 'default': 'GL_CCW'}],
225 'enum': 'GL_DEPTH_FUNC',
226 'states': [{'name': 'depth_func', 'type': 'GLenum', 'default': 'GL_LESS'}],
230 'func': 'DepthRange',
231 'enum': 'GL_DEPTH_RANGE',
233 {'name': 'z_near', 'type': 'GLclampf', 'default': '0.0f'},
234 {'name': 'z_far', 'type': 'GLclampf', 'default': '1.0f'},
239 'func': 'SampleCoverage',
242 'name': 'sample_coverage_value',
244 'enum': 'GL_SAMPLE_COVERAGE_VALUE',
248 'name': 'sample_coverage_invert',
250 'enum': 'GL_SAMPLE_COVERAGE_INVERT',
257 'func': 'StencilMaskSeparate',
258 'state_flag': 'framebuffer_state_.clear_state_dirty',
261 'name': 'stencil_front_writemask',
263 'enum': 'GL_STENCIL_WRITEMASK',
264 'default': '0xFFFFFFFFU',
267 'name': 'stencil_back_writemask',
269 'enum': 'GL_STENCIL_BACK_WRITEMASK',
270 'default': '0xFFFFFFFFU',
276 'func': 'StencilOpSeparate',
279 'name': 'stencil_front_fail_op',
281 'enum': 'GL_STENCIL_FAIL',
282 'default': 'GL_KEEP',
285 'name': 'stencil_front_z_fail_op',
287 'enum': 'GL_STENCIL_PASS_DEPTH_FAIL',
288 'default': 'GL_KEEP',
291 'name': 'stencil_front_z_pass_op',
293 'enum': 'GL_STENCIL_PASS_DEPTH_PASS',
294 'default': 'GL_KEEP',
297 'name': 'stencil_back_fail_op',
299 'enum': 'GL_STENCIL_BACK_FAIL',
300 'default': 'GL_KEEP',
303 'name': 'stencil_back_z_fail_op',
305 'enum': 'GL_STENCIL_BACK_PASS_DEPTH_FAIL',
306 'default': 'GL_KEEP',
309 'name': 'stencil_back_z_pass_op',
311 'enum': 'GL_STENCIL_BACK_PASS_DEPTH_PASS',
312 'default': 'GL_KEEP',
318 'func': 'StencilFuncSeparate',
321 'name': 'stencil_front_func',
323 'enum': 'GL_STENCIL_FUNC',
324 'default': 'GL_ALWAYS',
327 'name': 'stencil_front_ref',
329 'enum': 'GL_STENCIL_REF',
333 'name': 'stencil_front_mask',
335 'enum': 'GL_STENCIL_VALUE_MASK',
336 'default': '0xFFFFFFFFU',
339 'name': 'stencil_back_func',
341 'enum': 'GL_STENCIL_BACK_FUNC',
342 'default': 'GL_ALWAYS',
345 'name': 'stencil_back_ref',
347 'enum': 'GL_STENCIL_BACK_REF',
351 'name': 'stencil_back_mask',
353 'enum': 'GL_STENCIL_BACK_VALUE_MASK',
354 'default': '0xFFFFFFFFU',
359 'type': 'NamedParameter',
363 'name': 'hint_generate_mipmap',
365 'enum': 'GL_GENERATE_MIPMAP_HINT',
366 'default': 'GL_DONT_CARE'
369 'name': 'hint_fragment_shader_derivative',
371 'enum': 'GL_FRAGMENT_SHADER_DERIVATIVE_HINT_OES',
372 'default': 'GL_DONT_CARE',
373 'extension_flag': 'oes_standard_derivatives'
378 'type': 'NamedParameter',
379 'func': 'PixelStorei',
382 'name': 'pack_alignment',
384 'enum': 'GL_PACK_ALIGNMENT',
388 'name': 'unpack_alignment',
390 'enum': 'GL_UNPACK_ALIGNMENT',
395 # TODO: Consider implemenenting these states
400 'enum': 'GL_LINE_WIDTH',
403 'name': 'line_width',
406 'range_checks': [{'check': "<= 0.0f", 'test_value': "0.0f"}],
412 'enum': 'GL_DEPTH_WRITEMASK',
414 {'name': 'depth_mask', 'type': 'GLboolean', 'default': 'true'},
416 'state_flag': 'framebuffer_state_.clear_state_dirty',
421 'enum': 'GL_SCISSOR_BOX',
423 # NOTE: These defaults reset at GLES2DecoderImpl::Initialization.
428 'expected': 'kViewportX',
434 'expected': 'kViewportY',
437 'name': 'scissor_width',
440 'expected': 'kViewportWidth',
443 'name': 'scissor_height',
446 'expected': 'kViewportHeight',
453 'enum': 'GL_VIEWPORT',
455 # NOTE: These defaults reset at GLES2DecoderImpl::Initialization.
457 'name': 'viewport_x',
460 'expected': 'kViewportX',
463 'name': 'viewport_y',
466 'expected': 'kViewportY',
469 'name': 'viewport_width',
472 'expected': 'kViewportWidth',
475 'name': 'viewport_height',
478 'expected': 'kViewportHeight',
484 # This is a list of enum names and their valid values. It is used to map
485 # GLenum arguments to a specific set of valid values.
494 'GL_LINEAR_MIPMAP_LINEAR',
497 'FrameBufferTarget': {
503 'GL_DRAW_FRAMEBUFFER' ,
504 'GL_READ_FRAMEBUFFER' ,
507 'RenderBufferTarget': {
520 'GL_ELEMENT_ARRAY_BUFFER',
537 'CompressedTextureFormat': {
545 # NOTE: State an Capability entries added later.
547 'GL_ALIASED_LINE_WIDTH_RANGE',
548 'GL_ALIASED_POINT_SIZE_RANGE',
550 'GL_ARRAY_BUFFER_BINDING',
552 'GL_COMPRESSED_TEXTURE_FORMATS',
553 'GL_CURRENT_PROGRAM',
556 'GL_ELEMENT_ARRAY_BUFFER_BINDING',
557 'GL_FRAMEBUFFER_BINDING',
558 'GL_GENERATE_MIPMAP_HINT',
560 'GL_IMPLEMENTATION_COLOR_READ_FORMAT',
561 'GL_IMPLEMENTATION_COLOR_READ_TYPE',
562 'GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS',
563 'GL_MAX_CUBE_MAP_TEXTURE_SIZE',
564 'GL_MAX_FRAGMENT_UNIFORM_VECTORS',
565 'GL_MAX_RENDERBUFFER_SIZE',
566 'GL_MAX_TEXTURE_IMAGE_UNITS',
567 'GL_MAX_TEXTURE_SIZE',
568 'GL_MAX_VARYING_VECTORS',
569 'GL_MAX_VERTEX_ATTRIBS',
570 'GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS',
571 'GL_MAX_VERTEX_UNIFORM_VECTORS',
572 'GL_MAX_VIEWPORT_DIMS',
573 'GL_NUM_COMPRESSED_TEXTURE_FORMATS',
574 'GL_NUM_SHADER_BINARY_FORMATS',
577 'GL_RENDERBUFFER_BINDING',
579 'GL_SAMPLE_COVERAGE_INVERT',
580 'GL_SAMPLE_COVERAGE_VALUE',
583 'GL_SHADER_BINARY_FORMATS',
584 'GL_SHADER_COMPILER',
587 'GL_TEXTURE_BINDING_2D',
588 'GL_TEXTURE_BINDING_CUBE_MAP',
589 'GL_UNPACK_ALIGNMENT',
590 'GL_UNPACK_FLIP_Y_CHROMIUM',
591 'GL_UNPACK_PREMULTIPLY_ALPHA_CHROMIUM',
592 'GL_UNPACK_UNPREMULTIPLY_ALPHA_CHROMIUM',
593 # we can add this because we emulate it if the driver does not support it.
594 'GL_VERTEX_ARRAY_BINDING_OES',
601 'GetTexParamTarget': {
605 'GL_TEXTURE_CUBE_MAP',
608 'GL_PROXY_TEXTURE_CUBE_MAP',
615 'GL_TEXTURE_CUBE_MAP_POSITIVE_X',
616 'GL_TEXTURE_CUBE_MAP_NEGATIVE_X',
617 'GL_TEXTURE_CUBE_MAP_POSITIVE_Y',
618 'GL_TEXTURE_CUBE_MAP_NEGATIVE_Y',
619 'GL_TEXTURE_CUBE_MAP_POSITIVE_Z',
620 'GL_TEXTURE_CUBE_MAP_NEGATIVE_Z',
623 'GL_PROXY_TEXTURE_CUBE_MAP',
626 'TextureBindTarget': {
630 'GL_TEXTURE_CUBE_MAP',
641 'GL_FRAGMENT_SHADER',
644 'GL_GEOMETRY_SHADER',
680 'GL_FUNC_REVERSE_SUBTRACT',
693 'GL_ONE_MINUS_SRC_COLOR',
695 'GL_ONE_MINUS_DST_COLOR',
697 'GL_ONE_MINUS_SRC_ALPHA',
699 'GL_ONE_MINUS_DST_ALPHA',
701 'GL_ONE_MINUS_CONSTANT_COLOR',
703 'GL_ONE_MINUS_CONSTANT_ALPHA',
704 'GL_SRC_ALPHA_SATURATE',
713 'GL_ONE_MINUS_SRC_COLOR',
715 'GL_ONE_MINUS_DST_COLOR',
717 'GL_ONE_MINUS_SRC_ALPHA',
719 'GL_ONE_MINUS_DST_ALPHA',
721 'GL_ONE_MINUS_CONSTANT_COLOR',
723 'GL_ONE_MINUS_CONSTANT_ALPHA',
728 'valid': ["GL_%s" % cap
['name'].upper() for cap
in _CAPABILITY_FLAGS
],
775 'GL_COLOR_ATTACHMENT0',
776 'GL_DEPTH_ATTACHMENT',
777 'GL_STENCIL_ATTACHMENT',
780 'BackbufferAttachment': {
795 'GL_PIXEL_PACK_BUFFER',
798 'FrameBufferParameter': {
801 'GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE',
802 'GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME',
803 'GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL',
804 'GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE',
807 'ProgramParameter': {
812 'GL_VALIDATE_STATUS',
813 'GL_INFO_LOG_LENGTH',
814 'GL_ATTACHED_SHADERS',
815 'GL_ACTIVE_ATTRIBUTES',
816 'GL_ACTIVE_ATTRIBUTE_MAX_LENGTH',
817 'GL_ACTIVE_UNIFORMS',
818 'GL_ACTIVE_UNIFORM_MAX_LENGTH',
821 'QueryObjectParameter': {
824 'GL_QUERY_RESULT_EXT',
825 'GL_QUERY_RESULT_AVAILABLE_EXT',
831 'GL_CURRENT_QUERY_EXT',
837 'GL_ANY_SAMPLES_PASSED_EXT',
838 'GL_ANY_SAMPLES_PASSED_CONSERVATIVE_EXT',
839 'GL_COMMANDS_ISSUED_CHROMIUM',
840 'GL_LATENCY_QUERY_CHROMIUM',
841 'GL_ASYNC_PIXEL_UNPACK_COMPLETED_CHROMIUM',
842 'GL_ASYNC_PIXEL_PACK_COMPLETED_CHROMIUM',
845 'RenderBufferParameter': {
848 'GL_RENDERBUFFER_RED_SIZE',
849 'GL_RENDERBUFFER_GREEN_SIZE',
850 'GL_RENDERBUFFER_BLUE_SIZE',
851 'GL_RENDERBUFFER_ALPHA_SIZE',
852 'GL_RENDERBUFFER_DEPTH_SIZE',
853 'GL_RENDERBUFFER_STENCIL_SIZE',
854 'GL_RENDERBUFFER_WIDTH',
855 'GL_RENDERBUFFER_HEIGHT',
856 'GL_RENDERBUFFER_INTERNAL_FORMAT',
865 'GL_INFO_LOG_LENGTH',
866 'GL_SHADER_SOURCE_LENGTH',
867 'GL_TRANSLATED_SHADER_SOURCE_LENGTH_ANGLE',
887 'GL_SHADING_LANGUAGE_VERSION',
891 'TextureParameter': {
894 'GL_TEXTURE_MAG_FILTER',
895 'GL_TEXTURE_MIN_FILTER',
896 'GL_TEXTURE_POOL_CHROMIUM',
901 'GL_GENERATE_MIPMAP',
907 'GL_TEXTURE_POOL_MANAGED_CHROMIUM',
908 'GL_TEXTURE_POOL_UNMANAGED_CHROMIUM',
915 'GL_MIRRORED_REPEAT',
919 'TextureMinFilterMode': {
924 'GL_NEAREST_MIPMAP_NEAREST',
925 'GL_LINEAR_MIPMAP_NEAREST',
926 'GL_NEAREST_MIPMAP_LINEAR',
927 'GL_LINEAR_MIPMAP_LINEAR',
930 'TextureMagFilterMode': {
941 'GL_FRAMEBUFFER_ATTACHMENT_ANGLE',
947 # some enum that the decoder actually passes through to GL needs
948 # to be the first listed here since it's used in unit tests.
949 'GL_VERTEX_ATTRIB_ARRAY_NORMALIZED',
950 'GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING',
951 'GL_VERTEX_ATTRIB_ARRAY_ENABLED',
952 'GL_VERTEX_ATTRIB_ARRAY_SIZE',
953 'GL_VERTEX_ATTRIB_ARRAY_STRIDE',
954 'GL_VERTEX_ATTRIB_ARRAY_TYPE',
955 'GL_CURRENT_VERTEX_ATTRIB',
961 'GL_VERTEX_ATTRIB_ARRAY_POINTER',
967 'GL_GENERATE_MIPMAP_HINT',
970 'GL_PERSPECTIVE_CORRECTION_HINT',
985 'GL_UNPACK_ALIGNMENT',
986 'GL_UNPACK_FLIP_Y_CHROMIUM',
987 'GL_UNPACK_PREMULTIPLY_ALPHA_CHROMIUM',
988 'GL_UNPACK_UNPREMULTIPLY_ALPHA_CHROMIUM',
991 'GL_PACK_SWAP_BYTES',
992 'GL_UNPACK_SWAP_BYTES',
995 'PixelStoreAlignment': {
1008 'ReadPixelFormat': {
1020 'GL_UNSIGNED_SHORT_5_6_5',
1021 'GL_UNSIGNED_SHORT_4_4_4_4',
1022 'GL_UNSIGNED_SHORT_5_5_5_1',
1033 'GL_UNSIGNED_SHORT_5_6_5',
1034 'GL_UNSIGNED_SHORT_4_4_4_4',
1035 'GL_UNSIGNED_SHORT_5_5_5_1',
1042 'RenderBufferFormat': {
1048 'GL_DEPTH_COMPONENT16',
1049 'GL_STENCIL_INDEX8',
1052 'ShaderBinaryFormat': {
1075 'GL_LUMINANCE_ALPHA',
1084 'TextureInternalFormat': {
1089 'GL_LUMINANCE_ALPHA',
1098 'TextureInternalFormatStorage': {
1105 'GL_LUMINANCE8_EXT',
1106 'GL_LUMINANCE8_ALPHA8_EXT',
1111 'VertexAttribType': {
1117 'GL_UNSIGNED_SHORT',
1118 # 'GL_FIXED', // This is not available on Desktop GL.
1134 'VertexAttribSize': {
1157 'type': 'GLboolean',
1168 'GL_GUILTY_CONTEXT_RESET_ARB',
1169 'GL_INNOCENT_CONTEXT_RESET_ARB',
1170 'GL_UNKNOWN_CONTEXT_RESET_ARB',
1175 # This table specifies the different pepper interfaces that are supported for
1176 # GL commands. 'dev' is true if it's a dev interface.
1177 _PEPPER_INTERFACES
= [
1178 {'name': '', 'dev': False},
1179 {'name': 'InstancedArrays', 'dev': False},
1180 {'name': 'FramebufferBlit', 'dev': False},
1181 {'name': 'FramebufferMultisample', 'dev': False},
1182 {'name': 'ChromiumEnableFeature', 'dev': False},
1183 {'name': 'ChromiumMapSub', 'dev': False},
1184 {'name': 'Query', 'dev': False},
1187 # This table specifies types and other special data for the commands that
1188 # will be generated.
1190 # Must match function names specified in "cmd_buffer_functions.txt".
1192 # cmd_comment: A comment added to the cmd format.
1193 # type: defines which handler will be used to generate code.
1194 # decoder_func: defines which function to call in the decoder to execute the
1195 # corresponding GL command. If not specified the GL command will
1196 # be called directly.
1197 # gl_test_func: GL function that is expected to be called when testing.
1198 # cmd_args: The arguments to use for the command. This overrides generating
1199 # them based on the GL function arguments.
1200 # a NonImmediate type is a type that stays a pointer even in
1201 # and immediate version of acommand.
1202 # gen_cmd: Whether or not this function geneates a command. Default = True.
1203 # immediate: Whether or not to generate an immediate command for the GL
1204 # function. The default is if there is exactly 1 pointer argument
1205 # in the GL function an immediate command is generated.
1206 # bucket: True to generate a bucket version of the command.
1207 # impl_func: Whether or not to generate the GLES2Implementation part of this
1209 # impl_decl: Whether or not to generate the GLES2Implementation declaration
1211 # needs_size: If true a data_size field is added to the command.
1212 # data_type: The type of data the command uses. For PUTn or PUT types.
1213 # count: The number of units per element. For PUTn or PUT types.
1214 # unit_test: If False no service side unit test will be generated.
1215 # client_test: If False no client side unit test will be generated.
1216 # expectation: If False the unit test will have no expected calls.
1217 # gen_func: Name of function that generates GL resource for corresponding
1219 # states: array of states that get set by this function corresponding to
1220 # the given arguments
1221 # state_flag: name of flag that is set to true when function is called.
1222 # no_gl: no GL function is called.
1223 # valid_args: A dictionary of argument indices to args to use in unit tests
1224 # when they can not be automatically determined.
1225 # pepper_interface: The pepper interface that is used for this extension
1226 # pepper_name: The name of the function as exposed to pepper.
1227 # pepper_args: A string representing the argument list (what would appear in
1228 # C/C++ between the parentheses for the function declaration)
1229 # that the Pepper API expects for this function. Use this only if
1230 # the stable Pepper API differs from the GLES2 argument list.
1231 # invalid_test: False if no invalid test needed.
1232 # shadowed: True = the value is shadowed so no glGetXXX call will be made.
1233 # first_element_only: For PUT types, True if only the first element of an
1234 # array is used and we end up calling the single value
1235 # corresponding function. eg. TexParameteriv -> TexParameteri
1239 'decoder_func': 'DoActiveTexture',
1242 'client_test': False,
1244 'AttachShader': {'decoder_func': 'DoAttachShader'},
1245 'BindAttribLocation': {
1253 'decoder_func': 'DoBindBuffer',
1254 'gen_func': 'GenBuffersARB',
1256 'BindFramebuffer': {
1258 'decoder_func': 'DoBindFramebuffer',
1259 'gl_test_func': 'glBindFramebufferEXT',
1260 'gen_func': 'GenFramebuffersEXT',
1263 'BindRenderbuffer': {
1265 'decoder_func': 'DoBindRenderbuffer',
1266 'gl_test_func': 'glBindRenderbufferEXT',
1267 'gen_func': 'GenRenderbuffersEXT',
1271 'decoder_func': 'DoBindTexture',
1272 'gen_func': 'GenTextures',
1273 # TODO(gman): remove this once client side caching works.
1274 'client_test': False,
1277 'BlitFramebufferCHROMIUM': {
1278 'decoder_func': 'DoBlitFramebufferCHROMIUM',
1281 'pepper_interface': 'FramebufferBlit',
1282 'pepper_name': 'BlitFramebufferEXT',
1283 'defer_reads': True,
1284 'defer_draws': True,
1290 'client_test': False,
1294 'client_test': False,
1295 'decoder_func': 'DoBufferSubData',
1298 'CheckFramebufferStatus': {
1300 'decoder_func': 'DoCheckFramebufferStatus',
1301 'gl_test_func': 'glCheckFramebufferStatusEXT',
1302 'error_value': 'GL_FRAMEBUFFER_UNSUPPORTED',
1303 'result': ['GLenum'],
1306 'decoder_func': 'DoClear',
1307 'defer_draws': True,
1312 'state': 'ClearColor',
1316 'state': 'ClearDepthf',
1317 'decoder_func': 'glClearDepth',
1318 'gl_test_func': 'glClearDepth',
1325 'state': 'ColorMask',
1327 'expectation': False,
1329 'ConsumeTextureCHROMIUM': {
1330 'decoder_func': 'DoConsumeTextureCHROMIUM',
1333 'data_type': 'GLbyte',
1334 'count': 64, # GL_MAILBOX_SIZE_CHROMIUM
1336 'client_test': False,
1343 'state': 'ClearStencil',
1345 'EnableFeatureCHROMIUM': {
1348 'decoder_func': 'DoEnableFeatureCHROMIUM',
1349 'expectation': False,
1350 'cmd_args': 'GLuint bucket_id, GLint* result',
1351 'result': ['GLint'],
1354 'pepper_interface': 'ChromiumEnableFeature',
1356 'CompileShader': {'decoder_func': 'DoCompileShader', 'unit_test': False},
1357 'CompressedTexImage2D': {
1362 'CompressedTexSubImage2D': {
1365 'decoder_func': 'DoCompressedTexSubImage2D',
1369 'decoder_func': 'DoCopyTexImage2D',
1371 'defer_reads': True,
1373 'CopyTexSubImage2D': {
1374 'decoder_func': 'DoCopyTexSubImage2D',
1375 'defer_reads': True,
1377 'CreateImageCHROMIUM': {
1379 'cmd_args': 'GLsizei width, GLsizei height, GLenum internalformat',
1380 'result': ['GLuint'],
1381 'client_test': False,
1383 'expectation': False,
1387 'DestroyImageCHROMIUM': {
1390 'client_test': False,
1395 'GetImageParameterivCHROMIUM': {
1397 'client_test': False,
1399 'expectation': False,
1405 'client_test': False,
1409 'client_test': False,
1413 'state': 'BlendColor',
1416 'type': 'StateSetRGBAlpha',
1417 'state': 'BlendEquation',
1419 '0': 'GL_FUNC_SUBTRACT'
1422 'BlendEquationSeparate': {
1424 'state': 'BlendEquation',
1426 '0': 'GL_FUNC_SUBTRACT'
1430 'type': 'StateSetRGBAlpha',
1431 'state': 'BlendFunc',
1433 'BlendFuncSeparate': {
1435 'state': 'BlendFunc',
1437 'SampleCoverage': {'decoder_func': 'DoSampleCoverage'},
1439 'type': 'StateSetFrontBack',
1440 'state': 'StencilFunc',
1442 'StencilFuncSeparate': {
1443 'type': 'StateSetFrontBackSeparate',
1444 'state': 'StencilFunc',
1447 'type': 'StateSetFrontBack',
1448 'state': 'StencilOp',
1453 'StencilOpSeparate': {
1454 'type': 'StateSetFrontBackSeparate',
1455 'state': 'StencilOp',
1461 'type': 'StateSetNamedParameter',
1464 'CullFace': {'type': 'StateSet', 'state': 'CullFace'},
1465 'FrontFace': {'type': 'StateSet', 'state': 'FrontFace'},
1466 'DepthFunc': {'type': 'StateSet', 'state': 'DepthFunc'},
1469 'state': 'LineWidth',
1476 'state': 'PolygonOffset',
1480 'gl_test_func': 'glDeleteBuffersARB',
1481 'resource_type': 'Buffer',
1482 'resource_types': 'Buffers',
1484 'DeleteFramebuffers': {
1486 'gl_test_func': 'glDeleteFramebuffersEXT',
1487 'resource_type': 'Framebuffer',
1488 'resource_types': 'Framebuffers',
1490 'DeleteProgram': {'type': 'Delete', 'decoder_func': 'DoDeleteProgram'},
1491 'DeleteRenderbuffers': {
1493 'gl_test_func': 'glDeleteRenderbuffersEXT',
1494 'resource_type': 'Renderbuffer',
1495 'resource_types': 'Renderbuffers',
1497 'DeleteShader': {'type': 'Delete', 'decoder_func': 'DoDeleteShader'},
1498 'DeleteSharedIdsCHROMIUM': {
1500 'decoder_func': 'DoDeleteSharedIdsCHROMIUM',
1502 'expectation': False,
1509 'resource_type': 'Texture',
1510 'resource_types': 'Textures',
1513 'decoder_func': 'DoDepthRangef',
1514 'gl_test_func': 'glDepthRange',
1518 'state': 'DepthMask',
1520 'expectation': False,
1522 'DetachShader': {'decoder_func': 'DoDetachShader'},
1524 'decoder_func': 'DoDisable',
1526 'client_test': False,
1528 'DisableVertexAttribArray': {
1529 'decoder_func': 'DoDisableVertexAttribArray',
1534 'cmd_args': 'GLenumDrawMode mode, GLint first, GLsizei count',
1535 'defer_draws': True,
1540 'cmd_args': 'GLenumDrawMode mode, GLsizei count, '
1541 'GLenumIndexType type, GLuint index_offset',
1542 'client_test': False,
1543 'defer_draws': True,
1547 'decoder_func': 'DoEnable',
1549 'client_test': False,
1551 'EnableVertexAttribArray': {
1552 'decoder_func': 'DoEnableVertexAttribArray',
1557 'client_test': False,
1558 'decoder_func': 'DoFinish',
1559 'defer_reads': True,
1563 'decoder_func': 'DoFlush',
1565 'FramebufferRenderbuffer': {
1566 'decoder_func': 'DoFramebufferRenderbuffer',
1567 'gl_test_func': 'glFramebufferRenderbufferEXT',
1569 'FramebufferTexture2D': {
1570 'decoder_func': 'DoFramebufferTexture2D',
1571 'gl_test_func': 'glFramebufferTexture2DEXT',
1574 'FramebufferTexture2DMultisampleEXT': {
1575 'decoder_func': 'DoFramebufferTexture2DMultisample',
1576 'gl_test_func': 'glFramebufferTexture2DMultisampleEXT',
1577 'expectation': False,
1583 'decoder_func': 'DoGenerateMipmap',
1584 'gl_test_func': 'glGenerateMipmapEXT',
1588 'gl_test_func': 'glGenBuffersARB',
1589 'resource_type': 'Buffer',
1590 'resource_types': 'Buffers',
1592 'GenMailboxCHROMIUM': {
1593 'type': 'HandWritten',
1599 'GenFramebuffers': {
1601 'gl_test_func': 'glGenFramebuffersEXT',
1602 'resource_type': 'Framebuffer',
1603 'resource_types': 'Framebuffers',
1605 'GenRenderbuffers': {
1606 'type': 'GENn', 'gl_test_func': 'glGenRenderbuffersEXT',
1607 'resource_type': 'Renderbuffer',
1608 'resource_types': 'Renderbuffers',
1612 'gl_test_func': 'glGenTextures',
1613 'resource_type': 'Texture',
1614 'resource_types': 'Textures',
1616 'GenSharedIdsCHROMIUM': {
1618 'decoder_func': 'DoGenSharedIdsCHROMIUM',
1620 'expectation': False,
1625 'GetActiveAttrib': {
1629 'GLidProgram program, GLuint index, uint32 name_bucket_id, '
1637 'GetActiveUniform': {
1641 'GLidProgram program, GLuint index, uint32 name_bucket_id, '
1649 'GetAttachedShaders': {
1652 'cmd_args': 'GLidProgram program, void* result, uint32 result_size',
1653 'result': ['SizedResult<GLuint>'],
1655 'GetAttribLocation': {
1656 'type': 'HandWritten',
1661 'GLidProgram program, const char* name, NonImmediate GLint* location',
1662 'result': ['GLint'],
1663 'error_return': -1, # http://www.opengl.org/sdk/docs/man/xhtml/glGetAttribLocation.xml
1667 'result': ['SizedResult<GLboolean>'],
1668 'decoder_func': 'DoGetBooleanv',
1669 'gl_test_func': 'glGetBooleanv',
1671 'GetBufferParameteriv': {
1673 'result': ['SizedResult<GLint>'],
1674 'decoder_func': 'DoGetBufferParameteriv',
1675 'expectation': False,
1680 'decoder_func': 'GetErrorState()->GetGLError',
1682 'result': ['GLenum'],
1683 'client_test': False,
1687 'result': ['SizedResult<GLfloat>'],
1688 'decoder_func': 'DoGetFloatv',
1689 'gl_test_func': 'glGetFloatv',
1691 'GetFramebufferAttachmentParameteriv': {
1693 'decoder_func': 'DoGetFramebufferAttachmentParameteriv',
1694 'gl_test_func': 'glGetFramebufferAttachmentParameterivEXT',
1695 'result': ['SizedResult<GLint>'],
1699 'result': ['SizedResult<GLint>'],
1700 'decoder_func': 'DoGetIntegerv',
1701 'client_test': False,
1703 'GetMaxValueInBufferCHROMIUM': {
1705 'decoder_func': 'DoGetMaxValueInBufferCHROMIUM',
1706 'result': ['GLuint'],
1708 'client_test': False,
1713 'GetMultipleIntegervCHROMIUM': {
1716 'expectation': False,
1719 'client_test': False,
1723 'decoder_func': 'DoGetProgramiv',
1724 'result': ['SizedResult<GLint>'],
1725 'expectation': False,
1727 'GetProgramInfoCHROMIUM': {
1730 'expectation': False,
1734 'client_test': False,
1735 'cmd_args': 'GLidProgram program, uint32 bucket_id',
1737 'uint32 link_status',
1738 'uint32 num_attribs',
1739 'uint32 num_uniforms',
1742 'GetProgramInfoLog': {
1744 'expectation': False,
1746 'GetRenderbufferParameteriv': {
1748 'decoder_func': 'DoGetRenderbufferParameteriv',
1749 'gl_test_func': 'glGetRenderbufferParameterivEXT',
1750 'result': ['SizedResult<GLint>'],
1754 'decoder_func': 'DoGetShaderiv',
1755 'result': ['SizedResult<GLint>'],
1757 'GetShaderInfoLog': {
1759 'get_len_func': 'glGetShaderiv',
1760 'get_len_enum': 'GL_INFO_LOG_LENGTH',
1763 'GetShaderPrecisionFormat': {
1767 'GLenumShaderType shadertype, GLenumShaderPrecision precisiontype, '
1776 'GetShaderSource': {
1778 'get_len_func': 'DoGetShaderiv',
1779 'get_len_enum': 'GL_SHADER_SOURCE_LENGTH',
1781 'client_test': False,
1785 'client_test': False,
1786 'cmd_args': 'GLenumStringType name, uint32 bucket_id',
1788 'GetTexParameterfv': {
1790 'decoder_func': 'DoGetTexParameterfv',
1791 'result': ['SizedResult<GLfloat>']
1793 'GetTexParameteriv': {
1795 'decoder_func': 'DoGetTexParameteriv',
1796 'result': ['SizedResult<GLint>']
1798 'GetTranslatedShaderSourceANGLE': {
1800 'get_len_func': 'DoGetShaderiv',
1801 'get_len_enum': 'GL_TRANSLATED_SHADER_SOURCE_LENGTH_ANGLE',
1808 'result': ['SizedResult<GLfloat>'],
1813 'result': ['SizedResult<GLint>'],
1815 'GetUniformLocation': {
1816 'type': 'HandWritten',
1821 'GLidProgram program, const char* name, NonImmediate GLint* location',
1822 'result': ['GLint'],
1823 'error_return': -1, # http://www.opengl.org/sdk/docs/man/xhtml/glGetUniformLocation.xml
1825 'GetVertexAttribfv': {
1827 'result': ['SizedResult<GLfloat>'],
1829 'decoder_func': 'DoGetVertexAttribfv',
1830 'expectation': False,
1831 'client_test': False,
1833 'GetVertexAttribiv': {
1835 'result': ['SizedResult<GLint>'],
1837 'decoder_func': 'DoGetVertexAttribiv',
1838 'expectation': False,
1839 'client_test': False,
1841 'GetVertexAttribPointerv': {
1844 'result': ['SizedResult<GLuint>'],
1845 'client_test': False,
1849 'decoder_func': 'DoIsBuffer',
1850 'expectation': False,
1854 'decoder_func': 'DoIsEnabled',
1856 'expectation': False,
1860 'decoder_func': 'DoIsFramebuffer',
1861 'expectation': False,
1865 'decoder_func': 'DoIsProgram',
1866 'expectation': False,
1870 'decoder_func': 'DoIsRenderbuffer',
1871 'expectation': False,
1875 'decoder_func': 'DoIsShader',
1876 'expectation': False,
1880 'decoder_func': 'DoIsTexture',
1881 'expectation': False,
1884 'decoder_func': 'DoLinkProgram',
1887 'MapBufferCHROMIUM': {
1891 'client_test': False,
1893 'MapBufferSubDataCHROMIUM': {
1897 'client_test': False,
1898 'pepper_interface': 'ChromiumMapSub',
1900 'MapImageCHROMIUM': {
1904 'client_test': False,
1906 'MapTexSubImage2DCHROMIUM': {
1910 'client_test': False,
1911 'pepper_interface': 'ChromiumMapSub',
1913 'PixelStorei': {'type': 'Manual'},
1914 'PostSubBufferCHROMIUM': {
1918 'client_test': False,
1922 'ProduceTextureCHROMIUM': {
1923 'decoder_func': 'DoProduceTextureCHROMIUM',
1926 'data_type': 'GLbyte',
1927 'count': 64, # GL_MAILBOX_SIZE_CHROMIUM
1929 'client_test': False,
1934 'RenderbufferStorage': {
1935 'decoder_func': 'DoRenderbufferStorage',
1936 'gl_test_func': 'glRenderbufferStorageEXT',
1937 'expectation': False,
1939 'RenderbufferStorageMultisampleCHROMIUM': {
1941 '// GL_CHROMIUM_framebuffer_multisample\n',
1942 'decoder_func': 'DoRenderbufferStorageMultisampleCHROMIUM',
1943 'gl_test_func': 'glRenderbufferStorageMultisampleCHROMIUM',
1944 'expectation': False,
1947 'pepper_interface': 'FramebufferMultisample',
1948 'pepper_name': 'RenderbufferStorageMultisampleEXT',
1950 'RenderbufferStorageMultisampleEXT': {
1952 '// GL_EXT_multisampled_render_to_texture\n',
1953 'decoder_func': 'DoRenderbufferStorageMultisampleEXT',
1954 'gl_test_func': 'glRenderbufferStorageMultisampleEXT',
1955 'expectation': False,
1961 '// ReadPixels has the result separated from the pixel buffer so that\n'
1962 '// it is easier to specify the result going to some specific place\n'
1963 '// that exactly fits the rectangle of pixels.\n',
1967 'client_test': False,
1969 'GLint x, GLint y, GLsizei width, GLsizei height, '
1970 'GLenumReadPixelFormat format, GLenumReadPixelType type, '
1971 'uint32 pixels_shm_id, uint32 pixels_shm_offset, '
1972 'uint32 result_shm_id, uint32 result_shm_offset, '
1974 'result': ['uint32'],
1975 'defer_reads': True,
1977 'RegisterSharedIdsCHROMIUM': {
1979 'decoder_func': 'DoRegisterSharedIdsCHROMIUM',
1981 'expectation': False,
1986 'ReleaseShaderCompiler': {
1987 'decoder_func': 'DoReleaseShaderCompiler',
1992 'client_test': False,
1999 'client_test': False,
2001 'GLuint shader, const char* data',
2003 'GLuint shader, GLsizei count, const char** str, const GLint* length',
2006 'type': 'StateSetFrontBack',
2007 'state': 'StencilMask',
2009 'expectation': False,
2011 'StencilMaskSeparate': {
2012 'type': 'StateSetFrontBackSeparate',
2013 'state': 'StencilMask',
2015 'expectation': False,
2019 'decoder_func': 'DoSwapBuffers',
2021 'client_test': False,
2028 'client_test': False,
2031 'decoder_func': 'DoTexParameterf',
2032 'gl_test_func': 'glTexParameteri',
2038 'decoder_func': 'DoTexParameteri',
2045 'data_type': 'GLfloat',
2046 'data_value': 'GL_NEAREST',
2048 'decoder_func': 'DoTexParameterfv',
2049 'gl_test_func': 'glTexParameteri',
2050 'first_element_only': True,
2054 'data_type': 'GLint',
2055 'data_value': 'GL_NEAREST',
2057 'decoder_func': 'DoTexParameteriv',
2058 'gl_test_func': 'glTexParameteri',
2059 'first_element_only': True,
2064 'client_test': False,
2065 'cmd_args': 'GLenumTextureTarget target, GLint level, '
2066 'GLint xoffset, GLint yoffset, '
2067 'GLsizei width, GLsizei height, '
2068 'GLenumTextureFormat format, GLenumPixelType type, '
2069 'const void* pixels, GLboolean internal'
2071 'Uniform1f': {'type': 'PUTXn', 'data_type': 'GLfloat', 'count': 1},
2074 'data_type': 'GLfloat',
2076 'decoder_func': 'DoUniform1fv',
2078 'Uniform1i': {'decoder_func': 'DoUniform1i', 'unit_test': False},
2081 'data_type': 'GLint',
2083 'decoder_func': 'DoUniform1iv',
2086 'Uniform2i': {'type': 'PUTXn', 'data_type': 'GLint', 'count': 2},
2087 'Uniform2f': {'type': 'PUTXn', 'data_type': 'GLfloat', 'count': 2},
2090 'data_type': 'GLfloat',
2092 'decoder_func': 'DoUniform2fv',
2096 'data_type': 'GLint',
2098 'decoder_func': 'DoUniform2iv',
2100 'Uniform3i': {'type': 'PUTXn', 'data_type': 'GLint', 'count': 3},
2101 'Uniform3f': {'type': 'PUTXn', 'data_type': 'GLfloat', 'count': 3},
2104 'data_type': 'GLfloat',
2106 'decoder_func': 'DoUniform3fv',
2110 'data_type': 'GLint',
2112 'decoder_func': 'DoUniform3iv',
2114 'Uniform4i': {'type': 'PUTXn', 'data_type': 'GLint', 'count': 4},
2115 'Uniform4f': {'type': 'PUTXn', 'data_type': 'GLfloat', 'count': 4},
2118 'data_type': 'GLfloat',
2120 'decoder_func': 'DoUniform4fv',
2124 'data_type': 'GLint',
2126 'decoder_func': 'DoUniform4iv',
2128 'UniformMatrix2fv': {
2130 'data_type': 'GLfloat',
2132 'decoder_func': 'DoUniformMatrix2fv',
2134 'UniformMatrix3fv': {
2136 'data_type': 'GLfloat',
2138 'decoder_func': 'DoUniformMatrix3fv',
2140 'UniformMatrix4fv': {
2142 'data_type': 'GLfloat',
2144 'decoder_func': 'DoUniformMatrix4fv',
2146 'UnmapBufferCHROMIUM': {
2150 'client_test': False,
2152 'UnmapBufferSubDataCHROMIUM': {
2156 'client_test': False,
2157 'pepper_interface': 'ChromiumMapSub',
2159 'UnmapImageCHROMIUM': {
2163 'client_test': False,
2165 'UnmapTexSubImage2DCHROMIUM': {
2169 'client_test': False,
2170 'pepper_interface': 'ChromiumMapSub',
2173 'decoder_func': 'DoUseProgram',
2177 'ValidateProgram': {'decoder_func': 'DoValidateProgram'},
2178 'VertexAttrib1f': {'decoder_func': 'DoVertexAttrib1f'},
2179 'VertexAttrib1fv': {
2181 'data_type': 'GLfloat',
2183 'decoder_func': 'DoVertexAttrib1fv',
2185 'VertexAttrib2f': {'decoder_func': 'DoVertexAttrib2f'},
2186 'VertexAttrib2fv': {
2188 'data_type': 'GLfloat',
2190 'decoder_func': 'DoVertexAttrib2fv',
2192 'VertexAttrib3f': {'decoder_func': 'DoVertexAttrib3f'},
2193 'VertexAttrib3fv': {
2195 'data_type': 'GLfloat',
2197 'decoder_func': 'DoVertexAttrib3fv',
2199 'VertexAttrib4f': {'decoder_func': 'DoVertexAttrib4f'},
2200 'VertexAttrib4fv': {
2202 'data_type': 'GLfloat',
2204 'decoder_func': 'DoVertexAttrib4fv',
2206 'VertexAttribPointer': {
2208 'cmd_args': 'GLuint indx, GLintVertexAttribSize size, '
2209 'GLenumVertexAttribType type, GLboolean normalized, '
2210 'GLsizei stride, GLuint offset',
2211 'client_test': False,
2218 'decoder_func': 'DoViewport',
2227 'GetRequestableExtensionsCHROMIUM': {
2231 'cmd_args': 'uint32 bucket_id',
2235 'RequestExtensionCHROMIUM': {
2239 'client_test': False,
2240 'cmd_args': 'uint32 bucket_id',
2244 'RateLimitOffscreenContextCHROMIUM': {
2248 'client_test': False,
2250 'CreateStreamTextureCHROMIUM': {
2251 'type': 'HandWritten',
2258 'TexImageIOSurface2DCHROMIUM': {
2259 'decoder_func': 'DoTexImageIOSurface2DCHROMIUM',
2264 'CopyTextureCHROMIUM': {
2265 'decoder_func': 'DoCopyTextureCHROMIUM',
2270 'TexStorage2DEXT': {
2273 'decoder_func': 'DoTexStorage2DEXT',
2275 'DrawArraysInstancedANGLE': {
2277 'cmd_args': 'GLenumDrawMode mode, GLint first, GLsizei count, '
2278 'GLsizei primcount',
2281 'pepper_interface': 'InstancedArrays',
2282 'defer_draws': True,
2286 'decoder_func': 'DoDrawBuffersEXT',
2287 'data_type': 'GLenum',
2289 'client_test': False,
2293 'DrawElementsInstancedANGLE': {
2295 'cmd_args': 'GLenumDrawMode mode, GLsizei count, '
2296 'GLenumIndexType type, GLuint index_offset, GLsizei primcount',
2299 'client_test': False,
2300 'pepper_interface': 'InstancedArrays',
2301 'defer_draws': True,
2303 'VertexAttribDivisorANGLE': {
2305 'cmd_args': 'GLuint index, GLuint divisor',
2308 'pepper_interface': 'InstancedArrays',
2312 'gl_test_func': 'glGenQueriesARB',
2313 'resource_type': 'Query',
2314 'resource_types': 'Queries',
2316 'pepper_interface': 'Query',
2318 'DeleteQueriesEXT': {
2320 'gl_test_func': 'glDeleteQueriesARB',
2321 'resource_type': 'Query',
2322 'resource_types': 'Queries',
2324 'pepper_interface': 'Query',
2328 'client_test': False,
2329 'pepper_interface': 'Query',
2333 'cmd_args': 'GLenumQueryTarget target, GLidQuery id, void* sync_data',
2335 'gl_test_func': 'glBeginQuery',
2336 'pepper_interface': 'Query',
2340 'cmd_args': 'GLenumQueryTarget target, GLuint submit_count',
2341 'gl_test_func': 'glEndnQuery',
2342 'client_test': False,
2343 'pepper_interface': 'Query',
2347 'client_test': False,
2348 'gl_test_func': 'glGetQueryiv',
2349 'pepper_interface': 'Query',
2351 'GetQueryObjectuivEXT': {
2353 'client_test': False,
2354 'gl_test_func': 'glGetQueryObjectuiv',
2355 'pepper_interface': 'Query',
2357 'BindUniformLocationCHROMIUM': {
2362 'gl_test_func': 'DoBindUniformLocationCHROMIUM',
2365 'InsertEventMarkerEXT': {
2367 'decoder_func': 'DoInsertEventMarkerEXT',
2368 'expectation': False,
2371 'PushGroupMarkerEXT': {
2373 'decoder_func': 'DoPushGroupMarkerEXT',
2374 'expectation': False,
2377 'PopGroupMarkerEXT': {
2378 'decoder_func': 'DoPopGroupMarkerEXT',
2379 'expectation': False,
2384 'GenVertexArraysOES': {
2387 'gl_test_func': 'glGenVertexArraysOES',
2388 'resource_type': 'VertexArray',
2389 'resource_types': 'VertexArrays',
2392 'BindVertexArrayOES': {
2395 'gl_test_func': 'glBindVertexArrayOES',
2396 'decoder_func': 'DoBindVertexArrayOES',
2397 'gen_func': 'GenVertexArraysOES',
2399 'client_test': False,
2401 'DeleteVertexArraysOES': {
2404 'gl_test_func': 'glDeleteVertexArraysOES',
2405 'resource_type': 'VertexArray',
2406 'resource_types': 'VertexArrays',
2409 'IsVertexArrayOES': {
2412 'gl_test_func': 'glIsVertexArrayOES',
2413 'decoder_func': 'DoIsVertexArrayOES',
2414 'expectation': False,
2417 'BindTexImage2DCHROMIUM': {
2418 'decoder_func': 'DoBindTexImage2DCHROMIUM',
2423 'ReleaseTexImage2DCHROMIUM': {
2424 'decoder_func': 'DoReleaseTexImage2DCHROMIUM',
2429 'ShallowFinishCHROMIUM': {
2434 'client_test': False,
2436 'ShallowFlushCHROMIUM': {
2441 'client_test': False,
2443 'TraceBeginCHROMIUM': {
2447 'client_test': False,
2448 'cmd_args': 'GLuint bucket_id',
2452 'TraceEndCHROMIUM': {
2455 'client_test': False,
2456 'decoder_func': 'DoTraceEndCHROMIUM',
2461 'AsyncTexImage2DCHROMIUM': {
2464 'client_test': False,
2468 'AsyncTexSubImage2DCHROMIUM': {
2471 'client_test': False,
2475 'WaitAsyncTexImage2DCHROMIUM': {
2478 'client_test': False,
2482 'DiscardFramebufferEXT': {
2485 'data_type': 'GLenum',
2486 'cmd_args': 'GLenum target, GLsizei count, '
2487 'const GLenum* attachments',
2488 'decoder_func': 'DoDiscardFramebufferEXT',
2490 'client_test': False,
2493 'LoseContextCHROMIUM': {
2499 'InsertSyncPointCHROMIUM': {
2500 'type': 'HandWritten',
2505 'WaitSyncPointCHROMIUM': {
2512 'DiscardBackbufferCHROMIUM': {
2521 def Grouper(n
, iterable
, fillvalue
=None):
2522 """Collect data into fixed-length chunks or blocks"""
2523 args
= [iter(iterable
)] * n
2524 return itertools
.izip_longest(fillvalue
=fillvalue
, *args
)
2527 def SplitWords(input_string
):
2528 """Transforms a input_string into a list of lower-case components.
2531 input_string: the input string.
2534 a list of lower-case words.
2536 if input_string
.find('_') > -1:
2537 # 'some_TEXT_' -> 'some text'
2538 return input_string
.replace('_', ' ').strip().lower().split()
2540 if re
.search('[A-Z]', input_string
) and re
.search('[a-z]', input_string
):
2542 # look for capitalization to cut input_strings
2543 # 'SomeText' -> 'Some Text'
2544 input_string
= re
.sub('([A-Z])', r
' \1', input_string
).strip()
2545 # 'Vector3' -> 'Vector 3'
2546 input_string
= re
.sub('([^0-9])([0-9])', r
'\1 \2', input_string
)
2547 return input_string
.lower().split()
2551 """Makes a lower-case identifier from words.
2554 words: a list of lower-case words.
2557 the lower-case identifier.
2559 return '_'.join(words
)
2562 def ToUnderscore(input_string
):
2563 """converts CamelCase to camel_case."""
2564 words
= SplitWords(input_string
)
2568 class CWriter(object):
2569 """Writes to a file formatting it for Google's style guidelines."""
2571 def __init__(self
, filename
):
2572 self
.filename
= filename
2576 def SetFileNum(self
, num
):
2577 """Used to help write number files and tests."""
2580 def Write(self
, string
):
2581 """Writes a string to a file spliting if it's > 80 characters."""
2582 lines
= string
.splitlines()
2583 num_lines
= len(lines
)
2584 for ii
in range(0, num_lines
):
2585 self
.__WriteLine
(lines
[ii
], ii
< (num_lines
- 1) or string
[-1] == '\n')
2587 def __FindSplit(self
, string
):
2588 """Finds a place to split a string."""
2589 splitter
= string
.find('=')
2590 if splitter
>= 1 and not string
[splitter
+ 1] == '=' and splitter
< 80:
2592 # parts = string.split('(')
2593 parts
= re
.split("(?<=[^\"])\((?!\")", string
)
2594 fptr
= re
.compile('\*\w*\)')
2596 splitter
= len(parts
[0])
2597 for ii
in range(1, len(parts
)):
2598 # Don't split on the dot in "if (.condition)".
2599 if (not parts
[ii
- 1][-3:] == "if " and
2600 # Don't split "(.)" or "(.*fptr)".
2601 (len(parts
[ii
]) > 0 and
2602 not parts
[ii
][0] == ")" and not fptr
.match(parts
[ii
]))
2605 splitter
+= len(parts
[ii
]) + 1
2610 splitter
= string
[0:end
].rfind(',')
2611 if splitter
< 0 or (splitter
> 0 and string
[splitter
- 1] == '"'):
2612 return last_splitter
2613 elif splitter
>= 80:
2618 def __WriteLine(self
, line
, ends_with_eol
):
2619 """Given a signle line, writes it to a file, splitting if it's > 80 chars"""
2621 i
= self
.__FindSplit
(line
)
2623 line1
= line
[0:i
+ 1]
2624 if line1
[-1] == ' ':
2631 nolint
= ' // NOLINT'
2632 self
.__AddLine
(line1
+ nolint
+ lineend
+ '\n')
2633 match
= re
.match("( +)", line1
)
2636 indent
= match
.group(1)
2638 if not splitter
== ',':
2639 indent
= " " + indent
2640 self
.__WriteLine
(indent
+ line
[i
+ 1:].lstrip(), True)
2644 nolint
= ' // NOLINT'
2645 self
.__AddLine
(line
+ nolint
)
2647 self
.__AddLine
('\n')
2649 def __AddLine(self
, line
):
2650 self
.content
.append(line
)
2653 """Close the file."""
2654 content
= "".join(self
.content
)
2656 if os
.path
.exists(self
.filename
):
2657 old_file
= open(self
.filename
, "rb");
2658 old_content
= old_file
.read()
2660 if content
== old_content
:
2663 file = open(self
.filename
, "wb")
2668 class CHeaderWriter(CWriter
):
2669 """Writes a C Header file."""
2671 _non_alnum_re
= re
.compile(r
'[^a-zA-Z0-9]')
2673 def __init__(self
, filename
, file_comment
= None):
2674 CWriter
.__init
__(self
, filename
)
2676 base
= os
.path
.abspath(filename
)
2677 while os
.path
.basename(base
) != 'src':
2678 new_base
= os
.path
.dirname(base
)
2679 assert new_base
!= base
# Prevent infinite loop.
2682 hpath
= os
.path
.relpath(filename
, base
)
2683 self
.guard
= self
._non
_alnum
_re
.sub('_', hpath
).upper() + '_'
2685 self
.Write(_LICENSE
)
2686 self
.Write(_DO_NOT_EDIT_WARNING
)
2687 if not file_comment
== None:
2688 self
.Write(file_comment
)
2689 self
.Write("#ifndef %s\n" % self
.guard
)
2690 self
.Write("#define %s\n\n" % self
.guard
)
2693 self
.Write("#endif // %s\n\n" % self
.guard
)
2696 class TypeHandler(object):
2697 """This class emits code for a particular type of function."""
2699 _remove_expected_call_re
= re
.compile(r
' EXPECT_CALL.*?;\n', re
.S
)
2704 def InitFunction(self
, func
):
2705 """Add or adjust anything type specific for this function."""
2706 if func
.GetInfo('needs_size') and not func
.name
.endswith('Bucket'):
2707 func
.AddCmdArg(DataSizeArgument('data_size'))
2709 def AddImmediateFunction(self
, generator
, func
):
2710 """Adds an immediate version of a function."""
2711 # Generate an immediate command if there is only 1 pointer arg.
2712 immediate
= func
.GetInfo('immediate') # can be True, False or None
2713 if immediate
== True or immediate
== None:
2714 if func
.num_pointer_args
== 1 or immediate
:
2715 generator
.AddFunction(ImmediateFunction(func
))
2717 def AddBucketFunction(self
, generator
, func
):
2718 """Adds a bucket version of a function."""
2719 # Generate an immediate command if there is only 1 pointer arg.
2720 bucket
= func
.GetInfo('bucket') # can be True, False or None
2722 generator
.AddFunction(BucketFunction(func
))
2724 def WriteStruct(self
, func
, file):
2725 """Writes a structure that matches the arguments to a function."""
2726 comment
= func
.GetInfo('cmd_comment')
2727 if not comment
== None:
2729 file.Write("struct %s {\n" % func
.name
)
2730 file.Write(" typedef %s ValueType;\n" % func
.name
)
2731 file.Write(" static const CommandId kCmdId = k%s;\n" % func
.name
)
2732 func
.WriteCmdArgFlag(file)
2733 func
.WriteCmdFlag(file)
2735 result
= func
.GetInfo('result')
2736 if not result
== None:
2737 if len(result
) == 1:
2738 file.Write(" typedef %s Result;\n\n" % result
[0])
2740 file.Write(" struct Result {\n")
2742 file.Write(" %s;\n" % line
)
2743 file.Write(" };\n\n")
2745 func
.WriteCmdComputeSize(file)
2746 func
.WriteCmdSetHeader(file)
2747 func
.WriteCmdInit(file)
2748 func
.WriteCmdSet(file)
2750 file.Write(" gpu::CommandHeader header;\n")
2751 args
= func
.GetCmdArgs()
2753 file.Write(" %s %s;\n" % (arg
.cmd_type
, arg
.name
))
2757 size
= len(args
) * _SIZE_OF_UINT32
+ _SIZE_OF_COMMAND_HEADER
2758 file.Write("COMPILE_ASSERT(sizeof(%s) == %d,\n" % (func
.name
, size
))
2759 file.Write(" Sizeof_%s_is_not_%d);\n" % (func
.name
, size
))
2760 file.Write("COMPILE_ASSERT(offsetof(%s, header) == 0,\n" % func
.name
)
2761 file.Write(" OffsetOf_%s_header_not_0);\n" % func
.name
)
2762 offset
= _SIZE_OF_COMMAND_HEADER
2764 file.Write("COMPILE_ASSERT(offsetof(%s, %s) == %d,\n" %
2765 (func
.name
, arg
.name
, offset
))
2766 file.Write(" OffsetOf_%s_%s_not_%d);\n" %
2767 (func
.name
, arg
.name
, offset
))
2768 offset
+= _SIZE_OF_UINT32
2769 if not result
== None and len(result
) > 1:
2772 parts
= line
.split()
2775 COMPILE_ASSERT(offsetof(%(cmd_name)s::Result, %(field_name)s) == %(offset)d,
2776 OffsetOf_%(cmd_name)s_Result_%(field_name)s_not_%(offset)d);
2778 file.Write((check
.strip() + "\n") % {
2779 'cmd_name': func
.name
,
2783 offset
+= _SIZE_OF_UINT32
2786 def WriteHandlerImplementation(self
, func
, file):
2787 """Writes the handler implementation for this command."""
2788 file.Write(" %s(%s);\n" %
2789 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
2791 def WriteCmdSizeTest(self
, func
, file):
2792 """Writes the size test for a command."""
2793 file.Write(" EXPECT_EQ(sizeof(cmd), cmd.header.size * 4u);\n")
2795 def WriteFormatTest(self
, func
, file):
2796 """Writes a format test for a command."""
2797 file.Write("TEST_F(GLES2FormatTest, %s) {\n" % func
.name
)
2798 file.Write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
2799 (func
.name
, func
.name
))
2800 file.Write(" void* next_cmd = cmd.Set(\n")
2802 args
= func
.GetCmdArgs()
2803 for value
, arg
in enumerate(args
):
2804 file.Write(",\n static_cast<%s>(%d)" % (arg
.type, value
+ 11))
2806 file.Write(" EXPECT_EQ(static_cast<uint32>(cmds::%s::kCmdId),\n" %
2808 file.Write(" cmd.header.command);\n")
2809 func
.type_handler
.WriteCmdSizeTest(func
, file)
2810 for value
, arg
in enumerate(args
):
2811 file.Write(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);\n" %
2812 (arg
.type, value
+ 11, arg
.name
))
2813 file.Write(" CheckBytesWrittenMatchesExpectedSize(\n")
2814 file.Write(" next_cmd, sizeof(cmd));\n")
2818 def WriteImmediateFormatTest(self
, func
, file):
2819 """Writes a format test for an immediate version of a command."""
2822 def WriteBucketFormatTest(self
, func
, file):
2823 """Writes a format test for a bucket version of a command."""
2826 def WriteGetDataSizeCode(self
, func
, file):
2827 """Writes the code to set data_size used in validation"""
2830 def WriteImmediateCmdSizeTest(self
, func
, file):
2831 """Writes a size test for an immediate version of a command."""
2832 file.Write(" // TODO(gman): Compute correct size.\n")
2833 file.Write(" EXPECT_EQ(sizeof(cmd), cmd.header.size * 4u);\n")
2835 def WriteImmediateHandlerImplementation (self
, func
, file):
2836 """Writes the handler impl for the immediate version of a command."""
2837 file.Write(" %s(%s);\n" %
2838 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
2840 def WriteBucketHandlerImplementation (self
, func
, file):
2841 """Writes the handler impl for the bucket version of a command."""
2842 file.Write(" %s(%s);\n" %
2843 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
2845 def WriteServiceImplementation(self
, func
, file):
2846 """Writes the service implementation for a 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 if len(func
.GetOriginalArgs()) > 0:
2854 last_arg
= func
.GetLastOriginalArg()
2855 all_but_last_arg
= func
.GetOriginalArgs()[:-1]
2856 for arg
in all_but_last_arg
:
2857 arg
.WriteGetCode(file)
2858 self
.WriteGetDataSizeCode(func
, file)
2859 last_arg
.WriteGetCode(file)
2860 func
.WriteHandlerValidation(file)
2861 func
.WriteHandlerImplementation(file)
2862 file.Write(" return error::kNoError;\n")
2866 def WriteImmediateServiceImplementation(self
, func
, file):
2867 """Writes the service implementation for an immediate version of command."""
2869 "error::Error GLES2DecoderImpl::Handle%s(\n" % func
.name
)
2871 " uint32 immediate_data_size, const gles2::cmds::%s& c) {\n" %
2873 self
.WriteHandlerDeferReadWrite(func
, file);
2874 last_arg
= func
.GetLastOriginalArg()
2875 all_but_last_arg
= func
.GetOriginalArgs()[:-1]
2876 for arg
in all_but_last_arg
:
2877 arg
.WriteGetCode(file)
2878 self
.WriteGetDataSizeCode(func
, file)
2879 last_arg
.WriteGetCode(file)
2880 func
.WriteHandlerValidation(file)
2881 func
.WriteHandlerImplementation(file)
2882 file.Write(" return error::kNoError;\n")
2886 def WriteBucketServiceImplementation(self
, func
, file):
2887 """Writes the service implementation for a bucket version of command."""
2889 "error::Error GLES2DecoderImpl::Handle%s(\n" % func
.name
)
2891 " uint32 immediate_data_size, const gles2::cmds::%s& c) {\n" %
2893 self
.WriteHandlerDeferReadWrite(func
, file);
2894 last_arg
= func
.GetLastOriginalArg()
2895 all_but_last_arg
= func
.GetOriginalArgs()[:-1]
2896 for arg
in all_but_last_arg
:
2897 arg
.WriteGetCode(file)
2898 self
.WriteGetDataSizeCode(func
, file)
2899 last_arg
.WriteGetCode(file)
2900 func
.WriteHandlerValidation(file)
2901 func
.WriteHandlerImplementation(file)
2902 file.Write(" return error::kNoError;\n")
2906 def WriteHandlerDeferReadWrite(self
, func
, file):
2907 """Writes the code to handle deferring reads or writes."""
2908 defer_draws
= func
.GetInfo('defer_draws')
2909 defer_reads
= func
.GetInfo('defer_reads')
2910 if defer_draws
or defer_reads
:
2911 file.Write(" error::Error error;\n")
2913 file.Write(" error = WillAccessBoundFramebufferForDraw();\n")
2914 file.Write(" if (error != error::kNoError)\n")
2915 file.Write(" return error;\n")
2917 file.Write(" error = WillAccessBoundFramebufferForRead();\n")
2918 file.Write(" if (error != error::kNoError)\n")
2919 file.Write(" return error;\n")
2921 def WriteValidUnitTest(self
, func
, file, test
, extra
= {}):
2922 """Writes a valid unit test."""
2923 if func
.GetInfo('expectation') == False:
2924 test
= self
._remove
_expected
_call
_re
.sub('', test
)
2927 for count
, arg
in enumerate(func
.GetOriginalArgs()):
2928 arg_strings
.append(arg
.GetValidArg(func
, count
, 0))
2930 for count
, arg
in enumerate(func
.GetOriginalArgs()):
2931 gl_arg_strings
.append(arg
.GetValidGLArg(func
, count
, 0))
2932 gl_func_name
= func
.GetGLTestFunctionName()
2934 'test_name': 'GLES2DecoderTest%d' % file.file_num
,
2936 'gl_func_name': gl_func_name
,
2937 'args': ", ".join(arg_strings
),
2938 'gl_args': ", ".join(gl_arg_strings
),
2942 while (old_test
!= test
):
2945 file.Write(test
% vars)
2947 def WriteInvalidUnitTest(self
, func
, file, test
, extra
= {}):
2948 """Writes a invalid unit test."""
2949 for arg_index
, arg
in enumerate(func
.GetOriginalArgs()):
2950 num_invalid_values
= arg
.GetNumInvalidValues(func
)
2951 for value_index
in range(0, num_invalid_values
):
2953 parse_result
= "kNoError"
2955 for count
, arg
in enumerate(func
.GetOriginalArgs()):
2956 if count
== arg_index
:
2957 (arg_string
, parse_result
, gl_error
) = arg
.GetInvalidArg(
2960 arg_string
= arg
.GetValidArg(func
, count
, 0)
2961 arg_strings
.append(arg_string
)
2963 for arg
in func
.GetOriginalArgs():
2964 gl_arg_strings
.append("_")
2965 gl_func_name
= func
.GetGLTestFunctionName()
2967 if not gl_error
== None:
2968 gl_error_test
= '\n EXPECT_EQ(%s, GetGLError());' % gl_error
2971 'test_name': 'GLES2DecoderTest%d' % file.file_num
,
2973 'arg_index': arg_index
,
2974 'value_index': value_index
,
2975 'gl_func_name': gl_func_name
,
2976 'args': ", ".join(arg_strings
),
2977 'all_but_last_args': ", ".join(arg_strings
[:-1]),
2978 'gl_args': ", ".join(gl_arg_strings
),
2979 'parse_result': parse_result
,
2980 'gl_error_test': gl_error_test
,
2983 file.Write(test
% vars)
2985 def WriteServiceUnitTest(self
, func
, file):
2986 """Writes the service unit test for a command."""
2988 TEST_F(%(test_name)s, %(name)sValidArgs) {
2989 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
2990 SpecializedSetup<cmds::%(name)s, 0>(true);
2993 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
2994 EXPECT_EQ(GL_NO_ERROR, GetGLError());
2997 self
.WriteValidUnitTest(func
, file, valid_test
)
3000 TEST_F(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
3001 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
3002 SpecializedSetup<cmds::%(name)s, 0>(false);
3005 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
3008 self
.WriteInvalidUnitTest(func
, file, invalid_test
)
3010 def WriteImmediateServiceUnitTest(self
, func
, file):
3011 """Writes the service unit test for an immediate command."""
3012 file.Write("// TODO(gman): %s\n" % func
.name
)
3014 def WriteImmediateValidationCode(self
, func
, file):
3015 """Writes the validation code for an immediate version of a command."""
3018 def WriteBucketServiceUnitTest(self
, func
, file):
3019 """Writes the service unit test for a bucket command."""
3020 file.Write("// TODO(gman): %s\n" % func
.name
)
3022 def WriteBucketValidationCode(self
, func
, file):
3023 """Writes the validation code for a bucket version of a command."""
3024 file.Write("// TODO(gman): %s\n" % func
.name
)
3026 def WriteGLES2ImplementationDeclaration(self
, func
, file):
3027 """Writes the GLES2 Implemention declaration."""
3028 impl_decl
= func
.GetInfo('impl_decl')
3029 if impl_decl
== None or impl_decl
== True:
3030 file.Write("virtual %s %s(%s) OVERRIDE;\n" %
3031 (func
.return_type
, func
.original_name
,
3032 func
.MakeTypedOriginalArgString("")))
3035 def WriteGLES2CLibImplementation(self
, func
, file):
3036 file.Write("%s GLES2%s(%s) {\n" %
3037 (func
.return_type
, func
.name
,
3038 func
.MakeTypedOriginalArgString("")))
3039 result_string
= "return "
3040 if func
.return_type
== "void":
3042 file.Write(" %sgles2::GetGLContext()->%s(%s);\n" %
3043 (result_string
, func
.original_name
,
3044 func
.MakeOriginalArgString("")))
3047 def WriteGLES2Header(self
, func
, file):
3048 """Writes a re-write macro for GLES"""
3049 file.Write("#define gl%s GLES2_GET_FUN(%s)\n" %(func
.name
, func
.name
))
3051 def WriteClientGLCallLog(self
, func
, file):
3052 """Writes a logging macro for the client side code."""
3054 if len(func
.GetOriginalArgs()):
3057 ' GPU_CLIENT_LOG("[" << GetLogPrefix() << "] gl%s("%s%s << ")");\n' %
3058 (func
.original_name
, comma
, func
.MakeLogArgString()))
3060 def WriteClientGLReturnLog(self
, func
, file):
3061 """Writes the return value logging code."""
3062 if func
.return_type
!= "void":
3063 file.Write(' GPU_CLIENT_LOG("return:" << result)\n')
3065 def WriteGLES2ImplementationHeader(self
, func
, file):
3066 """Writes the GLES2 Implemention."""
3067 self
.WriteGLES2ImplementationDeclaration(func
, file)
3069 def WriteGLES2TraceImplementationHeader(self
, func
, file):
3070 """Writes the GLES2 Trace Implemention header."""
3071 file.Write("virtual %s %s(%s) OVERRIDE;\n" %
3072 (func
.return_type
, func
.original_name
,
3073 func
.MakeTypedOriginalArgString("")))
3075 def WriteGLES2TraceImplementation(self
, func
, file):
3076 """Writes the GLES2 Trace Implemention."""
3077 file.Write("%s GLES2TraceImplementation::%s(%s) {\n" %
3078 (func
.return_type
, func
.original_name
,
3079 func
.MakeTypedOriginalArgString("")))
3080 result_string
= "return "
3081 if func
.return_type
== "void":
3083 file.Write(' TRACE_EVENT_BINARY_EFFICIENT0("gpu", "GLES2Trace::%s");\n' %
3085 file.Write(" %sgl_->%s(%s);\n" %
3086 (result_string
, func
.name
, func
.MakeOriginalArgString("")))
3090 def WriteGLES2Implementation(self
, func
, file):
3091 """Writes the GLES2 Implemention."""
3092 impl_func
= func
.GetInfo('impl_func')
3093 impl_decl
= func
.GetInfo('impl_decl')
3094 gen_cmd
= func
.GetInfo('gen_cmd')
3095 if (func
.can_auto_generate
and
3096 (impl_func
== None or impl_func
== True) and
3097 (impl_decl
== None or impl_decl
== True) and
3098 (gen_cmd
== None or gen_cmd
== True)):
3099 file.Write("%s GLES2Implementation::%s(%s) {\n" %
3100 (func
.return_type
, func
.original_name
,
3101 func
.MakeTypedOriginalArgString("")))
3102 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
3103 self
.WriteClientGLCallLog(func
, file)
3104 func
.WriteDestinationInitalizationValidation(file)
3105 for arg
in func
.GetOriginalArgs():
3106 arg
.WriteClientSideValidationCode(file, func
)
3107 file.Write(" helper_->%s(%s);\n" %
3108 (func
.name
, func
.MakeOriginalArgString("")))
3109 file.Write(" CheckGLError();\n")
3110 self
.WriteClientGLReturnLog(func
, file)
3114 def WriteGLES2InterfaceHeader(self
, func
, file):
3115 """Writes the GLES2 Interface."""
3116 file.Write("virtual %s %s(%s) = 0;\n" %
3117 (func
.return_type
, func
.original_name
,
3118 func
.MakeTypedOriginalArgString("")))
3120 def WriteGLES2InterfaceStub(self
, func
, file):
3121 """Writes the GLES2 Interface stub declaration."""
3122 file.Write("virtual %s %s(%s) OVERRIDE;\n" %
3123 (func
.return_type
, func
.original_name
,
3124 func
.MakeTypedOriginalArgString("")))
3126 def WriteGLES2InterfaceStubImpl(self
, func
, file):
3127 """Writes the GLES2 Interface stub declaration."""
3128 args
= func
.GetOriginalArgs()
3129 arg_string
= ", ".join(
3130 ["%s /* %s */" % (arg
.type, arg
.name
) for arg
in args
])
3131 file.Write("%s GLES2InterfaceStub::%s(%s) {\n" %
3132 (func
.return_type
, func
.original_name
, arg_string
))
3133 if func
.return_type
!= "void":
3134 file.Write(" return 0;\n")
3137 def WriteGLES2ImplementationUnitTest(self
, func
, file):
3138 """Writes the GLES2 Implemention unit test."""
3139 client_test
= func
.GetInfo('client_test')
3140 if (func
.can_auto_generate
and
3141 (client_test
== None or client_test
== True)):
3143 TEST_F(GLES2ImplementationTest, %(name)s) {
3148 expected.cmd.Init(%(cmd_args)s);
3150 gl_->%(name)s(%(args)s);
3151 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
3154 cmd_arg_strings
= []
3155 for count
, arg
in enumerate(func
.GetCmdArgs()):
3156 cmd_arg_strings
.append(arg
.GetValidClientSideCmdArg(func
, count
, 0))
3159 for count
, arg
in enumerate(func
.GetOriginalArgs()):
3160 gl_arg_strings
.append(arg
.GetValidClientSideArg(func
, count
, 0))
3163 'args': ", ".join(gl_arg_strings
),
3164 'cmd_args': ", ".join(cmd_arg_strings
),
3167 if client_test
!= False:
3168 file.Write("// TODO: Implement unit test for %s\n" % func
.name
)
3170 def WriteDestinationInitalizationValidation(self
, func
, file):
3171 """Writes the client side destintion initialization validation."""
3172 for arg
in func
.GetOriginalArgs():
3173 arg
.WriteDestinationInitalizationValidation(file, func
)
3175 def WriteTraceEvent(self
, func
, file):
3176 file.Write(' TRACE_EVENT0("gpu", "GLES2Implementation::%s");\n' %
3179 def WriteImmediateCmdComputeSize(self
, func
, file):
3180 """Writes the size computation code for the immediate version of a cmd."""
3181 file.Write(" static uint32 ComputeSize(uint32 size_in_bytes) {\n")
3182 file.Write(" return static_cast<uint32>(\n")
3183 file.Write(" sizeof(ValueType) + // NOLINT\n")
3184 file.Write(" RoundSizeToMultipleOfEntries(size_in_bytes));\n")
3188 def WriteImmediateCmdSetHeader(self
, func
, file):
3189 """Writes the SetHeader function for the immediate version of a cmd."""
3190 file.Write(" void SetHeader(uint32 size_in_bytes) {\n")
3191 file.Write(" header.SetCmdByTotalSize<ValueType>(size_in_bytes);\n")
3195 def WriteImmediateCmdInit(self
, func
, file):
3196 """Writes the Init function for the immediate version of a command."""
3197 raise NotImplementedError(func
.name
)
3199 def WriteImmediateCmdSet(self
, func
, file):
3200 """Writes the Set function for the immediate version of a command."""
3201 raise NotImplementedError(func
.name
)
3203 def WriteCmdHelper(self
, func
, file):
3204 """Writes the cmd helper definition for a cmd."""
3205 code
= """ void %(name)s(%(typed_args)s) {
3206 gles2::cmds::%(name)s* c = GetCmdSpace<gles2::cmds::%(name)s>();
3215 "typed_args": func
.MakeTypedCmdArgString(""),
3216 "args": func
.MakeCmdArgString(""),
3219 def WriteImmediateCmdHelper(self
, func
, file):
3220 """Writes the cmd helper definition for the immediate version of a cmd."""
3221 code
= """ void %(name)s(%(typed_args)s) {
3222 const uint32 s = 0; // TODO(gman): compute correct size
3223 gles2::cmds::%(name)s* c =
3224 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(s);
3233 "typed_args": func
.MakeTypedCmdArgString(""),
3234 "args": func
.MakeCmdArgString(""),
3238 class StateSetHandler(TypeHandler
):
3239 """Handler for commands that simply set state."""
3242 TypeHandler
.__init
__(self
)
3244 def WriteHandlerImplementation(self
, func
, file):
3245 """Overrriden from TypeHandler."""
3246 state_name
= func
.GetInfo('state')
3247 state
= _STATES
[state_name
]
3248 states
= state
['states']
3249 args
= func
.GetOriginalArgs()
3251 for ndx
,item
in enumerate(states
):
3252 if 'range_checks' in item
:
3253 for range_check
in item
['range_checks']:
3254 code
.append("%s %s" % (args
[ndx
].name
, range_check
['check']))
3256 file.Write(" if (%s) {\n" % " ||\n ".join(code
))
3258 ' LOCAL_SET_GL_ERROR(GL_INVALID_VALUE,'
3259 ' "%s", "%s out of range");\n' %
3260 (func
.name
, args
[ndx
].name
))
3261 file.Write(" return error::kNoError;\n")
3264 for ndx
,item
in enumerate(states
):
3265 code
.append("state_.%s != %s" % (item
['name'], args
[ndx
].name
))
3266 file.Write(" if (%s) {\n" % " ||\n ".join(code
))
3267 for ndx
,item
in enumerate(states
):
3268 file.Write(" state_.%s = %s;\n" % (item
['name'], args
[ndx
].name
))
3269 if 'state_flag' in state
:
3270 file.Write(" %s = true;\n" % state
['state_flag'])
3271 if not func
.GetInfo("no_gl"):
3272 file.Write(" %s(%s);\n" %
3273 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
3276 def WriteServiceUnitTest(self
, func
, file):
3277 """Overrriden from TypeHandler."""
3278 TypeHandler
.WriteServiceUnitTest(self
, func
, file)
3279 state_name
= func
.GetInfo('state')
3280 state
= _STATES
[state_name
]
3281 states
= state
['states']
3282 for ndx
,item
in enumerate(states
):
3283 if 'range_checks' in item
:
3284 for check_ndx
, range_check
in enumerate(item
['range_checks']):
3286 TEST_F(%(test_name)s, %(name)sInvalidValue%(ndx)d_%(check_ndx)d) {
3287 SpecializedSetup<cmds::%(name)s, 0>(false);
3290 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
3291 EXPECT_EQ(GL_INVALID_VALUE, GetGLError());
3296 for count
, arg
in enumerate(func
.GetOriginalArgs()):
3297 arg_strings
.append(arg
.GetValidArg(func
, count
, 0))
3298 arg_strings
[ndx
] = range_check
['test_value']
3300 'test_name': 'GLES2DecoderTest%d' % file.file_num
,
3303 'check_ndx': check_ndx
,
3304 'args': ", ".join(arg_strings
),
3306 file.Write(valid_test
% vars)
3309 class StateSetRGBAlphaHandler(TypeHandler
):
3310 """Handler for commands that simply set state that have rgb/alpha."""
3313 TypeHandler
.__init
__(self
)
3315 def WriteHandlerImplementation(self
, func
, file):
3316 """Overrriden from TypeHandler."""
3317 state_name
= func
.GetInfo('state')
3318 state
= _STATES
[state_name
]
3319 states
= state
['states']
3320 args
= func
.GetOriginalArgs()
3321 num_args
= len(args
)
3323 for ndx
,item
in enumerate(states
):
3324 code
.append("state_.%s != %s" % (item
['name'], args
[ndx
% num_args
].name
))
3325 file.Write(" if (%s) {\n" % " ||\n ".join(code
))
3326 for ndx
, item
in enumerate(states
):
3327 file.Write(" state_.%s = %s;\n" %
3328 (item
['name'], args
[ndx
% num_args
].name
))
3329 if 'state_flag' in state
:
3330 file.Write(" %s = true;\n" % state
['state_flag'])
3331 if not func
.GetInfo("no_gl"):
3332 file.Write(" %s(%s);\n" %
3333 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
3337 class StateSetFrontBackSeparateHandler(TypeHandler
):
3338 """Handler for commands that simply set state that have front/back."""
3341 TypeHandler
.__init
__(self
)
3343 def WriteHandlerImplementation(self
, func
, file):
3344 """Overrriden from TypeHandler."""
3345 state_name
= func
.GetInfo('state')
3346 state
= _STATES
[state_name
]
3347 states
= state
['states']
3348 args
= func
.GetOriginalArgs()
3350 num_args
= len(args
)
3351 file.Write(" bool changed = false;\n")
3352 for group_ndx
, group
in enumerate(Grouper(num_args
- 1, states
)):
3353 file.Write(" if (%s == %s || %s == GL_FRONT_AND_BACK) {\n" %
3354 (face
, ('GL_FRONT', 'GL_BACK')[group_ndx
], face
))
3356 for ndx
, item
in enumerate(group
):
3357 code
.append("state_.%s != %s" % (item
['name'], args
[ndx
+ 1].name
))
3358 file.Write(" changed |= %s;\n" % " ||\n ".join(code
))
3360 file.Write(" if (changed) {\n")
3361 for group_ndx
, group
in enumerate(Grouper(num_args
- 1, states
)):
3362 file.Write(" if (%s == %s || %s == GL_FRONT_AND_BACK) {\n" %
3363 (face
, ('GL_FRONT', 'GL_BACK')[group_ndx
], face
))
3364 for ndx
, item
in enumerate(group
):
3365 file.Write(" state_.%s = %s;\n" %
3366 (item
['name'], args
[ndx
+ 1].name
))
3368 if 'state_flag' in state
:
3369 file.Write(" %s = true;\n" % state
['state_flag'])
3370 if not func
.GetInfo("no_gl"):
3371 file.Write(" %s(%s);\n" %
3372 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
3376 class StateSetFrontBackHandler(TypeHandler
):
3377 """Handler for commands that simply set state that set both front/back."""
3380 TypeHandler
.__init
__(self
)
3382 def WriteHandlerImplementation(self
, func
, file):
3383 """Overrriden from TypeHandler."""
3384 state_name
= func
.GetInfo('state')
3385 state
= _STATES
[state_name
]
3386 states
= state
['states']
3387 args
= func
.GetOriginalArgs()
3388 num_args
= len(args
)
3390 for group_ndx
, group
in enumerate(Grouper(num_args
, states
)):
3391 for ndx
, item
in enumerate(group
):
3392 code
.append("state_.%s != %s" % (item
['name'], args
[ndx
].name
))
3393 file.Write(" if (%s) {\n" % " ||\n ".join(code
))
3394 for group_ndx
, group
in enumerate(Grouper(num_args
, states
)):
3395 for ndx
, item
in enumerate(group
):
3396 file.Write(" state_.%s = %s;\n" % (item
['name'], args
[ndx
].name
))
3397 if 'state_flag' in state
:
3398 file.Write(" %s = true;\n" % state
['state_flag'])
3399 if not func
.GetInfo("no_gl"):
3400 file.Write(" %s(%s);\n" %
3401 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
3405 class StateSetNamedParameter(TypeHandler
):
3406 """Handler for commands that set a state chosen with an enum parameter."""
3409 TypeHandler
.__init
__(self
)
3411 def WriteHandlerImplementation(self
, func
, file):
3412 """Overridden from TypeHandler."""
3413 state_name
= func
.GetInfo('state')
3414 state
= _STATES
[state_name
]
3415 states
= state
['states']
3416 args
= func
.GetOriginalArgs()
3417 num_args
= len(args
)
3418 assert num_args
== 2
3419 file.Write(" switch (%s) {\n" % args
[0].name
)
3420 for state
in states
:
3421 file.Write(" case %s:\n" % state
['enum'])
3422 file.Write(" if (state_.%s != %s) {\n" %
3423 (state
['name'], args
[1].name
))
3424 file.Write(" state_.%s = %s;\n" % (state
['name'], args
[1].name
))
3425 if not func
.GetInfo("no_gl"):
3426 file.Write(" %s(%s);\n" %
3427 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
3429 file.Write(" break;\n")
3430 file.Write(" default:\n")
3431 file.Write(" NOTREACHED();\n")
3435 class CustomHandler(TypeHandler
):
3436 """Handler for commands that are auto-generated but require minor tweaks."""
3439 TypeHandler
.__init
__(self
)
3441 def WriteServiceImplementation(self
, func
, file):
3442 """Overrriden from TypeHandler."""
3445 def WriteImmediateServiceImplementation(self
, func
, file):
3446 """Overrriden from TypeHandler."""
3449 def WriteBucketServiceImplementation(self
, func
, file):
3450 """Overrriden from TypeHandler."""
3453 def WriteServiceUnitTest(self
, func
, file):
3454 """Overrriden from TypeHandler."""
3455 file.Write("// TODO(gman): %s\n\n" % func
.name
)
3457 def WriteImmediateServiceUnitTest(self
, func
, file):
3458 """Overrriden from TypeHandler."""
3459 file.Write("// TODO(gman): %s\n\n" % func
.name
)
3461 def WriteImmediateCmdGetTotalSize(self
, func
, file):
3462 """Overrriden from TypeHandler."""
3463 file.Write(" uint32 total_size = 0; // TODO(gman): get correct size.\n")
3465 def WriteImmediateCmdInit(self
, func
, file):
3466 """Overrriden from TypeHandler."""
3467 file.Write(" void Init(%s) {\n" % func
.MakeTypedCmdArgString("_"))
3468 self
.WriteImmediateCmdGetTotalSize(func
, file)
3469 file.Write(" SetHeader(total_size);\n")
3470 args
= func
.GetCmdArgs()
3472 file.Write(" %s = _%s;\n" % (arg
.name
, arg
.name
))
3476 def WriteImmediateCmdSet(self
, func
, file):
3477 """Overrriden from TypeHandler."""
3478 copy_args
= func
.MakeCmdArgString("_", False)
3479 file.Write(" void* Set(void* cmd%s) {\n" %
3480 func
.MakeTypedCmdArgString("_", True))
3481 self
.WriteImmediateCmdGetTotalSize(func
, file)
3482 file.Write(" static_cast<ValueType*>(cmd)->Init(%s);\n" % copy_args
)
3483 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
3484 "cmd, total_size);\n")
3489 class TodoHandler(CustomHandler
):
3490 """Handle for commands that are not yet implemented."""
3492 def AddImmediateFunction(self
, generator
, func
):
3493 """Overrriden from TypeHandler."""
3496 def WriteImmediateFormatTest(self
, func
, file):
3497 """Overrriden from TypeHandler."""
3500 def WriteGLES2ImplementationUnitTest(self
, func
, file):
3501 """Overrriden from TypeHandler."""
3504 def WriteGLES2Implementation(self
, func
, file):
3505 """Overrriden from TypeHandler."""
3506 file.Write("%s GLES2Implementation::%s(%s) {\n" %
3507 (func
.return_type
, func
.original_name
,
3508 func
.MakeTypedOriginalArgString("")))
3509 file.Write(" // TODO: for now this is a no-op\n")
3512 "GL_INVALID_OPERATION, \"gl%s\", \"not implemented\");\n" %
3514 if func
.return_type
!= "void":
3515 file.Write(" return 0;\n")
3519 def WriteServiceImplementation(self
, func
, file):
3520 """Overrriden from TypeHandler."""
3522 "error::Error GLES2DecoderImpl::Handle%s(\n" % func
.name
)
3524 " uint32 immediate_data_size, const gles2::cmds::%s& c) {\n" %
3526 file.Write(" // TODO: for now this is a no-op\n")
3528 " LOCAL_SET_GL_ERROR("
3529 "GL_INVALID_OPERATION, \"gl%s\", \"not implemented\");\n" %
3531 file.Write(" return error::kNoError;\n")
3536 class HandWrittenHandler(CustomHandler
):
3537 """Handler for comands where everything must be written by hand."""
3539 def InitFunction(self
, func
):
3540 """Add or adjust anything type specific for this function."""
3541 CustomHandler
.InitFunction(self
, func
)
3542 func
.can_auto_generate
= False
3544 def WriteStruct(self
, func
, file):
3545 """Overrriden from TypeHandler."""
3548 def WriteDocs(self
, func
, file):
3549 """Overrriden from TypeHandler."""
3552 def WriteServiceUnitTest(self
, func
, file):
3553 """Overrriden from TypeHandler."""
3554 file.Write("// TODO(gman): %s\n\n" % func
.name
)
3556 def WriteImmediateServiceUnitTest(self
, func
, file):
3557 """Overrriden from TypeHandler."""
3558 file.Write("// TODO(gman): %s\n\n" % func
.name
)
3560 def WriteBucketServiceUnitTest(self
, func
, file):
3561 """Overrriden from TypeHandler."""
3562 file.Write("// TODO(gman): %s\n\n" % func
.name
)
3564 def WriteServiceImplementation(self
, func
, file):
3565 """Overrriden from TypeHandler."""
3568 def WriteImmediateServiceImplementation(self
, func
, file):
3569 """Overrriden from TypeHandler."""
3572 def WriteBucketServiceImplementation(self
, func
, file):
3573 """Overrriden from TypeHandler."""
3576 def WriteImmediateCmdHelper(self
, func
, file):
3577 """Overrriden from TypeHandler."""
3580 def WriteBucketCmdHelper(self
, func
, file):
3581 """Overrriden from TypeHandler."""
3584 def WriteCmdHelper(self
, func
, file):
3585 """Overrriden from TypeHandler."""
3588 def WriteFormatTest(self
, func
, file):
3589 """Overrriden from TypeHandler."""
3590 file.Write("// TODO(gman): Write test for %s\n" % func
.name
)
3592 def WriteImmediateFormatTest(self
, func
, file):
3593 """Overrriden from TypeHandler."""
3594 file.Write("// TODO(gman): Write test for %s\n" % func
.name
)
3596 def WriteBucketFormatTest(self
, func
, file):
3597 """Overrriden from TypeHandler."""
3598 file.Write("// TODO(gman): Write test for %s\n" % func
.name
)
3602 class ManualHandler(CustomHandler
):
3603 """Handler for commands who's handlers must be written by hand."""
3606 CustomHandler
.__init
__(self
)
3608 def InitFunction(self
, func
):
3609 """Overrriden from TypeHandler."""
3610 if (func
.name
== 'CompressedTexImage2DBucket'):
3611 func
.cmd_args
= func
.cmd_args
[:-1]
3612 func
.AddCmdArg(Argument('bucket_id', 'GLuint'))
3614 CustomHandler
.InitFunction(self
, func
)
3616 def WriteServiceImplementation(self
, func
, file):
3617 """Overrriden from TypeHandler."""
3620 def WriteBucketServiceImplementation(self
, func
, file):
3621 """Overrriden from TypeHandler."""
3624 def WriteServiceUnitTest(self
, func
, file):
3625 """Overrriden from TypeHandler."""
3626 file.Write("// TODO(gman): %s\n\n" % func
.name
)
3628 def WriteImmediateServiceUnitTest(self
, func
, file):
3629 """Overrriden from TypeHandler."""
3630 file.Write("// TODO(gman): %s\n\n" % func
.name
)
3632 def WriteImmediateServiceImplementation(self
, func
, file):
3633 """Overrriden from TypeHandler."""
3636 def WriteImmediateFormatTest(self
, func
, file):
3637 """Overrriden from TypeHandler."""
3638 file.Write("// TODO(gman): Implement test for %s\n" % func
.name
)
3640 def WriteGLES2Implementation(self
, func
, file):
3641 """Overrriden from TypeHandler."""
3642 if func
.GetInfo('impl_func'):
3643 super(ManualHandler
, self
).WriteGLES2Implementation(func
, file)
3645 def WriteGLES2ImplementationHeader(self
, func
, file):
3646 """Overrriden from TypeHandler."""
3647 file.Write("virtual %s %s(%s) OVERRIDE;\n" %
3648 (func
.return_type
, func
.original_name
,
3649 func
.MakeTypedOriginalArgString("")))
3652 def WriteImmediateCmdGetTotalSize(self
, func
, file):
3653 """Overrriden from TypeHandler."""
3654 # TODO(gman): Move this data to _FUNCTION_INFO?
3655 CustomHandler
.WriteImmediateCmdGetTotalSize(self
, func
, file)
3658 class DataHandler(TypeHandler
):
3659 """Handler for glBufferData, glBufferSubData, glTexImage2D, glTexSubImage2D,
3660 glCompressedTexImage2D, glCompressedTexImageSub2D."""
3662 TypeHandler
.__init
__(self
)
3664 def InitFunction(self
, func
):
3665 """Overrriden from TypeHandler."""
3666 if func
.name
== 'CompressedTexSubImage2DBucket':
3667 func
.cmd_args
= func
.cmd_args
[:-1]
3668 func
.AddCmdArg(Argument('bucket_id', 'GLuint'))
3670 def WriteGetDataSizeCode(self
, func
, file):
3671 """Overrriden from TypeHandler."""
3672 # TODO(gman): Move this data to _FUNCTION_INFO?
3674 if name
.endswith("Immediate"):
3676 if name
== 'BufferData' or name
== 'BufferSubData':
3677 file.Write(" uint32 data_size = size;\n")
3678 elif (name
== 'CompressedTexImage2D' or
3679 name
== 'CompressedTexSubImage2D'):
3680 file.Write(" uint32 data_size = imageSize;\n")
3681 elif (name
== 'CompressedTexSubImage2DBucket'):
3682 file.Write(" Bucket* bucket = GetBucket(c.bucket_id);\n")
3683 file.Write(" uint32 data_size = bucket->size();\n")
3684 file.Write(" GLsizei imageSize = data_size;\n")
3685 elif name
== 'TexImage2D' or name
== 'TexSubImage2D':
3686 code
= """ uint32 data_size;
3687 if (!GLES2Util::ComputeImageDataSize(
3688 width, height, format, type, unpack_alignment_, &data_size)) {
3689 return error::kOutOfBounds;
3694 file.Write("// uint32 data_size = 0; // TODO(gman): get correct size!\n")
3696 def WriteImmediateCmdGetTotalSize(self
, func
, file):
3697 """Overrriden from TypeHandler."""
3700 def WriteImmediateCmdSizeTest(self
, func
, file):
3701 """Overrriden from TypeHandler."""
3702 file.Write(" EXPECT_EQ(sizeof(cmd), total_size);\n")
3704 def WriteImmediateCmdInit(self
, func
, file):
3705 """Overrriden from TypeHandler."""
3706 file.Write(" void Init(%s) {\n" % func
.MakeTypedCmdArgString("_"))
3707 self
.WriteImmediateCmdGetTotalSize(func
, file)
3708 file.Write(" SetHeader(total_size);\n")
3709 args
= func
.GetCmdArgs()
3711 file.Write(" %s = _%s;\n" % (arg
.name
, arg
.name
))
3715 def WriteImmediateCmdSet(self
, func
, file):
3716 """Overrriden from TypeHandler."""
3717 copy_args
= func
.MakeCmdArgString("_", False)
3718 file.Write(" void* Set(void* cmd%s) {\n" %
3719 func
.MakeTypedCmdArgString("_", True))
3720 self
.WriteImmediateCmdGetTotalSize(func
, file)
3721 file.Write(" static_cast<ValueType*>(cmd)->Init(%s);\n" % copy_args
)
3722 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
3723 "cmd, total_size);\n")
3727 def WriteImmediateFormatTest(self
, func
, file):
3728 """Overrriden from TypeHandler."""
3729 # TODO(gman): Remove this exception.
3730 file.Write("// TODO(gman): Implement test for %s\n" % func
.name
)
3733 def WriteServiceUnitTest(self
, func
, file):
3734 """Overrriden from TypeHandler."""
3735 file.Write("// TODO(gman): %s\n\n" % func
.name
)
3737 def WriteImmediateServiceUnitTest(self
, func
, file):
3738 """Overrriden from TypeHandler."""
3739 file.Write("// TODO(gman): %s\n\n" % func
.name
)
3741 def WriteBucketServiceImplementation(self
, func
, file):
3742 """Overrriden from TypeHandler."""
3743 if not func
.name
== 'CompressedTexSubImage2DBucket':
3744 TypeHandler
.WriteBucketServiceImplemenation(self
, func
, file)
3747 class BindHandler(TypeHandler
):
3748 """Handler for glBind___ type functions."""
3751 TypeHandler
.__init
__(self
)
3753 def WriteServiceUnitTest(self
, func
, file):
3754 """Overrriden from TypeHandler."""
3756 if len(func
.GetOriginalArgs()) == 1:
3758 TEST_F(%(test_name)s, %(name)sValidArgs) {
3759 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
3760 SpecializedSetup<cmds::%(name)s, 0>(true);
3763 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
3764 EXPECT_EQ(GL_NO_ERROR, GetGLError());
3767 TEST_F(%(test_name)s, %(name)sValidArgsNewId) {
3768 EXPECT_CALL(*gl_, %(gl_func_name)s(kNewServiceId));
3769 EXPECT_CALL(*gl_, %(gl_gen_func_name)s(1, _))
3770 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
3771 SpecializedSetup<cmds::%(name)s, 0>(true);
3773 cmd.Init(kNewClientId);
3774 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
3775 EXPECT_EQ(GL_NO_ERROR, GetGLError());
3776 EXPECT_TRUE(Get%(resource_type)s(kNewClientId) != NULL);
3781 self
.WriteValidUnitTest(func
, file, valid_test
, {
3782 'resource_type': func
.GetOriginalArgs()[0].resource_type
,
3783 'gl_gen_func_name': func
.GetInfo("gen_func"),
3787 TEST_F(%(test_name)s, %(name)sValidArgs) {
3788 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
3789 SpecializedSetup<cmds::%(name)s, 0>(true);
3792 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
3793 EXPECT_EQ(GL_NO_ERROR, GetGLError());
3796 TEST_F(%(test_name)s, %(name)sValidArgsNewId) {
3797 EXPECT_CALL(*gl_, %(gl_func_name)s(%(first_gl_arg)s, kNewServiceId));
3798 EXPECT_CALL(*gl_, %(gl_gen_func_name)s(1, _))
3799 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
3800 SpecializedSetup<cmds::%(name)s, 0>(true);
3802 cmd.Init(%(first_arg)s, kNewClientId);
3803 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
3804 EXPECT_EQ(GL_NO_ERROR, GetGLError());
3805 EXPECT_TRUE(Get%(resource_type)s(kNewClientId) != NULL);
3810 self
.WriteValidUnitTest(func
, file, valid_test
, {
3811 'first_arg': func
.GetOriginalArgs()[0].GetValidArg(func
, 0, 0),
3812 'first_gl_arg': func
.GetOriginalArgs()[0].GetValidGLArg(func
, 0, 0),
3813 'resource_type': func
.GetOriginalArgs()[1].resource_type
,
3814 'gl_gen_func_name': func
.GetInfo("gen_func"),
3818 TEST_F(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
3819 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
3820 SpecializedSetup<cmds::%(name)s, 0>(false);
3823 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
3826 self
.WriteInvalidUnitTest(func
, file, invalid_test
)
3828 def WriteGLES2Implementation(self
, func
, file):
3829 """Writes the GLES2 Implemention."""
3831 impl_func
= func
.GetInfo('impl_func')
3832 impl_decl
= func
.GetInfo('impl_decl')
3834 if (func
.can_auto_generate
and
3835 (impl_func
== None or impl_func
== True) and
3836 (impl_decl
== None or impl_decl
== True)):
3838 file.Write("%s GLES2Implementation::%s(%s) {\n" %
3839 (func
.return_type
, func
.original_name
,
3840 func
.MakeTypedOriginalArgString("")))
3841 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
3842 func
.WriteDestinationInitalizationValidation(file)
3843 self
.WriteClientGLCallLog(func
, file)
3844 for arg
in func
.GetOriginalArgs():
3845 arg
.WriteClientSideValidationCode(file, func
)
3847 code
= """ if (Is%(type)sReservedId(%(id)s)) {
3848 SetGLError(GL_INVALID_OPERATION, "%(name)s\", \"%(id)s reserved id");
3851 if (Bind%(type)sHelper(%(arg_string)s)) {
3852 helper_->%(name)s(%(arg_string)s);
3859 if len(func
.GetOriginalArgs()) == 1:
3860 # Bind functions that have no target (like BindVertexArrayOES)
3861 name_arg
= func
.GetOriginalArgs()[0]
3863 # Bind functions that have both a target and a name (like BindTexture)
3864 name_arg
= func
.GetOriginalArgs()[1]
3868 'arg_string': func
.MakeOriginalArgString(""),
3869 'id': name_arg
.name
,
3870 'type': name_arg
.resource_type
,
3871 'lc_type': name_arg
.resource_type
.lower(),
3874 def WriteGLES2ImplementationUnitTest(self
, func
, file):
3875 """Overrriden from TypeHandler."""
3876 client_test
= func
.GetInfo('client_test')
3877 if client_test
== False:
3880 TEST_F(GLES2ImplementationTest, %(name)s) {
3885 expected.cmd.Init(%(cmd_args)s);
3887 gl_->%(name)s(%(args)s);
3888 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
3890 gl_->%(name)s(%(args)s);
3891 EXPECT_TRUE(NoCommandsWritten());
3894 cmd_arg_strings
= []
3895 for count
, arg
in enumerate(func
.GetCmdArgs()):
3896 cmd_arg_strings
.append(arg
.GetValidClientSideCmdArg(func
, count
, 0))
3899 for count
, arg
in enumerate(func
.GetOriginalArgs()):
3900 gl_arg_strings
.append(arg
.GetValidClientSideArg(func
, count
, 0))
3903 'args': ", ".join(gl_arg_strings
),
3904 'cmd_args': ", ".join(cmd_arg_strings
),
3908 class GENnHandler(TypeHandler
):
3909 """Handler for glGen___ type functions."""
3912 TypeHandler
.__init
__(self
)
3914 def InitFunction(self
, func
):
3915 """Overrriden from TypeHandler."""
3918 def WriteGetDataSizeCode(self
, func
, file):
3919 """Overrriden from TypeHandler."""
3920 code
= """ uint32 data_size;
3921 if (!SafeMultiplyUint32(n, sizeof(GLuint), &data_size)) {
3922 return error::kOutOfBounds;
3927 def WriteHandlerImplementation (self
, func
, file):
3928 """Overrriden from TypeHandler."""
3929 file.Write(" if (!%sHelper(n, %s)) {\n"
3930 " return error::kInvalidArguments;\n"
3932 (func
.name
, func
.GetLastOriginalArg().name
))
3934 def WriteImmediateHandlerImplementation(self
, func
, file):
3935 """Overrriden from TypeHandler."""
3936 file.Write(" if (!%sHelper(n, %s)) {\n"
3937 " return error::kInvalidArguments;\n"
3939 (func
.original_name
, func
.GetLastOriginalArg().name
))
3941 def WriteGLES2Implementation(self
, func
, file):
3942 """Overrriden from TypeHandler."""
3943 log_code
= (""" GPU_CLIENT_LOG_CODE_BLOCK({
3944 for (GLsizei i = 0; i < n; ++i) {
3945 GPU_CLIENT_LOG(" " << i << ": " << %s[i]);
3947 });""" % func
.GetOriginalArgs()[1].name
)
3949 'log_code': log_code
,
3950 'return_type': func
.return_type
,
3951 'name': func
.original_name
,
3952 'typed_args': func
.MakeTypedOriginalArgString(""),
3953 'args': func
.MakeOriginalArgString(""),
3954 'resource_types': func
.GetInfo('resource_types'),
3955 'count_name': func
.GetOriginalArgs()[0].name
,
3958 "%(return_type)s GLES2Implementation::%(name)s(%(typed_args)s) {\n" %
3960 func
.WriteDestinationInitalizationValidation(file)
3961 self
.WriteClientGLCallLog(func
, file)
3962 for arg
in func
.GetOriginalArgs():
3963 arg
.WriteClientSideValidationCode(file, func
)
3964 code
= """ GPU_CLIENT_SINGLE_THREAD_CHECK();
3965 GetIdHandler(id_namespaces::k%(resource_types)s)->
3966 MakeIds(this, 0, %(args)s);
3967 %(name)sHelper(%(args)s);
3968 helper_->%(name)sImmediate(%(args)s);
3969 if (share_group_->bind_generates_resource())
3970 helper_->CommandBufferHelper::Flush();
3976 file.Write(code
% args
)
3978 def WriteGLES2ImplementationUnitTest(self
, func
, file):
3979 """Overrriden from TypeHandler."""
3981 TEST_F(GLES2ImplementationTest, %(name)s) {
3982 GLuint ids[2] = { 0, };
3984 cmds::%(name)sImmediate gen;
3988 expected.gen.Init(arraysize(ids), &ids[0]);
3989 expected.data[0] = k%(types)sStartId;
3990 expected.data[1] = k%(types)sStartId + 1;
3991 gl_->%(name)s(arraysize(ids), &ids[0]);
3992 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
3993 EXPECT_EQ(k%(types)sStartId, ids[0]);
3994 EXPECT_EQ(k%(types)sStartId + 1, ids[1]);
3999 'types': func
.GetInfo('resource_types'),
4002 def WriteServiceUnitTest(self
, func
, file):
4003 """Overrriden from TypeHandler."""
4005 TEST_F(%(test_name)s, %(name)sValidArgs) {
4006 EXPECT_CALL(*gl_, %(gl_func_name)s(1, _))
4007 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
4008 GetSharedMemoryAs<GLuint*>()[0] = kNewClientId;
4009 SpecializedSetup<cmds::%(name)s, 0>(true);
4012 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4013 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4014 EXPECT_TRUE(Get%(resource_name)s(kNewClientId) != NULL);
4017 self
.WriteValidUnitTest(func
, file, valid_test
, {
4018 'resource_name': func
.GetInfo('resource_type'),
4021 TEST_F(%(test_name)s, %(name)sInvalidArgs) {
4022 EXPECT_CALL(*gl_, %(gl_func_name)s(_, _)).Times(0);
4023 GetSharedMemoryAs<GLuint*>()[0] = client_%(resource_name)s_id_;
4024 SpecializedSetup<cmds::%(name)s, 0>(false);
4027 EXPECT_EQ(error::kInvalidArguments, ExecuteCmd(cmd));
4030 self
.WriteValidUnitTest(func
, file, invalid_test
, {
4031 'resource_name': func
.GetInfo('resource_type').lower(),
4034 def WriteImmediateServiceUnitTest(self
, func
, file):
4035 """Overrriden from TypeHandler."""
4037 TEST_F(%(test_name)s, %(name)sValidArgs) {
4038 EXPECT_CALL(*gl_, %(gl_func_name)s(1, _))
4039 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
4040 cmds::%(name)s* cmd = GetImmediateAs<cmds::%(name)s>();
4041 GLuint temp = kNewClientId;
4042 SpecializedSetup<cmds::%(name)s, 0>(true);
4043 cmd->Init(1, &temp);
4044 EXPECT_EQ(error::kNoError,
4045 ExecuteImmediateCmd(*cmd, sizeof(temp)));
4046 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4047 EXPECT_TRUE(Get%(resource_name)s(kNewClientId) != NULL);
4050 self
.WriteValidUnitTest(func
, file, valid_test
, {
4051 'resource_name': func
.GetInfo('resource_type'),
4054 TEST_F(%(test_name)s, %(name)sInvalidArgs) {
4055 EXPECT_CALL(*gl_, %(gl_func_name)s(_, _)).Times(0);
4056 cmds::%(name)s* cmd = GetImmediateAs<cmds::%(name)s>();
4057 SpecializedSetup<cmds::%(name)s, 0>(false);
4058 cmd->Init(1, &client_%(resource_name)s_id_);
4059 EXPECT_EQ(error::kInvalidArguments,
4060 ExecuteImmediateCmd(*cmd, sizeof(&client_%(resource_name)s_id_)));
4063 self
.WriteValidUnitTest(func
, file, invalid_test
, {
4064 'resource_name': func
.GetInfo('resource_type').lower(),
4067 def WriteImmediateCmdComputeSize(self
, func
, file):
4068 """Overrriden from TypeHandler."""
4069 file.Write(" static uint32 ComputeDataSize(GLsizei n) {\n")
4071 " return static_cast<uint32>(sizeof(GLuint) * n); // NOLINT\n")
4074 file.Write(" static uint32 ComputeSize(GLsizei n) {\n")
4075 file.Write(" return static_cast<uint32>(\n")
4076 file.Write(" sizeof(ValueType) + ComputeDataSize(n)); // NOLINT\n")
4080 def WriteImmediateCmdSetHeader(self
, func
, file):
4081 """Overrriden from TypeHandler."""
4082 file.Write(" void SetHeader(GLsizei n) {\n")
4083 file.Write(" header.SetCmdByTotalSize<ValueType>(ComputeSize(n));\n")
4087 def WriteImmediateCmdInit(self
, func
, file):
4088 """Overrriden from TypeHandler."""
4089 last_arg
= func
.GetLastOriginalArg()
4090 file.Write(" void Init(%s, %s _%s) {\n" %
4091 (func
.MakeTypedCmdArgString("_"),
4092 last_arg
.type, last_arg
.name
))
4093 file.Write(" SetHeader(_n);\n")
4094 args
= func
.GetCmdArgs()
4096 file.Write(" %s = _%s;\n" % (arg
.name
, arg
.name
))
4097 file.Write(" memcpy(ImmediateDataAddress(this),\n")
4098 file.Write(" _%s, ComputeDataSize(_n));\n" % last_arg
.name
)
4102 def WriteImmediateCmdSet(self
, func
, file):
4103 """Overrriden from TypeHandler."""
4104 last_arg
= func
.GetLastOriginalArg()
4105 copy_args
= func
.MakeCmdArgString("_", False)
4106 file.Write(" void* Set(void* cmd%s, %s _%s) {\n" %
4107 (func
.MakeTypedCmdArgString("_", True),
4108 last_arg
.type, last_arg
.name
))
4109 file.Write(" static_cast<ValueType*>(cmd)->Init(%s, _%s);\n" %
4110 (copy_args
, last_arg
.name
))
4111 file.Write(" const uint32 size = ComputeSize(_n);\n")
4112 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
4117 def WriteImmediateCmdHelper(self
, func
, file):
4118 """Overrriden from TypeHandler."""
4119 code
= """ void %(name)s(%(typed_args)s) {
4120 const uint32 size = gles2::cmds::%(name)s::ComputeSize(n);
4121 gles2::cmds::%(name)s* c =
4122 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
4131 "typed_args": func
.MakeTypedOriginalArgString(""),
4132 "args": func
.MakeOriginalArgString(""),
4135 def WriteImmediateFormatTest(self
, func
, file):
4136 """Overrriden from TypeHandler."""
4137 file.Write("TEST_F(GLES2FormatTest, %s) {\n" % func
.name
)
4138 file.Write(" static GLuint ids[] = { 12, 23, 34, };\n")
4139 file.Write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
4140 (func
.name
, func
.name
))
4141 file.Write(" void* next_cmd = cmd.Set(\n")
4142 file.Write(" &cmd, static_cast<GLsizei>(arraysize(ids)), ids);\n")
4143 file.Write(" EXPECT_EQ(static_cast<uint32>(cmds::%s::kCmdId),\n" %
4145 file.Write(" cmd.header.command);\n")
4146 file.Write(" EXPECT_EQ(sizeof(cmd) +\n")
4147 file.Write(" RoundSizeToMultipleOfEntries(cmd.n * 4u),\n")
4148 file.Write(" cmd.header.size * 4u);\n")
4149 file.Write(" EXPECT_EQ(static_cast<GLsizei>(arraysize(ids)), cmd.n);\n");
4150 file.Write(" CheckBytesWrittenMatchesExpectedSize(\n")
4151 file.Write(" next_cmd, sizeof(cmd) +\n")
4152 file.Write(" RoundSizeToMultipleOfEntries(arraysize(ids) * 4u));\n")
4153 file.Write(" // TODO(gman): Check that ids were inserted;\n")
4158 class CreateHandler(TypeHandler
):
4159 """Handler for glCreate___ type functions."""
4162 TypeHandler
.__init
__(self
)
4164 def InitFunction(self
, func
):
4165 """Overrriden from TypeHandler."""
4166 func
.AddCmdArg(Argument("client_id", 'uint32'))
4168 def WriteServiceUnitTest(self
, func
, file):
4169 """Overrriden from TypeHandler."""
4171 TEST_F(%(test_name)s, %(name)sValidArgs) {
4172 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s))
4173 .WillOnce(Return(kNewServiceId));
4174 SpecializedSetup<cmds::%(name)s, 0>(true);
4176 cmd.Init(%(args)s%(comma)skNewClientId);
4177 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4178 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4179 EXPECT_TRUE(Get%(resource_type)s(kNewClientId) != NULL);
4183 if len(func
.GetOriginalArgs()):
4185 self
.WriteValidUnitTest(func
, file, valid_test
, {
4187 'resource_type': func
.name
[6:],
4190 TEST_F(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
4191 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
4192 SpecializedSetup<cmds::%(name)s, 0>(false);
4194 cmd.Init(%(args)s%(comma)skNewClientId);
4195 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));%(gl_error_test)s
4198 self
.WriteInvalidUnitTest(func
, file, invalid_test
, {
4202 def WriteHandlerImplementation (self
, func
, file):
4203 """Overrriden from TypeHandler."""
4204 file.Write(" uint32 client_id = c.client_id;\n")
4205 file.Write(" if (!%sHelper(%s)) {\n" %
4206 (func
.name
, func
.MakeCmdArgString("")))
4207 file.Write(" return error::kInvalidArguments;\n")
4210 def WriteGLES2Implementation(self
, func
, file):
4211 """Overrriden from TypeHandler."""
4212 file.Write("%s GLES2Implementation::%s(%s) {\n" %
4213 (func
.return_type
, func
.original_name
,
4214 func
.MakeTypedOriginalArgString("")))
4215 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
4216 func
.WriteDestinationInitalizationValidation(file)
4217 self
.WriteClientGLCallLog(func
, file)
4218 for arg
in func
.GetOriginalArgs():
4219 arg
.WriteClientSideValidationCode(file, func
)
4220 file.Write(" GLuint client_id;\n")
4222 " GetIdHandler(id_namespaces::kProgramsAndShaders)->\n")
4223 file.Write(" MakeIds(this, 0, 1, &client_id);\n")
4224 file.Write(" helper_->%s(%s);\n" %
4225 (func
.name
, func
.MakeCmdArgString("")))
4226 file.Write(' GPU_CLIENT_LOG("returned " << client_id);\n')
4227 file.Write(" CheckGLError();\n")
4228 file.Write(" return client_id;\n")
4233 class DeleteHandler(TypeHandler
):
4234 """Handler for glDelete___ single resource type functions."""
4237 TypeHandler
.__init
__(self
)
4239 def WriteServiceImplementation(self
, func
, file):
4240 """Overrriden from TypeHandler."""
4243 def WriteGLES2Implementation(self
, func
, file):
4244 """Overrriden from TypeHandler."""
4245 file.Write("%s GLES2Implementation::%s(%s) {\n" %
4246 (func
.return_type
, func
.original_name
,
4247 func
.MakeTypedOriginalArgString("")))
4248 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
4249 func
.WriteDestinationInitalizationValidation(file)
4250 self
.WriteClientGLCallLog(func
, file)
4251 for arg
in func
.GetOriginalArgs():
4252 arg
.WriteClientSideValidationCode(file, func
)
4254 " GPU_CLIENT_DCHECK(%s != 0);\n" % func
.GetOriginalArgs()[-1].name
)
4255 file.Write(" %sHelper(%s);\n" %
4256 (func
.original_name
, func
.GetOriginalArgs()[-1].name
))
4257 file.Write(" CheckGLError();\n")
4262 class DELnHandler(TypeHandler
):
4263 """Handler for glDelete___ type functions."""
4266 TypeHandler
.__init
__(self
)
4268 def WriteGetDataSizeCode(self
, func
, file):
4269 """Overrriden from TypeHandler."""
4270 code
= """ uint32 data_size;
4271 if (!SafeMultiplyUint32(n, sizeof(GLuint), &data_size)) {
4272 return error::kOutOfBounds;
4277 def WriteGLES2ImplementationUnitTest(self
, func
, file):
4278 """Overrriden from TypeHandler."""
4280 TEST_F(GLES2ImplementationTest, %(name)s) {
4281 GLuint ids[2] = { k%(types)sStartId, k%(types)sStartId + 1 };
4283 cmds::%(name)sImmediate del;
4287 expected.del.Init(arraysize(ids), &ids[0]);
4288 expected.data[0] = k%(types)sStartId;
4289 expected.data[1] = k%(types)sStartId + 1;
4290 gl_->%(name)s(arraysize(ids), &ids[0]);
4291 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
4296 'types': func
.GetInfo('resource_types'),
4299 def WriteServiceUnitTest(self
, func
, file):
4300 """Overrriden from TypeHandler."""
4302 TEST_F(%(test_name)s, %(name)sValidArgs) {
4305 %(gl_func_name)s(1, Pointee(kService%(upper_resource_name)sId)))
4307 GetSharedMemoryAs<GLuint*>()[0] = client_%(resource_name)s_id_;
4308 SpecializedSetup<cmds::%(name)s, 0>(true);
4311 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4312 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4314 Get%(upper_resource_name)s(client_%(resource_name)s_id_) == NULL);
4317 self
.WriteValidUnitTest(func
, file, valid_test
, {
4318 'resource_name': func
.GetInfo('resource_type').lower(),
4319 'upper_resource_name': func
.GetInfo('resource_type'),
4322 TEST_F(%(test_name)s, %(name)sInvalidArgs) {
4323 GetSharedMemoryAs<GLuint*>()[0] = kInvalidClientId;
4324 SpecializedSetup<cmds::%(name)s, 0>(false);
4327 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4330 self
.WriteValidUnitTest(func
, file, invalid_test
)
4332 def WriteImmediateServiceUnitTest(self
, func
, file):
4333 """Overrriden from TypeHandler."""
4335 TEST_F(%(test_name)s, %(name)sValidArgs) {
4338 %(gl_func_name)s(1, Pointee(kService%(upper_resource_name)sId)))
4340 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
4341 SpecializedSetup<cmds::%(name)s, 0>(true);
4342 cmd.Init(1, &client_%(resource_name)s_id_);
4343 EXPECT_EQ(error::kNoError,
4344 ExecuteImmediateCmd(cmd, sizeof(client_%(resource_name)s_id_)));
4345 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4347 Get%(upper_resource_name)s(client_%(resource_name)s_id_) == NULL);
4350 self
.WriteValidUnitTest(func
, file, valid_test
, {
4351 'resource_name': func
.GetInfo('resource_type').lower(),
4352 'upper_resource_name': func
.GetInfo('resource_type'),
4355 TEST_F(%(test_name)s, %(name)sInvalidArgs) {
4356 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
4357 SpecializedSetup<cmds::%(name)s, 0>(false);
4358 GLuint temp = kInvalidClientId;
4360 EXPECT_EQ(error::kNoError,
4361 ExecuteImmediateCmd(cmd, sizeof(temp)));
4364 self
.WriteValidUnitTest(func
, file, invalid_test
)
4366 def WriteHandlerImplementation (self
, func
, file):
4367 """Overrriden from TypeHandler."""
4368 file.Write(" %sHelper(n, %s);\n" %
4369 (func
.name
, func
.GetLastOriginalArg().name
))
4371 def WriteImmediateHandlerImplementation (self
, func
, file):
4372 """Overrriden from TypeHandler."""
4373 file.Write(" %sHelper(n, %s);\n" %
4374 (func
.original_name
, func
.GetLastOriginalArg().name
))
4376 def WriteGLES2Implementation(self
, func
, file):
4377 """Overrriden from TypeHandler."""
4378 impl_decl
= func
.GetInfo('impl_decl')
4379 if impl_decl
== None or impl_decl
== True:
4381 'return_type': func
.return_type
,
4382 'name': func
.original_name
,
4383 'typed_args': func
.MakeTypedOriginalArgString(""),
4384 'args': func
.MakeOriginalArgString(""),
4385 'resource_type': func
.GetInfo('resource_type').lower(),
4386 'count_name': func
.GetOriginalArgs()[0].name
,
4389 "%(return_type)s GLES2Implementation::%(name)s(%(typed_args)s) {\n" %
4391 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
4392 func
.WriteDestinationInitalizationValidation(file)
4393 self
.WriteClientGLCallLog(func
, file)
4394 file.Write(""" GPU_CLIENT_LOG_CODE_BLOCK({
4395 for (GLsizei i = 0; i < n; ++i) {
4396 GPU_CLIENT_LOG(" " << i << ": " << %s[i]);
4399 """ % func
.GetOriginalArgs()[1].name
)
4400 file.Write(""" GPU_CLIENT_DCHECK_CODE_BLOCK({
4401 for (GLsizei i = 0; i < n; ++i) {
4405 """ % func
.GetOriginalArgs()[1].name
)
4406 for arg
in func
.GetOriginalArgs():
4407 arg
.WriteClientSideValidationCode(file, func
)
4408 code
= """ %(name)sHelper(%(args)s);
4413 file.Write(code
% args
)
4415 def WriteImmediateCmdComputeSize(self
, func
, file):
4416 """Overrriden from TypeHandler."""
4417 file.Write(" static uint32 ComputeDataSize(GLsizei n) {\n")
4419 " return static_cast<uint32>(sizeof(GLuint) * n); // NOLINT\n")
4422 file.Write(" static uint32 ComputeSize(GLsizei n) {\n")
4423 file.Write(" return static_cast<uint32>(\n")
4424 file.Write(" sizeof(ValueType) + ComputeDataSize(n)); // NOLINT\n")
4428 def WriteImmediateCmdSetHeader(self
, func
, file):
4429 """Overrriden from TypeHandler."""
4430 file.Write(" void SetHeader(GLsizei n) {\n")
4431 file.Write(" header.SetCmdByTotalSize<ValueType>(ComputeSize(n));\n")
4435 def WriteImmediateCmdInit(self
, func
, file):
4436 """Overrriden from TypeHandler."""
4437 last_arg
= func
.GetLastOriginalArg()
4438 file.Write(" void Init(%s, %s _%s) {\n" %
4439 (func
.MakeTypedCmdArgString("_"),
4440 last_arg
.type, last_arg
.name
))
4441 file.Write(" SetHeader(_n);\n")
4442 args
= func
.GetCmdArgs()
4444 file.Write(" %s = _%s;\n" % (arg
.name
, arg
.name
))
4445 file.Write(" memcpy(ImmediateDataAddress(this),\n")
4446 file.Write(" _%s, ComputeDataSize(_n));\n" % last_arg
.name
)
4450 def WriteImmediateCmdSet(self
, func
, file):
4451 """Overrriden from TypeHandler."""
4452 last_arg
= func
.GetLastOriginalArg()
4453 copy_args
= func
.MakeCmdArgString("_", False)
4454 file.Write(" void* Set(void* cmd%s, %s _%s) {\n" %
4455 (func
.MakeTypedCmdArgString("_", True),
4456 last_arg
.type, last_arg
.name
))
4457 file.Write(" static_cast<ValueType*>(cmd)->Init(%s, _%s);\n" %
4458 (copy_args
, last_arg
.name
))
4459 file.Write(" const uint32 size = ComputeSize(_n);\n")
4460 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
4465 def WriteImmediateCmdHelper(self
, func
, file):
4466 """Overrriden from TypeHandler."""
4467 code
= """ void %(name)s(%(typed_args)s) {
4468 const uint32 size = gles2::cmds::%(name)s::ComputeSize(n);
4469 gles2::cmds::%(name)s* c =
4470 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
4479 "typed_args": func
.MakeTypedOriginalArgString(""),
4480 "args": func
.MakeOriginalArgString(""),
4483 def WriteImmediateFormatTest(self
, func
, file):
4484 """Overrriden from TypeHandler."""
4485 file.Write("TEST_F(GLES2FormatTest, %s) {\n" % func
.name
)
4486 file.Write(" static GLuint ids[] = { 12, 23, 34, };\n")
4487 file.Write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
4488 (func
.name
, func
.name
))
4489 file.Write(" void* next_cmd = cmd.Set(\n")
4490 file.Write(" &cmd, static_cast<GLsizei>(arraysize(ids)), ids);\n")
4491 file.Write(" EXPECT_EQ(static_cast<uint32>(cmds::%s::kCmdId),\n" %
4493 file.Write(" cmd.header.command);\n")
4494 file.Write(" EXPECT_EQ(sizeof(cmd) +\n")
4495 file.Write(" RoundSizeToMultipleOfEntries(cmd.n * 4u),\n")
4496 file.Write(" cmd.header.size * 4u);\n")
4497 file.Write(" EXPECT_EQ(static_cast<GLsizei>(arraysize(ids)), cmd.n);\n");
4498 file.Write(" CheckBytesWrittenMatchesExpectedSize(\n")
4499 file.Write(" next_cmd, sizeof(cmd) +\n")
4500 file.Write(" RoundSizeToMultipleOfEntries(arraysize(ids) * 4u));\n")
4501 file.Write(" // TODO(gman): Check that ids were inserted;\n")
4506 class GETnHandler(TypeHandler
):
4507 """Handler for GETn for glGetBooleanv, glGetFloatv, ... type functions."""
4510 TypeHandler
.__init
__(self
)
4512 def AddImmediateFunction(self
, generator
, func
):
4513 """Overrriden from TypeHandler."""
4516 def WriteServiceImplementation(self
, func
, file):
4517 """Overrriden from TypeHandler."""
4519 "error::Error GLES2DecoderImpl::Handle%s(\n" % func
.name
)
4521 " uint32 immediate_data_size, const gles2::cmds::%s& c) {\n" %
4523 last_arg
= func
.GetLastOriginalArg()
4525 all_but_last_args
= func
.GetOriginalArgs()[:-1]
4526 for arg
in all_but_last_args
:
4527 arg
.WriteGetCode(file)
4529 code
= """ typedef cmds::%(func_name)s::Result Result;
4530 GLsizei num_values = 0;
4531 GetNumValuesReturnedForGLGet(pname, &num_values);
4532 Result* result = GetSharedMemoryAs<Result*>(
4533 c.params_shm_id, c.params_shm_offset, Result::ComputeSize(num_values));
4534 %(last_arg_type)s params = result ? result->GetData() : NULL;
4537 'last_arg_type': last_arg
.type,
4538 'func_name': func
.name
,
4540 func
.WriteHandlerValidation(file)
4541 code
= """ // Check that the client initialized the result.
4542 if (result->size != 0) {
4543 return error::kInvalidArguments;
4546 shadowed
= func
.GetInfo('shadowed')
4548 file.Write(' LOCAL_COPY_REAL_GL_ERRORS_TO_WRAPPER("%s");\n' % func
.name
)
4550 func
.WriteHandlerImplementation(file)
4552 code
= """ result->SetNumResults(num_values);
4553 return error::kNoError;
4557 code
= """ GLenum error = glGetError();
4558 if (error == GL_NO_ERROR) {
4559 result->SetNumResults(num_values);
4561 LOCAL_SET_GL_ERROR(error, "%(func_name)s", "");
4563 return error::kNoError;
4567 file.Write(code
% {'func_name': func
.name
})
4569 def WriteGLES2Implementation(self
, func
, file):
4570 """Overrriden from TypeHandler."""
4571 impl_decl
= func
.GetInfo('impl_decl')
4572 if impl_decl
== None or impl_decl
== True:
4573 file.Write("%s GLES2Implementation::%s(%s) {\n" %
4574 (func
.return_type
, func
.original_name
,
4575 func
.MakeTypedOriginalArgString("")))
4576 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
4577 func
.WriteDestinationInitalizationValidation(file)
4578 self
.WriteClientGLCallLog(func
, file)
4579 for arg
in func
.GetOriginalArgs():
4580 arg
.WriteClientSideValidationCode(file, func
)
4581 all_but_last_args
= func
.GetOriginalArgs()[:-1]
4583 ", ".join(["%s" % arg
.name
for arg
in all_but_last_args
]))
4585 ", ".join(["%s" % arg
.name
for arg
in func
.GetOriginalArgs()]))
4586 self
.WriteTraceEvent(func
, file)
4587 code
= """ if (%(func_name)sHelper(%(all_arg_string)s)) {
4590 typedef cmds::%(func_name)s::Result Result;
4591 Result* result = GetResultAs<Result*>();
4595 result->SetNumResults(0);
4596 helper_->%(func_name)s(%(arg_string)s,
4597 GetResultShmId(), GetResultShmOffset());
4599 result->CopyResult(params);
4600 GPU_CLIENT_LOG_CODE_BLOCK({
4601 for (int32 i = 0; i < result->GetNumResults(); ++i) {
4602 GPU_CLIENT_LOG(" " << i << ": " << result->GetData()[i]);
4609 'func_name': func
.name
,
4610 'arg_string': arg_string
,
4611 'all_arg_string': all_arg_string
,
4614 def WriteGLES2ImplementationUnitTest(self
, func
, file):
4615 """Writes the GLES2 Implemention unit test."""
4617 TEST_F(GLES2ImplementationTest, %(name)s) {
4621 typedef cmds::%(name)s::Result Result;
4622 Result::Type result = 0;
4624 ExpectedMemoryInfo result1 = GetExpectedResultMemory(4);
4625 expected.cmd.Init(%(cmd_args)s, result1.id, result1.offset);
4626 EXPECT_CALL(*command_buffer(), OnFlush())
4627 .WillOnce(SetMemory(result1.ptr, SizedResultHelper<Result::Type>(1)))
4628 .RetiresOnSaturation();
4629 gl_->%(name)s(%(args)s, &result);
4630 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
4631 EXPECT_EQ(static_cast<Result::Type>(1), result);
4634 cmd_arg_strings
= []
4635 for count
, arg
in enumerate(func
.GetCmdArgs()[0:-2]):
4636 cmd_arg_strings
.append(arg
.GetValidClientSideCmdArg(func
, count
, 0))
4637 cmd_arg_strings
[0] = '123'
4639 for count
, arg
in enumerate(func
.GetOriginalArgs()[0:-1]):
4640 gl_arg_strings
.append(arg
.GetValidClientSideArg(func
, count
, 0))
4641 gl_arg_strings
[0] = '123'
4644 'args': ", ".join(gl_arg_strings
),
4645 'cmd_args': ", ".join(cmd_arg_strings
),
4648 def WriteServiceUnitTest(self
, func
, file):
4649 """Overrriden from TypeHandler."""
4651 TEST_F(%(test_name)s, %(name)sValidArgs) {
4652 EXPECT_CALL(*gl_, GetError())
4653 .WillOnce(Return(GL_NO_ERROR))
4654 .WillOnce(Return(GL_NO_ERROR))
4655 .RetiresOnSaturation();
4656 SpecializedSetup<cmds::%(name)s, 0>(true);
4657 typedef cmds::%(name)s::Result Result;
4658 Result* result = static_cast<Result*>(shared_memory_address_);
4659 EXPECT_CALL(*gl_, %(gl_func_name)s(%(local_gl_args)s));
4663 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4664 EXPECT_EQ(decoder_->GetGLES2Util()->GLGetNumValuesReturned(
4666 result->GetNumResults());
4667 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4672 for count
, arg
in enumerate(func
.GetOriginalArgs()[:-1]):
4673 arg_value
= arg
.GetValidGLArg(func
, count
, 0)
4674 gl_arg_strings
.append(arg_value
)
4675 if arg
.name
== 'pname':
4676 valid_pname
= arg_value
4677 if func
.GetInfo('gl_test_func') == 'glGetIntegerv':
4678 gl_arg_strings
.append("_")
4680 gl_arg_strings
.append("result->GetData()")
4682 self
.WriteValidUnitTest(func
, file, valid_test
, {
4683 'local_gl_args': ", ".join(gl_arg_strings
),
4684 'valid_pname': valid_pname
,
4688 TEST_F(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
4689 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
4690 SpecializedSetup<cmds::%(name)s, 0>(false);
4691 cmds::%(name)s::Result* result =
4692 static_cast<cmds::%(name)s::Result*>(shared_memory_address_);
4696 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));
4697 EXPECT_EQ(0u, result->size);%(gl_error_test)s
4700 self
.WriteInvalidUnitTest(func
, file, invalid_test
)
4703 class PUTHandler(TypeHandler
):
4704 """Handler for glTexParameter_v, glVertexAttrib_v functions."""
4707 TypeHandler
.__init
__(self
)
4709 def WriteServiceUnitTest(self
, func
, file):
4710 """Writes the service unit test for a command."""
4711 expected_call
= "EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));"
4712 if func
.GetInfo("first_element_only"):
4714 for count
, arg
in enumerate(func
.GetOriginalArgs()):
4715 gl_arg_strings
.append(arg
.GetValidGLArg(func
, count
, 0))
4716 gl_arg_strings
[-1] = "*" + gl_arg_strings
[-1]
4717 expected_call
= ("EXPECT_CALL(*gl_, %%(gl_func_name)s(%s));" %
4718 ", ".join(gl_arg_strings
))
4720 TEST_F(%(test_name)s, %(name)sValidArgs) {
4721 SpecializedSetup<cmds::%(name)s, 0>(true);
4724 GetSharedMemoryAs<%(data_type)s*>()[0] = %(data_value)s;
4726 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4727 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4731 'data_type': func
.GetInfo('data_type'),
4732 'data_value': func
.GetInfo('data_value') or '0',
4733 'expected_call': expected_call
,
4735 self
.WriteValidUnitTest(func
, file, valid_test
, extra
)
4738 TEST_F(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
4739 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
4740 SpecializedSetup<cmds::%(name)s, 0>(false);
4743 GetSharedMemoryAs<%(data_type)s*>()[0] = %(data_value)s;
4744 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
4747 self
.WriteInvalidUnitTest(func
, file, invalid_test
, extra
)
4749 def WriteImmediateServiceUnitTest(self
, func
, file):
4750 """Writes the service unit test for a command."""
4752 TEST_F(%(test_name)s, %(name)sValidArgs) {
4753 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
4754 SpecializedSetup<cmds::%(name)s, 0>(true);
4755 %(data_type)s temp[%(data_count)s] = { %(data_value)s, };
4756 cmd.Init(%(gl_args)s, &temp[0]);
4759 %(gl_func_name)s(%(gl_args)s, %(data_ref)sreinterpret_cast<
4760 %(data_type)s*>(ImmediateDataAddress(&cmd))));
4761 EXPECT_EQ(error::kNoError,
4762 ExecuteImmediateCmd(cmd, sizeof(temp)));
4763 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4768 for count
, arg
in enumerate(func
.GetOriginalArgs()[0:-1]):
4769 gl_arg_strings
.append(arg
.GetValidGLArg(func
, count
, 0))
4770 gl_any_strings
.append("_")
4772 'data_ref': ("*" if func
.GetInfo('first_element_only') else ""),
4773 'data_type': func
.GetInfo('data_type'),
4774 'data_count': func
.GetInfo('count'),
4775 'data_value': func
.GetInfo('data_value') or '0',
4776 'gl_args': ", ".join(gl_arg_strings
),
4777 'gl_any_args': ", ".join(gl_any_strings
),
4779 self
.WriteValidUnitTest(func
, file, valid_test
, extra
)
4782 TEST_F(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
4783 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
4784 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_any_args)s, _)).Times(0);
4785 SpecializedSetup<cmds::%(name)s, 0>(false);
4786 %(data_type)s temp[%(data_count)s] = { %(data_value)s, };
4787 cmd.Init(%(all_but_last_args)s, &temp[0]);
4788 EXPECT_EQ(error::%(parse_result)s,
4789 ExecuteImmediateCmd(cmd, sizeof(temp)));%(gl_error_test)s
4792 self
.WriteInvalidUnitTest(func
, file, invalid_test
, extra
)
4794 def WriteGetDataSizeCode(self
, func
, file):
4795 """Overrriden from TypeHandler."""
4796 code
= """ uint32 data_size;
4797 if (!ComputeDataSize(1, sizeof(%s), %d, &data_size)) {
4798 return error::kOutOfBounds;
4801 file.Write(code
% (func
.info
.data_type
, func
.info
.count
))
4802 if func
.is_immediate
:
4803 file.Write(" if (data_size > immediate_data_size) {\n")
4804 file.Write(" return error::kOutOfBounds;\n")
4807 def WriteGLES2Implementation(self
, func
, file):
4808 """Overrriden from TypeHandler."""
4809 impl_func
= func
.GetInfo('impl_func')
4810 if (impl_func
!= None and impl_func
!= True):
4812 file.Write("%s GLES2Implementation::%s(%s) {\n" %
4813 (func
.return_type
, func
.original_name
,
4814 func
.MakeTypedOriginalArgString("")))
4815 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
4816 func
.WriteDestinationInitalizationValidation(file)
4817 self
.WriteClientGLCallLog(func
, file)
4818 last_arg_name
= func
.GetLastOriginalArg().name
4819 values_str
= ' << ", " << '.join(
4820 ["%s[%d]" % (last_arg_name
, ndx
) for ndx
in range(0, func
.info
.count
)])
4821 file.Write(' GPU_CLIENT_LOG("values: " << %s);\n' % values_str
)
4822 for arg
in func
.GetOriginalArgs():
4823 arg
.WriteClientSideValidationCode(file, func
)
4824 file.Write(" helper_->%sImmediate(%s);\n" %
4825 (func
.name
, func
.MakeOriginalArgString("")))
4826 file.Write(" CheckGLError();\n")
4830 def WriteGLES2ImplementationUnitTest(self
, func
, file):
4831 """Writes the GLES2 Implemention unit test."""
4832 client_test
= func
.GetInfo('client_test')
4833 if (client_test
!= None and client_test
!= True):
4836 TEST_F(GLES2ImplementationTest, %(name)s) {
4837 %(type)s data[%(count)d] = {0};
4839 cmds::%(name)sImmediate cmd;
4840 %(type)s data[%(count)d];
4843 for (int jj = 0; jj < %(count)d; ++jj) {
4844 data[jj] = static_cast<%(type)s>(jj);
4847 expected.cmd.Init(%(cmd_args)s, &data[0]);
4848 gl_->%(name)s(%(args)s, &data[0]);
4849 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
4852 cmd_arg_strings
= []
4853 for count
, arg
in enumerate(func
.GetCmdArgs()[0:-2]):
4854 cmd_arg_strings
.append(arg
.GetValidClientSideCmdArg(func
, count
, 0))
4856 for count
, arg
in enumerate(func
.GetOriginalArgs()[0:-1]):
4857 gl_arg_strings
.append(arg
.GetValidClientSideArg(func
, count
, 0))
4860 'type': func
.GetInfo('data_type'),
4861 'count': func
.GetInfo('count'),
4862 'args': ", ".join(gl_arg_strings
),
4863 'cmd_args': ", ".join(cmd_arg_strings
),
4866 def WriteImmediateCmdComputeSize(self
, func
, file):
4867 """Overrriden from TypeHandler."""
4868 file.Write(" static uint32 ComputeDataSize() {\n")
4869 file.Write(" return static_cast<uint32>(\n")
4870 file.Write(" sizeof(%s) * %d); // NOLINT\n" %
4871 (func
.info
.data_type
, func
.info
.count
))
4874 file.Write(" static uint32 ComputeSize() {\n")
4875 file.Write(" return static_cast<uint32>(\n")
4877 " sizeof(ValueType) + ComputeDataSize()); // NOLINT\n")
4881 def WriteImmediateCmdSetHeader(self
, func
, file):
4882 """Overrriden from TypeHandler."""
4883 file.Write(" void SetHeader() {\n")
4885 " header.SetCmdByTotalSize<ValueType>(ComputeSize());\n")
4889 def WriteImmediateCmdInit(self
, func
, file):
4890 """Overrriden from TypeHandler."""
4891 last_arg
= func
.GetLastOriginalArg()
4892 file.Write(" void Init(%s, %s _%s) {\n" %
4893 (func
.MakeTypedCmdArgString("_"),
4894 last_arg
.type, last_arg
.name
))
4895 file.Write(" SetHeader();\n")
4896 args
= func
.GetCmdArgs()
4898 file.Write(" %s = _%s;\n" % (arg
.name
, arg
.name
))
4899 file.Write(" memcpy(ImmediateDataAddress(this),\n")
4900 file.Write(" _%s, ComputeDataSize());\n" % last_arg
.name
)
4904 def WriteImmediateCmdSet(self
, func
, file):
4905 """Overrriden from TypeHandler."""
4906 last_arg
= func
.GetLastOriginalArg()
4907 copy_args
= func
.MakeCmdArgString("_", False)
4908 file.Write(" void* Set(void* cmd%s, %s _%s) {\n" %
4909 (func
.MakeTypedCmdArgString("_", True),
4910 last_arg
.type, last_arg
.name
))
4911 file.Write(" static_cast<ValueType*>(cmd)->Init(%s, _%s);\n" %
4912 (copy_args
, last_arg
.name
))
4913 file.Write(" const uint32 size = ComputeSize();\n")
4914 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
4919 def WriteImmediateCmdHelper(self
, func
, file):
4920 """Overrriden from TypeHandler."""
4921 code
= """ void %(name)s(%(typed_args)s) {
4922 const uint32 size = gles2::cmds::%(name)s::ComputeSize();
4923 gles2::cmds::%(name)s* c =
4924 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
4933 "typed_args": func
.MakeTypedOriginalArgString(""),
4934 "args": func
.MakeOriginalArgString(""),
4937 def WriteImmediateFormatTest(self
, func
, file):
4938 """Overrriden from TypeHandler."""
4939 file.Write("TEST_F(GLES2FormatTest, %s) {\n" % func
.name
)
4940 file.Write(" const int kSomeBaseValueToTestWith = 51;\n")
4941 file.Write(" static %s data[] = {\n" % func
.info
.data_type
)
4942 for v
in range(0, func
.info
.count
):
4943 file.Write(" static_cast<%s>(kSomeBaseValueToTestWith + %d),\n" %
4944 (func
.info
.data_type
, v
))
4946 file.Write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
4947 (func
.name
, func
.name
))
4948 file.Write(" void* next_cmd = cmd.Set(\n")
4950 args
= func
.GetCmdArgs()
4951 for value
, arg
in enumerate(args
):
4952 file.Write(",\n static_cast<%s>(%d)" % (arg
.type, value
+ 11))
4953 file.Write(",\n data);\n")
4954 args
= func
.GetCmdArgs()
4955 file.Write(" EXPECT_EQ(static_cast<uint32>(cmds::%s::kCmdId),\n"
4957 file.Write(" cmd.header.command);\n")
4958 file.Write(" EXPECT_EQ(sizeof(cmd) +\n")
4959 file.Write(" RoundSizeToMultipleOfEntries(sizeof(data)),\n")
4960 file.Write(" cmd.header.size * 4u);\n")
4961 for value
, arg
in enumerate(args
):
4962 file.Write(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);\n" %
4963 (arg
.type, value
+ 11, arg
.name
))
4964 file.Write(" CheckBytesWrittenMatchesExpectedSize(\n")
4965 file.Write(" next_cmd, sizeof(cmd) +\n")
4966 file.Write(" RoundSizeToMultipleOfEntries(sizeof(data)));\n")
4967 file.Write(" // TODO(gman): Check that data was inserted;\n")
4972 class PUTnHandler(TypeHandler
):
4973 """Handler for PUTn 'glUniform__v' type functions."""
4976 TypeHandler
.__init
__(self
)
4978 def WriteServiceUnitTest(self
, func
, file):
4979 """Overridden from TypeHandler."""
4980 TypeHandler
.WriteServiceUnitTest(self
, func
, file)
4983 TEST_F(%(test_name)s, %(name)sValidArgsCountTooLarge) {
4984 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
4985 SpecializedSetup<cmds::%(name)s, 0>(true);
4988 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4989 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4994 for count
, arg
in enumerate(func
.GetOriginalArgs()):
4995 # hardcoded to match unit tests.
4997 # the location of the second element of the 2nd uniform.
4998 # defined in GLES2DecoderBase::SetupShaderForUniform
4999 gl_arg_strings
.append("3")
5000 arg_strings
.append("ProgramManager::MakeFakeLocation(1, 1)")
5002 # the number of elements that gl will be called with.
5003 gl_arg_strings
.append("3")
5004 # the number of elements requested in the command.
5005 arg_strings
.append("5")
5007 gl_arg_strings
.append(arg
.GetValidGLArg(func
, count
, 0))
5008 arg_strings
.append(arg
.GetValidArg(func
, count
, 0))
5010 'gl_args': ", ".join(gl_arg_strings
),
5011 'args': ", ".join(arg_strings
),
5013 self
.WriteValidUnitTest(func
, file, valid_test
, extra
)
5015 def WriteImmediateServiceUnitTest(self
, func
, file):
5016 """Overridden from TypeHandler."""
5018 TEST_F(%(test_name)s, %(name)sValidArgs) {
5019 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
5022 %(gl_func_name)s(%(gl_args)s,
5023 reinterpret_cast<%(data_type)s*>(ImmediateDataAddress(&cmd))));
5024 SpecializedSetup<cmds::%(name)s, 0>(true);
5025 %(data_type)s temp[%(data_count)s * 2] = { 0, };
5026 cmd.Init(%(args)s, &temp[0]);
5027 EXPECT_EQ(error::kNoError,
5028 ExecuteImmediateCmd(cmd, sizeof(temp)));
5029 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5035 for count
, arg
in enumerate(func
.GetOriginalArgs()[0:-1]):
5036 gl_arg_strings
.append(arg
.GetValidGLArg(func
, count
, 0))
5037 gl_any_strings
.append("_")
5038 arg_strings
.append(arg
.GetValidArg(func
, count
, 0))
5040 'data_type': func
.GetInfo('data_type'),
5041 'data_count': func
.GetInfo('count'),
5042 'args': ", ".join(arg_strings
),
5043 'gl_args': ", ".join(gl_arg_strings
),
5044 'gl_any_args': ", ".join(gl_any_strings
),
5046 self
.WriteValidUnitTest(func
, file, valid_test
, extra
)
5049 TEST_F(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
5050 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
5051 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_any_args)s, _)).Times(0);
5052 SpecializedSetup<cmds::%(name)s, 0>(false);
5053 %(data_type)s temp[%(data_count)s * 2] = { 0, };
5054 cmd.Init(%(all_but_last_args)s, &temp[0]);
5055 EXPECT_EQ(error::%(parse_result)s,
5056 ExecuteImmediateCmd(cmd, sizeof(temp)));%(gl_error_test)s
5059 self
.WriteInvalidUnitTest(func
, file, invalid_test
, extra
)
5061 def WriteGetDataSizeCode(self
, func
, file):
5062 """Overrriden from TypeHandler."""
5063 code
= """ uint32 data_size;
5064 if (!ComputeDataSize(count, sizeof(%s), %d, &data_size)) {
5065 return error::kOutOfBounds;
5068 file.Write(code
% (func
.info
.data_type
, func
.info
.count
))
5069 if func
.is_immediate
:
5070 file.Write(" if (data_size > immediate_data_size) {\n")
5071 file.Write(" return error::kOutOfBounds;\n")
5074 def WriteGLES2Implementation(self
, func
, file):
5075 """Overrriden from TypeHandler."""
5076 file.Write("%s GLES2Implementation::%s(%s) {\n" %
5077 (func
.return_type
, func
.original_name
,
5078 func
.MakeTypedOriginalArgString("")))
5079 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
5080 func
.WriteDestinationInitalizationValidation(file)
5081 self
.WriteClientGLCallLog(func
, file)
5082 last_arg_name
= func
.GetLastOriginalArg().name
5083 file.Write(""" GPU_CLIENT_LOG_CODE_BLOCK({
5084 for (GLsizei i = 0; i < count; ++i) {
5086 values_str
= ' << ", " << '.join(
5087 ["%s[%d + i * %d]" % (
5088 last_arg_name
, ndx
, func
.info
.count
) for ndx
in range(
5089 0, func
.info
.count
)])
5090 file.Write(' GPU_CLIENT_LOG(" " << i << ": " << %s);\n' % values_str
)
5091 file.Write(" }\n });\n")
5092 for arg
in func
.GetOriginalArgs():
5093 arg
.WriteClientSideValidationCode(file, func
)
5094 file.Write(" helper_->%sImmediate(%s);\n" %
5095 (func
.name
, func
.MakeOriginalArgString("")))
5096 file.Write(" CheckGLError();\n")
5100 def WriteGLES2ImplementationUnitTest(self
, func
, file):
5101 """Writes the GLES2 Implemention unit test."""
5103 TEST_F(GLES2ImplementationTest, %(name)s) {
5104 %(type)s data[%(count_param)d][%(count)d] = {{0}};
5106 cmds::%(name)sImmediate cmd;
5107 %(type)s data[%(count_param)d][%(count)d];
5111 for (int ii = 0; ii < %(count_param)d; ++ii) {
5112 for (int jj = 0; jj < %(count)d; ++jj) {
5113 data[ii][jj] = static_cast<%(type)s>(ii * %(count)d + jj);
5116 expected.cmd.Init(%(cmd_args)s, &data[0][0]);
5117 gl_->%(name)s(%(args)s, &data[0][0]);
5118 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
5121 cmd_arg_strings
= []
5122 for count
, arg
in enumerate(func
.GetCmdArgs()[0:-2]):
5123 cmd_arg_strings
.append(arg
.GetValidClientSideCmdArg(func
, count
, 0))
5126 for count
, arg
in enumerate(func
.GetOriginalArgs()[0:-1]):
5127 gl_arg_strings
.append(arg
.GetValidClientSideArg(func
, count
, 0))
5128 if arg
.name
== "count":
5129 count_param
= int(arg
.GetValidClientSideArg(func
, count
, 0))
5132 'type': func
.GetInfo('data_type'),
5133 'count': func
.GetInfo('count'),
5134 'args': ", ".join(gl_arg_strings
),
5135 'cmd_args': ", ".join(cmd_arg_strings
),
5136 'count_param': count_param
,
5139 def WriteImmediateCmdComputeSize(self
, func
, file):
5140 """Overrriden from TypeHandler."""
5141 file.Write(" static uint32 ComputeDataSize(GLsizei count) {\n")
5142 file.Write(" return static_cast<uint32>(\n")
5143 file.Write(" sizeof(%s) * %d * count); // NOLINT\n" %
5144 (func
.info
.data_type
, func
.info
.count
))
5147 file.Write(" static uint32 ComputeSize(GLsizei count) {\n")
5148 file.Write(" return static_cast<uint32>(\n")
5150 " sizeof(ValueType) + ComputeDataSize(count)); // NOLINT\n")
5154 def WriteImmediateCmdSetHeader(self
, func
, file):
5155 """Overrriden from TypeHandler."""
5156 file.Write(" void SetHeader(GLsizei count) {\n")
5158 " header.SetCmdByTotalSize<ValueType>(ComputeSize(count));\n")
5162 def WriteImmediateCmdInit(self
, func
, file):
5163 """Overrriden from TypeHandler."""
5164 last_arg
= func
.GetLastOriginalArg()
5165 file.Write(" void Init(%s, %s _%s) {\n" %
5166 (func
.MakeTypedCmdArgString("_"),
5167 last_arg
.type, last_arg
.name
))
5168 file.Write(" SetHeader(_count);\n")
5169 args
= func
.GetCmdArgs()
5171 file.Write(" %s = _%s;\n" % (arg
.name
, arg
.name
))
5172 file.Write(" memcpy(ImmediateDataAddress(this),\n")
5173 file.Write(" _%s, ComputeDataSize(_count));\n" % last_arg
.name
)
5177 def WriteImmediateCmdSet(self
, func
, file):
5178 """Overrriden from TypeHandler."""
5179 last_arg
= func
.GetLastOriginalArg()
5180 copy_args
= func
.MakeCmdArgString("_", False)
5181 file.Write(" void* Set(void* cmd%s, %s _%s) {\n" %
5182 (func
.MakeTypedCmdArgString("_", True),
5183 last_arg
.type, last_arg
.name
))
5184 file.Write(" static_cast<ValueType*>(cmd)->Init(%s, _%s);\n" %
5185 (copy_args
, last_arg
.name
))
5186 file.Write(" const uint32 size = ComputeSize(_count);\n")
5187 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
5192 def WriteImmediateCmdHelper(self
, func
, file):
5193 """Overrriden from TypeHandler."""
5194 code
= """ void %(name)s(%(typed_args)s) {
5195 const uint32 size = gles2::cmds::%(name)s::ComputeSize(count);
5196 gles2::cmds::%(name)s* c =
5197 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
5206 "typed_args": func
.MakeTypedOriginalArgString(""),
5207 "args": func
.MakeOriginalArgString(""),
5210 def WriteImmediateFormatTest(self
, func
, file):
5211 """Overrriden from TypeHandler."""
5212 args
= func
.GetCmdArgs()
5214 for value
, arg
in enumerate(args
):
5215 if arg
.name
== "count":
5216 count_param
= int(arg
.GetValidClientSideArg(func
, value
, 0))
5217 file.Write("TEST_F(GLES2FormatTest, %s) {\n" % func
.name
)
5218 file.Write(" const int kSomeBaseValueToTestWith = 51;\n")
5219 file.Write(" static %s data[] = {\n" % func
.info
.data_type
)
5220 for v
in range(0, func
.info
.count
* count_param
):
5221 file.Write(" static_cast<%s>(kSomeBaseValueToTestWith + %d),\n" %
5222 (func
.info
.data_type
, v
))
5224 file.Write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
5225 (func
.name
, func
.name
))
5226 file.Write(" const GLsizei kNumElements = %d;\n" % count_param
)
5227 file.Write(" const size_t kExpectedCmdSize =\n")
5228 file.Write(" sizeof(cmd) + kNumElements * sizeof(%s) * %d;\n" %
5229 (func
.info
.data_type
, func
.info
.count
))
5230 file.Write(" void* next_cmd = cmd.Set(\n")
5232 for value
, arg
in enumerate(args
):
5233 file.Write(",\n static_cast<%s>(%d)" % (arg
.type, value
+ 1))
5234 file.Write(",\n data);\n")
5235 file.Write(" EXPECT_EQ(static_cast<uint32>(cmds::%s::kCmdId),\n" %
5237 file.Write(" cmd.header.command);\n")
5238 file.Write(" EXPECT_EQ(kExpectedCmdSize, cmd.header.size * 4u);\n")
5239 for value
, arg
in enumerate(args
):
5240 file.Write(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);\n" %
5241 (arg
.type, value
+ 1, arg
.name
))
5242 file.Write(" CheckBytesWrittenMatchesExpectedSize(\n")
5243 file.Write(" next_cmd, sizeof(cmd) +\n")
5244 file.Write(" RoundSizeToMultipleOfEntries(sizeof(data)));\n")
5245 file.Write(" // TODO(gman): Check that data was inserted;\n")
5250 class PUTXnHandler(TypeHandler
):
5251 """Handler for glUniform?f functions."""
5253 TypeHandler
.__init
__(self
)
5255 def WriteHandlerImplementation(self
, func
, file):
5256 """Overrriden from TypeHandler."""
5257 code
= """ %(type)s temp[%(count)s] = { %(values)s};
5258 Do%(name)sv(%(location)s, 1, &temp[0]);
5261 args
= func
.GetOriginalArgs()
5262 count
= int(func
.GetInfo('count'))
5263 num_args
= len(args
)
5264 for ii
in range(count
):
5265 values
+= "%s, " % args
[len(args
) - count
+ ii
].name
5269 'count': func
.GetInfo('count'),
5270 'type': func
.GetInfo('data_type'),
5271 'location': args
[0].name
,
5272 'args': func
.MakeOriginalArgString(""),
5276 def WriteServiceUnitTest(self
, func
, file):
5277 """Overrriden from TypeHandler."""
5279 TEST_F(%(test_name)s, %(name)sValidArgs) {
5280 EXPECT_CALL(*gl_, %(name)sv(%(local_args)s));
5281 SpecializedSetup<cmds::%(name)s, 0>(true);
5284 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5285 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5288 args
= func
.GetOriginalArgs()
5289 local_args
= "%s, 1, _" % args
[0].GetValidGLArg(func
, 0, 0)
5290 self
.WriteValidUnitTest(func
, file, valid_test
, {
5292 'count': func
.GetInfo('count'),
5293 'local_args': local_args
,
5297 TEST_F(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
5298 EXPECT_CALL(*gl_, %(name)sv(_, _, _).Times(0);
5299 SpecializedSetup<cmds::%(name)s, 0>(false);
5302 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
5305 self
.WriteInvalidUnitTest(func
, file, invalid_test
, {
5306 'name': func
.GetInfo('name'),
5307 'count': func
.GetInfo('count'),
5311 class GLcharHandler(CustomHandler
):
5312 """Handler for functions that pass a single string ."""
5315 CustomHandler
.__init
__(self
)
5317 def WriteImmediateCmdComputeSize(self
, func
, file):
5318 """Overrriden from TypeHandler."""
5319 file.Write(" static uint32 ComputeSize(uint32 data_size) {\n")
5320 file.Write(" return static_cast<uint32>(\n")
5321 file.Write(" sizeof(ValueType) + data_size); // NOLINT\n")
5324 def WriteImmediateCmdSetHeader(self
, func
, file):
5325 """Overrriden from TypeHandler."""
5327 void SetHeader(uint32 data_size) {
5328 header.SetCmdBySize<ValueType>(data_size);
5333 def WriteImmediateCmdInit(self
, func
, file):
5334 """Overrriden from TypeHandler."""
5335 last_arg
= func
.GetLastOriginalArg()
5336 args
= func
.GetCmdArgs()
5339 set_code
.append(" %s = _%s;" % (arg
.name
, arg
.name
))
5341 void Init(%(typed_args)s, uint32 _data_size) {
5342 SetHeader(_data_size);
5344 memcpy(ImmediateDataAddress(this), _%(last_arg)s, _data_size);
5349 "typed_args": func
.MakeTypedOriginalArgString("_"),
5350 "set_code": "\n".join(set_code
),
5351 "last_arg": last_arg
.name
5354 def WriteImmediateCmdSet(self
, func
, file):
5355 """Overrriden from TypeHandler."""
5356 last_arg
= func
.GetLastOriginalArg()
5357 file.Write(" void* Set(void* cmd%s, uint32 _data_size) {\n" %
5358 func
.MakeTypedOriginalArgString("_", True))
5359 file.Write(" static_cast<ValueType*>(cmd)->Init(%s, _data_size);\n" %
5360 func
.MakeOriginalArgString("_"))
5361 file.Write(" return NextImmediateCmdAddress<ValueType>("
5362 "cmd, _data_size);\n")
5366 def WriteImmediateCmdHelper(self
, func
, file):
5367 """Overrriden from TypeHandler."""
5368 code
= """ void %(name)s(%(typed_args)s) {
5369 const uint32 data_size = strlen(name);
5370 gles2::cmds::%(name)s* c =
5371 GetImmediateCmdSpace<gles2::cmds::%(name)s>(data_size);
5373 c->Init(%(args)s, data_size);
5380 "typed_args": func
.MakeTypedOriginalArgString(""),
5381 "args": func
.MakeOriginalArgString(""),
5385 def WriteImmediateFormatTest(self
, func
, file):
5386 """Overrriden from TypeHandler."""
5389 all_but_last_arg
= func
.GetCmdArgs()[:-1]
5390 for value
, arg
in enumerate(all_but_last_arg
):
5391 init_code
.append(" static_cast<%s>(%d)," % (arg
.type, value
+ 11))
5392 for value
, arg
in enumerate(all_but_last_arg
):
5393 check_code
.append(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);" %
5394 (arg
.type, value
+ 11, arg
.name
))
5396 TEST_F(GLES2FormatTest, %(func_name)s) {
5397 cmds::%(func_name)s& cmd = *GetBufferAs<cmds::%(func_name)s>();
5398 static const char* const test_str = \"test string\";
5399 void* next_cmd = cmd.Set(
5404 EXPECT_EQ(static_cast<uint32>(cmds::%(func_name)s::kCmdId),
5405 cmd.header.command);
5406 EXPECT_EQ(sizeof(cmd) +
5407 RoundSizeToMultipleOfEntries(strlen(test_str)),
5408 cmd.header.size * 4u);
5409 EXPECT_EQ(static_cast<char*>(next_cmd),
5410 reinterpret_cast<char*>(&cmd) + sizeof(cmd) +
5411 RoundSizeToMultipleOfEntries(strlen(test_str)));
5413 EXPECT_EQ(static_cast<uint32>(strlen(test_str)), cmd.data_size);
5414 EXPECT_EQ(0, memcmp(test_str, ImmediateDataAddress(&cmd), strlen(test_str)));
5417 sizeof(cmd) + RoundSizeToMultipleOfEntries(strlen(test_str)),
5418 sizeof(cmd) + strlen(test_str));
5423 'func_name': func
.name
,
5424 'init_code': "\n".join(init_code
),
5425 'check_code': "\n".join(check_code
),
5429 class GLcharNHandler(CustomHandler
):
5430 """Handler for functions that pass a single string with an optional len."""
5433 CustomHandler
.__init
__(self
)
5435 def InitFunction(self
, func
):
5436 """Overrriden from TypeHandler."""
5438 func
.AddCmdArg(Argument('bucket_id', 'GLuint'))
5440 def AddImmediateFunction(self
, generator
, func
):
5441 """Overrriden from TypeHandler."""
5444 def AddBucketFunction(self
, generator
, func
):
5445 """Overrriden from TypeHandler."""
5448 def WriteServiceImplementation(self
, func
, file):
5449 """Overrriden from TypeHandler."""
5450 file.Write("""error::Error GLES2DecoderImpl::Handle%(name)s(
5451 uint32 immediate_data_size, const gles2::cmds::%(name)s& c) {
5452 GLuint bucket_id = static_cast<GLuint>(c.%(bucket_id)s);
5453 Bucket* bucket = GetBucket(bucket_id);
5454 if (!bucket || bucket->size() == 0) {
5455 return error::kInvalidArguments;
5458 if (!bucket->GetAsString(&str)) {
5459 return error::kInvalidArguments;
5461 %(gl_func_name)s(0, str.c_str());
5462 return error::kNoError;
5467 'gl_func_name': func
.GetGLFunctionName(),
5468 'bucket_id': func
.cmd_args
[0].name
,
5472 class IsHandler(TypeHandler
):
5473 """Handler for glIs____ type and glGetError functions."""
5476 TypeHandler
.__init
__(self
)
5478 def InitFunction(self
, func
):
5479 """Overrriden from TypeHandler."""
5480 func
.AddCmdArg(Argument("result_shm_id", 'uint32'))
5481 func
.AddCmdArg(Argument("result_shm_offset", 'uint32'))
5482 if func
.GetInfo('result') == None:
5483 func
.AddInfo('result', ['uint32'])
5485 def WriteServiceUnitTest(self
, func
, file):
5486 """Overrriden from TypeHandler."""
5488 TEST_F(%(test_name)s, %(name)sValidArgs) {
5489 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
5490 SpecializedSetup<cmds::%(name)s, 0>(true);
5492 cmd.Init(%(args)s%(comma)sshared_memory_id_, shared_memory_offset_);
5493 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5494 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5498 if len(func
.GetOriginalArgs()):
5500 self
.WriteValidUnitTest(func
, file, valid_test
, {
5505 TEST_F(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
5506 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
5507 SpecializedSetup<cmds::%(name)s, 0>(false);
5509 cmd.Init(%(args)s%(comma)sshared_memory_id_, shared_memory_offset_);
5510 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
5513 self
.WriteInvalidUnitTest(func
, file, invalid_test
, {
5518 TEST_F(%(test_name)s, %(name)sInvalidArgsBadSharedMemoryId) {
5519 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
5520 SpecializedSetup<cmds::%(name)s, 0>(false);
5522 cmd.Init(%(args)s%(comma)skInvalidSharedMemoryId, shared_memory_offset_);
5523 EXPECT_EQ(error::kOutOfBounds, ExecuteCmd(cmd));
5524 cmd.Init(%(args)s%(comma)sshared_memory_id_, kInvalidSharedMemoryOffset);
5525 EXPECT_EQ(error::kOutOfBounds, ExecuteCmd(cmd));
5528 self
.WriteValidUnitTest(func
, file, invalid_test
, {
5532 def WriteServiceImplementation(self
, func
, file):
5533 """Overrriden from TypeHandler."""
5535 "error::Error GLES2DecoderImpl::Handle%s(\n" % func
.name
)
5537 " uint32 immediate_data_size, const gles2::cmds::%s& c) {\n" %
5539 args
= func
.GetOriginalArgs()
5541 arg
.WriteGetCode(file)
5543 code
= """ typedef cmds::%(func_name)s::Result Result;
5544 Result* result_dst = GetSharedMemoryAs<Result*>(
5545 c.result_shm_id, c.result_shm_offset, sizeof(*result_dst));
5547 return error::kOutOfBounds;
5550 file.Write(code
% {'func_name': func
.name
})
5551 func
.WriteHandlerValidation(file)
5552 file.Write(" *result_dst = %s(%s);\n" %
5553 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
5554 file.Write(" return error::kNoError;\n")
5558 def WriteGLES2Implementation(self
, func
, file):
5559 """Overrriden from TypeHandler."""
5560 impl_func
= func
.GetInfo('impl_func')
5561 if impl_func
== None or impl_func
== True:
5562 error_value
= func
.GetInfo("error_value") or "GL_FALSE"
5563 file.Write("%s GLES2Implementation::%s(%s) {\n" %
5564 (func
.return_type
, func
.original_name
,
5565 func
.MakeTypedOriginalArgString("")))
5566 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
5567 self
.WriteTraceEvent(func
, file)
5568 func
.WriteDestinationInitalizationValidation(file)
5569 self
.WriteClientGLCallLog(func
, file)
5570 file.Write(" typedef cmds::%s::Result Result;\n" % func
.name
)
5571 file.Write(" Result* result = GetResultAs<Result*>();\n")
5572 file.Write(" if (!result) {\n")
5573 file.Write(" return %s;\n" % error_value
)
5575 file.Write(" *result = 0;\n")
5576 arg_string
= func
.MakeOriginalArgString("")
5578 if len(arg_string
) > 0:
5581 " helper_->%s(%s%sGetResultShmId(), GetResultShmOffset());\n" %
5582 (func
.name
, arg_string
, comma
))
5583 file.Write(" WaitForCmd();\n")
5584 file.Write(" %s result_value = *result;\n" % func
.return_type
)
5585 file.Write(' GPU_CLIENT_LOG("returned " << result_value);\n')
5586 file.Write(" CheckGLError();\n")
5587 file.Write(" return result_value;\n")
5591 def WriteGLES2ImplementationUnitTest(self
, func
, file):
5592 """Overrriden from TypeHandler."""
5593 client_test
= func
.GetInfo('client_test')
5594 if client_test
== None or client_test
== True:
5596 TEST_F(GLES2ImplementationTest, %(name)s) {
5601 typedef cmds::%(name)s::Result Result;
5603 ExpectedMemoryInfo result1 =
5604 GetExpectedResultMemory(sizeof(cmds::%(name)s::Result));
5605 expected.cmd.Init(1, result1.id, result1.offset);
5607 EXPECT_CALL(*command_buffer(), OnFlush())
5608 .WillOnce(SetMemory(result1.ptr, uint32(1)))
5609 .RetiresOnSaturation();
5611 GLboolean result = gl_->%(name)s(1);
5612 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
5613 EXPECT_TRUE(result);
5621 class STRnHandler(TypeHandler
):
5622 """Handler for GetProgramInfoLog, GetShaderInfoLog, GetShaderSource, and
5623 GetTranslatedShaderSourceANGLE."""
5626 TypeHandler
.__init
__(self
)
5628 def InitFunction(self
, func
):
5629 """Overrriden from TypeHandler."""
5630 # remove all but the first cmd args.
5631 cmd_args
= func
.GetCmdArgs()
5633 func
.AddCmdArg(cmd_args
[0])
5634 # add on a bucket id.
5635 func
.AddCmdArg(Argument('bucket_id', 'uint32'))
5637 def WriteGLES2Implementation(self
, func
, file):
5638 """Overrriden from TypeHandler."""
5639 code_1
= """%(return_type)s GLES2Implementation::%(func_name)s(%(args)s) {
5640 GPU_CLIENT_SINGLE_THREAD_CHECK();
5642 code_2
= """ GPU_CLIENT_LOG("[" << GetLogPrefix()
5643 << "] gl%(func_name)s" << "("
5646 << static_cast<void*>(%(arg2)s) << ", "
5647 << static_cast<void*>(%(arg3)s) << ")");
5648 helper_->SetBucketSize(kResultBucketId, 0);
5649 helper_->%(func_name)s(%(id_name)s, kResultBucketId);
5651 GLsizei max_size = 0;
5652 if (GetBucketAsString(kResultBucketId, &str)) {
5655 std::min(static_cast<size_t>(%(bufsize_name)s) - 1, str.size());
5656 memcpy(%(dest_name)s, str.c_str(), max_size);
5657 %(dest_name)s[max_size] = '\\0';
5658 GPU_CLIENT_LOG("------\\n" << %(dest_name)s << "\\n------");
5661 if (%(length_name)s != NULL) {
5662 *%(length_name)s = max_size;
5667 args
= func
.GetOriginalArgs()
5669 'return_type': func
.return_type
,
5670 'func_name': func
.original_name
,
5671 'args': func
.MakeTypedOriginalArgString(""),
5672 'id_name': args
[0].name
,
5673 'bufsize_name': args
[1].name
,
5674 'length_name': args
[2].name
,
5675 'dest_name': args
[3].name
,
5676 'arg0': args
[0].name
,
5677 'arg1': args
[1].name
,
5678 'arg2': args
[2].name
,
5679 'arg3': args
[3].name
,
5681 file.Write(code_1
% str_args
)
5682 func
.WriteDestinationInitalizationValidation(file)
5683 file.Write(code_2
% str_args
)
5685 def WriteServiceUnitTest(self
, func
, file):
5686 """Overrriden from TypeHandler."""
5688 TEST_F(%(test_name)s, %(name)sValidArgs) {
5689 const char* kInfo = "hello";
5690 const uint32 kBucketId = 123;
5691 SpecializedSetup<cmds::%(name)s, 0>(true);
5693 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s))
5694 .WillOnce(DoAll(SetArgumentPointee<2>(strlen(kInfo)),
5695 SetArrayArgument<3>(kInfo, kInfo + strlen(kInfo) + 1)));
5698 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5699 CommonDecoder::Bucket* bucket = decoder_->GetBucket(kBucketId);
5700 ASSERT_TRUE(bucket != NULL);
5701 EXPECT_EQ(strlen(kInfo) + 1, bucket->size());
5702 EXPECT_EQ(0, memcmp(bucket->GetData(0, bucket->size()), kInfo,
5704 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5707 args
= func
.GetOriginalArgs()
5708 id_name
= args
[0].GetValidGLArg(func
, 0, 0)
5709 get_len_func
= func
.GetInfo('get_len_func')
5710 get_len_enum
= func
.GetInfo('get_len_enum')
5713 'get_len_func': get_len_func
,
5714 'get_len_enum': get_len_enum
,
5715 'gl_args': '%s, strlen(kInfo) + 1, _, _' %
5716 args
[0].GetValidGLArg(func
, 0, 0),
5717 'args': '%s, kBucketId' % args
[0].GetValidArg(func
, 0, 0),
5718 'expect_len_code': '',
5720 if get_len_func
and get_len_func
[0:2] == 'gl':
5721 sub
['expect_len_code'] = (
5722 " EXPECT_CALL(*gl_, %s(%s, %s, _))\n"
5723 " .WillOnce(SetArgumentPointee<2>(strlen(kInfo) + 1));") % (
5724 get_len_func
[2:], id_name
, get_len_enum
)
5725 self
.WriteValidUnitTest(func
, file, valid_test
, sub
)
5728 TEST_F(%(test_name)s, %(name)sInvalidArgs) {
5729 const uint32 kBucketId = 123;
5730 EXPECT_CALL(*gl_, %(gl_func_name)s(_, _, _, _))
5733 cmd.Init(kInvalidClientId, kBucketId);
5734 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5735 EXPECT_EQ(GL_INVALID_VALUE, GetGLError());
5738 self
.WriteValidUnitTest(func
, file, invalid_test
)
5740 def WriteServiceImplementation(self
, func
, file):
5741 """Overrriden from TypeHandler."""
5745 class FunctionInfo(object):
5746 """Holds info about a function."""
5748 def __init__(self
, info
, type_handler
):
5750 setattr(self
, key
, info
[key
])
5751 self
.type_handler
= type_handler
5752 if not 'type' in info
:
5756 class Argument(object):
5757 """A class that represents a function argument."""
5762 'GLintptr': 'int32',
5764 'GLsizeiptr': 'int32',
5766 'GLclampf': 'float',
5768 need_validation_
= ['GLsizei*', 'GLboolean*', 'GLenum*', 'GLint*']
5770 def __init__(self
, name
, type):
5772 self
.optional
= type.endswith("Optional*")
5774 type = type[:-9] + "*"
5777 if type in self
.cmd_type_map_
:
5778 self
.cmd_type
= self
.cmd_type_map_
[type]
5780 self
.cmd_type
= 'uint32'
5782 def IsPointer(self
):
5783 """Returns true if argument is a pointer."""
5786 def AddCmdArgs(self
, args
):
5787 """Adds command arguments for this argument to the given list."""
5788 return args
.append(self
)
5790 def AddInitArgs(self
, args
):
5791 """Adds init arguments for this argument to the given list."""
5792 return args
.append(self
)
5794 def GetValidArg(self
, func
, offset
, index
):
5795 """Gets a valid value for this argument."""
5796 valid_arg
= func
.GetValidArg(offset
)
5797 if valid_arg
!= None:
5799 return str(offset
+ 1)
5801 def GetValidClientSideArg(self
, func
, offset
, index
):
5802 """Gets a valid value for this argument."""
5803 return str(offset
+ 1)
5805 def GetValidClientSideCmdArg(self
, func
, offset
, index
):
5806 """Gets a valid value for this argument."""
5807 return str(offset
+ 1)
5809 def GetValidGLArg(self
, func
, offset
, index
):
5810 """Gets a valid GL value for this argument."""
5811 valid_arg
= func
.GetValidArg(offset
)
5812 if valid_arg
!= None:
5814 return str(offset
+ 1)
5816 def GetNumInvalidValues(self
, func
):
5817 """returns the number of invalid values to be tested."""
5820 def GetInvalidArg(self
, offset
, index
):
5821 """returns an invalid value and expected parse result by index."""
5822 return ("---ERROR0---", "---ERROR2---", None)
5824 def GetLogArg(self
):
5825 """Get argument appropriate for LOG macro."""
5826 if self
.type == 'GLboolean':
5827 return 'GLES2Util::GetStringBool(%s)' % self
.name
5828 if self
.type == 'GLenum':
5829 return 'GLES2Util::GetStringEnum(%s)' % self
.name
5832 def WriteGetCode(self
, file):
5833 """Writes the code to get an argument from a command structure."""
5834 file.Write(" %s %s = static_cast<%s>(c.%s);\n" %
5835 (self
.type, self
.name
, self
.type, self
.name
))
5837 def WriteValidationCode(self
, file, func
):
5838 """Writes the validation code for an argument."""
5841 def WriteClientSideValidationCode(self
, file, func
):
5842 """Writes the validation code for an argument."""
5845 def WriteDestinationInitalizationValidation(self
, file, func
):
5846 """Writes the client side destintion initialization validation."""
5849 def WriteDestinationInitalizationValidatationIfNeeded(self
, file, func
):
5850 """Writes the client side destintion initialization validation if needed."""
5851 parts
= self
.type.split(" ")
5854 if parts
[0] in self
.need_validation_
:
5856 " GPU_CLIENT_VALIDATE_DESTINATION_%sINITALIZATION(%s, %s);\n" %
5857 ("OPTIONAL_" if self
.optional
else "", self
.type[:-1], self
.name
))
5860 def WriteGetAddress(self
, file):
5861 """Writes the code to get the address this argument refers to."""
5864 def GetImmediateVersion(self
):
5865 """Gets the immediate version of this argument."""
5868 def GetBucketVersion(self
):
5869 """Gets the bucket version of this argument."""
5873 class BoolArgument(Argument
):
5874 """class for GLboolean"""
5876 def __init__(self
, name
, type):
5877 Argument
.__init
__(self
, name
, 'GLboolean')
5879 def GetValidArg(self
, func
, offset
, index
):
5880 """Gets a valid value for this argument."""
5883 def GetValidClientSideArg(self
, func
, offset
, index
):
5884 """Gets a valid value for this argument."""
5887 def GetValidClientSideCmdArg(self
, func
, offset
, index
):
5888 """Gets a valid value for this argument."""
5891 def GetValidGLArg(self
, func
, offset
, index
):
5892 """Gets a valid GL value for this argument."""
5896 class UniformLocationArgument(Argument
):
5897 """class for uniform locations."""
5899 def __init__(self
, name
):
5900 Argument
.__init
__(self
, name
, "GLint")
5902 def WriteGetCode(self
, file):
5903 """Writes the code to get an argument from a command structure."""
5904 code
= """ %s %s = static_cast<%s>(c.%s);
5906 file.Write(code
% (self
.type, self
.name
, self
.type, self
.name
))
5908 def GetValidArg(self
, func
, offset
, index
):
5909 """Gets a valid value for this argument."""
5910 return "%d" % (offset
+ 1)
5913 class DataSizeArgument(Argument
):
5914 """class for data_size which Bucket commands do not need."""
5916 def __init__(self
, name
):
5917 Argument
.__init
__(self
, name
, "uint32")
5919 def GetBucketVersion(self
):
5923 class SizeArgument(Argument
):
5924 """class for GLsizei and GLsizeiptr."""
5926 def __init__(self
, name
, type):
5927 Argument
.__init
__(self
, name
, type)
5929 def GetNumInvalidValues(self
, func
):
5930 """overridden from Argument."""
5931 if func
.is_immediate
:
5935 def GetInvalidArg(self
, offset
, index
):
5936 """overridden from Argument."""
5937 return ("-1", "kNoError", "GL_INVALID_VALUE")
5939 def WriteValidationCode(self
, file, func
):
5940 """overridden from Argument."""
5941 file.Write(" if (%s < 0) {\n" % self
.name
)
5943 " LOCAL_SET_GL_ERROR(GL_INVALID_VALUE, \"gl%s\", \"%s < 0\");\n" %
5944 (func
.original_name
, self
.name
))
5945 file.Write(" return error::kNoError;\n")
5948 def WriteClientSideValidationCode(self
, file, func
):
5949 """overridden from Argument."""
5950 file.Write(" if (%s < 0) {\n" % self
.name
)
5952 " SetGLError(GL_INVALID_VALUE, \"gl%s\", \"%s < 0\");\n" %
5953 (func
.original_name
, self
.name
))
5954 file.Write(" return;\n")
5958 class SizeNotNegativeArgument(SizeArgument
):
5959 """class for GLsizeiNotNegative. It's NEVER allowed to be negative"""
5961 def __init__(self
, name
, type, gl_type
):
5962 SizeArgument
.__init
__(self
, name
, gl_type
)
5964 def GetInvalidArg(self
, offset
, index
):
5965 """overridden from SizeArgument."""
5966 return ("-1", "kOutOfBounds", "GL_NO_ERROR")
5968 def WriteValidationCode(self
, file, func
):
5969 """overridden from SizeArgument."""
5973 class EnumBaseArgument(Argument
):
5974 """Base class for EnumArgument, IntArgument and ValidatedBoolArgument"""
5976 def __init__(self
, name
, gl_type
, type, gl_error
):
5977 Argument
.__init
__(self
, name
, gl_type
)
5979 self
.local_type
= type
5980 self
.gl_error
= gl_error
5981 name
= type[len(gl_type
):]
5982 self
.type_name
= name
5983 self
.enum_info
= _ENUM_LISTS
[name
]
5985 def WriteValidationCode(self
, file, func
):
5986 file.Write(" if (!validators_->%s.IsValid(%s)) {\n" %
5987 (ToUnderscore(self
.type_name
), self
.name
))
5988 if self
.gl_error
== "GL_INVALID_ENUM":
5990 " LOCAL_SET_GL_ERROR_INVALID_ENUM(\"gl%s\", %s, \"%s\");\n" %
5991 (func
.original_name
, self
.name
, self
.name
))
5994 " LOCAL_SET_GL_ERROR(%s, \"gl%s\", \"%s %s\");\n" %
5995 (self
.gl_error
, func
.original_name
, self
.name
, self
.gl_error
))
5996 file.Write(" return error::kNoError;\n")
5999 def GetValidArg(self
, func
, offset
, index
):
6000 valid_arg
= func
.GetValidArg(offset
)
6001 if valid_arg
!= None:
6003 if 'valid' in self
.enum_info
:
6004 valid
= self
.enum_info
['valid']
6005 num_valid
= len(valid
)
6006 if index
>= num_valid
:
6007 index
= num_valid
- 1
6009 return str(offset
+ 1)
6011 def GetValidClientSideArg(self
, func
, offset
, index
):
6012 """Gets a valid value for this argument."""
6013 return self
.GetValidArg(func
, offset
, index
)
6015 def GetValidClientSideCmdArg(self
, func
, offset
, index
):
6016 """Gets a valid value for this argument."""
6017 return self
.GetValidArg(func
, offset
, index
)
6019 def GetValidGLArg(self
, func
, offset
, index
):
6020 """Gets a valid value for this argument."""
6021 return self
.GetValidArg(func
, offset
, index
)
6023 def GetNumInvalidValues(self
, func
):
6024 """returns the number of invalid values to be tested."""
6025 if 'invalid' in self
.enum_info
:
6026 invalid
= self
.enum_info
['invalid']
6030 def GetInvalidArg(self
, offset
, index
):
6031 """returns an invalid value by index."""
6032 if 'invalid' in self
.enum_info
:
6033 invalid
= self
.enum_info
['invalid']
6034 num_invalid
= len(invalid
)
6035 if index
>= num_invalid
:
6036 index
= num_invalid
- 1
6037 return (invalid
[index
], "kNoError", self
.gl_error
)
6038 return ("---ERROR1---", "kNoError", self
.gl_error
)
6041 class EnumArgument(EnumBaseArgument
):
6042 """A class that represents a GLenum argument"""
6044 def __init__(self
, name
, type):
6045 EnumBaseArgument
.__init
__(self
, name
, "GLenum", type, "GL_INVALID_ENUM")
6047 def GetLogArg(self
):
6048 """Overridden from Argument."""
6049 return ("GLES2Util::GetString%s(%s)" %
6050 (self
.type_name
, self
.name
))
6053 class IntArgument(EnumBaseArgument
):
6054 """A class for a GLint argument that can only except specific values.
6056 For example glTexImage2D takes a GLint for its internalformat
6057 argument instead of a GLenum.
6060 def __init__(self
, name
, type):
6061 EnumBaseArgument
.__init
__(self
, name
, "GLint", type, "GL_INVALID_VALUE")
6064 class ValidatedBoolArgument(EnumBaseArgument
):
6065 """A class for a GLboolean argument that can only except specific values.
6067 For example glUniformMatrix takes a GLboolean for it's transpose but it
6071 def __init__(self
, name
, type):
6072 EnumBaseArgument
.__init
__(self
, name
, "GLboolean", type, "GL_INVALID_VALUE")
6074 def GetLogArg(self
):
6075 """Overridden from Argument."""
6076 return 'GLES2Util::GetStringBool(%s)' % self
.name
6079 class ImmediatePointerArgument(Argument
):
6080 """A class that represents an immediate argument to a function.
6082 An immediate argument is one where the data follows the command.
6085 def __init__(self
, name
, type):
6086 Argument
.__init
__(self
, name
, type)
6088 def AddCmdArgs(self
, args
):
6089 """Overridden from Argument."""
6092 def WriteGetCode(self
, file):
6093 """Overridden from Argument."""
6095 " %s %s = GetImmediateDataAs<%s>(\n" %
6096 (self
.type, self
.name
, self
.type))
6097 file.Write(" c, data_size, immediate_data_size);\n")
6099 def WriteValidationCode(self
, file, func
):
6100 """Overridden from Argument."""
6101 file.Write(" if (%s == NULL) {\n" % self
.name
)
6102 file.Write(" return error::kOutOfBounds;\n")
6105 def GetImmediateVersion(self
):
6106 """Overridden from Argument."""
6109 def WriteDestinationInitalizationValidation(self
, file, func
):
6110 """Overridden from Argument."""
6111 self
.WriteDestinationInitalizationValidatationIfNeeded(file, func
)
6113 def GetLogArg(self
):
6114 """Overridden from Argument."""
6115 return "static_cast<const void*>(%s)" % self
.name
6118 class BucketPointerArgument(Argument
):
6119 """A class that represents an bucket argument to a function."""
6121 def __init__(self
, name
, type):
6122 Argument
.__init
__(self
, name
, type)
6124 def AddCmdArgs(self
, args
):
6125 """Overridden from Argument."""
6128 def WriteGetCode(self
, file):
6129 """Overridden from Argument."""
6131 " %s %s = bucket->GetData(0, data_size);\n" %
6132 (self
.type, self
.name
))
6134 def WriteValidationCode(self
, file, func
):
6135 """Overridden from Argument."""
6138 def GetImmediateVersion(self
):
6139 """Overridden from Argument."""
6142 def WriteDestinationInitalizationValidation(self
, file, func
):
6143 """Overridden from Argument."""
6144 self
.WriteDestinationInitalizationValidatationIfNeeded(file, func
)
6146 def GetLogArg(self
):
6147 """Overridden from Argument."""
6148 return "static_cast<const void*>(%s)" % self
.name
6151 class PointerArgument(Argument
):
6152 """A class that represents a pointer argument to a function."""
6154 def __init__(self
, name
, type):
6155 Argument
.__init
__(self
, name
, type)
6157 def IsPointer(self
):
6158 """Returns true if argument is a pointer."""
6161 def GetValidArg(self
, func
, offset
, index
):
6162 """Overridden from Argument."""
6163 return "shared_memory_id_, shared_memory_offset_"
6165 def GetValidGLArg(self
, func
, offset
, index
):
6166 """Overridden from Argument."""
6167 return "reinterpret_cast<%s>(shared_memory_address_)" % self
.type
6169 def GetNumInvalidValues(self
, func
):
6170 """Overridden from Argument."""
6173 def GetInvalidArg(self
, offset
, index
):
6174 """Overridden from Argument."""
6176 return ("kInvalidSharedMemoryId, 0", "kOutOfBounds", None)
6178 return ("shared_memory_id_, kInvalidSharedMemoryOffset",
6179 "kOutOfBounds", None)
6181 def GetLogArg(self
):
6182 """Overridden from Argument."""
6183 return "static_cast<const void*>(%s)" % self
.name
6185 def AddCmdArgs(self
, args
):
6186 """Overridden from Argument."""
6187 args
.append(Argument("%s_shm_id" % self
.name
, 'uint32'))
6188 args
.append(Argument("%s_shm_offset" % self
.name
, 'uint32'))
6190 def WriteGetCode(self
, file):
6191 """Overridden from Argument."""
6193 " %s %s = GetSharedMemoryAs<%s>(\n" %
6194 (self
.type, self
.name
, self
.type))
6196 " c.%s_shm_id, c.%s_shm_offset, data_size);\n" %
6197 (self
.name
, self
.name
))
6199 def WriteGetAddress(self
, file):
6200 """Overridden from Argument."""
6202 " %s %s = GetSharedMemoryAs<%s>(\n" %
6203 (self
.type, self
.name
, self
.type))
6205 " %s_shm_id, %s_shm_offset, %s_size);\n" %
6206 (self
.name
, self
.name
, self
.name
))
6208 def WriteValidationCode(self
, file, func
):
6209 """Overridden from Argument."""
6210 file.Write(" if (%s == NULL) {\n" % self
.name
)
6211 file.Write(" return error::kOutOfBounds;\n")
6214 def GetImmediateVersion(self
):
6215 """Overridden from Argument."""
6216 return ImmediatePointerArgument(self
.name
, self
.type)
6218 def GetBucketVersion(self
):
6219 """Overridden from Argument."""
6220 if self
.type == "const char*":
6221 return InputStringBucketArgument(self
.name
, self
.type)
6222 return BucketPointerArgument(self
.name
, self
.type)
6224 def WriteDestinationInitalizationValidation(self
, file, func
):
6225 """Overridden from Argument."""
6226 self
.WriteDestinationInitalizationValidatationIfNeeded(file, func
)
6229 class InputStringBucketArgument(Argument
):
6230 """An string input argument where the string is passed in a bucket."""
6232 def __init__(self
, name
, type):
6233 Argument
.__init
__(self
, name
+ "_bucket_id", "uint32")
6235 def WriteGetCode(self
, file):
6236 """Overridden from Argument."""
6238 Bucket* %(name)s_bucket = GetBucket(c.%(name)s);
6239 if (!%(name)s_bucket) {
6240 return error::kInvalidArguments;
6242 std::string %(name)s_str;
6243 if (!%(name)s_bucket->GetAsString(&%(name)s_str)) {
6244 return error::kInvalidArguments;
6246 const char* %(name)s = %(name)s_str.c_str();
6252 def GetValidArg(self
, func
, offset
, index
):
6253 return "kNameBucketId"
6255 def GetValidGLArg(self
, func
, offset
, index
):
6259 class NonImmediatePointerArgument(PointerArgument
):
6260 """A pointer argument that stays a pointer even in an immediate cmd."""
6262 def __init__(self
, name
, type):
6263 PointerArgument
.__init
__(self
, name
, type)
6265 def IsPointer(self
):
6266 """Returns true if argument is a pointer."""
6269 def GetImmediateVersion(self
):
6270 """Overridden from Argument."""
6274 class ResourceIdArgument(Argument
):
6275 """A class that represents a resource id argument to a function."""
6277 def __init__(self
, name
, type):
6278 match
= re
.match("(GLid\w+)", type)
6279 self
.resource_type
= match
.group(1)[4:]
6280 type = type.replace(match
.group(1), "GLuint")
6281 Argument
.__init
__(self
, name
, type)
6283 def WriteGetCode(self
, file):
6284 """Overridden from Argument."""
6285 file.Write(" %s %s = c.%s;\n" % (self
.type, self
.name
, self
.name
))
6287 def GetValidArg(self
, func
, offset
, index
):
6288 return "client_%s_id_" % self
.resource_type
.lower()
6290 def GetValidGLArg(self
, func
, offset
, index
):
6291 return "kService%sId" % self
.resource_type
6294 class ResourceIdBindArgument(Argument
):
6295 """Represents a resource id argument to a bind function."""
6297 def __init__(self
, name
, type):
6298 match
= re
.match("(GLidBind\w+)", type)
6299 self
.resource_type
= match
.group(1)[8:]
6300 type = type.replace(match
.group(1), "GLuint")
6301 Argument
.__init
__(self
, name
, type)
6303 def WriteGetCode(self
, file):
6304 """Overridden from Argument."""
6305 code
= """ %(type)s %(name)s = c.%(name)s;
6307 file.Write(code
% {'type': self
.type, 'name': self
.name
})
6309 def GetValidArg(self
, func
, offset
, index
):
6310 return "client_%s_id_" % self
.resource_type
.lower()
6312 def GetValidGLArg(self
, func
, offset
, index
):
6313 return "kService%sId" % self
.resource_type
6316 class ResourceIdZeroArgument(Argument
):
6317 """Represents a resource id argument to a function that can be zero."""
6319 def __init__(self
, name
, type):
6320 match
= re
.match("(GLidZero\w+)", type)
6321 self
.resource_type
= match
.group(1)[8:]
6322 type = type.replace(match
.group(1), "GLuint")
6323 Argument
.__init
__(self
, name
, type)
6325 def WriteGetCode(self
, file):
6326 """Overridden from Argument."""
6327 file.Write(" %s %s = c.%s;\n" % (self
.type, self
.name
, self
.name
))
6329 def GetValidArg(self
, func
, offset
, index
):
6330 return "client_%s_id_" % self
.resource_type
.lower()
6332 def GetValidGLArg(self
, func
, offset
, index
):
6333 return "kService%sId" % self
.resource_type
6335 def GetNumInvalidValues(self
, func
):
6336 """returns the number of invalid values to be tested."""
6339 def GetInvalidArg(self
, offset
, index
):
6340 """returns an invalid value by index."""
6341 return ("kInvalidClientId", "kNoError", "GL_INVALID_VALUE")
6344 class Function(object):
6345 """A class that represents a function."""
6347 def __init__(self
, original_name
, name
, info
, return_type
, original_args
,
6348 args_for_cmds
, cmd_args
, init_args
, num_pointer_args
):
6350 self
.original_name
= original_name
6352 self
.type_handler
= info
.type_handler
6353 self
.return_type
= return_type
6354 self
.original_args
= original_args
6355 self
.num_pointer_args
= num_pointer_args
6356 self
.can_auto_generate
= num_pointer_args
== 0 and return_type
== "void"
6357 self
.cmd_args
= cmd_args
6358 self
.init_args
= init_args
6360 self
.args_for_cmds
= args_for_cmds
6361 self
.is_immediate
= False
6363 def IsType(self
, type_name
):
6364 """Returns true if function is a certain type."""
6365 return self
.info
.type == type_name
6367 def InitFunction(self
):
6368 """Calls the init function for the type handler."""
6369 self
.type_handler
.InitFunction(self
)
6371 def GetInfo(self
, name
):
6372 """Returns a value from the function info for this function."""
6373 if hasattr(self
.info
, name
):
6374 return getattr(self
.info
, name
)
6377 def GetValidArg(self
, index
):
6378 """Gets a valid arg from the function info if one exists."""
6379 valid_args
= self
.GetInfo('valid_args')
6380 if valid_args
and str(index
) in valid_args
:
6381 return valid_args
[str(index
)]
6384 def AddInfo(self
, name
, value
):
6386 setattr(self
.info
, name
, value
)
6388 def IsCoreGLFunction(self
):
6389 return (not self
.GetInfo('extension') and
6390 not self
.GetInfo('pepper_interface'))
6392 def InPepperInterface(self
, interface
):
6393 ext
= self
.GetInfo('pepper_interface')
6394 if not interface
.GetName():
6395 return self
.IsCoreGLFunction()
6396 return ext
== interface
.GetName()
6398 def InAnyPepperExtension(self
):
6399 return self
.IsCoreGLFunction() or self
.GetInfo('pepper_interface')
6401 def GetGLFunctionName(self
):
6402 """Gets the function to call to execute GL for this command."""
6403 if self
.GetInfo('decoder_func'):
6404 return self
.GetInfo('decoder_func')
6405 return "gl%s" % self
.original_name
6407 def GetGLTestFunctionName(self
):
6408 gl_func_name
= self
.GetInfo('gl_test_func')
6409 if gl_func_name
== None:
6410 gl_func_name
= self
.GetGLFunctionName()
6411 if gl_func_name
.startswith("gl"):
6412 gl_func_name
= gl_func_name
[2:]
6414 gl_func_name
= self
.original_name
6417 def AddCmdArg(self
, arg
):
6418 """Adds a cmd argument to this function."""
6419 self
.cmd_args
.append(arg
)
6421 def GetCmdArgs(self
):
6422 """Gets the command args for this function."""
6423 return self
.cmd_args
6425 def ClearCmdArgs(self
):
6426 """Clears the command args for this function."""
6429 def GetInitArgs(self
):
6430 """Gets the init args for this function."""
6431 return self
.init_args
6433 def GetOriginalArgs(self
):
6434 """Gets the original arguments to this function."""
6435 return self
.original_args
6437 def GetLastOriginalArg(self
):
6438 """Gets the last original argument to this function."""
6439 return self
.original_args
[len(self
.original_args
) - 1]
6441 def __MaybePrependComma(self
, arg_string
, add_comma
):
6442 """Adds a comma if arg_string is not empty and add_comma is true."""
6444 if add_comma
and len(arg_string
):
6446 return "%s%s" % (comma
, arg_string
)
6448 def MakeTypedOriginalArgString(self
, prefix
, add_comma
= False):
6449 """Gets a list of arguments as they are in GL."""
6450 args
= self
.GetOriginalArgs()
6451 arg_string
= ", ".join(
6452 ["%s %s%s" % (arg
.type, prefix
, arg
.name
) for arg
in args
])
6453 return self
.__MaybePrependComma
(arg_string
, add_comma
)
6455 def MakeOriginalArgString(self
, prefix
, add_comma
= False, separator
= ", "):
6456 """Gets the list of arguments as they are in GL."""
6457 args
= self
.GetOriginalArgs()
6458 arg_string
= separator
.join(
6459 ["%s%s" % (prefix
, arg
.name
) for arg
in args
])
6460 return self
.__MaybePrependComma
(arg_string
, add_comma
)
6462 def MakeTypedPepperArgString(self
, prefix
):
6463 """Gets a list of arguments as they need to be for Pepper."""
6464 if self
.GetInfo("pepper_args"):
6465 return self
.GetInfo("pepper_args")
6467 return self
.MakeTypedOriginalArgString(prefix
, False)
6469 def GetPepperName(self
):
6470 if self
.GetInfo("pepper_name"):
6471 return self
.GetInfo("pepper_name")
6474 def MakeTypedCmdArgString(self
, prefix
, add_comma
= False):
6475 """Gets a typed list of arguments as they need to be for command buffers."""
6476 args
= self
.GetCmdArgs()
6477 arg_string
= ", ".join(
6478 ["%s %s%s" % (arg
.type, prefix
, arg
.name
) for arg
in args
])
6479 return self
.__MaybePrependComma
(arg_string
, add_comma
)
6481 def MakeCmdArgString(self
, prefix
, add_comma
= False):
6482 """Gets the list of arguments as they need to be for command buffers."""
6483 args
= self
.GetCmdArgs()
6484 arg_string
= ", ".join(
6485 ["%s%s" % (prefix
, arg
.name
) for arg
in args
])
6486 return self
.__MaybePrependComma
(arg_string
, add_comma
)
6488 def MakeTypedInitString(self
, prefix
, add_comma
= False):
6489 """Gets a typed list of arguments as they need to be for cmd Init/Set."""
6490 args
= self
.GetInitArgs()
6491 arg_string
= ", ".join(
6492 ["%s %s%s" % (arg
.type, prefix
, arg
.name
) for arg
in args
])
6493 return self
.__MaybePrependComma
(arg_string
, add_comma
)
6495 def MakeInitString(self
, prefix
, add_comma
= False):
6496 """Gets the list of arguments as they need to be for cmd Init/Set."""
6497 args
= self
.GetInitArgs()
6498 arg_string
= ", ".join(
6499 ["%s%s" % (prefix
, arg
.name
) for arg
in args
])
6500 return self
.__MaybePrependComma
(arg_string
, add_comma
)
6502 def MakeLogArgString(self
):
6503 """Makes a string of the arguments for the LOG macros"""
6504 args
= self
.GetOriginalArgs()
6505 return ' << ", " << '.join([arg
.GetLogArg() for arg
in args
])
6507 def WriteCommandDescription(self
, file):
6508 """Writes a description of the command."""
6509 file.Write("//! Command that corresponds to gl%s.\n" % self
.original_name
)
6511 def WriteHandlerValidation(self
, file):
6512 """Writes validation code for the function."""
6513 for arg
in self
.GetOriginalArgs():
6514 arg
.WriteValidationCode(file, self
)
6515 self
.WriteValidationCode(file)
6517 def WriteHandlerImplementation(self
, file):
6518 """Writes the handler implementation for this command."""
6519 self
.type_handler
.WriteHandlerImplementation(self
, file)
6521 def WriteValidationCode(self
, file):
6522 """Writes the validation code for a command."""
6525 def WriteCmdFlag(self
, file):
6526 """Writes the cmd cmd_flags constant."""
6528 trace_level
= 3 # By default trace only at the highest level
6529 if hasattr(self
.info
, 'trace_level'):
6530 if (self
.info
.trace_level
< 0) or (self
.info
.trace_level
> 3):
6531 raise KeyError("Unhandled trace_level: %d" % self
.info
.trace_level
)
6532 trace_level
= self
.info
.trace_level
6534 flags
.append('CMD_FLAG_SET_TRACE_LEVEL(%d)' % trace_level
)
6537 cmd_flags
= ' | '.join(flags
)
6541 file.Write(" static const uint8 cmd_flags = %s;\n" % cmd_flags
)
6544 def WriteCmdArgFlag(self
, file):
6545 """Writes the cmd kArgFlags constant."""
6546 file.Write(" static const cmd::ArgFlags kArgFlags = cmd::kFixed;\n")
6548 def WriteCmdComputeSize(self
, file):
6549 """Writes the ComputeSize function for the command."""
6550 file.Write(" static uint32 ComputeSize() {\n")
6552 " return static_cast<uint32>(sizeof(ValueType)); // NOLINT\n")
6556 def WriteCmdSetHeader(self
, file):
6557 """Writes the cmd's SetHeader function."""
6558 file.Write(" void SetHeader() {\n")
6559 file.Write(" header.SetCmd<ValueType>();\n")
6563 def WriteCmdInit(self
, file):
6564 """Writes the cmd's Init function."""
6565 file.Write(" void Init(%s) {\n" % self
.MakeTypedCmdArgString("_"))
6566 file.Write(" SetHeader();\n")
6567 args
= self
.GetCmdArgs()
6569 file.Write(" %s = _%s;\n" % (arg
.name
, arg
.name
))
6573 def WriteCmdSet(self
, file):
6574 """Writes the cmd's Set function."""
6575 copy_args
= self
.MakeCmdArgString("_", False)
6576 file.Write(" void* Set(void* cmd%s) {\n" %
6577 self
.MakeTypedCmdArgString("_", True))
6578 file.Write(" static_cast<ValueType*>(cmd)->Init(%s);\n" % copy_args
)
6579 file.Write(" return NextCmdAddress<ValueType>(cmd);\n")
6583 def WriteStruct(self
, file):
6584 self
.type_handler
.WriteStruct(self
, file)
6586 def WriteDocs(self
, file):
6587 self
.type_handler
.WriteDocs(self
, file)
6589 def WriteCmdHelper(self
, file):
6590 """Writes the cmd's helper."""
6591 self
.type_handler
.WriteCmdHelper(self
, file)
6593 def WriteServiceImplementation(self
, file):
6594 """Writes the service implementation for a command."""
6595 self
.type_handler
.WriteServiceImplementation(self
, file)
6597 def WriteServiceUnitTest(self
, file):
6598 """Writes the service implementation for a command."""
6599 self
.type_handler
.WriteServiceUnitTest(self
, file)
6601 def WriteGLES2CLibImplementation(self
, file):
6602 """Writes the GLES2 C Lib Implemention."""
6603 self
.type_handler
.WriteGLES2CLibImplementation(self
, file)
6605 def WriteGLES2InterfaceHeader(self
, file):
6606 """Writes the GLES2 Interface declaration."""
6607 self
.type_handler
.WriteGLES2InterfaceHeader(self
, file)
6609 def WriteGLES2InterfaceStub(self
, file):
6610 """Writes the GLES2 Interface Stub declaration."""
6611 self
.type_handler
.WriteGLES2InterfaceStub(self
, file)
6613 def WriteGLES2InterfaceStubImpl(self
, file):
6614 """Writes the GLES2 Interface Stub declaration."""
6615 self
.type_handler
.WriteGLES2InterfaceStubImpl(self
, file)
6617 def WriteGLES2ImplementationHeader(self
, file):
6618 """Writes the GLES2 Implemention declaration."""
6619 self
.type_handler
.WriteGLES2ImplementationHeader(self
, file)
6621 def WriteGLES2Implementation(self
, file):
6622 """Writes the GLES2 Implemention definition."""
6623 self
.type_handler
.WriteGLES2Implementation(self
, file)
6625 def WriteGLES2TraceImplementationHeader(self
, file):
6626 """Writes the GLES2 Trace Implemention declaration."""
6627 self
.type_handler
.WriteGLES2TraceImplementationHeader(self
, file)
6629 def WriteGLES2TraceImplementation(self
, file):
6630 """Writes the GLES2 Trace Implemention definition."""
6631 self
.type_handler
.WriteGLES2TraceImplementation(self
, file)
6633 def WriteGLES2Header(self
, file):
6634 """Writes the GLES2 Implemention unit test."""
6635 self
.type_handler
.WriteGLES2Header(self
, file)
6637 def WriteGLES2ImplementationUnitTest(self
, file):
6638 """Writes the GLES2 Implemention unit test."""
6639 self
.type_handler
.WriteGLES2ImplementationUnitTest(self
, file)
6641 def WriteDestinationInitalizationValidation(self
, file):
6642 """Writes the client side destintion initialization validation."""
6643 self
.type_handler
.WriteDestinationInitalizationValidation(self
, file)
6645 def WriteFormatTest(self
, file):
6646 """Writes the cmd's format test."""
6647 self
.type_handler
.WriteFormatTest(self
, file)
6650 class PepperInterface(object):
6651 """A class that represents a function."""
6653 def __init__(self
, info
):
6654 self
.name
= info
["name"]
6655 self
.dev
= info
["dev"]
6660 def GetInterfaceName(self
):
6664 upperint
= "_" + self
.name
.upper()
6667 return "PPB_OPENGLES2%s%s_INTERFACE" % (upperint
, dev
)
6669 def GetInterfaceString(self
):
6673 return "PPB_OpenGLES2%s%s" % (self
.name
, dev
)
6675 def GetStructName(self
):
6679 return "PPB_OpenGLES2%s%s" % (self
.name
, dev
)
6682 class ImmediateFunction(Function
):
6683 """A class that represnets an immediate function command."""
6685 def __init__(self
, func
):
6687 for arg
in func
.GetOriginalArgs():
6688 new_arg
= arg
.GetImmediateVersion()
6690 new_args
.append(new_arg
)
6693 new_args_for_cmds
= []
6694 for arg
in func
.args_for_cmds
:
6695 new_arg
= arg
.GetImmediateVersion()
6697 new_args_for_cmds
.append(new_arg
)
6698 new_arg
.AddCmdArgs(cmd_args
)
6701 for arg
in new_args_for_cmds
:
6702 arg
.AddInitArgs(new_init_args
)
6707 "%sImmediate" % func
.name
,
6715 self
.is_immediate
= True
6717 def WriteCommandDescription(self
, file):
6718 """Overridden from Function"""
6719 file.Write("//! Immediate version of command that corresponds to gl%s.\n" %
6722 def WriteServiceImplementation(self
, file):
6723 """Overridden from Function"""
6724 self
.type_handler
.WriteImmediateServiceImplementation(self
, file)
6726 def WriteHandlerImplementation(self
, file):
6727 """Overridden from Function"""
6728 self
.type_handler
.WriteImmediateHandlerImplementation(self
, file)
6730 def WriteServiceUnitTest(self
, file):
6731 """Writes the service implementation for a command."""
6732 self
.type_handler
.WriteImmediateServiceUnitTest(self
, file)
6734 def WriteValidationCode(self
, file):
6735 """Overridden from Function"""
6736 self
.type_handler
.WriteImmediateValidationCode(self
, file)
6738 def WriteCmdArgFlag(self
, file):
6739 """Overridden from Function"""
6740 file.Write(" static const cmd::ArgFlags kArgFlags = cmd::kAtLeastN;\n")
6742 def WriteCmdComputeSize(self
, file):
6743 """Overridden from Function"""
6744 self
.type_handler
.WriteImmediateCmdComputeSize(self
, file)
6746 def WriteCmdSetHeader(self
, file):
6747 """Overridden from Function"""
6748 self
.type_handler
.WriteImmediateCmdSetHeader(self
, file)
6750 def WriteCmdInit(self
, file):
6751 """Overridden from Function"""
6752 self
.type_handler
.WriteImmediateCmdInit(self
, file)
6754 def WriteCmdSet(self
, file):
6755 """Overridden from Function"""
6756 self
.type_handler
.WriteImmediateCmdSet(self
, file)
6758 def WriteCmdHelper(self
, file):
6759 """Overridden from Function"""
6760 self
.type_handler
.WriteImmediateCmdHelper(self
, file)
6762 def WriteFormatTest(self
, file):
6763 """Overridden from Function"""
6764 self
.type_handler
.WriteImmediateFormatTest(self
, file)
6767 class BucketFunction(Function
):
6768 """A class that represnets a bucket version of a function command."""
6770 def __init__(self
, func
):
6772 for arg
in func
.GetOriginalArgs():
6773 new_arg
= arg
.GetBucketVersion()
6775 new_args
.append(new_arg
)
6778 new_args_for_cmds
= []
6779 for arg
in func
.args_for_cmds
:
6780 new_arg
= arg
.GetBucketVersion()
6782 new_args_for_cmds
.append(new_arg
)
6783 new_arg
.AddCmdArgs(cmd_args
)
6786 for arg
in new_args_for_cmds
:
6787 arg
.AddInitArgs(new_init_args
)
6792 "%sBucket" % func
.name
,
6801 # def InitFunction(self):
6802 # """Overridden from Function"""
6805 def WriteCommandDescription(self
, file):
6806 """Overridden from Function"""
6807 file.Write("//! Bucket version of command that corresponds to gl%s.\n" %
6810 def WriteServiceImplementation(self
, file):
6811 """Overridden from Function"""
6812 self
.type_handler
.WriteBucketServiceImplementation(self
, file)
6814 def WriteHandlerImplementation(self
, file):
6815 """Overridden from Function"""
6816 self
.type_handler
.WriteBucketHandlerImplementation(self
, file)
6818 def WriteServiceUnitTest(self
, file):
6819 """Writes the service implementation for a command."""
6820 self
.type_handler
.WriteBucketServiceUnitTest(self
, file)
6823 def CreateArg(arg_string
):
6824 """Creates an Argument."""
6825 arg_parts
= arg_string
.split()
6826 if len(arg_parts
) == 1 and arg_parts
[0] == 'void':
6828 # Is this a pointer argument?
6829 elif arg_string
.find('*') >= 0:
6830 if arg_parts
[0] == 'NonImmediate':
6831 return NonImmediatePointerArgument(
6833 " ".join(arg_parts
[1:-1]))
6835 return PointerArgument(
6837 " ".join(arg_parts
[0:-1]))
6838 # Is this a resource argument? Must come after pointer check.
6839 elif arg_parts
[0].startswith('GLidBind'):
6840 return ResourceIdBindArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
6841 elif arg_parts
[0].startswith('GLidZero'):
6842 return ResourceIdZeroArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
6843 elif arg_parts
[0].startswith('GLid'):
6844 return ResourceIdArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
6845 elif arg_parts
[0].startswith('GLenum') and len(arg_parts
[0]) > 6:
6846 return EnumArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
6847 elif arg_parts
[0].startswith('GLboolean') and len(arg_parts
[0]) > 9:
6848 return ValidatedBoolArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
6849 elif arg_parts
[0].startswith('GLboolean'):
6850 return BoolArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
6851 elif arg_parts
[0].startswith('GLintUniformLocation'):
6852 return UniformLocationArgument(arg_parts
[-1])
6853 elif (arg_parts
[0].startswith('GLint') and len(arg_parts
[0]) > 5 and
6854 not arg_parts
[0].startswith('GLintptr')):
6855 return IntArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
6856 elif (arg_parts
[0].startswith('GLsizeiNotNegative') or
6857 arg_parts
[0].startswith('GLintptrNotNegative')):
6858 return SizeNotNegativeArgument(arg_parts
[-1],
6859 " ".join(arg_parts
[0:-1]),
6860 arg_parts
[0][0:-11])
6861 elif arg_parts
[0].startswith('GLsize'):
6862 return SizeArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
6864 return Argument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
6867 class GLGenerator(object):
6868 """A class to generate GL command buffers."""
6870 _function_re
= re
.compile(r
'GL_APICALL(.*?)GL_APIENTRY (.*?) \((.*?)\);')
6872 def __init__(self
, verbose
):
6873 self
.original_functions
= []
6875 self
.verbose
= verbose
6877 self
._function
_info
= {}
6878 self
._empty
_type
_handler
= TypeHandler()
6879 self
._empty
_function
_info
= FunctionInfo({}, self
._empty
_type
_handler
)
6880 self
.pepper_interfaces
= []
6881 self
.interface_info
= {}
6883 self
._type
_handlers
= {
6884 'Bind': BindHandler(),
6885 'Create': CreateHandler(),
6886 'Custom': CustomHandler(),
6887 'Data': DataHandler(),
6888 'Delete': DeleteHandler(),
6889 'DELn': DELnHandler(),
6890 'GENn': GENnHandler(),
6891 'GETn': GETnHandler(),
6892 'GLchar': GLcharHandler(),
6893 'GLcharN': GLcharNHandler(),
6894 'HandWritten': HandWrittenHandler(),
6896 'Manual': ManualHandler(),
6897 'PUT': PUTHandler(),
6898 'PUTn': PUTnHandler(),
6899 'PUTXn': PUTXnHandler(),
6900 'StateSet': StateSetHandler(),
6901 'StateSetRGBAlpha': StateSetRGBAlphaHandler(),
6902 'StateSetFrontBack': StateSetFrontBackHandler(),
6903 'StateSetFrontBackSeparate': StateSetFrontBackSeparateHandler(),
6904 'StateSetNamedParameter': StateSetNamedParameter(),
6905 'STRn': STRnHandler(),
6906 'Todo': TodoHandler(),
6909 for func_name
in _FUNCTION_INFO
:
6910 info
= _FUNCTION_INFO
[func_name
]
6914 self
._function
_info
[func_name
] = FunctionInfo(info
,
6915 self
.GetTypeHandler(type))
6916 for interface
in _PEPPER_INTERFACES
:
6917 interface
= PepperInterface(interface
)
6918 self
.pepper_interfaces
.append(interface
)
6919 self
.interface_info
[interface
.GetName()] = interface
6921 def AddFunction(self
, func
):
6922 """Adds a function."""
6923 self
.functions
.append(func
)
6925 def GetTypeHandler(self
, name
):
6926 """Gets a type info for the given type."""
6928 if name
in self
._type
_handlers
:
6929 return self
._type
_handlers
[name
]
6931 raise KeyError("no such type handler: %s" % name
)
6932 return self
._empty
_type
_handler
6934 def GetFunctionInfo(self
, name
):
6935 """Gets a type info for the given function name."""
6936 if name
in self
._function
_info
:
6937 return self
._function
_info
[name
]
6938 return self
._empty
_function
_info
6941 """Prints something if verbose is true."""
6945 def Error(self
, msg
):
6946 """Prints an error."""
6947 print "Error: %s" % msg
6950 def WriteLicense(self
, file):
6951 """Writes the license."""
6952 file.Write(_LICENSE
)
6954 def WriteNamespaceOpen(self
, file):
6955 """Writes the code for the namespace."""
6956 file.Write("namespace gpu {\n")
6957 file.Write("namespace gles2 {\n")
6960 def WriteNamespaceClose(self
, file):
6961 """Writes the code to close the namespace."""
6962 file.Write("} // namespace gles2\n")
6963 file.Write("} // namespace gpu\n")
6966 def ParseArgs(self
, arg_string
):
6967 """Parses a function arg string."""
6969 num_pointer_args
= 0
6970 parts
= arg_string
.split(',')
6972 for arg_string
in parts
:
6973 if arg_string
.startswith('GLenum '):
6975 arg
= CreateArg(arg_string
)
6979 num_pointer_args
+= 1
6980 return (args
, num_pointer_args
, is_gl_enum
)
6982 def ParseGLH(self
, filename
):
6983 """Parses the cmd_buffer_functions.txt file and extracts the functions"""
6984 f
= open("gpu/command_buffer/cmd_buffer_functions.txt", "r")
6985 functions
= f
.read()
6987 for line
in functions
.splitlines():
6988 match
= self
._function
_re
.match(line
)
6990 func_name
= match
.group(2)[2:]
6991 func_info
= self
.GetFunctionInfo(func_name
)
6992 if func_info
.type != 'Noop':
6993 return_type
= match
.group(1).strip()
6994 arg_string
= match
.group(3)
6995 (args
, num_pointer_args
, is_gl_enum
) = self
.ParseArgs(arg_string
)
6996 # comment in to find out which functions use bare enums.
6998 # self.Log("%s uses bare GLenum" % func_name)
6999 args_for_cmds
= args
7000 if hasattr(func_info
, 'cmd_args'):
7001 (args_for_cmds
, num_pointer_args
, is_gl_enum
) = (
7002 self
.ParseArgs(getattr(func_info
, 'cmd_args')))
7004 for arg
in args_for_cmds
:
7005 arg
.AddCmdArgs(cmd_args
)
7007 for arg
in args_for_cmds
:
7008 arg
.AddInitArgs(init_args
)
7009 return_arg
= CreateArg(return_type
+ " result")
7011 init_args
.append(return_arg
)
7012 f
= Function(func_name
, func_name
, func_info
, return_type
, args
,
7013 args_for_cmds
, cmd_args
, init_args
, num_pointer_args
)
7014 self
.original_functions
.append(f
)
7015 gen_cmd
= f
.GetInfo('gen_cmd')
7016 if gen_cmd
== True or gen_cmd
== None:
7018 f
.type_handler
.AddImmediateFunction(self
, f
)
7019 f
.type_handler
.AddBucketFunction(self
, f
)
7021 self
.Log("Auto Generated Functions : %d" %
7022 len([f
for f
in self
.functions
if f
.can_auto_generate
or
7023 (not f
.IsType('') and not f
.IsType('Custom') and
7024 not f
.IsType('Todo'))]))
7026 funcs
= [f
for f
in self
.functions
if not f
.can_auto_generate
and
7027 (f
.IsType('') or f
.IsType('Custom') or f
.IsType('Todo'))]
7028 self
.Log("Non Auto Generated Functions: %d" % len(funcs
))
7031 self
.Log(" %-10s %-20s gl%s" % (f
.info
.type, f
.return_type
, f
.name
))
7033 def WriteCommandIds(self
, filename
):
7034 """Writes the command buffer format"""
7035 file = CHeaderWriter(filename
)
7036 file.Write("#define GLES2_COMMAND_LIST(OP) \\\n")
7038 for func
in self
.functions
:
7039 file.Write(" %-60s /* %d */ \\\n" %
7040 ("OP(%s)" % func
.name
, id))
7044 file.Write("enum CommandId {\n")
7045 file.Write(" kStartPoint = cmd::kLastCommonId, "
7046 "// All GLES2 commands start after this.\n")
7047 file.Write("#define GLES2_CMD_OP(name) k ## name,\n")
7048 file.Write(" GLES2_COMMAND_LIST(GLES2_CMD_OP)\n")
7049 file.Write("#undef GLES2_CMD_OP\n")
7050 file.Write(" kNumCommands\n")
7055 def WriteFormat(self
, filename
):
7056 """Writes the command buffer format"""
7057 file = CHeaderWriter(filename
)
7058 for func
in self
.functions
:
7060 #gen_cmd = func.GetInfo('gen_cmd')
7061 #if gen_cmd == True or gen_cmd == None:
7062 func
.WriteStruct(file)
7066 def WriteDocs(self
, filename
):
7067 """Writes the command buffer doc version of the commands"""
7068 file = CWriter(filename
)
7069 for func
in self
.functions
:
7071 #gen_cmd = func.GetInfo('gen_cmd')
7072 #if gen_cmd == True or gen_cmd == None:
7073 func
.WriteDocs(file)
7077 def WriteFormatTest(self
, filename
):
7078 """Writes the command buffer format test."""
7079 file = CHeaderWriter(
7081 "// This file contains unit tests for gles2 commmands\n"
7082 "// It is included by gles2_cmd_format_test.cc\n"
7085 for func
in self
.functions
:
7087 #gen_cmd = func.GetInfo('gen_cmd')
7088 #if gen_cmd == True or gen_cmd == None:
7089 func
.WriteFormatTest(file)
7093 def WriteCmdHelperHeader(self
, filename
):
7094 """Writes the gles2 command helper."""
7095 file = CHeaderWriter(filename
)
7097 for func
in self
.functions
:
7099 #gen_cmd = func.GetInfo('gen_cmd')
7100 #if gen_cmd == True or gen_cmd == None:
7101 func
.WriteCmdHelper(file)
7105 def WriteServiceContextStateHeader(self
, filename
):
7106 """Writes the service context state header."""
7107 file = CHeaderWriter(
7109 "// It is included by context_state.h\n")
7110 file.Write("struct EnableFlags {\n")
7111 file.Write(" EnableFlags();\n")
7112 for capability
in _CAPABILITY_FLAGS
:
7113 file.Write(" bool %s;\n" % capability
['name'])
7114 file.Write("};\n\n")
7116 for state_name
in sorted(_STATES
.keys()):
7117 state
= _STATES
[state_name
]
7118 for item
in state
['states']:
7119 file.Write("%s %s;\n" % (item
['type'], item
['name']))
7124 def WriteClientContextStateHeader(self
, filename
):
7125 """Writes the client context state header."""
7126 file = CHeaderWriter(
7128 "// It is included by client_context_state.h\n")
7129 file.Write("struct EnableFlags {\n")
7130 file.Write(" EnableFlags();\n")
7131 for capability
in _CAPABILITY_FLAGS
:
7132 file.Write(" bool %s;\n" % capability
['name'])
7133 file.Write("};\n\n")
7137 def WriteContextStateGetters(self
, file, class_name
):
7138 """Writes the state getters."""
7139 for gl_type
in ["GLint", "GLfloat"]:
7141 bool %s::GetStateAs%s(
7142 GLenum pname, %s* params, GLsizei* num_written) const {
7144 """ % (class_name
, gl_type
, gl_type
))
7145 for state_name
in sorted(_STATES
.keys()):
7146 state
= _STATES
[state_name
]
7148 file.Write(" case %s:\n" % state
['enum'])
7149 file.Write(" *num_written = %d;\n" % len(state
['states']))
7150 file.Write(" if (params) {\n")
7151 for ndx
,item
in enumerate(state
['states']):
7152 file.Write(" params[%d] = static_cast<%s>(%s);\n" %
7153 (ndx
, gl_type
, item
['name']))
7155 file.Write(" return true;\n")
7157 for item
in state
['states']:
7158 file.Write(" case %s:\n" % item
['enum'])
7159 file.Write(" *num_written = 1;\n")
7160 file.Write(" if (params) {\n")
7161 file.Write(" params[0] = static_cast<%s>(%s);\n" %
7162 (gl_type
, item
['name']))
7164 file.Write(" return true;\n")
7165 for capability
in _CAPABILITY_FLAGS
:
7166 file.Write(" case GL_%s:\n" % capability
['name'].upper())
7167 file.Write(" *num_written = 1;\n")
7168 file.Write(" if (params) {\n")
7170 " params[0] = static_cast<%s>(enable_flags.%s);\n" %
7171 (gl_type
, capability
['name']))
7173 file.Write(" return true;\n")
7174 file.Write(""" default:
7180 def WriteServiceContextStateImpl(self
, filename
):
7181 """Writes the context state service implementation."""
7182 file = CHeaderWriter(
7184 "// It is included by context_state.cc\n")
7186 for capability
in _CAPABILITY_FLAGS
:
7187 code
.append("%s(%s)" %
7188 (capability
['name'],
7189 ('false', 'true')['default' in capability
]))
7190 file.Write("ContextState::EnableFlags::EnableFlags()\n : %s {\n}\n" %
7194 file.Write("void ContextState::Initialize() {\n")
7195 for state_name
in sorted(_STATES
.keys()):
7196 state
= _STATES
[state_name
]
7197 for item
in state
['states']:
7198 file.Write(" %s = %s;\n" % (item
['name'], item
['default']))
7202 void ContextState::InitCapabilities() const {
7204 for capability
in _CAPABILITY_FLAGS
:
7205 file.Write(" EnableDisable(GL_%s, enable_flags.%s);\n" %
7206 (capability
['name'].upper(), capability
['name']))
7209 void ContextState::InitState() const {
7212 # We need to sort the keys so the expectations match
7213 for state_name
in sorted(_STATES
.keys()):
7214 state
= _STATES
[state_name
]
7215 if state
['type'] == 'FrontBack':
7216 num_states
= len(state
['states'])
7217 for ndx
, group
in enumerate(Grouper(num_states
/ 2, state
['states'])):
7220 args
.append('%s' % item
['name'])
7222 " gl%s(%s, %s);\n" %
7223 (state
['func'], ('GL_FRONT', 'GL_BACK')[ndx
], ", ".join(args
)))
7224 elif state
['type'] == 'NamedParameter':
7225 for item
in state
['states']:
7226 if 'extension_flag' in item
:
7227 file.Write(" if (feature_info_->feature_flags().%s)\n " %
7228 item
['extension_flag'])
7229 file.Write(" gl%s(%s, %s);\n" %
7230 (state
['func'], item
['enum'], item
['name']))
7233 for item
in state
['states']:
7234 args
.append('%s' % item
['name'])
7235 file.Write(" gl%s(%s);\n" % (state
['func'], ", ".join(args
)))
7238 file.Write("""bool ContextState::GetEnabled(GLenum cap) const {
7241 for capability
in _CAPABILITY_FLAGS
:
7242 file.Write(" case GL_%s:\n" % capability
['name'].upper())
7243 file.Write(" return enable_flags.%s;\n" % capability
['name'])
7244 file.Write(""" default:
7251 self
.WriteContextStateGetters(file, "ContextState")
7254 def WriteClientContextStateImpl(self
, filename
):
7255 """Writes the context state client side implementation."""
7256 file = CHeaderWriter(
7258 "// It is included by client_context_state.cc\n")
7260 for capability
in _CAPABILITY_FLAGS
:
7261 code
.append("%s(%s)" %
7262 (capability
['name'],
7263 ('false', 'true')['default' in capability
]))
7265 "ClientContextState::EnableFlags::EnableFlags()\n : %s {\n}\n" %
7270 bool ClientContextState::SetCapabilityState(
7271 GLenum cap, bool enabled, bool* changed) {
7275 for capability
in _CAPABILITY_FLAGS
:
7276 file.Write(" case GL_%s:\n" % capability
['name'].upper())
7277 file.Write(""" if (enable_flags.%(name)s != enabled) {
7279 enable_flags.%(name)s = enabled;
7283 file.Write(""" default:
7288 file.Write("""bool ClientContextState::GetEnabled(
7289 GLenum cap, bool* enabled) const {
7292 for capability
in _CAPABILITY_FLAGS
:
7293 file.Write(" case GL_%s:\n" % capability
['name'].upper())
7294 file.Write(" *enabled = enable_flags.%s;\n" % capability
['name'])
7295 file.Write(" return true;\n")
7296 file.Write(""" default:
7303 def WriteServiceImplementation(self
, filename
):
7304 """Writes the service decorder implementation."""
7305 file = CHeaderWriter(
7307 "// It is included by gles2_cmd_decoder.cc\n")
7309 for func
in self
.functions
:
7311 #gen_cmd = func.GetInfo('gen_cmd')
7312 #if gen_cmd == True or gen_cmd == None:
7313 func
.WriteServiceImplementation(file)
7316 bool GLES2DecoderImpl::SetCapabilityState(GLenum cap, bool enabled) {
7319 for capability
in _CAPABILITY_FLAGS
:
7320 file.Write(" case GL_%s:\n" % capability
['name'].upper())
7321 if 'state_flag' in capability
:
7322 file.Write(""" if (state_.enable_flags.%(name)s != enabled) {
7323 state_.enable_flags.%(name)s = enabled;
7324 %(state_flag)s = true;
7329 file.Write(""" state_.enable_flags.%(name)s = enabled;
7332 file.Write(""" default:
7340 def WriteServiceUnitTests(self
, filename
):
7341 """Writes the service decorder unit tests."""
7342 num_tests
= len(self
.functions
)
7343 FUNCTIONS_PER_FILE
= 98 # hard code this so it doesn't change.
7345 for test_num
in range(0, num_tests
, FUNCTIONS_PER_FILE
):
7347 name
= filename
% count
7348 file = CHeaderWriter(
7350 "// It is included by gles2_cmd_decoder_unittest_%d.cc\n" % count
)
7351 file.SetFileNum(count
)
7352 end
= test_num
+ FUNCTIONS_PER_FILE
7355 for idx
in range(test_num
, end
):
7356 func
= self
.functions
[idx
]
7358 #gen_cmd = func.GetInfo('gen_cmd')
7359 #if gen_cmd == True or gen_cmd == None:
7360 if func
.GetInfo('unit_test') == False:
7361 file.Write("// TODO(gman): %s\n" % func
.name
)
7363 func
.WriteServiceUnitTest(file)
7366 file = CHeaderWriter(
7368 "// It is included by gles2_cmd_decoder_unittest_base.cc\n")
7370 """void GLES2DecoderTestBase::SetupInitCapabilitiesExpectations() {
7372 for capability
in _CAPABILITY_FLAGS
:
7373 file.Write(" ExpectEnableDisable(GL_%s, %s);\n" %
7374 (capability
['name'].upper(),
7375 ('false', 'true')['default' in capability
]))
7378 void GLES2DecoderTestBase::SetupInitStateExpectations() {
7381 # We need to sort the keys so the expectations match
7382 for state_name
in sorted(_STATES
.keys()):
7383 state
= _STATES
[state_name
]
7384 if state
['type'] == 'FrontBack':
7385 num_states
= len(state
['states'])
7386 for ndx
, group
in enumerate(Grouper(num_states
/ 2, state
['states'])):
7389 if 'expected' in item
:
7390 args
.append(item
['expected'])
7392 args
.append(item
['default'])
7394 " EXPECT_CALL(*gl_, %s(%s, %s))\n" %
7395 (state
['func'], ('GL_FRONT', 'GL_BACK')[ndx
], ", ".join(args
)))
7396 file.Write(" .Times(1)\n")
7397 file.Write(" .RetiresOnSaturation();\n")
7398 elif state
['type'] == 'NamedParameter':
7399 for item
in state
['states']:
7400 if 'extension_flag' in item
:
7403 " EXPECT_CALL(*gl_, %s(%s, %s))\n" %
7404 (state
['func'], item
['enum'], item
['default']))
7405 file.Write(" .Times(1)\n")
7406 file.Write(" .RetiresOnSaturation();\n")
7409 for item
in state
['states']:
7410 if 'expected' in item
:
7411 args
.append(item
['expected'])
7413 args
.append(item
['default'])
7414 file.Write(" EXPECT_CALL(*gl_, %s(%s))\n" %
7415 (state
['func'], ", ".join(args
)))
7416 file.Write(" .Times(1)\n")
7417 file.Write(" .RetiresOnSaturation();\n")
7422 def WriteGLES2Header(self
, filename
):
7423 """Writes the GLES2 header."""
7424 file = CHeaderWriter(
7426 "// This file contains Chromium-specific GLES2 declarations.\n\n")
7428 for func
in self
.original_functions
:
7429 func
.WriteGLES2Header(file)
7434 def WriteGLES2CLibImplementation(self
, filename
):
7435 """Writes the GLES2 c lib implementation."""
7436 file = CHeaderWriter(
7438 "// These functions emulate GLES2 over command buffers.\n")
7440 for func
in self
.original_functions
:
7441 func
.WriteGLES2CLibImplementation(file)
7446 extern const NameToFunc g_gles2_function_table[] = {
7448 for func
in self
.original_functions
:
7450 ' { "gl%s", reinterpret_cast<GLES2FunctionPointer>(gl%s), },\n' %
7451 (func
.name
, func
.name
))
7452 file.Write(""" { NULL, NULL, },
7455 } // namespace gles2
7459 def WriteGLES2InterfaceHeader(self
, filename
):
7460 """Writes the GLES2 interface header."""
7461 file = CHeaderWriter(
7463 "// This file is included by gles2_interface.h to declare the\n"
7464 "// GL api functions.\n")
7465 for func
in self
.original_functions
:
7466 func
.WriteGLES2InterfaceHeader(file)
7469 def WriteGLES2InterfaceStub(self
, filename
):
7470 """Writes the GLES2 interface stub header."""
7471 file = CHeaderWriter(
7473 "// This file is included by gles2_interface_stub.h.\n")
7474 for func
in self
.original_functions
:
7475 func
.WriteGLES2InterfaceStub(file)
7478 def WriteGLES2InterfaceStubImpl(self
, filename
):
7479 """Writes the GLES2 interface header."""
7480 file = CHeaderWriter(
7482 "// This file is included by gles2_interface_stub.cc.\n")
7483 for func
in self
.original_functions
:
7484 func
.WriteGLES2InterfaceStubImpl(file)
7487 def WriteGLES2ImplementationHeader(self
, filename
):
7488 """Writes the GLES2 Implementation header."""
7489 file = CHeaderWriter(
7491 "// This file is included by gles2_implementation.h to declare the\n"
7492 "// GL api functions.\n")
7493 for func
in self
.original_functions
:
7494 func
.WriteGLES2ImplementationHeader(file)
7497 def WriteGLES2Implementation(self
, filename
):
7498 """Writes the GLES2 Implementation."""
7499 file = CHeaderWriter(
7501 "// This file is included by gles2_implementation.cc to define the\n"
7502 "// GL api functions.\n")
7503 for func
in self
.original_functions
:
7504 func
.WriteGLES2Implementation(file)
7507 def WriteGLES2TraceImplementationHeader(self
, filename
):
7508 """Writes the GLES2 Trace Implementation header."""
7509 file = CHeaderWriter(
7511 "// This file is included by gles2_trace_implementation.h\n")
7512 for func
in self
.original_functions
:
7513 func
.WriteGLES2TraceImplementationHeader(file)
7516 def WriteGLES2TraceImplementation(self
, filename
):
7517 """Writes the GLES2 Trace Implementation."""
7518 file = CHeaderWriter(
7520 "// This file is included by gles2_trace_implementation.cc\n")
7521 for func
in self
.original_functions
:
7522 func
.WriteGLES2TraceImplementation(file)
7525 def WriteGLES2ImplementationUnitTests(self
, filename
):
7526 """Writes the GLES2 helper header."""
7527 file = CHeaderWriter(
7529 "// This file is included by gles2_implementation.h to declare the\n"
7530 "// GL api functions.\n")
7531 for func
in self
.original_functions
:
7532 func
.WriteGLES2ImplementationUnitTest(file)
7535 def WriteServiceUtilsHeader(self
, filename
):
7536 """Writes the gles2 auto generated utility header."""
7537 file = CHeaderWriter(filename
)
7538 for enum
in sorted(_ENUM_LISTS
.keys()):
7539 file.Write("ValueValidator<%s> %s;\n" %
7540 (_ENUM_LISTS
[enum
]['type'], ToUnderscore(enum
)))
7544 def WriteServiceUtilsImplementation(self
, filename
):
7545 """Writes the gles2 auto generated utility implementation."""
7546 file = CHeaderWriter(filename
)
7547 enums
= sorted(_ENUM_LISTS
.keys())
7549 if len(_ENUM_LISTS
[enum
]['valid']) > 0:
7550 file.Write("static const %s valid_%s_table[] = {\n" %
7551 (_ENUM_LISTS
[enum
]['type'], ToUnderscore(enum
)))
7552 for value
in _ENUM_LISTS
[enum
]['valid']:
7553 file.Write(" %s,\n" % value
)
7556 file.Write("Validators::Validators()\n")
7559 for count
, enum
in enumerate(enums
):
7560 if count
+ 1 == len(enums
):
7562 if len(_ENUM_LISTS
[enum
]['valid']) > 0:
7563 code
= """ %(pre)s%(name)s(
7564 valid_%(name)s_table, arraysize(valid_%(name)s_table))%(post)s
7567 code
= """ %(pre)s%(name)s()%(post)s
7570 'name': ToUnderscore(enum
),
7575 file.Write("}\n\n");
7578 def WriteCommonUtilsHeader(self
, filename
):
7579 """Writes the gles2 common utility header."""
7580 file = CHeaderWriter(filename
)
7581 enums
= sorted(_ENUM_LISTS
.keys())
7583 if _ENUM_LISTS
[enum
]['type'] == 'GLenum':
7584 file.Write("static std::string GetString%s(uint32 value);\n" % enum
)
7588 def WriteCommonUtilsImpl(self
, filename
):
7589 """Writes the gles2 common utility header."""
7590 enum_re
= re
.compile(r
'\#define\s+(GL_[a-zA-Z0-9_]+)\s+([0-9A-Fa-fx]+)')
7592 for fname
in ['../../third_party/khronos/GLES2/gl2.h',
7593 '../../third_party/khronos/GLES2/gl2ext.h',
7594 '../../gpu/GLES2/gl2chromium.h',
7595 '../../gpu/GLES2/gl2extchromium.h']:
7596 lines
= open(fname
).readlines()
7598 m
= enum_re
.match(line
)
7602 if len(value
) <= 10 and not value
in dict:
7605 file = CHeaderWriter(filename
)
7606 file.Write("static const GLES2Util::EnumToString "
7607 "enum_to_string_table[] = {\n")
7609 file.Write(' { %s, "%s", },\n' % (value
, dict[value
]))
7612 const GLES2Util::EnumToString* const GLES2Util::enum_to_string_table_ =
7613 enum_to_string_table;
7614 const size_t GLES2Util::enum_to_string_table_len_ =
7615 sizeof(enum_to_string_table) / sizeof(enum_to_string_table[0]);
7619 enums
= sorted(_ENUM_LISTS
.keys())
7621 if _ENUM_LISTS
[enum
]['type'] == 'GLenum':
7622 file.Write("std::string GLES2Util::GetString%s(uint32 value) {\n" %
7624 if len(_ENUM_LISTS
[enum
]['valid']) > 0:
7625 file.Write(" static const EnumToString string_table[] = {\n")
7626 for value
in _ENUM_LISTS
[enum
]['valid']:
7627 file.Write(' { %s, "%s" },\n' % (value
, value
))
7629 return GLES2Util::GetQualifiedEnumString(
7630 string_table, arraysize(string_table), value);
7635 file.Write(""" return GLES2Util::GetQualifiedEnumString(
7642 def WritePepperGLES2Interface(self
, filename
, dev
):
7643 """Writes the Pepper OpenGLES interface definition."""
7644 file = CHeaderWriter(
7646 "// OpenGL ES interface.\n")
7648 file.Write("#include \"ppapi/c/pp_resource.h\"\n")
7650 file.Write("#include \"ppapi/c/ppb_opengles2.h\"\n\n")
7652 file.Write("\n#ifndef __gl2_h_\n")
7653 for (k
, v
) in _GL_TYPES
.iteritems():
7654 file.Write("typedef %s %s;\n" % (v
, k
))
7655 file.Write("#ifdef _WIN64\n")
7656 for (k
, v
) in _GL_TYPES_64
.iteritems():
7657 file.Write("typedef %s %s;\n" % (v
, k
))
7658 file.Write("#else\n")
7659 for (k
, v
) in _GL_TYPES_32
.iteritems():
7660 file.Write("typedef %s %s;\n" % (v
, k
))
7661 file.Write("#endif // _WIN64\n")
7662 file.Write("#endif // __gl2_h_\n\n")
7664 for interface
in self
.pepper_interfaces
:
7665 if interface
.dev
!= dev
:
7667 file.Write("#define %s_1_0 \"%s;1.0\"\n" %
7668 (interface
.GetInterfaceName(), interface
.GetInterfaceString()))
7669 file.Write("#define %s %s_1_0\n" %
7670 (interface
.GetInterfaceName(), interface
.GetInterfaceName()))
7672 file.Write("\nstruct %s {\n" % interface
.GetStructName())
7673 for func
in self
.original_functions
:
7674 if not func
.InPepperInterface(interface
):
7677 original_arg
= func
.MakeTypedPepperArgString("")
7678 context_arg
= "PP_Resource context"
7679 if len(original_arg
):
7680 arg
= context_arg
+ ", " + original_arg
7683 file.Write(" %s (*%s)(%s);\n" %
7684 (func
.return_type
, func
.GetPepperName(), arg
))
7685 file.Write("};\n\n")
7690 def WritePepperGLES2Implementation(self
, filename
):
7691 """Writes the Pepper OpenGLES interface implementation."""
7693 file = CWriter(filename
)
7694 file.Write(_LICENSE
)
7695 file.Write(_DO_NOT_EDIT_WARNING
)
7697 file.Write("#include \"ppapi/shared_impl/ppb_opengles2_shared.h\"\n\n")
7698 file.Write("#include \"base/logging.h\"\n")
7699 file.Write("#include \"gpu/command_buffer/client/gles2_implementation.h\"\n")
7700 file.Write("#include \"ppapi/shared_impl/ppb_graphics_3d_shared.h\"\n")
7701 file.Write("#include \"ppapi/thunk/enter.h\"\n\n")
7703 file.Write("namespace ppapi {\n\n")
7704 file.Write("namespace {\n\n")
7706 file.Write("typedef thunk::EnterResource<thunk::PPB_Graphics3D_API>"
7709 file.Write("gpu::gles2::GLES2Implementation* ToGles2Impl(Enter3D*"
7711 file.Write(" DCHECK(enter);\n")
7712 file.Write(" DCHECK(enter->succeeded());\n")
7713 file.Write(" return static_cast<PPB_Graphics3D_Shared*>(enter->object())->"
7715 file.Write("}\n\n");
7717 for func
in self
.original_functions
:
7718 if not func
.InAnyPepperExtension():
7721 original_arg
= func
.MakeTypedPepperArgString("")
7722 context_arg
= "PP_Resource context_id"
7723 if len(original_arg
):
7724 arg
= context_arg
+ ", " + original_arg
7727 file.Write("%s %s(%s) {\n" %
7728 (func
.return_type
, func
.GetPepperName(), arg
))
7729 file.Write(" Enter3D enter(context_id, true);\n")
7730 file.Write(" if (enter.succeeded()) {\n")
7732 return_str
= "" if func
.return_type
== "void" else "return "
7733 file.Write(" %sToGles2Impl(&enter)->%s(%s);\n" %
7734 (return_str
, func
.original_name
,
7735 func
.MakeOriginalArgString("")))
7737 if func
.return_type
== "void":
7740 file.Write(" else {\n")
7742 if func
.GetInfo("error_return"):
7743 error_return
= func
.GetInfo("error_return")
7744 elif func
.return_type
== "GLboolean":
7745 error_return
= "GL_FALSE"
7746 elif "*" in func
.return_type
:
7747 error_return
= "NULL"
7748 file.Write(" return %s;\n" % error_return
)
7752 file.Write("} // namespace\n")
7754 for interface
in self
.pepper_interfaces
:
7755 file.Write("const %s* PPB_OpenGLES2_Shared::Get%sInterface() {\n" %
7756 (interface
.GetStructName(), interface
.GetName()))
7757 file.Write(" static const struct %s "
7758 "ppb_opengles2 = {\n" % interface
.GetStructName())
7760 file.Write(",\n &".join(
7761 f
.GetPepperName() for f
in self
.original_functions
7762 if f
.InPepperInterface(interface
)))
7766 file.Write(" return &ppb_opengles2;\n")
7769 file.Write("} // namespace ppapi\n")
7772 def WriteGLES2ToPPAPIBridge(self
, filename
):
7773 """Connects GLES2 helper library to PPB_OpenGLES2 interface"""
7775 file = CWriter(filename
)
7776 file.Write(_LICENSE
)
7777 file.Write(_DO_NOT_EDIT_WARNING
)
7779 file.Write("#ifndef GL_GLEXT_PROTOTYPES\n")
7780 file.Write("#define GL_GLEXT_PROTOTYPES\n")
7781 file.Write("#endif\n")
7782 file.Write("#include <GLES2/gl2.h>\n")
7783 file.Write("#include <GLES2/gl2ext.h>\n")
7784 file.Write("#include \"ppapi/lib/gl/gles2/gl2ext_ppapi.h\"\n\n")
7786 for func
in self
.original_functions
:
7787 if not func
.InAnyPepperExtension():
7790 interface
= self
.interface_info
[func
.GetInfo('pepper_interface') or '']
7792 file.Write("%s GL_APIENTRY gl%s(%s) {\n" %
7793 (func
.return_type
, func
.GetPepperName(),
7794 func
.MakeTypedPepperArgString("")))
7795 return_str
= "" if func
.return_type
== "void" else "return "
7796 interface_str
= "glGet%sInterfacePPAPI()" % interface
.GetName()
7797 original_arg
= func
.MakeOriginalArgString("")
7798 context_arg
= "glGetCurrentContextPPAPI()"
7799 if len(original_arg
):
7800 arg
= context_arg
+ ", " + original_arg
7803 if interface
.GetName():
7804 file.Write(" const struct %s* ext = %s;\n" %
7805 (interface
.GetStructName(), interface_str
))
7806 file.Write(" if (ext)\n")
7807 file.Write(" %sext->%s(%s);\n" %
7808 (return_str
, func
.GetPepperName(), arg
))
7810 file.Write(" %s0;\n" % return_str
)
7812 file.Write(" %s%s->%s(%s);\n" %
7813 (return_str
, interface_str
, func
.GetPepperName(), arg
))
7817 def WriteMojoGLCallVisitor(self
, filename
):
7818 """Provides the GL implementation for mojo"""
7819 file = CWriter(filename
)
7820 file.Write(_LICENSE
)
7821 file.Write(_DO_NOT_EDIT_WARNING
)
7823 for func
in self
.original_functions
:
7824 if not func
.IsCoreGLFunction():
7826 file.Write("VISIT_GL_CALL(%s, %s, (%s), (%s))\n" %
7827 (func
.name
, func
.return_type
,
7828 func
.MakeTypedOriginalArgString(""),
7829 func
.MakeOriginalArgString("")))
7833 def Format(generated_files
):
7834 for filename
in generated_files
:
7835 call(["clang-format", "-i", "-style=chromium", filename
])
7838 """This is the main function."""
7839 parser
= OptionParser()
7841 "-g", "--generate-implementation-templates", action
="store_true",
7842 help="generates files that are generally hand edited..")
7845 help="base directory for resulting files, under chrome/src. default is "
7846 "empty. Use this if you want the result stored under gen.")
7848 "-v", "--verbose", action
="store_true",
7849 help="prints more output.")
7851 (options
, args
) = parser
.parse_args(args
=argv
)
7853 # Add in states and capabilites to GLState
7854 for state_name
in sorted(_STATES
.keys()):
7855 state
= _STATES
[state_name
]
7857 _ENUM_LISTS
['GLState']['valid'].append(state
['enum'])
7859 for item
in state
['states']:
7860 if 'extension_flag' in item
:
7862 _ENUM_LISTS
['GLState']['valid'].append(item
['enum'])
7863 for capability
in _CAPABILITY_FLAGS
:
7864 _ENUM_LISTS
['GLState']['valid'].append("GL_%s" % capability
['name'].upper())
7866 # This script lives under gpu/command_buffer, cd to base directory.
7867 os
.chdir(os
.path
.dirname(__file__
) + "/../..")
7869 gen
= GLGenerator(options
.verbose
)
7870 gen
.ParseGLH("common/GLES2/gl2.h")
7872 # Support generating files under gen/
7873 if options
.output_dir
!= None:
7874 os
.chdir(options
.output_dir
)
7876 gen
.WritePepperGLES2Interface("ppapi/c/ppb_opengles2.h", False)
7877 gen
.WritePepperGLES2Interface("ppapi/c/dev/ppb_opengles2ext_dev.h", True)
7878 gen
.WriteGLES2ToPPAPIBridge("ppapi/lib/gl/gles2/gles2.c")
7879 gen
.WritePepperGLES2Implementation(
7880 "ppapi/shared_impl/ppb_opengles2_shared.cc")
7881 os
.chdir("gpu/command_buffer")
7882 gen
.WriteCommandIds("common/gles2_cmd_ids_autogen.h")
7883 gen
.WriteFormat("common/gles2_cmd_format_autogen.h")
7884 gen
.WriteFormatTest("common/gles2_cmd_format_test_autogen.h")
7885 gen
.WriteGLES2InterfaceHeader("client/gles2_interface_autogen.h")
7886 gen
.WriteGLES2InterfaceStub("client/gles2_interface_stub_autogen.h")
7887 gen
.WriteGLES2InterfaceStubImpl(
7888 "client/gles2_interface_stub_impl_autogen.h")
7889 gen
.WriteGLES2ImplementationHeader("client/gles2_implementation_autogen.h")
7890 gen
.WriteGLES2Implementation("client/gles2_implementation_impl_autogen.h")
7891 gen
.WriteGLES2ImplementationUnitTests(
7892 "client/gles2_implementation_unittest_autogen.h")
7893 gen
.WriteGLES2TraceImplementationHeader(
7894 "client/gles2_trace_implementation_autogen.h")
7895 gen
.WriteGLES2TraceImplementation(
7896 "client/gles2_trace_implementation_impl_autogen.h")
7897 gen
.WriteGLES2CLibImplementation("client/gles2_c_lib_autogen.h")
7898 gen
.WriteCmdHelperHeader("client/gles2_cmd_helper_autogen.h")
7899 gen
.WriteServiceImplementation("service/gles2_cmd_decoder_autogen.h")
7900 gen
.WriteServiceContextStateHeader("service/context_state_autogen.h")
7901 gen
.WriteServiceContextStateImpl("service/context_state_impl_autogen.h")
7902 gen
.WriteClientContextStateHeader("client/client_context_state_autogen.h")
7903 gen
.WriteClientContextStateImpl(
7904 "client/client_context_state_impl_autogen.h")
7905 gen
.WriteServiceUnitTests("service/gles2_cmd_decoder_unittest_%d_autogen.h")
7906 gen
.WriteServiceUtilsHeader("service/gles2_cmd_validation_autogen.h")
7907 gen
.WriteServiceUtilsImplementation(
7908 "service/gles2_cmd_validation_implementation_autogen.h")
7909 gen
.WriteCommonUtilsHeader("common/gles2_cmd_utils_autogen.h")
7910 gen
.WriteCommonUtilsImpl("common/gles2_cmd_utils_implementation_autogen.h")
7911 gen
.WriteGLES2Header("../GLES2/gl2chromium_autogen.h")
7912 gen
.WriteMojoGLCallVisitor(
7913 "../../mojo/public/gles2/gles2_call_visitor_autogen.h")
7916 "common/gles2_cmd_format_autogen.h",
7917 "common/gles2_cmd_format_test_autogen.h",
7918 "common/gles2_cmd_ids_autogen.h",
7919 "common/gles2_cmd_utils_autogen.h",
7920 "common/gles2_cmd_utils_implementation_autogen.h",
7921 "client/client_context_state_autogen.h",
7922 "client/client_context_state_impl_autogen.h",
7923 "client/gles2_cmd_helper_autogen.h",
7924 "client/gles2_c_lib_autogen.h",
7925 "client/gles2_implementation_autogen.h",
7926 "client/gles2_implementation_impl_autogen.h",
7927 "client/gles2_implementation_unittest_autogen.h",
7928 "client/gles2_interface_autogen.h",
7929 "client/gles2_interface_stub_autogen.h",
7930 "client/gles2_interface_stub_impl_autogen.h",
7931 "client/gles2_trace_implementation_autogen.h",
7932 "client/gles2_trace_implementation_impl_autogen.h",
7933 "service/context_state_autogen.h",
7934 "service/context_state_impl_autogen.h",
7935 "service/gles2_cmd_decoder_autogen.h",
7936 "service/gles2_cmd_decoder_unittest_0_autogen.h",
7937 "service/gles2_cmd_decoder_unittest_1_autogen.h",
7938 "service/gles2_cmd_decoder_unittest_2_autogen.h",
7939 "service/gles2_cmd_decoder_unittest_3_autogen.h",
7940 "service/gles2_cmd_validation_autogen.h",
7941 "service/gles2_cmd_validation_implementation_autogen.h"])
7944 "gpu/GLES2/gl2chromium_autogen.h",
7945 "mojo/public/gles2/gles2_call_visitor_autogen.h",
7946 "ppapi/c/dev/ppb_opengles2ext_dev.h",
7947 "ppapi/c/ppb_opengles2.h",
7948 "ppapi/lib/gl/gles2/gles2.c",
7949 "ppapi/shared_impl/ppb_opengles2_shared.cc"])
7952 print "%d errors" % gen
.errors
7957 if __name__
== '__main__':
7958 sys
.exit(main(sys
.argv
[1:]))