2 # Copyright (c) 2012 The Chromium Authors. All rights reserved.
3 # Use of this source code is governed by a BSD-style license that can be
4 # found in the LICENSE file.
6 """code generator for GLES2 command buffers."""
13 from optparse
import OptionParser
16 _SIZE_OF_COMMAND_HEADER
= 4
17 _FIRST_SPECIFIC_COMMAND_ID
= 256
19 _LICENSE
= """// Copyright (c) 2012 The Chromium Authors. All rights reserved.
20 // Use of this source code is governed by a BSD-style license that can be
21 // found in the LICENSE file.
25 _DO_NOT_EDIT_WARNING
= """// This file is auto-generated from
26 // gpu/command_buffer/build_gles2_cmd_buffer.py
31 # This string is copied directly out of the gl2.h file from GLES2.0
35 # *) Any argument that is a resourceID has been changed to GLid<Type>.
36 # (not pointer arguments) and if it's allowed to be zero it's GLidZero<Type>
37 # If it's allowed to not exist it's GLidBind<Type>
39 # *) All GLenums have been changed to GLenumTypeOfEnum
42 'GLenum': 'unsigned int',
43 'GLboolean': 'unsigned char',
44 'GLbitfield': 'unsigned int',
45 'GLbyte': 'signed char',
49 'GLubyte': 'unsigned char',
50 'GLushort': 'unsigned short',
51 'GLuint': 'unsigned int',
57 'GLintptr': 'long int',
58 'GLsizeiptr': 'long int',
61 # Capabilites selected with glEnable
64 {'name': 'cull_face'},
65 {'name': 'depth_test', 'state_flag': 'framebuffer_state_.clear_state_dirty'},
66 {'name': 'dither', 'default': True},
67 {'name': 'polygon_offset_fill'},
68 {'name': 'sample_alpha_to_coverage'},
69 {'name': 'sample_coverage'},
70 {'name': 'scissor_test',
71 'state_flag': 'framebuffer_state_.clear_state_dirty'},
72 {'name': 'stencil_test',
73 'state_flag': 'framebuffer_state_.clear_state_dirty'},
80 'enum': 'GL_COLOR_CLEAR_VALUE',
82 {'name': 'color_clear_red', 'type': 'GLfloat', 'default': '0.0f'},
83 {'name': 'color_clear_green', 'type': 'GLfloat', 'default': '0.0f'},
84 {'name': 'color_clear_blue', 'type': 'GLfloat', 'default': '0.0f'},
85 {'name': 'color_clear_alpha', 'type': 'GLfloat', 'default': '0.0f'},
91 'enum': 'GL_DEPTH_CLEAR_VALUE',
93 {'name': 'depth_clear', 'type': 'GLclampf', 'default': '1.0f'},
99 'enum': 'GL_COLOR_WRITEMASK',
101 {'name': 'color_mask_red', 'type': 'GLboolean', 'default': 'true'},
102 {'name': 'color_mask_green', 'type': 'GLboolean', 'default': 'true'},
103 {'name': 'color_mask_blue', 'type': 'GLboolean', 'default': 'true'},
104 {'name': 'color_mask_alpha', 'type': 'GLboolean', 'default': 'true'},
106 'state_flag': 'framebuffer_state_.clear_state_dirty',
110 'func': 'ClearStencil',
111 'enum': 'GL_STENCIL_CLEAR_VALUE',
113 {'name': 'stencil_clear', 'type': 'GLint', 'default': '0'},
118 'func': 'BlendColor',
119 'enum': 'GL_BLEND_COLOR',
121 {'name': 'blend_color_red', 'type': 'GLfloat', 'default': '0.0f'},
122 {'name': 'blend_color_green', 'type': 'GLfloat', 'default': '0.0f'},
123 {'name': 'blend_color_blue', 'type': 'GLfloat', 'default': '0.0f'},
124 {'name': 'blend_color_alpha', 'type': 'GLfloat', 'default': '0.0f'},
129 'func': 'BlendEquationSeparate',
132 'name': 'blend_equation_rgb',
134 'enum': 'GL_BLEND_EQUATION_RGB',
135 'default': 'GL_FUNC_ADD',
138 'name': 'blend_equation_alpha',
140 'enum': 'GL_BLEND_EQUATION_ALPHA',
141 'default': 'GL_FUNC_ADD',
147 'func': 'BlendFuncSeparate',
150 'name': 'blend_source_rgb',
152 'enum': 'GL_BLEND_SRC_RGB',
156 'name': 'blend_dest_rgb',
158 'enum': 'GL_BLEND_DST_RGB',
159 'default': 'GL_ZERO',
162 'name': 'blend_source_alpha',
164 'enum': 'GL_BLEND_SRC_ALPHA',
168 'name': 'blend_dest_alpha',
170 'enum': 'GL_BLEND_DST_ALPHA',
171 'default': 'GL_ZERO',
177 'func': 'PolygonOffset',
180 'name': 'polygon_offset_factor',
182 'enum': 'GL_POLYGON_OFFSET_FACTOR',
186 'name': 'polygon_offset_units',
188 'enum': 'GL_POLYGON_OFFSET_UNITS',
196 'enum': 'GL_CULL_FACE_MODE',
201 'default': 'GL_BACK',
208 'enum': 'GL_FRONT_FACE',
209 'states': [{'name': 'front_face', 'type': 'GLenum', 'default': 'GL_CCW'}],
214 'enum': 'GL_DEPTH_FUNC',
215 'states': [{'name': 'depth_func', 'type': 'GLenum', 'default': 'GL_LESS'}],
219 'func': 'DepthRange',
220 'enum': 'GL_DEPTH_RANGE',
222 {'name': 'z_near', 'type': 'GLclampf', 'default': '0.0f'},
223 {'name': 'z_far', 'type': 'GLclampf', 'default': '1.0f'},
228 'func': 'SampleCoverage',
231 'name': 'sample_coverage_value',
233 'enum': 'GL_SAMPLE_COVERAGE_VALUE',
237 'name': 'sample_coverage_invert',
239 'enum': 'GL_SAMPLE_COVERAGE_INVERT',
246 'func': 'StencilMaskSeparate',
247 'state_flag': 'framebuffer_state_.clear_state_dirty',
250 'name': 'stencil_front_writemask',
252 'enum': 'GL_STENCIL_WRITEMASK',
253 'default': '0xFFFFFFFFU',
256 'name': 'stencil_back_writemask',
258 'enum': 'GL_STENCIL_BACK_WRITEMASK',
259 'default': '0xFFFFFFFFU',
265 'func': 'StencilOpSeparate',
268 'name': 'stencil_front_fail_op',
270 'enum': 'GL_STENCIL_FAIL',
271 'default': 'GL_KEEP',
274 'name': 'stencil_front_z_fail_op',
276 'enum': 'GL_STENCIL_PASS_DEPTH_FAIL',
277 'default': 'GL_KEEP',
280 'name': 'stencil_front_z_pass_op',
282 'enum': 'GL_STENCIL_PASS_DEPTH_PASS',
283 'default': 'GL_KEEP',
286 'name': 'stencil_back_fail_op',
288 'enum': 'GL_STENCIL_BACK_FAIL',
289 'default': 'GL_KEEP',
292 'name': 'stencil_back_z_fail_op',
294 'enum': 'GL_STENCIL_BACK_PASS_DEPTH_FAIL',
295 'default': 'GL_KEEP',
298 'name': 'stencil_back_z_pass_op',
300 'enum': 'GL_STENCIL_BACK_PASS_DEPTH_PASS',
301 'default': 'GL_KEEP',
307 'func': 'StencilFuncSeparate',
310 'name': 'stencil_front_func',
312 'enum': 'GL_STENCIL_FUNC',
313 'default': 'GL_ALWAYS',
316 'name': 'stencil_front_ref',
318 'enum': 'GL_STENCIL_REF',
322 'name': 'stencil_front_mask',
324 'enum': 'GL_STENCIL_VALUE_MASK',
325 'default': '0xFFFFFFFFU',
328 'name': 'stencil_back_func',
330 'enum': 'GL_STENCIL_BACK_FUNC',
331 'default': 'GL_ALWAYS',
334 'name': 'stencil_back_ref',
336 'enum': 'GL_STENCIL_BACK_REF',
340 'name': 'stencil_back_mask',
342 'enum': 'GL_STENCIL_BACK_VALUE_MASK',
343 'default': '0xFFFFFFFFU',
348 'type': 'NamedParameter',
352 'name': 'hint_generate_mipmap',
354 'enum': 'GL_GENERATE_MIPMAP_HINT',
355 'default': 'GL_DONT_CARE'
358 'name': 'hint_fragment_shader_derivative',
360 'enum': 'GL_FRAGMENT_SHADER_DERIVATIVE_HINT_OES',
361 'default': 'GL_DONT_CARE',
362 'extension_flag': 'oes_standard_derivatives'
367 'type': 'NamedParameter',
368 'func': 'PixelStorei',
371 'name': 'pack_alignment',
373 'enum': 'GL_PACK_ALIGNMENT',
377 'name': 'unpack_alignment',
379 'enum': 'GL_UNPACK_ALIGNMENT',
384 # TODO: Consider implemenenting these states
389 'enum': 'GL_LINE_WIDTH',
392 'name': 'line_width',
395 'range_checks': [{'check': "<= 0.0f", 'test_value': "0.0f"}],
401 'enum': 'GL_DEPTH_WRITEMASK',
403 {'name': 'depth_mask', 'type': 'GLboolean', 'default': 'true'},
405 'state_flag': 'framebuffer_state_.clear_state_dirty',
410 'enum': 'GL_SCISSOR_BOX',
412 # NOTE: These defaults reset at GLES2DecoderImpl::Initialization.
417 'expected': 'kViewportX',
423 'expected': 'kViewportY',
426 'name': 'scissor_width',
429 'expected': 'kViewportWidth',
432 'name': 'scissor_height',
435 'expected': 'kViewportHeight',
442 'enum': 'GL_VIEWPORT',
444 # NOTE: These defaults reset at GLES2DecoderImpl::Initialization.
446 'name': 'viewport_x',
449 'expected': 'kViewportX',
452 'name': 'viewport_y',
455 'expected': 'kViewportY',
458 'name': 'viewport_width',
461 'expected': 'kViewportWidth',
464 'name': 'viewport_height',
467 'expected': 'kViewportHeight',
473 # This is a list of enum names and their valid values. It is used to map
474 # GLenum arguments to a specific set of valid values.
483 'GL_LINEAR_MIPMAP_LINEAR',
486 'FrameBufferTarget': {
492 'GL_DRAW_FRAMEBUFFER' ,
493 'GL_READ_FRAMEBUFFER' ,
496 'RenderBufferTarget': {
509 'GL_ELEMENT_ARRAY_BUFFER',
526 'CompressedTextureFormat': {
534 # NOTE: State an Capability entries added later.
536 'GL_ALIASED_LINE_WIDTH_RANGE',
537 'GL_ALIASED_POINT_SIZE_RANGE',
539 'GL_ARRAY_BUFFER_BINDING',
541 'GL_COMPRESSED_TEXTURE_FORMATS',
542 'GL_CURRENT_PROGRAM',
545 'GL_ELEMENT_ARRAY_BUFFER_BINDING',
546 'GL_FRAMEBUFFER_BINDING',
547 'GL_GENERATE_MIPMAP_HINT',
549 'GL_IMPLEMENTATION_COLOR_READ_FORMAT',
550 'GL_IMPLEMENTATION_COLOR_READ_TYPE',
551 'GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS',
552 'GL_MAX_CUBE_MAP_TEXTURE_SIZE',
553 'GL_MAX_FRAGMENT_UNIFORM_VECTORS',
554 'GL_MAX_RENDERBUFFER_SIZE',
555 'GL_MAX_TEXTURE_IMAGE_UNITS',
556 'GL_MAX_TEXTURE_SIZE',
557 'GL_MAX_VARYING_VECTORS',
558 'GL_MAX_VERTEX_ATTRIBS',
559 'GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS',
560 'GL_MAX_VERTEX_UNIFORM_VECTORS',
561 'GL_MAX_VIEWPORT_DIMS',
562 'GL_NUM_COMPRESSED_TEXTURE_FORMATS',
563 'GL_NUM_SHADER_BINARY_FORMATS',
566 'GL_RENDERBUFFER_BINDING',
568 'GL_SAMPLE_COVERAGE_INVERT',
569 'GL_SAMPLE_COVERAGE_VALUE',
572 'GL_SHADER_BINARY_FORMATS',
573 'GL_SHADER_COMPILER',
576 'GL_TEXTURE_BINDING_2D',
577 'GL_TEXTURE_BINDING_CUBE_MAP',
578 'GL_UNPACK_ALIGNMENT',
579 'GL_UNPACK_FLIP_Y_CHROMIUM',
580 'GL_UNPACK_PREMULTIPLY_ALPHA_CHROMIUM',
581 'GL_UNPACK_UNPREMULTIPLY_ALPHA_CHROMIUM',
582 # we can add this because we emulate it if the driver does not support it.
583 'GL_VERTEX_ARRAY_BINDING_OES',
590 'GetTexParamTarget': {
594 'GL_TEXTURE_CUBE_MAP',
597 'GL_PROXY_TEXTURE_CUBE_MAP',
604 'GL_TEXTURE_CUBE_MAP_POSITIVE_X',
605 'GL_TEXTURE_CUBE_MAP_NEGATIVE_X',
606 'GL_TEXTURE_CUBE_MAP_POSITIVE_Y',
607 'GL_TEXTURE_CUBE_MAP_NEGATIVE_Y',
608 'GL_TEXTURE_CUBE_MAP_POSITIVE_Z',
609 'GL_TEXTURE_CUBE_MAP_NEGATIVE_Z',
612 'GL_PROXY_TEXTURE_CUBE_MAP',
615 'TextureBindTarget': {
619 'GL_TEXTURE_CUBE_MAP',
630 'GL_FRAGMENT_SHADER',
633 'GL_GEOMETRY_SHADER',
669 'GL_FUNC_REVERSE_SUBTRACT',
682 'GL_ONE_MINUS_SRC_COLOR',
684 'GL_ONE_MINUS_DST_COLOR',
686 'GL_ONE_MINUS_SRC_ALPHA',
688 'GL_ONE_MINUS_DST_ALPHA',
690 'GL_ONE_MINUS_CONSTANT_COLOR',
692 'GL_ONE_MINUS_CONSTANT_ALPHA',
693 'GL_SRC_ALPHA_SATURATE',
702 'GL_ONE_MINUS_SRC_COLOR',
704 'GL_ONE_MINUS_DST_COLOR',
706 'GL_ONE_MINUS_SRC_ALPHA',
708 'GL_ONE_MINUS_DST_ALPHA',
710 'GL_ONE_MINUS_CONSTANT_COLOR',
712 'GL_ONE_MINUS_CONSTANT_ALPHA',
717 'valid': ["GL_%s" % cap
['name'].upper() for cap
in _CAPABILITY_FLAGS
],
764 'GL_COLOR_ATTACHMENT0',
765 'GL_DEPTH_ATTACHMENT',
766 'GL_STENCIL_ATTACHMENT',
769 'BackbufferAttachment': {
784 'GL_PIXEL_PACK_BUFFER',
787 'FrameBufferParameter': {
790 'GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE',
791 'GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME',
792 'GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL',
793 'GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE',
796 'ProgramParameter': {
801 'GL_VALIDATE_STATUS',
802 'GL_INFO_LOG_LENGTH',
803 'GL_ATTACHED_SHADERS',
804 'GL_ACTIVE_ATTRIBUTES',
805 'GL_ACTIVE_ATTRIBUTE_MAX_LENGTH',
806 'GL_ACTIVE_UNIFORMS',
807 'GL_ACTIVE_UNIFORM_MAX_LENGTH',
810 'QueryObjectParameter': {
813 'GL_QUERY_RESULT_EXT',
814 'GL_QUERY_RESULT_AVAILABLE_EXT',
820 'GL_CURRENT_QUERY_EXT',
826 'GL_ANY_SAMPLES_PASSED_EXT',
827 'GL_ANY_SAMPLES_PASSED_CONSERVATIVE_EXT',
828 'GL_COMMANDS_ISSUED_CHROMIUM',
829 'GL_LATENCY_QUERY_CHROMIUM',
830 'GL_ASYNC_PIXEL_UNPACK_COMPLETED_CHROMIUM',
831 'GL_ASYNC_PIXEL_PACK_COMPLETED_CHROMIUM',
834 'RenderBufferParameter': {
837 'GL_RENDERBUFFER_RED_SIZE',
838 'GL_RENDERBUFFER_GREEN_SIZE',
839 'GL_RENDERBUFFER_BLUE_SIZE',
840 'GL_RENDERBUFFER_ALPHA_SIZE',
841 'GL_RENDERBUFFER_DEPTH_SIZE',
842 'GL_RENDERBUFFER_STENCIL_SIZE',
843 'GL_RENDERBUFFER_WIDTH',
844 'GL_RENDERBUFFER_HEIGHT',
845 'GL_RENDERBUFFER_INTERNAL_FORMAT',
854 'GL_INFO_LOG_LENGTH',
855 'GL_SHADER_SOURCE_LENGTH',
856 'GL_TRANSLATED_SHADER_SOURCE_LENGTH_ANGLE',
876 'GL_SHADING_LANGUAGE_VERSION',
880 'TextureParameter': {
883 'GL_TEXTURE_MAG_FILTER',
884 'GL_TEXTURE_MIN_FILTER',
885 'GL_TEXTURE_POOL_CHROMIUM',
890 'GL_GENERATE_MIPMAP',
896 'GL_TEXTURE_POOL_MANAGED_CHROMIUM',
897 'GL_TEXTURE_POOL_UNMANAGED_CHROMIUM',
904 'GL_MIRRORED_REPEAT',
908 'TextureMinFilterMode': {
913 'GL_NEAREST_MIPMAP_NEAREST',
914 'GL_LINEAR_MIPMAP_NEAREST',
915 'GL_NEAREST_MIPMAP_LINEAR',
916 'GL_LINEAR_MIPMAP_LINEAR',
919 'TextureMagFilterMode': {
930 'GL_FRAMEBUFFER_ATTACHMENT_ANGLE',
936 # some enum that the decoder actually passes through to GL needs
937 # to be the first listed here since it's used in unit tests.
938 'GL_VERTEX_ATTRIB_ARRAY_NORMALIZED',
939 'GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING',
940 'GL_VERTEX_ATTRIB_ARRAY_ENABLED',
941 'GL_VERTEX_ATTRIB_ARRAY_SIZE',
942 'GL_VERTEX_ATTRIB_ARRAY_STRIDE',
943 'GL_VERTEX_ATTRIB_ARRAY_TYPE',
944 'GL_CURRENT_VERTEX_ATTRIB',
950 'GL_VERTEX_ATTRIB_ARRAY_POINTER',
956 'GL_GENERATE_MIPMAP_HINT',
959 'GL_PERSPECTIVE_CORRECTION_HINT',
974 'GL_UNPACK_ALIGNMENT',
975 'GL_UNPACK_FLIP_Y_CHROMIUM',
976 'GL_UNPACK_PREMULTIPLY_ALPHA_CHROMIUM',
977 'GL_UNPACK_UNPREMULTIPLY_ALPHA_CHROMIUM',
980 'GL_PACK_SWAP_BYTES',
981 'GL_UNPACK_SWAP_BYTES',
984 'PixelStoreAlignment': {
1009 'GL_UNSIGNED_SHORT_5_6_5',
1010 'GL_UNSIGNED_SHORT_4_4_4_4',
1011 'GL_UNSIGNED_SHORT_5_5_5_1',
1022 'GL_UNSIGNED_SHORT_5_6_5',
1023 'GL_UNSIGNED_SHORT_4_4_4_4',
1024 'GL_UNSIGNED_SHORT_5_5_5_1',
1031 'RenderBufferFormat': {
1037 'GL_DEPTH_COMPONENT16',
1038 'GL_STENCIL_INDEX8',
1041 'ShaderBinaryFormat': {
1064 'GL_LUMINANCE_ALPHA',
1073 'TextureInternalFormat': {
1078 'GL_LUMINANCE_ALPHA',
1087 'TextureInternalFormatStorage': {
1094 'GL_LUMINANCE8_EXT',
1095 'GL_LUMINANCE8_ALPHA8_EXT',
1100 'VertexAttribType': {
1106 'GL_UNSIGNED_SHORT',
1107 # 'GL_FIXED', // This is not available on Desktop GL.
1123 'VertexAttribSize': {
1146 'type': 'GLboolean',
1157 'GL_GUILTY_CONTEXT_RESET_ARB',
1158 'GL_INNOCENT_CONTEXT_RESET_ARB',
1159 'GL_UNKNOWN_CONTEXT_RESET_ARB',
1164 # This table specifies the different pepper interfaces that are supported for
1165 # GL commands. 'dev' is true if it's a dev interface.
1166 _PEPPER_INTERFACES
= [
1167 {'name': '', 'dev': False},
1168 {'name': 'InstancedArrays', 'dev': False},
1169 {'name': 'FramebufferBlit', 'dev': False},
1170 {'name': 'FramebufferMultisample', 'dev': False},
1171 {'name': 'ChromiumEnableFeature', 'dev': False},
1172 {'name': 'ChromiumMapSub', 'dev': False},
1173 {'name': 'Query', 'dev': False},
1176 # This table specifies types and other special data for the commands that
1177 # will be generated.
1179 # Must match function names specified in "cmd_buffer_functions.txt".
1181 # cmd_comment: A comment added to the cmd format.
1182 # type: defines which handler will be used to generate code.
1183 # decoder_func: defines which function to call in the decoder to execute the
1184 # corresponding GL command. If not specified the GL command will
1185 # be called directly.
1186 # gl_test_func: GL function that is expected to be called when testing.
1187 # cmd_args: The arguments to use for the command. This overrides generating
1188 # them based on the GL function arguments.
1189 # a NonImmediate type is a type that stays a pointer even in
1190 # and immediate version of acommand.
1191 # gen_cmd: Whether or not this function geneates a command. Default = True.
1192 # immediate: Whether or not to generate an immediate command for the GL
1193 # function. The default is if there is exactly 1 pointer argument
1194 # in the GL function an immediate command is generated.
1195 # bucket: True to generate a bucket version of the command.
1196 # impl_func: Whether or not to generate the GLES2Implementation part of this
1198 # impl_decl: Whether or not to generate the GLES2Implementation declaration
1200 # needs_size: If true a data_size field is added to the command.
1201 # data_type: The type of data the command uses. For PUTn or PUT types.
1202 # count: The number of units per element. For PUTn or PUT types.
1203 # unit_test: If False no service side unit test will be generated.
1204 # client_test: If False no client side unit test will be generated.
1205 # expectation: If False the unit test will have no expected calls.
1206 # gen_func: Name of function that generates GL resource for corresponding
1208 # states: array of states that get set by this function corresponding to
1209 # the given arguments
1210 # state_flag: name of flag that is set to true when function is called.
1211 # no_gl: no GL function is called.
1212 # valid_args: A dictionary of argument indices to args to use in unit tests
1213 # when they can not be automatically determined.
1214 # pepper_interface: The pepper interface that is used for this extension
1215 # invalid_test: False if no invalid test needed.
1216 # shadowed: True = the value is shadowed so no glGetXXX call will be made.
1217 # first_element_only: For PUT types, True if only the first element of an
1218 # array is used and we end up calling the single value
1219 # corresponding function. eg. TexParameteriv -> TexParameteri
1223 'decoder_func': 'DoActiveTexture',
1226 'client_test': False,
1228 'AttachShader': {'decoder_func': 'DoAttachShader'},
1229 'BindAttribLocation': {'type': 'GLchar', 'bucket': True, 'needs_size': True},
1232 'decoder_func': 'DoBindBuffer',
1233 'gen_func': 'GenBuffersARB',
1235 'BindFramebuffer': {
1237 'decoder_func': 'DoBindFramebuffer',
1238 'gl_test_func': 'glBindFramebufferEXT',
1239 'gen_func': 'GenFramebuffersEXT',
1241 'BindRenderbuffer': {
1243 'decoder_func': 'DoBindRenderbuffer',
1244 'gl_test_func': 'glBindRenderbufferEXT',
1245 'gen_func': 'GenRenderbuffersEXT',
1249 'decoder_func': 'DoBindTexture',
1250 'gen_func': 'GenTextures',
1251 # TODO(gman): remove this once client side caching works.
1252 'client_test': False,
1254 'BlitFramebufferEXT': {
1255 'decoder_func': 'DoBlitFramebufferEXT',
1258 'pepper_interface': 'FramebufferBlit',
1259 'defer_reads': True,
1260 'defer_draws': True,
1265 'client_test': False,
1269 'client_test': False,
1270 'decoder_func': 'DoBufferSubData',
1272 'CheckFramebufferStatus': {
1274 'decoder_func': 'DoCheckFramebufferStatus',
1275 'gl_test_func': 'glCheckFramebufferStatusEXT',
1276 'error_value': 'GL_FRAMEBUFFER_UNSUPPORTED',
1277 'result': ['GLenum'],
1280 'decoder_func': 'DoClear',
1281 'defer_draws': True,
1285 'state': 'ClearColor',
1289 'state': 'ClearDepthf',
1290 'decoder_func': 'glClearDepth',
1291 'gl_test_func': 'glClearDepth',
1298 'state': 'ColorMask',
1300 'expectation': False,
1302 'ConsumeTextureCHROMIUM': {
1303 'decoder_func': 'DoConsumeTextureCHROMIUM',
1305 'data_type': 'GLbyte',
1313 'state': 'ClearStencil',
1315 'EnableFeatureCHROMIUM': {
1318 'decoder_func': 'DoEnableFeatureCHROMIUM',
1319 'expectation': False,
1320 'cmd_args': 'GLuint bucket_id, GLint* result',
1321 'result': ['GLint'],
1324 'pepper_interface': 'ChromiumEnableFeature',
1326 'CompileShader': {'decoder_func': 'DoCompileShader', 'unit_test': False},
1327 'CompressedTexImage2D': {
1332 'CompressedTexSubImage2D': {
1335 'decoder_func': 'DoCompressedTexSubImage2D',
1338 'decoder_func': 'DoCopyTexImage2D',
1340 'defer_reads': True,
1342 'CopyTexSubImage2D': {
1343 'decoder_func': 'DoCopyTexSubImage2D',
1344 'defer_reads': True,
1346 'CreateImageCHROMIUM': {
1348 'cmd_args': 'GLsizei width, GLsizei height, GLenum internalformat',
1349 'result': ['GLuint'],
1350 'client_test': False,
1352 'expectation': False,
1356 'DestroyImageCHROMIUM': {
1359 'client_test': False,
1364 'GetImageParameterivCHROMIUM': {
1366 'client_test': False,
1368 'expectation': False,
1374 'client_test': False,
1378 'client_test': False,
1382 'state': 'BlendColor',
1385 'type': 'StateSetRGBAlpha',
1386 'state': 'BlendEquation',
1388 '0': 'GL_FUNC_SUBTRACT'
1391 'BlendEquationSeparate': {
1393 'state': 'BlendEquation',
1395 '0': 'GL_FUNC_SUBTRACT'
1399 'type': 'StateSetRGBAlpha',
1400 'state': 'BlendFunc',
1402 'BlendFuncSeparate': {
1404 'state': 'BlendFunc',
1406 'SampleCoverage': {'decoder_func': 'DoSampleCoverage'},
1408 'type': 'StateSetFrontBack',
1409 'state': 'StencilFunc',
1411 'StencilFuncSeparate': {
1412 'type': 'StateSetFrontBackSeparate',
1413 'state': 'StencilFunc',
1416 'type': 'StateSetFrontBack',
1417 'state': 'StencilOp',
1422 'StencilOpSeparate': {
1423 'type': 'StateSetFrontBackSeparate',
1424 'state': 'StencilOp',
1430 'type': 'StateSetNamedParameter',
1433 'CullFace': {'type': 'StateSet', 'state': 'CullFace'},
1434 'FrontFace': {'type': 'StateSet', 'state': 'FrontFace'},
1435 'DepthFunc': {'type': 'StateSet', 'state': 'DepthFunc'},
1438 'state': 'LineWidth',
1445 'state': 'PolygonOffset',
1449 'gl_test_func': 'glDeleteBuffersARB',
1450 'resource_type': 'Buffer',
1451 'resource_types': 'Buffers',
1453 'DeleteFramebuffers': {
1455 'gl_test_func': 'glDeleteFramebuffersEXT',
1456 'resource_type': 'Framebuffer',
1457 'resource_types': 'Framebuffers',
1459 'DeleteProgram': {'type': 'Delete', 'decoder_func': 'DoDeleteProgram'},
1460 'DeleteRenderbuffers': {
1462 'gl_test_func': 'glDeleteRenderbuffersEXT',
1463 'resource_type': 'Renderbuffer',
1464 'resource_types': 'Renderbuffers',
1466 'DeleteShader': {'type': 'Delete', 'decoder_func': 'DoDeleteShader'},
1467 'DeleteSharedIdsCHROMIUM': {
1469 'decoder_func': 'DoDeleteSharedIdsCHROMIUM',
1471 'expectation': False,
1478 'resource_type': 'Texture',
1479 'resource_types': 'Textures',
1482 'decoder_func': 'DoDepthRangef',
1483 'gl_test_func': 'glDepthRange',
1487 'state': 'DepthMask',
1489 'expectation': False,
1491 'DetachShader': {'decoder_func': 'DoDetachShader'},
1493 'decoder_func': 'DoDisable',
1495 'client_test': False,
1497 'DisableVertexAttribArray': {
1498 'decoder_func': 'DoDisableVertexAttribArray',
1503 'cmd_args': 'GLenumDrawMode mode, GLint first, GLsizei count',
1504 'defer_draws': True,
1508 'cmd_args': 'GLenumDrawMode mode, GLsizei count, '
1509 'GLenumIndexType type, GLuint index_offset',
1510 'client_test': False,
1511 'defer_draws': True,
1514 'decoder_func': 'DoEnable',
1516 'client_test': False,
1518 'EnableVertexAttribArray': {
1519 'decoder_func': 'DoEnableVertexAttribArray',
1524 'client_test': False,
1525 'decoder_func': 'DoFinish',
1526 'defer_reads': True,
1530 'decoder_func': 'DoFlush',
1532 'FramebufferRenderbuffer': {
1533 'decoder_func': 'DoFramebufferRenderbuffer',
1534 'gl_test_func': 'glFramebufferRenderbufferEXT',
1536 'FramebufferTexture2D': {
1537 'decoder_func': 'DoFramebufferTexture2D',
1538 'gl_test_func': 'glFramebufferTexture2DEXT',
1540 'FramebufferTexture2DMultisampleEXT': {
1541 'decoder_func': 'DoFramebufferTexture2DMultisample',
1542 'gl_test_func': 'glFramebufferTexture2DMultisampleEXT',
1543 'expectation': False,
1548 'decoder_func': 'DoGenerateMipmap',
1549 'gl_test_func': 'glGenerateMipmapEXT',
1553 'gl_test_func': 'glGenBuffersARB',
1554 'resource_type': 'Buffer',
1555 'resource_types': 'Buffers',
1557 'GenMailboxCHROMIUM': {
1559 'cmd_args': 'GLuint bucket_id',
1560 'result': ['SizedResult<GLint>'],
1561 'client_test': False,
1566 'GenFramebuffers': {
1568 'gl_test_func': 'glGenFramebuffersEXT',
1569 'resource_type': 'Framebuffer',
1570 'resource_types': 'Framebuffers',
1572 'GenRenderbuffers': {
1573 'type': 'GENn', 'gl_test_func': 'glGenRenderbuffersEXT',
1574 'resource_type': 'Renderbuffer',
1575 'resource_types': 'Renderbuffers',
1579 'gl_test_func': 'glGenTextures',
1580 'resource_type': 'Texture',
1581 'resource_types': 'Textures',
1583 'GenSharedIdsCHROMIUM': {
1585 'decoder_func': 'DoGenSharedIdsCHROMIUM',
1587 'expectation': False,
1592 'GetActiveAttrib': {
1596 'GLidProgram program, GLuint index, uint32 name_bucket_id, '
1604 'GetActiveUniform': {
1608 'GLidProgram program, GLuint index, uint32 name_bucket_id, '
1616 'GetAttachedShaders': {
1619 'cmd_args': 'GLidProgram program, void* result, uint32 result_size',
1620 'result': ['SizedResult<GLuint>'],
1622 'GetAttribLocation': {
1623 'type': 'HandWritten',
1628 'GLidProgram program, const char* name, NonImmediate GLint* location',
1629 'result': ['GLint'],
1633 'result': ['SizedResult<GLboolean>'],
1634 'decoder_func': 'DoGetBooleanv',
1635 'gl_test_func': 'glGetBooleanv',
1637 'GetBufferParameteriv': {
1639 'result': ['SizedResult<GLint>'],
1640 'decoder_func': 'DoGetBufferParameteriv',
1641 'expectation': False,
1646 'decoder_func': 'GetErrorState()->GetGLError',
1648 'result': ['GLenum'],
1649 'client_test': False,
1653 'result': ['SizedResult<GLfloat>'],
1654 'decoder_func': 'DoGetFloatv',
1655 'gl_test_func': 'glGetFloatv',
1657 'GetFramebufferAttachmentParameteriv': {
1659 'decoder_func': 'DoGetFramebufferAttachmentParameteriv',
1660 'gl_test_func': 'glGetFramebufferAttachmentParameterivEXT',
1661 'result': ['SizedResult<GLint>'],
1665 'result': ['SizedResult<GLint>'],
1666 'decoder_func': 'DoGetIntegerv',
1667 'client_test': False,
1669 'GetMaxValueInBufferCHROMIUM': {
1671 'decoder_func': 'DoGetMaxValueInBufferCHROMIUM',
1672 'result': ['GLuint'],
1674 'client_test': False,
1679 'GetMultipleIntegervCHROMIUM': {
1682 'expectation': False,
1685 'client_test': False,
1689 'decoder_func': 'DoGetProgramiv',
1690 'result': ['SizedResult<GLint>'],
1691 'expectation': False,
1693 'GetProgramInfoCHROMIUM': {
1696 'expectation': False,
1700 'client_test': False,
1701 'cmd_args': 'GLidProgram program, uint32 bucket_id',
1703 'uint32 link_status',
1704 'uint32 num_attribs',
1705 'uint32 num_uniforms',
1708 'GetProgramInfoLog': {
1710 'expectation': False,
1712 'GetRenderbufferParameteriv': {
1714 'decoder_func': 'DoGetRenderbufferParameteriv',
1715 'gl_test_func': 'glGetRenderbufferParameterivEXT',
1716 'result': ['SizedResult<GLint>'],
1720 'decoder_func': 'DoGetShaderiv',
1721 'result': ['SizedResult<GLint>'],
1723 'GetShaderInfoLog': {
1725 'get_len_func': 'glGetShaderiv',
1726 'get_len_enum': 'GL_INFO_LOG_LENGTH',
1729 'GetShaderPrecisionFormat': {
1733 'GLenumShaderType shadertype, GLenumShaderPrecision precisiontype, '
1742 'GetShaderSource': {
1744 'get_len_func': 'DoGetShaderiv',
1745 'get_len_enum': 'GL_SHADER_SOURCE_LENGTH',
1747 'client_test': False,
1751 'client_test': False,
1752 'cmd_args': 'GLenumStringType name, uint32 bucket_id',
1754 'GetTexParameterfv': {'type': 'GETn', 'result': ['SizedResult<GLfloat>']},
1755 'GetTexParameteriv': {'type': 'GETn', 'result': ['SizedResult<GLint>']},
1756 'GetTranslatedShaderSourceANGLE': {
1758 'get_len_func': 'DoGetShaderiv',
1759 'get_len_enum': 'GL_TRANSLATED_SHADER_SOURCE_LENGTH_ANGLE',
1766 'result': ['SizedResult<GLfloat>'],
1771 'result': ['SizedResult<GLint>'],
1773 'GetUniformLocation': {
1774 'type': 'HandWritten',
1779 'GLidProgram program, const char* name, NonImmediate GLint* location',
1780 'result': ['GLint'],
1782 'GetVertexAttribfv': {
1784 'result': ['SizedResult<GLfloat>'],
1786 'decoder_func': 'DoGetVertexAttribfv',
1787 'expectation': False,
1788 'client_test': False,
1790 'GetVertexAttribiv': {
1792 'result': ['SizedResult<GLint>'],
1794 'decoder_func': 'DoGetVertexAttribiv',
1795 'expectation': False,
1796 'client_test': False,
1798 'GetVertexAttribPointerv': {
1801 'result': ['SizedResult<GLuint>'],
1802 'client_test': False,
1806 'decoder_func': 'DoIsBuffer',
1807 'expectation': False,
1811 'decoder_func': 'DoIsEnabled',
1813 'expectation': False,
1817 'decoder_func': 'DoIsFramebuffer',
1818 'expectation': False,
1822 'decoder_func': 'DoIsProgram',
1823 'expectation': False,
1827 'decoder_func': 'DoIsRenderbuffer',
1828 'expectation': False,
1832 'decoder_func': 'DoIsShader',
1833 'expectation': False,
1837 'decoder_func': 'DoIsTexture',
1838 'expectation': False,
1841 'decoder_func': 'DoLinkProgram',
1844 'MapBufferCHROMIUM': {
1848 'client_test': False,
1850 'MapBufferSubDataCHROMIUM': {
1854 'client_test': False,
1855 'pepper_interface': 'ChromiumMapSub',
1857 'MapImageCHROMIUM': {
1861 'client_test': False,
1863 'MapTexSubImage2DCHROMIUM': {
1867 'client_test': False,
1868 'pepper_interface': 'ChromiumMapSub',
1870 'PixelStorei': {'type': 'Manual'},
1871 'PostSubBufferCHROMIUM': {
1875 'client_test': False,
1879 'ProduceTextureCHROMIUM': {
1880 'decoder_func': 'DoProduceTextureCHROMIUM',
1882 'data_type': 'GLbyte',
1888 'RenderbufferStorage': {
1889 'decoder_func': 'DoRenderbufferStorage',
1890 'gl_test_func': 'glRenderbufferStorageEXT',
1891 'expectation': False,
1893 'RenderbufferStorageMultisampleEXT': {
1894 'decoder_func': 'DoRenderbufferStorageMultisample',
1895 'gl_test_func': 'glRenderbufferStorageMultisampleEXT',
1896 'expectation': False,
1899 'pepper_interface': 'FramebufferMultisample',
1903 '// ReadPixels has the result separated from the pixel buffer so that\n'
1904 '// it is easier to specify the result going to some specific place\n'
1905 '// that exactly fits the rectangle of pixels.\n',
1909 'client_test': False,
1911 'GLint x, GLint y, GLsizei width, GLsizei height, '
1912 'GLenumReadPixelFormat format, GLenumReadPixelType type, '
1913 'uint32 pixels_shm_id, uint32 pixels_shm_offset, '
1914 'uint32 result_shm_id, uint32 result_shm_offset, '
1916 'result': ['uint32'],
1917 'defer_reads': True,
1919 'RegisterSharedIdsCHROMIUM': {
1921 'decoder_func': 'DoRegisterSharedIdsCHROMIUM',
1923 'expectation': False,
1928 'ReleaseShaderCompiler': {
1929 'decoder_func': 'DoReleaseShaderCompiler',
1934 'client_test': False,
1941 'client_test': False,
1943 'GLuint shader, const char* data',
1946 'type': 'StateSetFrontBack',
1947 'state': 'StencilMask',
1949 'expectation': False,
1951 'StencilMaskSeparate': {
1952 'type': 'StateSetFrontBackSeparate',
1953 'state': 'StencilMask',
1955 'expectation': False,
1959 'decoder_func': 'DoSwapBuffers',
1961 'client_test': False,
1967 'client_test': False,
1970 'decoder_func': 'DoTexParameterf',
1971 'gl_test_func': 'glTexParameteri',
1977 'decoder_func': 'DoTexParameteri',
1984 'data_type': 'GLfloat',
1985 'data_value': 'GL_NEAREST',
1987 'decoder_func': 'DoTexParameterfv',
1988 'gl_test_func': 'glTexParameteri',
1989 'first_element_only': True,
1993 'data_type': 'GLint',
1994 'data_value': 'GL_NEAREST',
1996 'decoder_func': 'DoTexParameteriv',
1997 'gl_test_func': 'glTexParameteri',
1998 'first_element_only': True,
2003 'client_test': False,
2004 'cmd_args': 'GLenumTextureTarget target, GLint level, '
2005 'GLint xoffset, GLint yoffset, '
2006 'GLsizei width, GLsizei height, '
2007 'GLenumTextureFormat format, GLenumPixelType type, '
2008 'const void* pixels, GLboolean internal'
2010 'Uniform1f': {'type': 'PUTXn', 'data_type': 'GLfloat', 'count': 1},
2013 'data_type': 'GLfloat',
2015 'decoder_func': 'DoUniform1fv',
2017 'Uniform1i': {'decoder_func': 'DoUniform1i', 'unit_test': False},
2020 'data_type': 'GLint',
2022 'decoder_func': 'DoUniform1iv',
2025 'Uniform2i': {'type': 'PUTXn', 'data_type': 'GLint', 'count': 2},
2026 'Uniform2f': {'type': 'PUTXn', 'data_type': 'GLfloat', 'count': 2},
2029 'data_type': 'GLfloat',
2031 'decoder_func': 'DoUniform2fv',
2035 'data_type': 'GLint',
2037 'decoder_func': 'DoUniform2iv',
2039 'Uniform3i': {'type': 'PUTXn', 'data_type': 'GLint', 'count': 3},
2040 'Uniform3f': {'type': 'PUTXn', 'data_type': 'GLfloat', 'count': 3},
2043 'data_type': 'GLfloat',
2045 'decoder_func': 'DoUniform3fv',
2049 'data_type': 'GLint',
2051 'decoder_func': 'DoUniform3iv',
2053 'Uniform4i': {'type': 'PUTXn', 'data_type': 'GLint', 'count': 4},
2054 'Uniform4f': {'type': 'PUTXn', 'data_type': 'GLfloat', 'count': 4},
2057 'data_type': 'GLfloat',
2059 'decoder_func': 'DoUniform4fv',
2063 'data_type': 'GLint',
2065 'decoder_func': 'DoUniform4iv',
2067 'UniformMatrix2fv': {
2069 'data_type': 'GLfloat',
2071 'decoder_func': 'DoUniformMatrix2fv',
2073 'UniformMatrix3fv': {
2075 'data_type': 'GLfloat',
2077 'decoder_func': 'DoUniformMatrix3fv',
2079 'UniformMatrix4fv': {
2081 'data_type': 'GLfloat',
2083 'decoder_func': 'DoUniformMatrix4fv',
2085 'UnmapBufferCHROMIUM': {
2089 'client_test': False,
2091 'UnmapBufferSubDataCHROMIUM': {
2095 'client_test': False,
2096 'pepper_interface': 'ChromiumMapSub',
2098 'UnmapImageCHROMIUM': {
2102 'client_test': False,
2104 'UnmapTexSubImage2DCHROMIUM': {
2108 'client_test': False,
2109 'pepper_interface': 'ChromiumMapSub',
2112 'decoder_func': 'DoUseProgram',
2116 'ValidateProgram': {'decoder_func': 'DoValidateProgram'},
2117 'VertexAttrib1f': {'decoder_func': 'DoVertexAttrib1f'},
2118 'VertexAttrib1fv': {
2120 'data_type': 'GLfloat',
2122 'decoder_func': 'DoVertexAttrib1fv',
2124 'VertexAttrib2f': {'decoder_func': 'DoVertexAttrib2f'},
2125 'VertexAttrib2fv': {
2127 'data_type': 'GLfloat',
2129 'decoder_func': 'DoVertexAttrib2fv',
2131 'VertexAttrib3f': {'decoder_func': 'DoVertexAttrib3f'},
2132 'VertexAttrib3fv': {
2134 'data_type': 'GLfloat',
2136 'decoder_func': 'DoVertexAttrib3fv',
2138 'VertexAttrib4f': {'decoder_func': 'DoVertexAttrib4f'},
2139 'VertexAttrib4fv': {
2141 'data_type': 'GLfloat',
2143 'decoder_func': 'DoVertexAttrib4fv',
2145 'VertexAttribPointer': {
2147 'cmd_args': 'GLuint indx, GLintVertexAttribSize size, '
2148 'GLenumVertexAttribType type, GLboolean normalized, '
2149 'GLsizei stride, GLuint offset',
2150 'client_test': False,
2157 'decoder_func': 'DoViewport',
2166 'GetRequestableExtensionsCHROMIUM': {
2170 'cmd_args': 'uint32 bucket_id',
2174 'RequestExtensionCHROMIUM': {
2178 'client_test': False,
2179 'cmd_args': 'uint32 bucket_id',
2183 'RateLimitOffscreenContextCHROMIUM': {
2187 'client_test': False,
2189 'CreateStreamTextureCHROMIUM': {
2191 'cmd_args': 'GLuint client_id, void* result',
2192 'result': ['GLuint'],
2195 'expectation': False,
2198 'client_test': False,
2200 'DestroyStreamTextureCHROMIUM': {
2203 'expectation': False,
2207 'TexImageIOSurface2DCHROMIUM': {
2208 'decoder_func': 'DoTexImageIOSurface2DCHROMIUM',
2213 'CopyTextureCHROMIUM': {
2214 'decoder_func': 'DoCopyTextureCHROMIUM',
2219 'TexStorage2DEXT': {
2222 'decoder_func': 'DoTexStorage2DEXT',
2224 'DrawArraysInstancedANGLE': {
2226 'cmd_args': 'GLenumDrawMode mode, GLint first, GLsizei count, '
2227 'GLsizei primcount',
2230 'pepper_interface': 'InstancedArrays',
2231 'defer_draws': True,
2235 'decoder_func': 'DoDrawBuffersEXT',
2236 'data_type': 'GLenum',
2238 'client_test': False,
2242 'DrawElementsInstancedANGLE': {
2244 'cmd_args': 'GLenumDrawMode mode, GLsizei count, '
2245 'GLenumIndexType type, GLuint index_offset, GLsizei primcount',
2248 'client_test': False,
2249 'pepper_interface': 'InstancedArrays',
2250 'defer_draws': True,
2252 'VertexAttribDivisorANGLE': {
2254 'cmd_args': 'GLuint index, GLuint divisor',
2257 'pepper_interface': 'InstancedArrays',
2261 'gl_test_func': 'glGenQueriesARB',
2262 'resource_type': 'Query',
2263 'resource_types': 'Queries',
2265 'pepper_interface': 'Query',
2267 'DeleteQueriesEXT': {
2269 'gl_test_func': 'glDeleteQueriesARB',
2270 'resource_type': 'Query',
2271 'resource_types': 'Queries',
2273 'pepper_interface': 'Query',
2277 'client_test': False,
2278 'pepper_interface': 'Query',
2282 'cmd_args': 'GLenumQueryTarget target, GLidQuery id, void* sync_data',
2284 'gl_test_func': 'glBeginQuery',
2285 'pepper_interface': 'Query',
2289 'cmd_args': 'GLenumQueryTarget target, GLuint submit_count',
2290 'gl_test_func': 'glEndnQuery',
2291 'client_test': False,
2292 'pepper_interface': 'Query',
2296 'client_test': False,
2297 'gl_test_func': 'glGetQueryiv',
2298 'pepper_interface': 'Query',
2300 'GetQueryObjectuivEXT': {
2302 'client_test': False,
2303 'gl_test_func': 'glGetQueryObjectuiv',
2304 'pepper_interface': 'Query',
2306 'BindUniformLocationCHROMIUM': {
2310 'gl_test_func': 'DoBindUniformLocationCHROMIUM',
2312 'InsertEventMarkerEXT': {
2314 'decoder_func': 'DoInsertEventMarkerEXT',
2315 'expectation': False,
2317 'PushGroupMarkerEXT': {
2319 'decoder_func': 'DoPushGroupMarkerEXT',
2320 'expectation': False,
2322 'PopGroupMarkerEXT': {
2323 'decoder_func': 'DoPopGroupMarkerEXT',
2324 'expectation': False,
2328 'GenVertexArraysOES': {
2330 'gl_test_func': 'glGenVertexArraysOES',
2331 'resource_type': 'VertexArray',
2332 'resource_types': 'VertexArrays',
2335 'BindVertexArrayOES': {
2337 'gl_test_func': 'glBindVertexArrayOES',
2338 'decoder_func': 'DoBindVertexArrayOES',
2339 'gen_func': 'GenVertexArraysOES',
2341 'client_test': False,
2343 'DeleteVertexArraysOES': {
2345 'gl_test_func': 'glDeleteVertexArraysOES',
2346 'resource_type': 'VertexArray',
2347 'resource_types': 'VertexArrays',
2350 'IsVertexArrayOES': {
2352 'gl_test_func': 'glIsVertexArrayOES',
2353 'decoder_func': 'DoIsVertexArrayOES',
2354 'expectation': False,
2357 'BindTexImage2DCHROMIUM': {
2358 'decoder_func': 'DoBindTexImage2DCHROMIUM',
2363 'ReleaseTexImage2DCHROMIUM': {
2364 'decoder_func': 'DoReleaseTexImage2DCHROMIUM',
2369 'ShallowFinishCHROMIUM': {
2374 'client_test': False,
2376 'ShallowFlushCHROMIUM': {
2381 'client_test': False,
2383 'TraceBeginCHROMIUM': {
2387 'client_test': False,
2388 'cmd_args': 'GLuint bucket_id',
2392 'TraceEndCHROMIUM': {
2395 'client_test': False,
2396 'decoder_func': 'DoTraceEndCHROMIUM',
2401 'AsyncTexImage2DCHROMIUM': {
2404 'client_test': False,
2408 'AsyncTexSubImage2DCHROMIUM': {
2411 'client_test': False,
2415 'WaitAsyncTexImage2DCHROMIUM': {
2418 'client_test': False,
2422 'DiscardFramebufferEXT': {
2425 'data_type': 'GLenum',
2426 'cmd_args': 'GLenum target, GLsizei count, '
2427 'const GLenum* attachments',
2428 'decoder_func': 'DoDiscardFramebufferEXT',
2430 'client_test': False,
2433 'LoseContextCHROMIUM': {
2439 'InsertSyncPointCHROMIUM': {
2440 'type': 'HandWritten',
2445 'WaitSyncPointCHROMIUM': {
2454 def Grouper(n
, iterable
, fillvalue
=None):
2455 """Collect data into fixed-length chunks or blocks"""
2456 args
= [iter(iterable
)] * n
2457 return itertools
.izip_longest(fillvalue
=fillvalue
, *args
)
2460 def SplitWords(input_string
):
2461 """Transforms a input_string into a list of lower-case components.
2464 input_string: the input string.
2467 a list of lower-case words.
2469 if input_string
.find('_') > -1:
2470 # 'some_TEXT_' -> 'some text'
2471 return input_string
.replace('_', ' ').strip().lower().split()
2473 if re
.search('[A-Z]', input_string
) and re
.search('[a-z]', input_string
):
2475 # look for capitalization to cut input_strings
2476 # 'SomeText' -> 'Some Text'
2477 input_string
= re
.sub('([A-Z])', r
' \1', input_string
).strip()
2478 # 'Vector3' -> 'Vector 3'
2479 input_string
= re
.sub('([^0-9])([0-9])', r
'\1 \2', input_string
)
2480 return input_string
.lower().split()
2484 """Makes a lower-case identifier from words.
2487 words: a list of lower-case words.
2490 the lower-case identifier.
2492 return '_'.join(words
)
2495 def ToUnderscore(input_string
):
2496 """converts CamelCase to camel_case."""
2497 words
= SplitWords(input_string
)
2501 class CWriter(object):
2502 """Writes to a file formatting it for Google's style guidelines."""
2504 def __init__(self
, filename
):
2505 self
.filename
= filename
2509 def SetFileNum(self
, num
):
2510 """Used to help write number files and tests."""
2513 def Write(self
, string
):
2514 """Writes a string to a file spliting if it's > 80 characters."""
2515 lines
= string
.splitlines()
2516 num_lines
= len(lines
)
2517 for ii
in range(0, num_lines
):
2518 self
.__WriteLine
(lines
[ii
], ii
< (num_lines
- 1) or string
[-1] == '\n')
2520 def __FindSplit(self
, string
):
2521 """Finds a place to split a string."""
2522 splitter
= string
.find('=')
2523 if splitter
>= 1 and not string
[splitter
+ 1] == '=' and splitter
< 80:
2525 # parts = string.split('(')
2526 parts
= re
.split("(?<=[^\"])\((?!\")", string
)
2527 fptr
= re
.compile('\*\w*\)')
2529 splitter
= len(parts
[0])
2530 for ii
in range(1, len(parts
)):
2531 # Don't split on the dot in "if (.condition)".
2532 if (not parts
[ii
- 1][-3:] == "if " and
2533 # Don't split "(.)" or "(.*fptr)".
2534 (len(parts
[ii
]) > 0 and
2535 not parts
[ii
][0] == ")" and not fptr
.match(parts
[ii
]))
2538 splitter
+= len(parts
[ii
]) + 1
2543 splitter
= string
[0:end
].rfind(',')
2544 if splitter
< 0 or (splitter
> 0 and string
[splitter
- 1] == '"'):
2545 return last_splitter
2546 elif splitter
>= 80:
2551 def __WriteLine(self
, line
, ends_with_eol
):
2552 """Given a signle line, writes it to a file, splitting if it's > 80 chars"""
2554 i
= self
.__FindSplit
(line
)
2556 line1
= line
[0:i
+ 1]
2557 if line1
[-1] == ' ':
2564 nolint
= ' // NOLINT'
2565 self
.__AddLine
(line1
+ nolint
+ lineend
+ '\n')
2566 match
= re
.match("( +)", line1
)
2569 indent
= match
.group(1)
2571 if not splitter
== ',':
2572 indent
= " " + indent
2573 self
.__WriteLine
(indent
+ line
[i
+ 1:].lstrip(), True)
2577 nolint
= ' // NOLINT'
2578 self
.__AddLine
(line
+ nolint
)
2580 self
.__AddLine
('\n')
2582 def __AddLine(self
, line
):
2583 self
.content
.append(line
)
2586 """Close the file."""
2587 content
= "".join(self
.content
)
2589 if os
.path
.exists(self
.filename
):
2590 old_file
= open(self
.filename
, "rb");
2591 old_content
= old_file
.read()
2593 if content
== old_content
:
2596 file = open(self
.filename
, "wb")
2601 class CHeaderWriter(CWriter
):
2602 """Writes a C Header file."""
2604 _non_alnum_re
= re
.compile(r
'[^a-zA-Z0-9]')
2606 def __init__(self
, filename
, file_comment
= None):
2607 CWriter
.__init
__(self
, filename
)
2609 base
= os
.path
.abspath(filename
)
2610 while os
.path
.basename(base
) != 'src':
2611 new_base
= os
.path
.dirname(base
)
2612 assert new_base
!= base
# Prevent infinite loop.
2615 hpath
= os
.path
.relpath(filename
, base
)
2616 self
.guard
= self
._non
_alnum
_re
.sub('_', hpath
).upper() + '_'
2618 self
.Write(_LICENSE
)
2619 self
.Write(_DO_NOT_EDIT_WARNING
)
2620 if not file_comment
== None:
2621 self
.Write(file_comment
)
2622 self
.Write("#ifndef %s\n" % self
.guard
)
2623 self
.Write("#define %s\n\n" % self
.guard
)
2626 self
.Write("#endif // %s\n\n" % self
.guard
)
2629 class TypeHandler(object):
2630 """This class emits code for a particular type of function."""
2632 _remove_expected_call_re
= re
.compile(r
' EXPECT_CALL.*?;\n', re
.S
)
2637 def InitFunction(self
, func
):
2638 """Add or adjust anything type specific for this function."""
2639 if func
.GetInfo('needs_size') and not func
.name
.endswith('Bucket'):
2640 func
.AddCmdArg(DataSizeArgument('data_size'))
2642 def AddImmediateFunction(self
, generator
, func
):
2643 """Adds an immediate version of a function."""
2644 # Generate an immediate command if there is only 1 pointer arg.
2645 immediate
= func
.GetInfo('immediate') # can be True, False or None
2646 if immediate
== True or immediate
== None:
2647 if func
.num_pointer_args
== 1 or immediate
:
2648 generator
.AddFunction(ImmediateFunction(func
))
2650 def AddBucketFunction(self
, generator
, func
):
2651 """Adds a bucket version of a function."""
2652 # Generate an immediate command if there is only 1 pointer arg.
2653 bucket
= func
.GetInfo('bucket') # can be True, False or None
2655 generator
.AddFunction(BucketFunction(func
))
2657 def WriteStruct(self
, func
, file):
2658 """Writes a structure that matches the arguments to a function."""
2659 comment
= func
.GetInfo('cmd_comment')
2660 if not comment
== None:
2662 file.Write("struct %s {\n" % func
.name
)
2663 file.Write(" typedef %s ValueType;\n" % func
.name
)
2664 file.Write(" static const CommandId kCmdId = k%s;\n" % func
.name
)
2665 func
.WriteCmdArgFlag(file)
2667 result
= func
.GetInfo('result')
2668 if not result
== None:
2669 if len(result
) == 1:
2670 file.Write(" typedef %s Result;\n\n" % result
[0])
2672 file.Write(" struct Result {\n")
2674 file.Write(" %s;\n" % line
)
2675 file.Write(" };\n\n")
2677 func
.WriteCmdComputeSize(file)
2678 func
.WriteCmdSetHeader(file)
2679 func
.WriteCmdInit(file)
2680 func
.WriteCmdSet(file)
2682 file.Write(" gpu::CommandHeader header;\n")
2683 args
= func
.GetCmdArgs()
2685 file.Write(" %s %s;\n" % (arg
.cmd_type
, arg
.name
))
2689 size
= len(args
) * _SIZE_OF_UINT32
+ _SIZE_OF_COMMAND_HEADER
2690 file.Write("COMPILE_ASSERT(sizeof(%s) == %d,\n" % (func
.name
, size
))
2691 file.Write(" Sizeof_%s_is_not_%d);\n" % (func
.name
, size
))
2692 file.Write("COMPILE_ASSERT(offsetof(%s, header) == 0,\n" % func
.name
)
2693 file.Write(" OffsetOf_%s_header_not_0);\n" % func
.name
)
2694 offset
= _SIZE_OF_COMMAND_HEADER
2696 file.Write("COMPILE_ASSERT(offsetof(%s, %s) == %d,\n" %
2697 (func
.name
, arg
.name
, offset
))
2698 file.Write(" OffsetOf_%s_%s_not_%d);\n" %
2699 (func
.name
, arg
.name
, offset
))
2700 offset
+= _SIZE_OF_UINT32
2701 if not result
== None and len(result
) > 1:
2704 parts
= line
.split()
2707 COMPILE_ASSERT(offsetof(%(cmd_name)s::Result, %(field_name)s) == %(offset)d,
2708 OffsetOf_%(cmd_name)s_Result_%(field_name)s_not_%(offset)d);
2710 file.Write((check
.strip() + "\n") % {
2711 'cmd_name': func
.name
,
2715 offset
+= _SIZE_OF_UINT32
2718 def WriteHandlerImplementation(self
, func
, file):
2719 """Writes the handler implementation for this command."""
2720 file.Write(" %s(%s);\n" %
2721 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
2723 def WriteCmdSizeTest(self
, func
, file):
2724 """Writes the size test for a command."""
2725 file.Write(" EXPECT_EQ(sizeof(cmd), cmd.header.size * 4u);\n")
2727 def WriteFormatTest(self
, func
, file):
2728 """Writes a format test for a command."""
2729 file.Write("TEST_F(GLES2FormatTest, %s) {\n" % func
.name
)
2730 file.Write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
2731 (func
.name
, func
.name
))
2732 file.Write(" void* next_cmd = cmd.Set(\n")
2734 args
= func
.GetCmdArgs()
2735 for value
, arg
in enumerate(args
):
2736 file.Write(",\n static_cast<%s>(%d)" % (arg
.type, value
+ 11))
2738 file.Write(" EXPECT_EQ(static_cast<uint32>(cmds::%s::kCmdId),\n" %
2740 file.Write(" cmd.header.command);\n")
2741 func
.type_handler
.WriteCmdSizeTest(func
, file)
2742 for value
, arg
in enumerate(args
):
2743 file.Write(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);\n" %
2744 (arg
.type, value
+ 11, arg
.name
))
2745 file.Write(" CheckBytesWrittenMatchesExpectedSize(\n")
2746 file.Write(" next_cmd, sizeof(cmd));\n")
2750 def WriteImmediateFormatTest(self
, func
, file):
2751 """Writes a format test for an immediate version of a command."""
2754 def WriteBucketFormatTest(self
, func
, file):
2755 """Writes a format test for a bucket version of a command."""
2758 def WriteGetDataSizeCode(self
, func
, file):
2759 """Writes the code to set data_size used in validation"""
2762 def WriteImmediateCmdSizeTest(self
, func
, file):
2763 """Writes a size test for an immediate version of a command."""
2764 file.Write(" // TODO(gman): Compute correct size.\n")
2765 file.Write(" EXPECT_EQ(sizeof(cmd), cmd.header.size * 4u);\n")
2767 def WriteImmediateHandlerImplementation (self
, func
, file):
2768 """Writes the handler impl for the immediate version of a command."""
2769 file.Write(" %s(%s);\n" %
2770 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
2772 def WriteBucketHandlerImplementation (self
, func
, file):
2773 """Writes the handler impl for the bucket version of a command."""
2774 file.Write(" %s(%s);\n" %
2775 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
2777 def WriteServiceImplementation(self
, func
, file):
2778 """Writes the service implementation for a command."""
2780 "error::Error GLES2DecoderImpl::Handle%s(\n" % func
.name
)
2782 " uint32 immediate_data_size, const gles2::cmds::%s& c) {\n" %
2784 self
.WriteHandlerDeferReadWrite(func
, file);
2785 if len(func
.GetOriginalArgs()) > 0:
2786 last_arg
= func
.GetLastOriginalArg()
2787 all_but_last_arg
= func
.GetOriginalArgs()[:-1]
2788 for arg
in all_but_last_arg
:
2789 arg
.WriteGetCode(file)
2790 self
.WriteGetDataSizeCode(func
, file)
2791 last_arg
.WriteGetCode(file)
2792 func
.WriteHandlerValidation(file)
2793 func
.WriteHandlerImplementation(file)
2794 file.Write(" return error::kNoError;\n")
2798 def WriteImmediateServiceImplementation(self
, func
, file):
2799 """Writes the service implementation for an immediate version of command."""
2801 "error::Error GLES2DecoderImpl::Handle%s(\n" % func
.name
)
2803 " uint32 immediate_data_size, const gles2::cmds::%s& c) {\n" %
2805 self
.WriteHandlerDeferReadWrite(func
, file);
2806 last_arg
= func
.GetLastOriginalArg()
2807 all_but_last_arg
= func
.GetOriginalArgs()[:-1]
2808 for arg
in all_but_last_arg
:
2809 arg
.WriteGetCode(file)
2810 self
.WriteGetDataSizeCode(func
, file)
2811 last_arg
.WriteGetCode(file)
2812 func
.WriteHandlerValidation(file)
2813 func
.WriteHandlerImplementation(file)
2814 file.Write(" return error::kNoError;\n")
2818 def WriteBucketServiceImplementation(self
, func
, file):
2819 """Writes the service implementation for a bucket version of command."""
2821 "error::Error GLES2DecoderImpl::Handle%s(\n" % func
.name
)
2823 " uint32 immediate_data_size, const gles2::cmds::%s& c) {\n" %
2825 self
.WriteHandlerDeferReadWrite(func
, file);
2826 last_arg
= func
.GetLastOriginalArg()
2827 all_but_last_arg
= func
.GetOriginalArgs()[:-1]
2828 for arg
in all_but_last_arg
:
2829 arg
.WriteGetCode(file)
2830 self
.WriteGetDataSizeCode(func
, file)
2831 last_arg
.WriteGetCode(file)
2832 func
.WriteHandlerValidation(file)
2833 func
.WriteHandlerImplementation(file)
2834 file.Write(" return error::kNoError;\n")
2838 def WriteHandlerDeferReadWrite(self
, func
, file):
2839 """Writes the code to handle deferring reads or writes."""
2840 defer_reads
= func
.GetInfo('defer_reads')
2841 defer_draws
= func
.GetInfo('defer_draws')
2844 conditions
.append('ShouldDeferDraws()');
2846 conditions
.append('ShouldDeferReads()');
2849 file.Write(" if (%s)\n" % ' || '.join(conditions
))
2850 file.Write(" return error::kDeferCommandUntilLater;\n")
2852 def WriteValidUnitTest(self
, func
, file, test
, extra
= {}):
2853 """Writes a valid unit test."""
2854 if func
.GetInfo('expectation') == False:
2855 test
= self
._remove
_expected
_call
_re
.sub('', test
)
2858 for count
, arg
in enumerate(func
.GetOriginalArgs()):
2859 arg_strings
.append(arg
.GetValidArg(func
, count
, 0))
2861 for count
, arg
in enumerate(func
.GetOriginalArgs()):
2862 gl_arg_strings
.append(arg
.GetValidGLArg(func
, count
, 0))
2863 gl_func_name
= func
.GetGLTestFunctionName()
2865 'test_name': 'GLES2DecoderTest%d' % file.file_num
,
2867 'gl_func_name': gl_func_name
,
2868 'args': ", ".join(arg_strings
),
2869 'gl_args': ", ".join(gl_arg_strings
),
2873 while (old_test
!= test
):
2876 file.Write(test
% vars)
2878 def WriteInvalidUnitTest(self
, func
, file, test
, extra
= {}):
2879 """Writes a invalid unit test."""
2880 for arg_index
, arg
in enumerate(func
.GetOriginalArgs()):
2881 num_invalid_values
= arg
.GetNumInvalidValues(func
)
2882 for value_index
in range(0, num_invalid_values
):
2884 parse_result
= "kNoError"
2886 for count
, arg
in enumerate(func
.GetOriginalArgs()):
2887 if count
== arg_index
:
2888 (arg_string
, parse_result
, gl_error
) = arg
.GetInvalidArg(
2891 arg_string
= arg
.GetValidArg(func
, count
, 0)
2892 arg_strings
.append(arg_string
)
2894 for arg
in func
.GetOriginalArgs():
2895 gl_arg_strings
.append("_")
2896 gl_func_name
= func
.GetGLTestFunctionName()
2898 if not gl_error
== None:
2899 gl_error_test
= '\n EXPECT_EQ(%s, GetGLError());' % gl_error
2902 'test_name': 'GLES2DecoderTest%d' % file.file_num
,
2904 'arg_index': arg_index
,
2905 'value_index': value_index
,
2906 'gl_func_name': gl_func_name
,
2907 'args': ", ".join(arg_strings
),
2908 'all_but_last_args': ", ".join(arg_strings
[:-1]),
2909 'gl_args': ", ".join(gl_arg_strings
),
2910 'parse_result': parse_result
,
2911 'gl_error_test': gl_error_test
,
2914 file.Write(test
% vars)
2916 def WriteServiceUnitTest(self
, func
, file):
2917 """Writes the service unit test for a command."""
2919 TEST_F(%(test_name)s, %(name)sValidArgs) {
2920 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
2921 SpecializedSetup<cmds::%(name)s, 0>(true);
2924 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
2925 EXPECT_EQ(GL_NO_ERROR, GetGLError());
2928 self
.WriteValidUnitTest(func
, file, valid_test
)
2931 TEST_F(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
2932 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
2933 SpecializedSetup<cmds::%(name)s, 0>(false);
2936 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
2939 self
.WriteInvalidUnitTest(func
, file, invalid_test
)
2941 def WriteImmediateServiceUnitTest(self
, func
, file):
2942 """Writes the service unit test for an immediate command."""
2943 file.Write("// TODO(gman): %s\n" % func
.name
)
2945 def WriteImmediateValidationCode(self
, func
, file):
2946 """Writes the validation code for an immediate version of a command."""
2949 def WriteBucketServiceUnitTest(self
, func
, file):
2950 """Writes the service unit test for a bucket command."""
2951 file.Write("// TODO(gman): %s\n" % func
.name
)
2953 def WriteBucketValidationCode(self
, func
, file):
2954 """Writes the validation code for a bucket version of a command."""
2955 file.Write("// TODO(gman): %s\n" % func
.name
)
2957 def WriteGLES2ImplementationDeclaration(self
, func
, file):
2958 """Writes the GLES2 Implemention declaration."""
2959 impl_decl
= func
.GetInfo('impl_decl')
2960 if impl_decl
== None or impl_decl
== True:
2961 file.Write("virtual %s %s(%s) OVERRIDE;\n" %
2962 (func
.return_type
, func
.original_name
,
2963 func
.MakeTypedOriginalArgString("")))
2966 def WriteGLES2CLibImplementation(self
, func
, file):
2967 file.Write("%s GLES2%s(%s) {\n" %
2968 (func
.return_type
, func
.name
,
2969 func
.MakeTypedOriginalArgString("")))
2970 result_string
= "return "
2971 if func
.return_type
== "void":
2973 file.Write(" %sgles2::GetGLContext()->%s(%s);\n" %
2974 (result_string
, func
.original_name
,
2975 func
.MakeOriginalArgString("")))
2978 def WriteGLES2Header(self
, func
, file):
2979 """Writes a re-write macro for GLES"""
2980 file.Write("#define gl%s GLES2_GET_FUN(%s)\n" %(func
.name
, func
.name
))
2982 def WriteClientGLCallLog(self
, func
, file):
2983 """Writes a logging macro for the client side code."""
2985 if len(func
.GetOriginalArgs()):
2988 ' GPU_CLIENT_LOG("[" << GetLogPrefix() << "] gl%s("%s%s << ")");\n' %
2989 (func
.original_name
, comma
, func
.MakeLogArgString()))
2991 def WriteClientGLReturnLog(self
, func
, file):
2992 """Writes the return value logging code."""
2993 if func
.return_type
!= "void":
2994 file.Write(' GPU_CLIENT_LOG("return:" << result)\n')
2996 def WriteGLES2ImplementationHeader(self
, func
, file):
2997 """Writes the GLES2 Implemention."""
2998 self
.WriteGLES2ImplementationDeclaration(func
, file)
3000 def WriteGLES2TraceImplementationHeader(self
, func
, file):
3001 """Writes the GLES2 Trace Implemention header."""
3002 file.Write("virtual %s %s(%s) OVERRIDE;\n" %
3003 (func
.return_type
, func
.original_name
,
3004 func
.MakeTypedOriginalArgString("")))
3006 def WriteGLES2TraceImplementation(self
, func
, file):
3007 """Writes the GLES2 Trace Implemention."""
3008 file.Write("%s GLES2TraceImplementation::%s(%s) {\n" %
3009 (func
.return_type
, func
.original_name
,
3010 func
.MakeTypedOriginalArgString("")))
3011 result_string
= "return "
3012 if func
.return_type
== "void":
3014 file.Write(' TRACE_EVENT_BINARY_EFFICIENT0("gpu", "GLES2Trace::%s");\n' %
3016 file.Write(" %sgl_->%s(%s);\n" %
3017 (result_string
, func
.name
, func
.MakeOriginalArgString("")))
3021 def WriteGLES2Implementation(self
, func
, file):
3022 """Writes the GLES2 Implemention."""
3023 impl_func
= func
.GetInfo('impl_func')
3024 impl_decl
= func
.GetInfo('impl_decl')
3025 gen_cmd
= func
.GetInfo('gen_cmd')
3026 if (func
.can_auto_generate
and
3027 (impl_func
== None or impl_func
== True) and
3028 (impl_decl
== None or impl_decl
== True) and
3029 (gen_cmd
== None or gen_cmd
== True)):
3030 file.Write("%s GLES2Implementation::%s(%s) {\n" %
3031 (func
.return_type
, func
.original_name
,
3032 func
.MakeTypedOriginalArgString("")))
3033 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
3034 self
.WriteClientGLCallLog(func
, file)
3035 func
.WriteDestinationInitalizationValidation(file)
3036 for arg
in func
.GetOriginalArgs():
3037 arg
.WriteClientSideValidationCode(file, func
)
3038 file.Write(" helper_->%s(%s);\n" %
3039 (func
.name
, func
.MakeOriginalArgString("")))
3040 file.Write(" CheckGLError();\n")
3041 self
.WriteClientGLReturnLog(func
, file)
3045 def WriteGLES2InterfaceHeader(self
, func
, file):
3046 """Writes the GLES2 Interface."""
3047 file.Write("virtual %s %s(%s) = 0;\n" %
3048 (func
.return_type
, func
.original_name
,
3049 func
.MakeTypedOriginalArgString("")))
3051 def WriteGLES2InterfaceStub(self
, func
, file):
3052 """Writes the GLES2 Interface stub declaration."""
3053 file.Write("virtual %s %s(%s) OVERRIDE;\n" %
3054 (func
.return_type
, func
.original_name
,
3055 func
.MakeTypedOriginalArgString("")))
3057 def WriteGLES2InterfaceStubImpl(self
, func
, file):
3058 """Writes the GLES2 Interface stub declaration."""
3059 args
= func
.GetOriginalArgs()
3060 arg_string
= ", ".join(
3061 ["%s /* %s */" % (arg
.type, arg
.name
) for arg
in args
])
3062 file.Write("%s GLES2InterfaceStub::%s(%s) {\n" %
3063 (func
.return_type
, func
.original_name
, arg_string
))
3064 if func
.return_type
!= "void":
3065 file.Write(" return 0;\n")
3068 def WriteGLES2ImplementationUnitTest(self
, func
, file):
3069 """Writes the GLES2 Implemention unit test."""
3070 client_test
= func
.GetInfo('client_test')
3071 if (func
.can_auto_generate
and
3072 (client_test
== None or client_test
== True)):
3074 TEST_F(GLES2ImplementationTest, %(name)s) {
3079 expected.cmd.Init(%(cmd_args)s);
3081 gl_->%(name)s(%(args)s);
3082 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
3085 cmd_arg_strings
= []
3086 for count
, arg
in enumerate(func
.GetCmdArgs()):
3087 cmd_arg_strings
.append(arg
.GetValidClientSideCmdArg(func
, count
, 0))
3090 for count
, arg
in enumerate(func
.GetOriginalArgs()):
3091 gl_arg_strings
.append(arg
.GetValidClientSideArg(func
, count
, 0))
3094 'args': ", ".join(gl_arg_strings
),
3095 'cmd_args': ", ".join(cmd_arg_strings
),
3098 if client_test
!= False:
3099 file.Write("// TODO: Implement unit test for %s\n" % func
.name
)
3101 def WriteDestinationInitalizationValidation(self
, func
, file):
3102 """Writes the client side destintion initialization validation."""
3103 for arg
in func
.GetOriginalArgs():
3104 arg
.WriteDestinationInitalizationValidation(file, func
)
3106 def WriteTraceEvent(self
, func
, file):
3107 file.Write(' TRACE_EVENT0("gpu", "GLES2Implementation::%s");\n' %
3110 def WriteImmediateCmdComputeSize(self
, func
, file):
3111 """Writes the size computation code for the immediate version of a cmd."""
3112 file.Write(" static uint32 ComputeSize(uint32 size_in_bytes) {\n")
3113 file.Write(" return static_cast<uint32>(\n")
3114 file.Write(" sizeof(ValueType) + // NOLINT\n")
3115 file.Write(" RoundSizeToMultipleOfEntries(size_in_bytes));\n")
3119 def WriteImmediateCmdSetHeader(self
, func
, file):
3120 """Writes the SetHeader function for the immediate version of a cmd."""
3121 file.Write(" void SetHeader(uint32 size_in_bytes) {\n")
3122 file.Write(" header.SetCmdByTotalSize<ValueType>(size_in_bytes);\n")
3126 def WriteImmediateCmdInit(self
, func
, file):
3127 """Writes the Init function for the immediate version of a command."""
3128 raise NotImplementedError(func
.name
)
3130 def WriteImmediateCmdSet(self
, func
, file):
3131 """Writes the Set function for the immediate version of a command."""
3132 raise NotImplementedError(func
.name
)
3134 def WriteCmdHelper(self
, func
, file):
3135 """Writes the cmd helper definition for a cmd."""
3136 code
= """ void %(name)s(%(typed_args)s) {
3137 gles2::cmds::%(name)s* c = GetCmdSpace<gles2::cmds::%(name)s>();
3146 "typed_args": func
.MakeTypedCmdArgString(""),
3147 "args": func
.MakeCmdArgString(""),
3150 def WriteImmediateCmdHelper(self
, func
, file):
3151 """Writes the cmd helper definition for the immediate version of a cmd."""
3152 code
= """ void %(name)s(%(typed_args)s) {
3153 const uint32 s = 0; // TODO(gman): compute correct size
3154 gles2::cmds::%(name)s* c =
3155 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(s);
3164 "typed_args": func
.MakeTypedCmdArgString(""),
3165 "args": func
.MakeCmdArgString(""),
3169 class StateSetHandler(TypeHandler
):
3170 """Handler for commands that simply set state."""
3173 TypeHandler
.__init
__(self
)
3175 def WriteHandlerImplementation(self
, func
, file):
3176 """Overrriden from TypeHandler."""
3177 state_name
= func
.GetInfo('state')
3178 state
= _STATES
[state_name
]
3179 states
= state
['states']
3180 args
= func
.GetOriginalArgs()
3182 for ndx
,item
in enumerate(states
):
3183 if 'range_checks' in item
:
3184 for range_check
in item
['range_checks']:
3185 code
.append("%s %s" % (args
[ndx
].name
, range_check
['check']))
3187 file.Write(" if (%s) {\n" % " ||\n ".join(code
))
3189 ' LOCAL_SET_GL_ERROR(GL_INVALID_VALUE,'
3190 ' "%s", "%s out of range");\n' %
3191 (func
.name
, args
[ndx
].name
))
3192 file.Write(" return error::kNoError;\n")
3195 for ndx
,item
in enumerate(states
):
3196 code
.append("state_.%s != %s" % (item
['name'], args
[ndx
].name
))
3197 file.Write(" if (%s) {\n" % " ||\n ".join(code
))
3198 for ndx
,item
in enumerate(states
):
3199 file.Write(" state_.%s = %s;\n" % (item
['name'], args
[ndx
].name
))
3200 if 'state_flag' in state
:
3201 file.Write(" %s = true;\n" % state
['state_flag'])
3202 if not func
.GetInfo("no_gl"):
3203 file.Write(" %s(%s);\n" %
3204 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
3207 def WriteServiceUnitTest(self
, func
, file):
3208 """Overrriden from TypeHandler."""
3209 TypeHandler
.WriteServiceUnitTest(self
, func
, file)
3210 state_name
= func
.GetInfo('state')
3211 state
= _STATES
[state_name
]
3212 states
= state
['states']
3213 for ndx
,item
in enumerate(states
):
3214 if 'range_checks' in item
:
3215 for check_ndx
, range_check
in enumerate(item
['range_checks']):
3217 TEST_F(%(test_name)s, %(name)sInvalidValue%(ndx)d_%(check_ndx)d) {
3218 SpecializedSetup<cmds::%(name)s, 0>(false);
3221 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
3222 EXPECT_EQ(GL_INVALID_VALUE, GetGLError());
3227 for count
, arg
in enumerate(func
.GetOriginalArgs()):
3228 arg_strings
.append(arg
.GetValidArg(func
, count
, 0))
3229 arg_strings
[ndx
] = range_check
['test_value']
3231 'test_name': 'GLES2DecoderTest%d' % file.file_num
,
3234 'check_ndx': check_ndx
,
3235 'args': ", ".join(arg_strings
),
3237 file.Write(valid_test
% vars)
3240 class StateSetRGBAlphaHandler(TypeHandler
):
3241 """Handler for commands that simply set state that have rgb/alpha."""
3244 TypeHandler
.__init
__(self
)
3246 def WriteHandlerImplementation(self
, func
, file):
3247 """Overrriden from TypeHandler."""
3248 state_name
= func
.GetInfo('state')
3249 state
= _STATES
[state_name
]
3250 states
= state
['states']
3251 args
= func
.GetOriginalArgs()
3252 num_args
= len(args
)
3254 for ndx
,item
in enumerate(states
):
3255 code
.append("state_.%s != %s" % (item
['name'], args
[ndx
% num_args
].name
))
3256 file.Write(" if (%s) {\n" % " ||\n ".join(code
))
3257 for ndx
, item
in enumerate(states
):
3258 file.Write(" state_.%s = %s;\n" %
3259 (item
['name'], args
[ndx
% num_args
].name
))
3260 if 'state_flag' in state
:
3261 file.Write(" %s = true;\n" % state
['state_flag'])
3262 if not func
.GetInfo("no_gl"):
3263 file.Write(" %s(%s);\n" %
3264 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
3268 class StateSetFrontBackSeparateHandler(TypeHandler
):
3269 """Handler for commands that simply set state that have front/back."""
3272 TypeHandler
.__init
__(self
)
3274 def WriteHandlerImplementation(self
, func
, file):
3275 """Overrriden from TypeHandler."""
3276 state_name
= func
.GetInfo('state')
3277 state
= _STATES
[state_name
]
3278 states
= state
['states']
3279 args
= func
.GetOriginalArgs()
3281 num_args
= len(args
)
3282 file.Write(" bool changed = false;\n")
3283 for group_ndx
, group
in enumerate(Grouper(num_args
- 1, states
)):
3284 file.Write(" if (%s == %s || %s == GL_FRONT_AND_BACK) {\n" %
3285 (face
, ('GL_FRONT', 'GL_BACK')[group_ndx
], face
))
3287 for ndx
, item
in enumerate(group
):
3288 code
.append("state_.%s != %s" % (item
['name'], args
[ndx
+ 1].name
))
3289 file.Write(" changed |= %s;\n" % " ||\n ".join(code
))
3291 file.Write(" if (changed) {\n")
3292 for group_ndx
, group
in enumerate(Grouper(num_args
- 1, states
)):
3293 file.Write(" if (%s == %s || %s == GL_FRONT_AND_BACK) {\n" %
3294 (face
, ('GL_FRONT', 'GL_BACK')[group_ndx
], face
))
3295 for ndx
, item
in enumerate(group
):
3296 file.Write(" state_.%s = %s;\n" %
3297 (item
['name'], args
[ndx
+ 1].name
))
3299 if 'state_flag' in state
:
3300 file.Write(" %s = true;\n" % state
['state_flag'])
3301 if not func
.GetInfo("no_gl"):
3302 file.Write(" %s(%s);\n" %
3303 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
3307 class StateSetFrontBackHandler(TypeHandler
):
3308 """Handler for commands that simply set state that set both front/back."""
3311 TypeHandler
.__init
__(self
)
3313 def WriteHandlerImplementation(self
, func
, file):
3314 """Overrriden from TypeHandler."""
3315 state_name
= func
.GetInfo('state')
3316 state
= _STATES
[state_name
]
3317 states
= state
['states']
3318 args
= func
.GetOriginalArgs()
3319 num_args
= len(args
)
3321 for group_ndx
, group
in enumerate(Grouper(num_args
, states
)):
3322 for ndx
, item
in enumerate(group
):
3323 code
.append("state_.%s != %s" % (item
['name'], args
[ndx
].name
))
3324 file.Write(" if (%s) {\n" % " ||\n ".join(code
))
3325 for group_ndx
, group
in enumerate(Grouper(num_args
, states
)):
3326 for ndx
, item
in enumerate(group
):
3327 file.Write(" state_.%s = %s;\n" % (item
['name'], args
[ndx
].name
))
3328 if 'state_flag' in state
:
3329 file.Write(" %s = true;\n" % state
['state_flag'])
3330 if not func
.GetInfo("no_gl"):
3331 file.Write(" %s(%s);\n" %
3332 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
3336 class StateSetNamedParameter(TypeHandler
):
3337 """Handler for commands that set a state chosen with an enum parameter."""
3340 TypeHandler
.__init
__(self
)
3342 def WriteHandlerImplementation(self
, func
, file):
3343 """Overridden from TypeHandler."""
3344 state_name
= func
.GetInfo('state')
3345 state
= _STATES
[state_name
]
3346 states
= state
['states']
3347 args
= func
.GetOriginalArgs()
3348 num_args
= len(args
)
3349 assert num_args
== 2
3350 file.Write(" switch (%s) {\n" % args
[0].name
)
3351 for state
in states
:
3352 file.Write(" case %s:\n" % state
['enum'])
3353 file.Write(" if (state_.%s != %s) {\n" %
3354 (state
['name'], args
[1].name
))
3355 file.Write(" state_.%s = %s;\n" % (state
['name'], args
[1].name
))
3356 if not func
.GetInfo("no_gl"):
3357 file.Write(" %s(%s);\n" %
3358 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
3360 file.Write(" break;\n")
3361 file.Write(" default:\n")
3362 file.Write(" NOTREACHED();\n")
3366 class CustomHandler(TypeHandler
):
3367 """Handler for commands that are auto-generated but require minor tweaks."""
3370 TypeHandler
.__init
__(self
)
3372 def WriteServiceImplementation(self
, func
, file):
3373 """Overrriden from TypeHandler."""
3376 def WriteImmediateServiceImplementation(self
, func
, file):
3377 """Overrriden from TypeHandler."""
3380 def WriteBucketServiceImplementation(self
, func
, file):
3381 """Overrriden from TypeHandler."""
3384 def WriteServiceUnitTest(self
, func
, file):
3385 """Overrriden from TypeHandler."""
3386 file.Write("// TODO(gman): %s\n\n" % func
.name
)
3388 def WriteImmediateServiceUnitTest(self
, func
, file):
3389 """Overrriden from TypeHandler."""
3390 file.Write("// TODO(gman): %s\n\n" % func
.name
)
3392 def WriteImmediateCmdGetTotalSize(self
, func
, file):
3393 """Overrriden from TypeHandler."""
3394 file.Write(" uint32 total_size = 0; // TODO(gman): get correct size.\n")
3396 def WriteImmediateCmdInit(self
, func
, file):
3397 """Overrriden from TypeHandler."""
3398 file.Write(" void Init(%s) {\n" % func
.MakeTypedCmdArgString("_"))
3399 self
.WriteImmediateCmdGetTotalSize(func
, file)
3400 file.Write(" SetHeader(total_size);\n")
3401 args
= func
.GetCmdArgs()
3403 file.Write(" %s = _%s;\n" % (arg
.name
, arg
.name
))
3407 def WriteImmediateCmdSet(self
, func
, file):
3408 """Overrriden from TypeHandler."""
3409 copy_args
= func
.MakeCmdArgString("_", False)
3410 file.Write(" void* Set(void* cmd%s) {\n" %
3411 func
.MakeTypedCmdArgString("_", True))
3412 self
.WriteImmediateCmdGetTotalSize(func
, file)
3413 file.Write(" static_cast<ValueType*>(cmd)->Init(%s);\n" % copy_args
)
3414 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
3415 "cmd, total_size);\n")
3420 class TodoHandler(CustomHandler
):
3421 """Handle for commands that are not yet implemented."""
3423 def AddImmediateFunction(self
, generator
, func
):
3424 """Overrriden from TypeHandler."""
3427 def WriteImmediateFormatTest(self
, func
, file):
3428 """Overrriden from TypeHandler."""
3431 def WriteGLES2ImplementationUnitTest(self
, func
, file):
3432 """Overrriden from TypeHandler."""
3435 def WriteGLES2Implementation(self
, func
, file):
3436 """Overrriden from TypeHandler."""
3437 file.Write("%s GLES2Implementation::%s(%s) {\n" %
3438 (func
.return_type
, func
.original_name
,
3439 func
.MakeTypedOriginalArgString("")))
3440 file.Write(" // TODO: for now this is a no-op\n")
3443 "GL_INVALID_OPERATION, \"gl%s\", \"not implemented\");\n" %
3445 if func
.return_type
!= "void":
3446 file.Write(" return 0;\n")
3450 def WriteServiceImplementation(self
, func
, file):
3451 """Overrriden from TypeHandler."""
3453 "error::Error GLES2DecoderImpl::Handle%s(\n" % func
.name
)
3455 " uint32 immediate_data_size, const gles2::cmds::%s& c) {\n" %
3457 file.Write(" // TODO: for now this is a no-op\n")
3459 " LOCAL_SET_GL_ERROR("
3460 "GL_INVALID_OPERATION, \"gl%s\", \"not implemented\");\n" %
3462 file.Write(" return error::kNoError;\n")
3467 class HandWrittenHandler(CustomHandler
):
3468 """Handler for comands where everything must be written by hand."""
3470 def InitFunction(self
, func
):
3471 """Add or adjust anything type specific for this function."""
3472 CustomHandler
.InitFunction(self
, func
)
3473 func
.can_auto_generate
= False
3475 def WriteStruct(self
, func
, file):
3476 """Overrriden from TypeHandler."""
3479 def WriteDocs(self
, func
, file):
3480 """Overrriden from TypeHandler."""
3483 def WriteServiceUnitTest(self
, func
, file):
3484 """Overrriden from TypeHandler."""
3485 file.Write("// TODO(gman): %s\n\n" % func
.name
)
3487 def WriteImmediateServiceUnitTest(self
, func
, file):
3488 """Overrriden from TypeHandler."""
3489 file.Write("// TODO(gman): %s\n\n" % func
.name
)
3491 def WriteBucketServiceUnitTest(self
, func
, file):
3492 """Overrriden from TypeHandler."""
3493 file.Write("// TODO(gman): %s\n\n" % func
.name
)
3495 def WriteServiceImplementation(self
, func
, file):
3496 """Overrriden from TypeHandler."""
3499 def WriteImmediateServiceImplementation(self
, func
, file):
3500 """Overrriden from TypeHandler."""
3503 def WriteBucketServiceImplementation(self
, func
, file):
3504 """Overrriden from TypeHandler."""
3507 def WriteImmediateCmdHelper(self
, func
, file):
3508 """Overrriden from TypeHandler."""
3511 def WriteBucketCmdHelper(self
, func
, file):
3512 """Overrriden from TypeHandler."""
3515 def WriteCmdHelper(self
, func
, file):
3516 """Overrriden from TypeHandler."""
3519 def WriteFormatTest(self
, func
, file):
3520 """Overrriden from TypeHandler."""
3521 file.Write("// TODO(gman): Write test for %s\n" % func
.name
)
3523 def WriteImmediateFormatTest(self
, func
, file):
3524 """Overrriden from TypeHandler."""
3525 file.Write("// TODO(gman): Write test for %s\n" % func
.name
)
3527 def WriteBucketFormatTest(self
, func
, file):
3528 """Overrriden from TypeHandler."""
3529 file.Write("// TODO(gman): Write test for %s\n" % func
.name
)
3533 class ManualHandler(CustomHandler
):
3534 """Handler for commands who's handlers must be written by hand."""
3537 CustomHandler
.__init
__(self
)
3539 def InitFunction(self
, func
):
3540 """Overrriden from TypeHandler."""
3541 if (func
.name
== 'CompressedTexImage2DBucket'):
3542 func
.cmd_args
= func
.cmd_args
[:-1]
3543 func
.AddCmdArg(Argument('bucket_id', 'GLuint'))
3545 CustomHandler
.InitFunction(self
, func
)
3547 def WriteServiceImplementation(self
, func
, file):
3548 """Overrriden from TypeHandler."""
3551 def WriteBucketServiceImplementation(self
, func
, file):
3552 """Overrriden from TypeHandler."""
3555 def WriteServiceUnitTest(self
, func
, file):
3556 """Overrriden from TypeHandler."""
3557 file.Write("// TODO(gman): %s\n\n" % func
.name
)
3559 def WriteImmediateServiceUnitTest(self
, func
, file):
3560 """Overrriden from TypeHandler."""
3561 file.Write("// TODO(gman): %s\n\n" % func
.name
)
3563 def WriteImmediateServiceImplementation(self
, func
, file):
3564 """Overrriden from TypeHandler."""
3567 def WriteImmediateFormatTest(self
, func
, file):
3568 """Overrriden from TypeHandler."""
3569 file.Write("// TODO(gman): Implement test for %s\n" % func
.name
)
3571 def WriteGLES2Implementation(self
, func
, file):
3572 """Overrriden from TypeHandler."""
3573 if func
.GetInfo('impl_func'):
3574 super(ManualHandler
, self
).WriteGLES2Implementation(func
, file)
3576 def WriteGLES2ImplementationHeader(self
, func
, file):
3577 """Overrriden from TypeHandler."""
3578 file.Write("virtual %s %s(%s) OVERRIDE;\n" %
3579 (func
.return_type
, func
.original_name
,
3580 func
.MakeTypedOriginalArgString("")))
3583 def WriteImmediateCmdGetTotalSize(self
, func
, file):
3584 """Overrriden from TypeHandler."""
3585 # TODO(gman): Move this data to _FUNCTION_INFO?
3586 if func
.name
== 'ShaderSourceImmediate':
3587 file.Write(" uint32 total_size = ComputeSize(_data_size);\n")
3589 CustomHandler
.WriteImmediateCmdGetTotalSize(self
, func
, file)
3592 class DataHandler(TypeHandler
):
3593 """Handler for glBufferData, glBufferSubData, glTexImage2D, glTexSubImage2D,
3594 glCompressedTexImage2D, glCompressedTexImageSub2D."""
3596 TypeHandler
.__init
__(self
)
3598 def InitFunction(self
, func
):
3599 """Overrriden from TypeHandler."""
3600 if func
.name
== 'CompressedTexSubImage2DBucket':
3601 func
.cmd_args
= func
.cmd_args
[:-1]
3602 func
.AddCmdArg(Argument('bucket_id', 'GLuint'))
3604 def WriteGetDataSizeCode(self
, func
, file):
3605 """Overrriden from TypeHandler."""
3606 # TODO(gman): Move this data to _FUNCTION_INFO?
3608 if name
.endswith("Immediate"):
3610 if name
== 'BufferData' or name
== 'BufferSubData':
3611 file.Write(" uint32 data_size = size;\n")
3612 elif (name
== 'CompressedTexImage2D' or
3613 name
== 'CompressedTexSubImage2D'):
3614 file.Write(" uint32 data_size = imageSize;\n")
3615 elif (name
== 'CompressedTexSubImage2DBucket'):
3616 file.Write(" Bucket* bucket = GetBucket(c.bucket_id);\n")
3617 file.Write(" uint32 data_size = bucket->size();\n")
3618 file.Write(" GLsizei imageSize = data_size;\n")
3619 elif name
== 'TexImage2D' or name
== 'TexSubImage2D':
3620 code
= """ uint32 data_size;
3621 if (!GLES2Util::ComputeImageDataSize(
3622 width, height, format, type, unpack_alignment_, &data_size)) {
3623 return error::kOutOfBounds;
3628 file.Write("// uint32 data_size = 0; // TODO(gman): get correct size!\n")
3630 def WriteImmediateCmdGetTotalSize(self
, func
, file):
3631 """Overrriden from TypeHandler."""
3632 # TODO(gman): Move this data to _FUNCTION_INFO?
3633 if func
.name
== 'BufferDataImmediate':
3634 file.Write(" uint32 total_size = ComputeSize(_size);\n")
3635 elif func
.name
== 'BufferSubDataImmediate':
3636 file.Write(" uint32 total_size = ComputeSize(_size);\n")
3637 elif func
.name
== 'CompressedTexImage2DImmediate':
3638 file.Write(" uint32 total_size = ComputeSize(_imageSize);\n")
3639 elif func
.name
== 'CompressedTexSubImage2DImmediate':
3640 file.Write(" uint32 total_size = ComputeSize(_imageSize);\n")
3641 elif func
.name
== 'TexImage2DImmediate':
3643 " uint32 total_size = 0; // TODO(gman): get correct size\n")
3644 elif func
.name
== 'TexSubImage2DImmediate':
3646 " uint32 total_size = 0; // TODO(gman): get correct size\n")
3648 def WriteImmediateCmdSizeTest(self
, func
, file):
3649 """Overrriden from TypeHandler."""
3650 # TODO(gman): Move this data to _FUNCTION_INFO?
3651 if func
.name
== 'BufferDataImmediate':
3652 file.Write(" uint32 total_size = cmd.ComputeSize(cmd.size);\n")
3653 elif func
.name
== 'BufferSubDataImmediate':
3654 file.Write(" uint32 total_size = cmd.ComputeSize(cmd.size);\n")
3655 elif func
.name
== 'CompressedTexImage2DImmediate':
3656 file.Write(" uint32 total_size = cmd.ComputeSize(cmd.imageSize);\n")
3657 elif func
.name
== 'CompressedTexSubImage2DImmediate':
3658 file.Write(" uint32 total_size = cmd.ComputeSize(cmd.imageSize);\n")
3659 elif func
.name
== 'TexImage2DImmediate':
3661 " uint32 total_size = 0; // TODO(gman): get correct size\n")
3662 elif func
.name
== 'TexSubImage2DImmediate':
3664 " uint32 total_size = 0; // TODO(gman): get correct size\n")
3665 file.Write(" EXPECT_EQ(sizeof(cmd), total_size);\n")
3667 def WriteImmediateCmdInit(self
, func
, file):
3668 """Overrriden from TypeHandler."""
3669 file.Write(" void Init(%s) {\n" % func
.MakeTypedCmdArgString("_"))
3670 self
.WriteImmediateCmdGetTotalSize(func
, file)
3671 file.Write(" SetHeader(total_size);\n")
3672 args
= func
.GetCmdArgs()
3674 file.Write(" %s = _%s;\n" % (arg
.name
, arg
.name
))
3678 def WriteImmediateCmdSet(self
, func
, file):
3679 """Overrriden from TypeHandler."""
3680 copy_args
= func
.MakeCmdArgString("_", False)
3681 file.Write(" void* Set(void* cmd%s) {\n" %
3682 func
.MakeTypedCmdArgString("_", True))
3683 self
.WriteImmediateCmdGetTotalSize(func
, file)
3684 file.Write(" static_cast<ValueType*>(cmd)->Init(%s);\n" % copy_args
)
3685 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
3686 "cmd, total_size);\n")
3690 def WriteImmediateFormatTest(self
, func
, file):
3691 """Overrriden from TypeHandler."""
3692 # TODO(gman): Remove this exception.
3693 file.Write("// TODO(gman): Implement test for %s\n" % func
.name
)
3696 def WriteServiceUnitTest(self
, func
, file):
3697 """Overrriden from TypeHandler."""
3698 file.Write("// TODO(gman): %s\n\n" % func
.name
)
3700 def WriteImmediateServiceUnitTest(self
, func
, file):
3701 """Overrriden from TypeHandler."""
3702 file.Write("// TODO(gman): %s\n\n" % func
.name
)
3704 def WriteBucketServiceImplementation(self
, func
, file):
3705 """Overrriden from TypeHandler."""
3706 if not func
.name
== 'CompressedTexSubImage2DBucket':
3707 TypeHandler
.WriteBucketServiceImplemenation(self
, func
, file)
3710 class BindHandler(TypeHandler
):
3711 """Handler for glBind___ type functions."""
3714 TypeHandler
.__init
__(self
)
3716 def WriteServiceUnitTest(self
, func
, file):
3717 """Overrriden from TypeHandler."""
3719 if len(func
.GetOriginalArgs()) == 1:
3721 TEST_F(%(test_name)s, %(name)sValidArgs) {
3722 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
3723 SpecializedSetup<cmds::%(name)s, 0>(true);
3726 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
3727 EXPECT_EQ(GL_NO_ERROR, GetGLError());
3730 TEST_F(%(test_name)s, %(name)sValidArgsNewId) {
3731 EXPECT_CALL(*gl_, %(gl_func_name)s(kNewServiceId));
3732 EXPECT_CALL(*gl_, %(gl_gen_func_name)s(1, _))
3733 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
3734 SpecializedSetup<cmds::%(name)s, 0>(true);
3736 cmd.Init(kNewClientId);
3737 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
3738 EXPECT_EQ(GL_NO_ERROR, GetGLError());
3739 EXPECT_TRUE(Get%(resource_type)s(kNewClientId) != NULL);
3744 self
.WriteValidUnitTest(func
, file, valid_test
, {
3745 'resource_type': func
.GetOriginalArgs()[0].resource_type
,
3746 'gl_gen_func_name': func
.GetInfo("gen_func"),
3750 TEST_F(%(test_name)s, %(name)sValidArgs) {
3751 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
3752 SpecializedSetup<cmds::%(name)s, 0>(true);
3755 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
3756 EXPECT_EQ(GL_NO_ERROR, GetGLError());
3759 TEST_F(%(test_name)s, %(name)sValidArgsNewId) {
3760 EXPECT_CALL(*gl_, %(gl_func_name)s(%(first_gl_arg)s, kNewServiceId));
3761 EXPECT_CALL(*gl_, %(gl_gen_func_name)s(1, _))
3762 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
3763 SpecializedSetup<cmds::%(name)s, 0>(true);
3765 cmd.Init(%(first_arg)s, kNewClientId);
3766 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
3767 EXPECT_EQ(GL_NO_ERROR, GetGLError());
3768 EXPECT_TRUE(Get%(resource_type)s(kNewClientId) != NULL);
3773 self
.WriteValidUnitTest(func
, file, valid_test
, {
3774 'first_arg': func
.GetOriginalArgs()[0].GetValidArg(func
, 0, 0),
3775 'first_gl_arg': func
.GetOriginalArgs()[0].GetValidGLArg(func
, 0, 0),
3776 'resource_type': func
.GetOriginalArgs()[1].resource_type
,
3777 'gl_gen_func_name': func
.GetInfo("gen_func"),
3781 TEST_F(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
3782 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
3783 SpecializedSetup<cmds::%(name)s, 0>(false);
3786 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
3789 self
.WriteInvalidUnitTest(func
, file, invalid_test
)
3791 def WriteGLES2Implementation(self
, func
, file):
3792 """Writes the GLES2 Implemention."""
3794 impl_func
= func
.GetInfo('impl_func')
3795 impl_decl
= func
.GetInfo('impl_decl')
3797 if (func
.can_auto_generate
and
3798 (impl_func
== None or impl_func
== True) and
3799 (impl_decl
== None or impl_decl
== True)):
3801 file.Write("%s GLES2Implementation::%s(%s) {\n" %
3802 (func
.return_type
, func
.original_name
,
3803 func
.MakeTypedOriginalArgString("")))
3804 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
3805 func
.WriteDestinationInitalizationValidation(file)
3806 self
.WriteClientGLCallLog(func
, file)
3807 for arg
in func
.GetOriginalArgs():
3808 arg
.WriteClientSideValidationCode(file, func
)
3810 code
= """ if (Is%(type)sReservedId(%(id)s)) {
3811 SetGLError(GL_INVALID_OPERATION, "%(name)s\", \"%(id)s reserved id");
3814 if (Bind%(type)sHelper(%(arg_string)s)) {
3815 helper_->%(name)s(%(arg_string)s);
3822 if len(func
.GetOriginalArgs()) == 1:
3823 # Bind functions that have no target (like BindVertexArrayOES)
3824 name_arg
= func
.GetOriginalArgs()[0]
3826 # Bind functions that have both a target and a name (like BindTexture)
3827 name_arg
= func
.GetOriginalArgs()[1]
3831 'arg_string': func
.MakeOriginalArgString(""),
3832 'id': name_arg
.name
,
3833 'type': name_arg
.resource_type
,
3834 'lc_type': name_arg
.resource_type
.lower(),
3837 def WriteGLES2ImplementationUnitTest(self
, func
, file):
3838 """Overrriden from TypeHandler."""
3839 client_test
= func
.GetInfo('client_test')
3840 if client_test
== False:
3843 TEST_F(GLES2ImplementationTest, %(name)s) {
3848 expected.cmd.Init(%(cmd_args)s);
3850 gl_->%(name)s(%(args)s);
3851 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
3853 gl_->%(name)s(%(args)s);
3854 EXPECT_TRUE(NoCommandsWritten());
3857 cmd_arg_strings
= []
3858 for count
, arg
in enumerate(func
.GetCmdArgs()):
3859 cmd_arg_strings
.append(arg
.GetValidClientSideCmdArg(func
, count
, 0))
3862 for count
, arg
in enumerate(func
.GetOriginalArgs()):
3863 gl_arg_strings
.append(arg
.GetValidClientSideArg(func
, count
, 0))
3866 'args': ", ".join(gl_arg_strings
),
3867 'cmd_args': ", ".join(cmd_arg_strings
),
3871 class GENnHandler(TypeHandler
):
3872 """Handler for glGen___ type functions."""
3875 TypeHandler
.__init
__(self
)
3877 def InitFunction(self
, func
):
3878 """Overrriden from TypeHandler."""
3881 def WriteGetDataSizeCode(self
, func
, file):
3882 """Overrriden from TypeHandler."""
3883 code
= """ uint32 data_size;
3884 if (!SafeMultiplyUint32(n, sizeof(GLuint), &data_size)) {
3885 return error::kOutOfBounds;
3890 def WriteHandlerImplementation (self
, func
, file):
3891 """Overrriden from TypeHandler."""
3892 file.Write(" if (!%sHelper(n, %s)) {\n"
3893 " return error::kInvalidArguments;\n"
3895 (func
.name
, func
.GetLastOriginalArg().name
))
3897 def WriteImmediateHandlerImplementation(self
, func
, file):
3898 """Overrriden from TypeHandler."""
3899 file.Write(" if (!%sHelper(n, %s)) {\n"
3900 " return error::kInvalidArguments;\n"
3902 (func
.original_name
, func
.GetLastOriginalArg().name
))
3904 def WriteGLES2Implementation(self
, func
, file):
3905 """Overrriden from TypeHandler."""
3906 log_code
= (""" GPU_CLIENT_LOG_CODE_BLOCK({
3907 for (GLsizei i = 0; i < n; ++i) {
3908 GPU_CLIENT_LOG(" " << i << ": " << %s[i]);
3910 });""" % func
.GetOriginalArgs()[1].name
)
3912 'log_code': log_code
,
3913 'return_type': func
.return_type
,
3914 'name': func
.original_name
,
3915 'typed_args': func
.MakeTypedOriginalArgString(""),
3916 'args': func
.MakeOriginalArgString(""),
3917 'resource_types': func
.GetInfo('resource_types'),
3918 'count_name': func
.GetOriginalArgs()[0].name
,
3921 "%(return_type)s GLES2Implementation::%(name)s(%(typed_args)s) {\n" %
3923 func
.WriteDestinationInitalizationValidation(file)
3924 self
.WriteClientGLCallLog(func
, file)
3925 for arg
in func
.GetOriginalArgs():
3926 arg
.WriteClientSideValidationCode(file, func
)
3927 code
= """ GPU_CLIENT_SINGLE_THREAD_CHECK();
3928 GetIdHandler(id_namespaces::k%(resource_types)s)->
3929 MakeIds(this, 0, %(args)s);
3930 %(name)sHelper(%(args)s);
3931 helper_->%(name)sImmediate(%(args)s);
3932 helper_->CommandBufferHelper::Flush();
3938 file.Write(code
% args
)
3940 def WriteGLES2ImplementationUnitTest(self
, func
, file):
3941 """Overrriden from TypeHandler."""
3943 TEST_F(GLES2ImplementationTest, %(name)s) {
3944 GLuint ids[2] = { 0, };
3946 cmds::%(name)sImmediate gen;
3950 expected.gen.Init(arraysize(ids), &ids[0]);
3951 expected.data[0] = k%(types)sStartId;
3952 expected.data[1] = k%(types)sStartId + 1;
3953 gl_->%(name)s(arraysize(ids), &ids[0]);
3954 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
3955 EXPECT_EQ(k%(types)sStartId, ids[0]);
3956 EXPECT_EQ(k%(types)sStartId + 1, ids[1]);
3961 'types': func
.GetInfo('resource_types'),
3964 def WriteServiceUnitTest(self
, func
, file):
3965 """Overrriden from TypeHandler."""
3967 TEST_F(%(test_name)s, %(name)sValidArgs) {
3968 EXPECT_CALL(*gl_, %(gl_func_name)s(1, _))
3969 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
3970 GetSharedMemoryAs<GLuint*>()[0] = kNewClientId;
3971 SpecializedSetup<cmds::%(name)s, 0>(true);
3974 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
3975 EXPECT_EQ(GL_NO_ERROR, GetGLError());
3976 EXPECT_TRUE(Get%(resource_name)s(kNewClientId) != NULL);
3979 self
.WriteValidUnitTest(func
, file, valid_test
, {
3980 'resource_name': func
.GetInfo('resource_type'),
3983 TEST_F(%(test_name)s, %(name)sInvalidArgs) {
3984 EXPECT_CALL(*gl_, %(gl_func_name)s(_, _)).Times(0);
3985 GetSharedMemoryAs<GLuint*>()[0] = client_%(resource_name)s_id_;
3986 SpecializedSetup<cmds::%(name)s, 0>(false);
3989 EXPECT_EQ(error::kInvalidArguments, ExecuteCmd(cmd));
3992 self
.WriteValidUnitTest(func
, file, invalid_test
, {
3993 'resource_name': func
.GetInfo('resource_type').lower(),
3996 def WriteImmediateServiceUnitTest(self
, func
, file):
3997 """Overrriden from TypeHandler."""
3999 TEST_F(%(test_name)s, %(name)sValidArgs) {
4000 EXPECT_CALL(*gl_, %(gl_func_name)s(1, _))
4001 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
4002 cmds::%(name)s* cmd = GetImmediateAs<cmds::%(name)s>();
4003 GLuint temp = kNewClientId;
4004 SpecializedSetup<cmds::%(name)s, 0>(true);
4005 cmd->Init(1, &temp);
4006 EXPECT_EQ(error::kNoError,
4007 ExecuteImmediateCmd(*cmd, sizeof(temp)));
4008 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4009 EXPECT_TRUE(Get%(resource_name)s(kNewClientId) != NULL);
4012 self
.WriteValidUnitTest(func
, file, valid_test
, {
4013 'resource_name': func
.GetInfo('resource_type'),
4016 TEST_F(%(test_name)s, %(name)sInvalidArgs) {
4017 EXPECT_CALL(*gl_, %(gl_func_name)s(_, _)).Times(0);
4018 cmds::%(name)s* cmd = GetImmediateAs<cmds::%(name)s>();
4019 SpecializedSetup<cmds::%(name)s, 0>(false);
4020 cmd->Init(1, &client_%(resource_name)s_id_);
4021 EXPECT_EQ(error::kInvalidArguments,
4022 ExecuteImmediateCmd(*cmd, sizeof(&client_%(resource_name)s_id_)));
4025 self
.WriteValidUnitTest(func
, file, invalid_test
, {
4026 'resource_name': func
.GetInfo('resource_type').lower(),
4029 def WriteImmediateCmdComputeSize(self
, func
, file):
4030 """Overrriden from TypeHandler."""
4031 file.Write(" static uint32 ComputeDataSize(GLsizei n) {\n")
4033 " return static_cast<uint32>(sizeof(GLuint) * n); // NOLINT\n")
4036 file.Write(" static uint32 ComputeSize(GLsizei n) {\n")
4037 file.Write(" return static_cast<uint32>(\n")
4038 file.Write(" sizeof(ValueType) + ComputeDataSize(n)); // NOLINT\n")
4042 def WriteImmediateCmdSetHeader(self
, func
, file):
4043 """Overrriden from TypeHandler."""
4044 file.Write(" void SetHeader(GLsizei n) {\n")
4045 file.Write(" header.SetCmdByTotalSize<ValueType>(ComputeSize(n));\n")
4049 def WriteImmediateCmdInit(self
, func
, file):
4050 """Overrriden from TypeHandler."""
4051 last_arg
= func
.GetLastOriginalArg()
4052 file.Write(" void Init(%s, %s _%s) {\n" %
4053 (func
.MakeTypedCmdArgString("_"),
4054 last_arg
.type, last_arg
.name
))
4055 file.Write(" SetHeader(_n);\n")
4056 args
= func
.GetCmdArgs()
4058 file.Write(" %s = _%s;\n" % (arg
.name
, arg
.name
))
4059 file.Write(" memcpy(ImmediateDataAddress(this),\n")
4060 file.Write(" _%s, ComputeDataSize(_n));\n" % last_arg
.name
)
4064 def WriteImmediateCmdSet(self
, func
, file):
4065 """Overrriden from TypeHandler."""
4066 last_arg
= func
.GetLastOriginalArg()
4067 copy_args
= func
.MakeCmdArgString("_", False)
4068 file.Write(" void* Set(void* cmd%s, %s _%s) {\n" %
4069 (func
.MakeTypedCmdArgString("_", True),
4070 last_arg
.type, last_arg
.name
))
4071 file.Write(" static_cast<ValueType*>(cmd)->Init(%s, _%s);\n" %
4072 (copy_args
, last_arg
.name
))
4073 file.Write(" const uint32 size = ComputeSize(_n);\n")
4074 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
4079 def WriteImmediateCmdHelper(self
, func
, file):
4080 """Overrriden from TypeHandler."""
4081 code
= """ void %(name)s(%(typed_args)s) {
4082 const uint32 size = gles2::cmds::%(name)s::ComputeSize(n);
4083 gles2::cmds::%(name)s* c =
4084 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
4093 "typed_args": func
.MakeTypedOriginalArgString(""),
4094 "args": func
.MakeOriginalArgString(""),
4097 def WriteImmediateFormatTest(self
, func
, file):
4098 """Overrriden from TypeHandler."""
4099 file.Write("TEST_F(GLES2FormatTest, %s) {\n" % func
.name
)
4100 file.Write(" static GLuint ids[] = { 12, 23, 34, };\n")
4101 file.Write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
4102 (func
.name
, func
.name
))
4103 file.Write(" void* next_cmd = cmd.Set(\n")
4104 file.Write(" &cmd, static_cast<GLsizei>(arraysize(ids)), ids);\n")
4105 file.Write(" EXPECT_EQ(static_cast<uint32>(cmds::%s::kCmdId),\n" %
4107 file.Write(" cmd.header.command);\n")
4108 file.Write(" EXPECT_EQ(sizeof(cmd) +\n")
4109 file.Write(" RoundSizeToMultipleOfEntries(cmd.n * 4u),\n")
4110 file.Write(" cmd.header.size * 4u);\n")
4111 file.Write(" EXPECT_EQ(static_cast<GLsizei>(arraysize(ids)), cmd.n);\n");
4112 file.Write(" CheckBytesWrittenMatchesExpectedSize(\n")
4113 file.Write(" next_cmd, sizeof(cmd) +\n")
4114 file.Write(" RoundSizeToMultipleOfEntries(arraysize(ids) * 4u));\n")
4115 file.Write(" // TODO(gman): Check that ids were inserted;\n")
4120 class CreateHandler(TypeHandler
):
4121 """Handler for glCreate___ type functions."""
4124 TypeHandler
.__init
__(self
)
4126 def InitFunction(self
, func
):
4127 """Overrriden from TypeHandler."""
4128 func
.AddCmdArg(Argument("client_id", 'uint32'))
4130 def WriteServiceUnitTest(self
, func
, file):
4131 """Overrriden from TypeHandler."""
4133 TEST_F(%(test_name)s, %(name)sValidArgs) {
4134 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s))
4135 .WillOnce(Return(kNewServiceId));
4136 SpecializedSetup<cmds::%(name)s, 0>(true);
4138 cmd.Init(%(args)s%(comma)skNewClientId);
4139 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4140 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4141 EXPECT_TRUE(Get%(resource_type)s(kNewClientId) != NULL);
4145 if len(func
.GetOriginalArgs()):
4147 self
.WriteValidUnitTest(func
, file, valid_test
, {
4149 'resource_type': func
.name
[6:],
4152 TEST_F(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
4153 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
4154 SpecializedSetup<cmds::%(name)s, 0>(false);
4156 cmd.Init(%(args)s%(comma)skNewClientId);
4157 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));%(gl_error_test)s
4160 self
.WriteInvalidUnitTest(func
, file, invalid_test
, {
4164 def WriteHandlerImplementation (self
, func
, file):
4165 """Overrriden from TypeHandler."""
4166 file.Write(" uint32 client_id = c.client_id;\n")
4167 file.Write(" if (!%sHelper(%s)) {\n" %
4168 (func
.name
, func
.MakeCmdArgString("")))
4169 file.Write(" return error::kInvalidArguments;\n")
4172 def WriteGLES2Implementation(self
, func
, file):
4173 """Overrriden from TypeHandler."""
4174 file.Write("%s GLES2Implementation::%s(%s) {\n" %
4175 (func
.return_type
, func
.original_name
,
4176 func
.MakeTypedOriginalArgString("")))
4177 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
4178 func
.WriteDestinationInitalizationValidation(file)
4179 self
.WriteClientGLCallLog(func
, file)
4180 for arg
in func
.GetOriginalArgs():
4181 arg
.WriteClientSideValidationCode(file, func
)
4182 file.Write(" GLuint client_id;\n")
4184 " GetIdHandler(id_namespaces::kProgramsAndShaders)->\n")
4185 file.Write(" MakeIds(this, 0, 1, &client_id);\n")
4186 file.Write(" helper_->%s(%s);\n" %
4187 (func
.name
, func
.MakeCmdArgString("")))
4188 file.Write(' GPU_CLIENT_LOG("returned " << client_id);\n')
4189 file.Write(" CheckGLError();\n")
4190 file.Write(" return client_id;\n")
4195 class DeleteHandler(TypeHandler
):
4196 """Handler for glDelete___ single resource type functions."""
4199 TypeHandler
.__init
__(self
)
4201 def WriteServiceImplementation(self
, func
, file):
4202 """Overrriden from TypeHandler."""
4205 def WriteGLES2Implementation(self
, func
, file):
4206 """Overrriden from TypeHandler."""
4207 file.Write("%s GLES2Implementation::%s(%s) {\n" %
4208 (func
.return_type
, func
.original_name
,
4209 func
.MakeTypedOriginalArgString("")))
4210 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
4211 func
.WriteDestinationInitalizationValidation(file)
4212 self
.WriteClientGLCallLog(func
, file)
4213 for arg
in func
.GetOriginalArgs():
4214 arg
.WriteClientSideValidationCode(file, func
)
4216 " GPU_CLIENT_DCHECK(%s != 0);\n" % func
.GetOriginalArgs()[-1].name
)
4217 file.Write(" %sHelper(%s);\n" %
4218 (func
.original_name
, func
.GetOriginalArgs()[-1].name
))
4219 file.Write(" CheckGLError();\n")
4224 class DELnHandler(TypeHandler
):
4225 """Handler for glDelete___ type functions."""
4228 TypeHandler
.__init
__(self
)
4230 def WriteGetDataSizeCode(self
, func
, file):
4231 """Overrriden from TypeHandler."""
4232 code
= """ uint32 data_size;
4233 if (!SafeMultiplyUint32(n, sizeof(GLuint), &data_size)) {
4234 return error::kOutOfBounds;
4239 def WriteGLES2ImplementationUnitTest(self
, func
, file):
4240 """Overrriden from TypeHandler."""
4242 TEST_F(GLES2ImplementationTest, %(name)s) {
4243 GLuint ids[2] = { k%(types)sStartId, k%(types)sStartId + 1 };
4245 cmds::%(name)sImmediate del;
4249 expected.del.Init(arraysize(ids), &ids[0]);
4250 expected.data[0] = k%(types)sStartId;
4251 expected.data[1] = k%(types)sStartId + 1;
4252 gl_->%(name)s(arraysize(ids), &ids[0]);
4253 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
4258 'types': func
.GetInfo('resource_types'),
4261 def WriteServiceUnitTest(self
, func
, file):
4262 """Overrriden from TypeHandler."""
4264 TEST_F(%(test_name)s, %(name)sValidArgs) {
4267 %(gl_func_name)s(1, Pointee(kService%(upper_resource_name)sId)))
4269 GetSharedMemoryAs<GLuint*>()[0] = client_%(resource_name)s_id_;
4270 SpecializedSetup<cmds::%(name)s, 0>(true);
4273 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4274 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4276 Get%(upper_resource_name)s(client_%(resource_name)s_id_) == NULL);
4279 self
.WriteValidUnitTest(func
, file, valid_test
, {
4280 'resource_name': func
.GetInfo('resource_type').lower(),
4281 'upper_resource_name': func
.GetInfo('resource_type'),
4284 TEST_F(%(test_name)s, %(name)sInvalidArgs) {
4285 GetSharedMemoryAs<GLuint*>()[0] = kInvalidClientId;
4286 SpecializedSetup<cmds::%(name)s, 0>(false);
4289 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4292 self
.WriteValidUnitTest(func
, file, invalid_test
)
4294 def WriteImmediateServiceUnitTest(self
, func
, file):
4295 """Overrriden from TypeHandler."""
4297 TEST_F(%(test_name)s, %(name)sValidArgs) {
4300 %(gl_func_name)s(1, Pointee(kService%(upper_resource_name)sId)))
4302 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
4303 SpecializedSetup<cmds::%(name)s, 0>(true);
4304 cmd.Init(1, &client_%(resource_name)s_id_);
4305 EXPECT_EQ(error::kNoError,
4306 ExecuteImmediateCmd(cmd, sizeof(client_%(resource_name)s_id_)));
4307 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4309 Get%(upper_resource_name)s(client_%(resource_name)s_id_) == NULL);
4312 self
.WriteValidUnitTest(func
, file, valid_test
, {
4313 'resource_name': func
.GetInfo('resource_type').lower(),
4314 'upper_resource_name': func
.GetInfo('resource_type'),
4317 TEST_F(%(test_name)s, %(name)sInvalidArgs) {
4318 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
4319 SpecializedSetup<cmds::%(name)s, 0>(false);
4320 GLuint temp = kInvalidClientId;
4322 EXPECT_EQ(error::kNoError,
4323 ExecuteImmediateCmd(cmd, sizeof(temp)));
4326 self
.WriteValidUnitTest(func
, file, invalid_test
)
4328 def WriteHandlerImplementation (self
, func
, file):
4329 """Overrriden from TypeHandler."""
4330 file.Write(" %sHelper(n, %s);\n" %
4331 (func
.name
, func
.GetLastOriginalArg().name
))
4333 def WriteImmediateHandlerImplementation (self
, func
, file):
4334 """Overrriden from TypeHandler."""
4335 file.Write(" %sHelper(n, %s);\n" %
4336 (func
.original_name
, func
.GetLastOriginalArg().name
))
4338 def WriteGLES2Implementation(self
, func
, file):
4339 """Overrriden from TypeHandler."""
4340 impl_decl
= func
.GetInfo('impl_decl')
4341 if impl_decl
== None or impl_decl
== True:
4343 'return_type': func
.return_type
,
4344 'name': func
.original_name
,
4345 'typed_args': func
.MakeTypedOriginalArgString(""),
4346 'args': func
.MakeOriginalArgString(""),
4347 'resource_type': func
.GetInfo('resource_type').lower(),
4348 'count_name': func
.GetOriginalArgs()[0].name
,
4351 "%(return_type)s GLES2Implementation::%(name)s(%(typed_args)s) {\n" %
4353 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
4354 func
.WriteDestinationInitalizationValidation(file)
4355 self
.WriteClientGLCallLog(func
, file)
4356 file.Write(""" GPU_CLIENT_LOG_CODE_BLOCK({
4357 for (GLsizei i = 0; i < n; ++i) {
4358 GPU_CLIENT_LOG(" " << i << ": " << %s[i]);
4361 """ % func
.GetOriginalArgs()[1].name
)
4362 file.Write(""" GPU_CLIENT_DCHECK_CODE_BLOCK({
4363 for (GLsizei i = 0; i < n; ++i) {
4364 GPU_DCHECK(%s[i] != 0);
4367 """ % func
.GetOriginalArgs()[1].name
)
4368 for arg
in func
.GetOriginalArgs():
4369 arg
.WriteClientSideValidationCode(file, func
)
4370 code
= """ %(name)sHelper(%(args)s);
4375 file.Write(code
% args
)
4377 def WriteImmediateCmdComputeSize(self
, func
, file):
4378 """Overrriden from TypeHandler."""
4379 file.Write(" static uint32 ComputeDataSize(GLsizei n) {\n")
4381 " return static_cast<uint32>(sizeof(GLuint) * n); // NOLINT\n")
4384 file.Write(" static uint32 ComputeSize(GLsizei n) {\n")
4385 file.Write(" return static_cast<uint32>(\n")
4386 file.Write(" sizeof(ValueType) + ComputeDataSize(n)); // NOLINT\n")
4390 def WriteImmediateCmdSetHeader(self
, func
, file):
4391 """Overrriden from TypeHandler."""
4392 file.Write(" void SetHeader(GLsizei n) {\n")
4393 file.Write(" header.SetCmdByTotalSize<ValueType>(ComputeSize(n));\n")
4397 def WriteImmediateCmdInit(self
, func
, file):
4398 """Overrriden from TypeHandler."""
4399 last_arg
= func
.GetLastOriginalArg()
4400 file.Write(" void Init(%s, %s _%s) {\n" %
4401 (func
.MakeTypedCmdArgString("_"),
4402 last_arg
.type, last_arg
.name
))
4403 file.Write(" SetHeader(_n);\n")
4404 args
= func
.GetCmdArgs()
4406 file.Write(" %s = _%s;\n" % (arg
.name
, arg
.name
))
4407 file.Write(" memcpy(ImmediateDataAddress(this),\n")
4408 file.Write(" _%s, ComputeDataSize(_n));\n" % last_arg
.name
)
4412 def WriteImmediateCmdSet(self
, func
, file):
4413 """Overrriden from TypeHandler."""
4414 last_arg
= func
.GetLastOriginalArg()
4415 copy_args
= func
.MakeCmdArgString("_", False)
4416 file.Write(" void* Set(void* cmd%s, %s _%s) {\n" %
4417 (func
.MakeTypedCmdArgString("_", True),
4418 last_arg
.type, last_arg
.name
))
4419 file.Write(" static_cast<ValueType*>(cmd)->Init(%s, _%s);\n" %
4420 (copy_args
, last_arg
.name
))
4421 file.Write(" const uint32 size = ComputeSize(_n);\n")
4422 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
4427 def WriteImmediateCmdHelper(self
, func
, file):
4428 """Overrriden from TypeHandler."""
4429 code
= """ void %(name)s(%(typed_args)s) {
4430 const uint32 size = gles2::cmds::%(name)s::ComputeSize(n);
4431 gles2::cmds::%(name)s* c =
4432 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
4441 "typed_args": func
.MakeTypedOriginalArgString(""),
4442 "args": func
.MakeOriginalArgString(""),
4445 def WriteImmediateFormatTest(self
, func
, file):
4446 """Overrriden from TypeHandler."""
4447 file.Write("TEST_F(GLES2FormatTest, %s) {\n" % func
.name
)
4448 file.Write(" static GLuint ids[] = { 12, 23, 34, };\n")
4449 file.Write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
4450 (func
.name
, func
.name
))
4451 file.Write(" void* next_cmd = cmd.Set(\n")
4452 file.Write(" &cmd, static_cast<GLsizei>(arraysize(ids)), ids);\n")
4453 file.Write(" EXPECT_EQ(static_cast<uint32>(cmds::%s::kCmdId),\n" %
4455 file.Write(" cmd.header.command);\n")
4456 file.Write(" EXPECT_EQ(sizeof(cmd) +\n")
4457 file.Write(" RoundSizeToMultipleOfEntries(cmd.n * 4u),\n")
4458 file.Write(" cmd.header.size * 4u);\n")
4459 file.Write(" EXPECT_EQ(static_cast<GLsizei>(arraysize(ids)), cmd.n);\n");
4460 file.Write(" CheckBytesWrittenMatchesExpectedSize(\n")
4461 file.Write(" next_cmd, sizeof(cmd) +\n")
4462 file.Write(" RoundSizeToMultipleOfEntries(arraysize(ids) * 4u));\n")
4463 file.Write(" // TODO(gman): Check that ids were inserted;\n")
4468 class GETnHandler(TypeHandler
):
4469 """Handler for GETn for glGetBooleanv, glGetFloatv, ... type functions."""
4472 TypeHandler
.__init
__(self
)
4474 def AddImmediateFunction(self
, generator
, func
):
4475 """Overrriden from TypeHandler."""
4478 def WriteServiceImplementation(self
, func
, file):
4479 """Overrriden from TypeHandler."""
4481 "error::Error GLES2DecoderImpl::Handle%s(\n" % func
.name
)
4483 " uint32 immediate_data_size, const gles2::cmds::%s& c) {\n" %
4485 last_arg
= func
.GetLastOriginalArg()
4487 all_but_last_args
= func
.GetOriginalArgs()[:-1]
4488 for arg
in all_but_last_args
:
4489 arg
.WriteGetCode(file)
4491 code
= """ typedef cmds::%(func_name)s::Result Result;
4492 GLsizei num_values = 0;
4493 GetNumValuesReturnedForGLGet(pname, &num_values);
4494 Result* result = GetSharedMemoryAs<Result*>(
4495 c.params_shm_id, c.params_shm_offset, Result::ComputeSize(num_values));
4496 %(last_arg_type)s params = result ? result->GetData() : NULL;
4499 'last_arg_type': last_arg
.type,
4500 'func_name': func
.name
,
4502 func
.WriteHandlerValidation(file)
4503 code
= """ // Check that the client initialized the result.
4504 if (result->size != 0) {
4505 return error::kInvalidArguments;
4508 shadowed
= func
.GetInfo('shadowed')
4510 file.Write(' LOCAL_COPY_REAL_GL_ERRORS_TO_WRAPPER("%s");\n' % func
.name
)
4512 func
.WriteHandlerImplementation(file)
4514 code
= """ result->SetNumResults(num_values);
4515 return error::kNoError;
4519 code
= """ GLenum error = glGetError();
4520 if (error == GL_NO_ERROR) {
4521 result->SetNumResults(num_values);
4523 LOCAL_SET_GL_ERROR(error, "%(func_name)s", "");
4525 return error::kNoError;
4529 file.Write(code
% {'func_name': func
.name
})
4531 def WriteGLES2Implementation(self
, func
, file):
4532 """Overrriden from TypeHandler."""
4533 impl_decl
= func
.GetInfo('impl_decl')
4534 if impl_decl
== None or impl_decl
== True:
4535 file.Write("%s GLES2Implementation::%s(%s) {\n" %
4536 (func
.return_type
, func
.original_name
,
4537 func
.MakeTypedOriginalArgString("")))
4538 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
4539 func
.WriteDestinationInitalizationValidation(file)
4540 self
.WriteClientGLCallLog(func
, file)
4541 for arg
in func
.GetOriginalArgs():
4542 arg
.WriteClientSideValidationCode(file, func
)
4543 all_but_last_args
= func
.GetOriginalArgs()[:-1]
4545 ", ".join(["%s" % arg
.name
for arg
in all_but_last_args
]))
4547 ", ".join(["%s" % arg
.name
for arg
in func
.GetOriginalArgs()]))
4548 self
.WriteTraceEvent(func
, file)
4549 code
= """ if (%(func_name)sHelper(%(all_arg_string)s)) {
4552 typedef cmds::%(func_name)s::Result Result;
4553 Result* result = GetResultAs<Result*>();
4557 result->SetNumResults(0);
4558 helper_->%(func_name)s(%(arg_string)s,
4559 GetResultShmId(), GetResultShmOffset());
4561 result->CopyResult(params);
4562 GPU_CLIENT_LOG_CODE_BLOCK({
4563 for (int32 i = 0; i < result->GetNumResults(); ++i) {
4564 GPU_CLIENT_LOG(" " << i << ": " << result->GetData()[i]);
4571 'func_name': func
.name
,
4572 'arg_string': arg_string
,
4573 'all_arg_string': all_arg_string
,
4576 def WriteGLES2ImplementationUnitTest(self
, func
, file):
4577 """Writes the GLES2 Implemention unit test."""
4579 TEST_F(GLES2ImplementationTest, %(name)s) {
4583 typedef cmds::%(name)s::Result Result;
4584 Result::Type result = 0;
4586 ExpectedMemoryInfo result1 = GetExpectedResultMemory(4);
4587 expected.cmd.Init(%(cmd_args)s, result1.id, result1.offset);
4588 EXPECT_CALL(*command_buffer(), OnFlush())
4589 .WillOnce(SetMemory(result1.ptr, SizedResultHelper<Result::Type>(1)))
4590 .RetiresOnSaturation();
4591 gl_->%(name)s(%(args)s, &result);
4592 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
4593 EXPECT_EQ(static_cast<Result::Type>(1), result);
4596 cmd_arg_strings
= []
4597 for count
, arg
in enumerate(func
.GetCmdArgs()[0:-2]):
4598 cmd_arg_strings
.append(arg
.GetValidClientSideCmdArg(func
, count
, 0))
4599 cmd_arg_strings
[0] = '123'
4601 for count
, arg
in enumerate(func
.GetOriginalArgs()[0:-1]):
4602 gl_arg_strings
.append(arg
.GetValidClientSideArg(func
, count
, 0))
4603 gl_arg_strings
[0] = '123'
4606 'args': ", ".join(gl_arg_strings
),
4607 'cmd_args': ", ".join(cmd_arg_strings
),
4610 def WriteServiceUnitTest(self
, func
, file):
4611 """Overrriden from TypeHandler."""
4613 TEST_F(%(test_name)s, %(name)sValidArgs) {
4614 EXPECT_CALL(*gl_, GetError())
4615 .WillOnce(Return(GL_NO_ERROR))
4616 .WillOnce(Return(GL_NO_ERROR))
4617 .RetiresOnSaturation();
4618 SpecializedSetup<cmds::%(name)s, 0>(true);
4619 typedef cmds::%(name)s::Result Result;
4620 Result* result = static_cast<Result*>(shared_memory_address_);
4621 EXPECT_CALL(*gl_, %(gl_func_name)s(%(local_gl_args)s));
4625 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4626 EXPECT_EQ(decoder_->GetGLES2Util()->GLGetNumValuesReturned(
4628 result->GetNumResults());
4629 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4634 for count
, arg
in enumerate(func
.GetOriginalArgs()[:-1]):
4635 arg_value
= arg
.GetValidGLArg(func
, count
, 0)
4636 gl_arg_strings
.append(arg_value
)
4637 if arg
.name
== 'pname':
4638 valid_pname
= arg_value
4639 if func
.GetInfo('gl_test_func') == 'glGetIntegerv':
4640 gl_arg_strings
.append("_")
4642 gl_arg_strings
.append("result->GetData()")
4644 self
.WriteValidUnitTest(func
, file, valid_test
, {
4645 'local_gl_args': ", ".join(gl_arg_strings
),
4646 'valid_pname': valid_pname
,
4650 TEST_F(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
4651 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
4652 SpecializedSetup<cmds::%(name)s, 0>(false);
4653 cmds::%(name)s::Result* result =
4654 static_cast<cmds::%(name)s::Result*>(shared_memory_address_);
4658 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));
4659 EXPECT_EQ(0u, result->size);%(gl_error_test)s
4662 self
.WriteInvalidUnitTest(func
, file, invalid_test
)
4665 class PUTHandler(TypeHandler
):
4666 """Handler for glTexParameter_v, glVertexAttrib_v functions."""
4669 TypeHandler
.__init
__(self
)
4671 def WriteServiceUnitTest(self
, func
, file):
4672 """Writes the service unit test for a command."""
4673 expected_call
= "EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));"
4674 if func
.GetInfo("first_element_only"):
4676 for count
, arg
in enumerate(func
.GetOriginalArgs()):
4677 gl_arg_strings
.append(arg
.GetValidGLArg(func
, count
, 0))
4678 gl_arg_strings
[-1] = "*" + gl_arg_strings
[-1]
4679 expected_call
= ("EXPECT_CALL(*gl_, %%(gl_func_name)s(%s));" %
4680 ", ".join(gl_arg_strings
))
4682 TEST_F(%(test_name)s, %(name)sValidArgs) {
4683 SpecializedSetup<cmds::%(name)s, 0>(true);
4686 GetSharedMemoryAs<%(data_type)s*>()[0] = %(data_value)s;
4688 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4689 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4693 'data_type': func
.GetInfo('data_type'),
4694 'data_value': func
.GetInfo('data_value') or '0',
4695 'expected_call': expected_call
,
4697 self
.WriteValidUnitTest(func
, file, valid_test
, extra
)
4700 TEST_F(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
4701 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
4702 SpecializedSetup<cmds::%(name)s, 0>(false);
4705 GetSharedMemoryAs<%(data_type)s*>()[0] = %(data_value)s;
4706 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
4709 self
.WriteInvalidUnitTest(func
, file, invalid_test
, extra
)
4711 def WriteImmediateServiceUnitTest(self
, func
, file):
4712 """Writes the service unit test for a command."""
4714 TEST_F(%(test_name)s, %(name)sValidArgs) {
4715 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
4716 SpecializedSetup<cmds::%(name)s, 0>(true);
4717 %(data_type)s temp[%(data_count)s] = { %(data_value)s, };
4718 cmd.Init(%(gl_args)s, &temp[0]);
4721 %(gl_func_name)s(%(gl_args)s, %(data_ref)sreinterpret_cast<
4722 %(data_type)s*>(ImmediateDataAddress(&cmd))));
4723 EXPECT_EQ(error::kNoError,
4724 ExecuteImmediateCmd(cmd, sizeof(temp)));
4725 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4730 for count
, arg
in enumerate(func
.GetOriginalArgs()[0:-1]):
4731 gl_arg_strings
.append(arg
.GetValidGLArg(func
, count
, 0))
4732 gl_any_strings
.append("_")
4734 'data_ref': ("*" if func
.GetInfo('first_element_only') else ""),
4735 'data_type': func
.GetInfo('data_type'),
4736 'data_count': func
.GetInfo('count'),
4737 'data_value': func
.GetInfo('data_value') or '0',
4738 'gl_args': ", ".join(gl_arg_strings
),
4739 'gl_any_args': ", ".join(gl_any_strings
),
4741 self
.WriteValidUnitTest(func
, file, valid_test
, extra
)
4744 TEST_F(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
4745 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
4746 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_any_args)s, _)).Times(0);
4747 SpecializedSetup<cmds::%(name)s, 0>(false);
4748 %(data_type)s temp[%(data_count)s] = { %(data_value)s, };
4749 cmd.Init(%(all_but_last_args)s, &temp[0]);
4750 EXPECT_EQ(error::%(parse_result)s,
4751 ExecuteImmediateCmd(cmd, sizeof(temp)));%(gl_error_test)s
4754 self
.WriteInvalidUnitTest(func
, file, invalid_test
, extra
)
4756 def WriteGetDataSizeCode(self
, func
, file):
4757 """Overrriden from TypeHandler."""
4758 code
= """ uint32 data_size;
4759 if (!ComputeDataSize(1, sizeof(%s), %d, &data_size)) {
4760 return error::kOutOfBounds;
4763 file.Write(code
% (func
.info
.data_type
, func
.info
.count
))
4764 if func
.is_immediate
:
4765 file.Write(" if (data_size > immediate_data_size) {\n")
4766 file.Write(" return error::kOutOfBounds;\n")
4769 def WriteGLES2Implementation(self
, func
, file):
4770 """Overrriden from TypeHandler."""
4771 file.Write("%s GLES2Implementation::%s(%s) {\n" %
4772 (func
.return_type
, func
.original_name
,
4773 func
.MakeTypedOriginalArgString("")))
4774 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
4775 func
.WriteDestinationInitalizationValidation(file)
4776 self
.WriteClientGLCallLog(func
, file)
4777 last_arg_name
= func
.GetLastOriginalArg().name
4778 values_str
= ' << ", " << '.join(
4779 ["%s[%d]" % (last_arg_name
, ndx
) for ndx
in range(0, func
.info
.count
)])
4780 file.Write(' GPU_CLIENT_LOG("values: " << %s);\n' % values_str
)
4781 for arg
in func
.GetOriginalArgs():
4782 arg
.WriteClientSideValidationCode(file, func
)
4783 file.Write(" helper_->%sImmediate(%s);\n" %
4784 (func
.name
, func
.MakeOriginalArgString("")))
4785 file.Write(" CheckGLError();\n")
4789 def WriteGLES2ImplementationUnitTest(self
, func
, file):
4790 """Writes the GLES2 Implemention unit test."""
4792 TEST_F(GLES2ImplementationTest, %(name)s) {
4793 %(type)s data[%(count)d] = {0};
4795 cmds::%(name)sImmediate cmd;
4796 %(type)s data[%(count)d];
4799 for (int jj = 0; jj < %(count)d; ++jj) {
4800 data[jj] = static_cast<%(type)s>(jj);
4803 expected.cmd.Init(%(cmd_args)s, &data[0]);
4804 gl_->%(name)s(%(args)s, &data[0]);
4805 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
4808 cmd_arg_strings
= []
4809 for count
, arg
in enumerate(func
.GetCmdArgs()[0:-2]):
4810 cmd_arg_strings
.append(arg
.GetValidClientSideCmdArg(func
, count
, 0))
4812 for count
, arg
in enumerate(func
.GetOriginalArgs()[0:-1]):
4813 gl_arg_strings
.append(arg
.GetValidClientSideArg(func
, count
, 0))
4816 'type': func
.GetInfo('data_type'),
4817 'count': func
.GetInfo('count'),
4818 'args': ", ".join(gl_arg_strings
),
4819 'cmd_args': ", ".join(cmd_arg_strings
),
4822 def WriteImmediateCmdComputeSize(self
, func
, file):
4823 """Overrriden from TypeHandler."""
4824 file.Write(" static uint32 ComputeDataSize() {\n")
4825 file.Write(" return static_cast<uint32>(\n")
4826 file.Write(" sizeof(%s) * %d); // NOLINT\n" %
4827 (func
.info
.data_type
, func
.info
.count
))
4830 file.Write(" static uint32 ComputeSize() {\n")
4831 file.Write(" return static_cast<uint32>(\n")
4833 " sizeof(ValueType) + ComputeDataSize()); // NOLINT\n")
4837 def WriteImmediateCmdSetHeader(self
, func
, file):
4838 """Overrriden from TypeHandler."""
4839 file.Write(" void SetHeader() {\n")
4841 " header.SetCmdByTotalSize<ValueType>(ComputeSize());\n")
4845 def WriteImmediateCmdInit(self
, func
, file):
4846 """Overrriden from TypeHandler."""
4847 last_arg
= func
.GetLastOriginalArg()
4848 file.Write(" void Init(%s, %s _%s) {\n" %
4849 (func
.MakeTypedCmdArgString("_"),
4850 last_arg
.type, last_arg
.name
))
4851 file.Write(" SetHeader();\n")
4852 args
= func
.GetCmdArgs()
4854 file.Write(" %s = _%s;\n" % (arg
.name
, arg
.name
))
4855 file.Write(" memcpy(ImmediateDataAddress(this),\n")
4856 file.Write(" _%s, ComputeDataSize());\n" % last_arg
.name
)
4860 def WriteImmediateCmdSet(self
, func
, file):
4861 """Overrriden from TypeHandler."""
4862 last_arg
= func
.GetLastOriginalArg()
4863 copy_args
= func
.MakeCmdArgString("_", False)
4864 file.Write(" void* Set(void* cmd%s, %s _%s) {\n" %
4865 (func
.MakeTypedCmdArgString("_", True),
4866 last_arg
.type, last_arg
.name
))
4867 file.Write(" static_cast<ValueType*>(cmd)->Init(%s, _%s);\n" %
4868 (copy_args
, last_arg
.name
))
4869 file.Write(" const uint32 size = ComputeSize();\n")
4870 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
4875 def WriteImmediateCmdHelper(self
, func
, file):
4876 """Overrriden from TypeHandler."""
4877 code
= """ void %(name)s(%(typed_args)s) {
4878 const uint32 size = gles2::cmds::%(name)s::ComputeSize();
4879 gles2::cmds::%(name)s* c =
4880 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
4889 "typed_args": func
.MakeTypedOriginalArgString(""),
4890 "args": func
.MakeOriginalArgString(""),
4893 def WriteImmediateFormatTest(self
, func
, file):
4894 """Overrriden from TypeHandler."""
4895 file.Write("TEST_F(GLES2FormatTest, %s) {\n" % func
.name
)
4896 file.Write(" const int kSomeBaseValueToTestWith = 51;\n")
4897 file.Write(" static %s data[] = {\n" % func
.info
.data_type
)
4898 for v
in range(0, func
.info
.count
):
4899 file.Write(" static_cast<%s>(kSomeBaseValueToTestWith + %d),\n" %
4900 (func
.info
.data_type
, v
))
4902 file.Write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
4903 (func
.name
, func
.name
))
4904 file.Write(" void* next_cmd = cmd.Set(\n")
4906 args
= func
.GetCmdArgs()
4907 for value
, arg
in enumerate(args
):
4908 file.Write(",\n static_cast<%s>(%d)" % (arg
.type, value
+ 11))
4909 file.Write(",\n data);\n")
4910 args
= func
.GetCmdArgs()
4911 file.Write(" EXPECT_EQ(static_cast<uint32>(cmds::%s::kCmdId),\n"
4913 file.Write(" cmd.header.command);\n")
4914 file.Write(" EXPECT_EQ(sizeof(cmd) +\n")
4915 file.Write(" RoundSizeToMultipleOfEntries(sizeof(data)),\n")
4916 file.Write(" cmd.header.size * 4u);\n")
4917 for value
, arg
in enumerate(args
):
4918 file.Write(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);\n" %
4919 (arg
.type, value
+ 11, arg
.name
))
4920 file.Write(" CheckBytesWrittenMatchesExpectedSize(\n")
4921 file.Write(" next_cmd, sizeof(cmd) +\n")
4922 file.Write(" RoundSizeToMultipleOfEntries(sizeof(data)));\n")
4923 file.Write(" // TODO(gman): Check that data was inserted;\n")
4928 class PUTnHandler(TypeHandler
):
4929 """Handler for PUTn 'glUniform__v' type functions."""
4932 TypeHandler
.__init
__(self
)
4934 def WriteServiceUnitTest(self
, func
, file):
4935 """Overridden from TypeHandler."""
4936 TypeHandler
.WriteServiceUnitTest(self
, func
, file)
4939 TEST_F(%(test_name)s, %(name)sValidArgsCountTooLarge) {
4940 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
4941 SpecializedSetup<cmds::%(name)s, 0>(true);
4944 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4945 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4950 for count
, arg
in enumerate(func
.GetOriginalArgs()):
4951 # hardcoded to match unit tests.
4953 # the location of the second element of the 2nd uniform.
4954 # defined in GLES2DecoderBase::SetupShaderForUniform
4955 gl_arg_strings
.append("3")
4956 arg_strings
.append("ProgramManager::MakeFakeLocation(1, 1)")
4958 # the number of elements that gl will be called with.
4959 gl_arg_strings
.append("3")
4960 # the number of elements requested in the command.
4961 arg_strings
.append("5")
4963 gl_arg_strings
.append(arg
.GetValidGLArg(func
, count
, 0))
4964 arg_strings
.append(arg
.GetValidArg(func
, count
, 0))
4966 'gl_args': ", ".join(gl_arg_strings
),
4967 'args': ", ".join(arg_strings
),
4969 self
.WriteValidUnitTest(func
, file, valid_test
, extra
)
4971 def WriteImmediateServiceUnitTest(self
, func
, file):
4972 """Overridden from TypeHandler."""
4974 TEST_F(%(test_name)s, %(name)sValidArgs) {
4975 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
4978 %(gl_func_name)s(%(gl_args)s,
4979 reinterpret_cast<%(data_type)s*>(ImmediateDataAddress(&cmd))));
4980 SpecializedSetup<cmds::%(name)s, 0>(true);
4981 %(data_type)s temp[%(data_count)s * 2] = { 0, };
4982 cmd.Init(%(args)s, &temp[0]);
4983 EXPECT_EQ(error::kNoError,
4984 ExecuteImmediateCmd(cmd, sizeof(temp)));
4985 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4991 for count
, arg
in enumerate(func
.GetOriginalArgs()[0:-1]):
4992 gl_arg_strings
.append(arg
.GetValidGLArg(func
, count
, 0))
4993 gl_any_strings
.append("_")
4994 arg_strings
.append(arg
.GetValidArg(func
, count
, 0))
4996 'data_type': func
.GetInfo('data_type'),
4997 'data_count': func
.GetInfo('count'),
4998 'args': ", ".join(arg_strings
),
4999 'gl_args': ", ".join(gl_arg_strings
),
5000 'gl_any_args': ", ".join(gl_any_strings
),
5002 self
.WriteValidUnitTest(func
, file, valid_test
, extra
)
5005 TEST_F(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
5006 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
5007 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_any_args)s, _)).Times(0);
5008 SpecializedSetup<cmds::%(name)s, 0>(false);
5009 %(data_type)s temp[%(data_count)s * 2] = { 0, };
5010 cmd.Init(%(all_but_last_args)s, &temp[0]);
5011 EXPECT_EQ(error::%(parse_result)s,
5012 ExecuteImmediateCmd(cmd, sizeof(temp)));%(gl_error_test)s
5015 self
.WriteInvalidUnitTest(func
, file, invalid_test
, extra
)
5017 def WriteGetDataSizeCode(self
, func
, file):
5018 """Overrriden from TypeHandler."""
5019 code
= """ uint32 data_size;
5020 if (!ComputeDataSize(count, sizeof(%s), %d, &data_size)) {
5021 return error::kOutOfBounds;
5024 file.Write(code
% (func
.info
.data_type
, func
.info
.count
))
5025 if func
.is_immediate
:
5026 file.Write(" if (data_size > immediate_data_size) {\n")
5027 file.Write(" return error::kOutOfBounds;\n")
5030 def WriteGLES2Implementation(self
, func
, file):
5031 """Overrriden from TypeHandler."""
5032 file.Write("%s GLES2Implementation::%s(%s) {\n" %
5033 (func
.return_type
, func
.original_name
,
5034 func
.MakeTypedOriginalArgString("")))
5035 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
5036 func
.WriteDestinationInitalizationValidation(file)
5037 self
.WriteClientGLCallLog(func
, file)
5038 last_arg_name
= func
.GetLastOriginalArg().name
5039 file.Write(""" GPU_CLIENT_LOG_CODE_BLOCK({
5040 for (GLsizei i = 0; i < count; ++i) {
5042 values_str
= ' << ", " << '.join(
5043 ["%s[%d + i * %d]" % (
5044 last_arg_name
, ndx
, func
.info
.count
) for ndx
in range(
5045 0, func
.info
.count
)])
5046 file.Write(' GPU_CLIENT_LOG(" " << i << ": " << %s);\n' % values_str
)
5047 file.Write(" }\n });\n")
5048 for arg
in func
.GetOriginalArgs():
5049 arg
.WriteClientSideValidationCode(file, func
)
5050 file.Write(" helper_->%sImmediate(%s);\n" %
5051 (func
.name
, func
.MakeOriginalArgString("")))
5052 file.Write(" CheckGLError();\n")
5056 def WriteGLES2ImplementationUnitTest(self
, func
, file):
5057 """Writes the GLES2 Implemention unit test."""
5059 TEST_F(GLES2ImplementationTest, %(name)s) {
5060 %(type)s data[%(count_param)d][%(count)d] = {{0}};
5062 cmds::%(name)sImmediate cmd;
5063 %(type)s data[%(count_param)d][%(count)d];
5067 for (int ii = 0; ii < %(count_param)d; ++ii) {
5068 for (int jj = 0; jj < %(count)d; ++jj) {
5069 data[ii][jj] = static_cast<%(type)s>(ii * %(count)d + jj);
5072 expected.cmd.Init(%(cmd_args)s, &data[0][0]);
5073 gl_->%(name)s(%(args)s, &data[0][0]);
5074 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
5077 cmd_arg_strings
= []
5078 for count
, arg
in enumerate(func
.GetCmdArgs()[0:-2]):
5079 cmd_arg_strings
.append(arg
.GetValidClientSideCmdArg(func
, count
, 0))
5082 for count
, arg
in enumerate(func
.GetOriginalArgs()[0:-1]):
5083 gl_arg_strings
.append(arg
.GetValidClientSideArg(func
, count
, 0))
5084 if arg
.name
== "count":
5085 count_param
= int(arg
.GetValidClientSideArg(func
, count
, 0))
5088 'type': func
.GetInfo('data_type'),
5089 'count': func
.GetInfo('count'),
5090 'args': ", ".join(gl_arg_strings
),
5091 'cmd_args': ", ".join(cmd_arg_strings
),
5092 'count_param': count_param
,
5095 def WriteImmediateCmdComputeSize(self
, func
, file):
5096 """Overrriden from TypeHandler."""
5097 file.Write(" static uint32 ComputeDataSize(GLsizei count) {\n")
5098 file.Write(" return static_cast<uint32>(\n")
5099 file.Write(" sizeof(%s) * %d * count); // NOLINT\n" %
5100 (func
.info
.data_type
, func
.info
.count
))
5103 file.Write(" static uint32 ComputeSize(GLsizei count) {\n")
5104 file.Write(" return static_cast<uint32>(\n")
5106 " sizeof(ValueType) + ComputeDataSize(count)); // NOLINT\n")
5110 def WriteImmediateCmdSetHeader(self
, func
, file):
5111 """Overrriden from TypeHandler."""
5112 file.Write(" void SetHeader(GLsizei count) {\n")
5114 " header.SetCmdByTotalSize<ValueType>(ComputeSize(count));\n")
5118 def WriteImmediateCmdInit(self
, func
, file):
5119 """Overrriden from TypeHandler."""
5120 last_arg
= func
.GetLastOriginalArg()
5121 file.Write(" void Init(%s, %s _%s) {\n" %
5122 (func
.MakeTypedCmdArgString("_"),
5123 last_arg
.type, last_arg
.name
))
5124 file.Write(" SetHeader(_count);\n")
5125 args
= func
.GetCmdArgs()
5127 file.Write(" %s = _%s;\n" % (arg
.name
, arg
.name
))
5128 file.Write(" memcpy(ImmediateDataAddress(this),\n")
5129 file.Write(" _%s, ComputeDataSize(_count));\n" % last_arg
.name
)
5133 def WriteImmediateCmdSet(self
, func
, file):
5134 """Overrriden from TypeHandler."""
5135 last_arg
= func
.GetLastOriginalArg()
5136 copy_args
= func
.MakeCmdArgString("_", False)
5137 file.Write(" void* Set(void* cmd%s, %s _%s) {\n" %
5138 (func
.MakeTypedCmdArgString("_", True),
5139 last_arg
.type, last_arg
.name
))
5140 file.Write(" static_cast<ValueType*>(cmd)->Init(%s, _%s);\n" %
5141 (copy_args
, last_arg
.name
))
5142 file.Write(" const uint32 size = ComputeSize(_count);\n")
5143 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
5148 def WriteImmediateCmdHelper(self
, func
, file):
5149 """Overrriden from TypeHandler."""
5150 code
= """ void %(name)s(%(typed_args)s) {
5151 const uint32 size = gles2::cmds::%(name)s::ComputeSize(count);
5152 gles2::cmds::%(name)s* c =
5153 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
5162 "typed_args": func
.MakeTypedOriginalArgString(""),
5163 "args": func
.MakeOriginalArgString(""),
5166 def WriteImmediateFormatTest(self
, func
, file):
5167 """Overrriden from TypeHandler."""
5168 args
= func
.GetCmdArgs()
5170 for value
, arg
in enumerate(args
):
5171 if arg
.name
== "count":
5172 count_param
= int(arg
.GetValidClientSideArg(func
, value
, 0))
5173 file.Write("TEST_F(GLES2FormatTest, %s) {\n" % func
.name
)
5174 file.Write(" const int kSomeBaseValueToTestWith = 51;\n")
5175 file.Write(" static %s data[] = {\n" % func
.info
.data_type
)
5176 for v
in range(0, func
.info
.count
* count_param
):
5177 file.Write(" static_cast<%s>(kSomeBaseValueToTestWith + %d),\n" %
5178 (func
.info
.data_type
, v
))
5180 file.Write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
5181 (func
.name
, func
.name
))
5182 file.Write(" const GLsizei kNumElements = %d;\n" % count_param
)
5183 file.Write(" const size_t kExpectedCmdSize =\n")
5184 file.Write(" sizeof(cmd) + kNumElements * sizeof(%s) * %d;\n" %
5185 (func
.info
.data_type
, func
.info
.count
))
5186 file.Write(" void* next_cmd = cmd.Set(\n")
5188 for value
, arg
in enumerate(args
):
5189 file.Write(",\n static_cast<%s>(%d)" % (arg
.type, value
+ 1))
5190 file.Write(",\n data);\n")
5191 file.Write(" EXPECT_EQ(static_cast<uint32>(cmds::%s::kCmdId),\n" %
5193 file.Write(" cmd.header.command);\n")
5194 file.Write(" EXPECT_EQ(kExpectedCmdSize, cmd.header.size * 4u);\n")
5195 for value
, arg
in enumerate(args
):
5196 file.Write(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);\n" %
5197 (arg
.type, value
+ 1, arg
.name
))
5198 file.Write(" CheckBytesWrittenMatchesExpectedSize(\n")
5199 file.Write(" next_cmd, sizeof(cmd) +\n")
5200 file.Write(" RoundSizeToMultipleOfEntries(sizeof(data)));\n")
5201 file.Write(" // TODO(gman): Check that data was inserted;\n")
5206 class PUTXnHandler(TypeHandler
):
5207 """Handler for glUniform?f functions."""
5209 TypeHandler
.__init
__(self
)
5211 def WriteHandlerImplementation(self
, func
, file):
5212 """Overrriden from TypeHandler."""
5213 code
= """ %(type)s temp[%(count)s] = { %(values)s};
5214 Do%(name)sv(%(location)s, 1, &temp[0]);
5217 args
= func
.GetOriginalArgs()
5218 count
= int(func
.GetInfo('count'))
5219 num_args
= len(args
)
5220 for ii
in range(count
):
5221 values
+= "%s, " % args
[len(args
) - count
+ ii
].name
5225 'count': func
.GetInfo('count'),
5226 'type': func
.GetInfo('data_type'),
5227 'location': args
[0].name
,
5228 'args': func
.MakeOriginalArgString(""),
5232 def WriteServiceUnitTest(self
, func
, file):
5233 """Overrriden from TypeHandler."""
5235 TEST_F(%(test_name)s, %(name)sValidArgs) {
5236 EXPECT_CALL(*gl_, %(name)sv(%(local_args)s));
5237 SpecializedSetup<cmds::%(name)s, 0>(true);
5240 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5241 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5244 args
= func
.GetOriginalArgs()
5245 local_args
= "%s, 1, _" % args
[0].GetValidGLArg(func
, 0, 0)
5246 self
.WriteValidUnitTest(func
, file, valid_test
, {
5248 'count': func
.GetInfo('count'),
5249 'local_args': local_args
,
5253 TEST_F(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
5254 EXPECT_CALL(*gl_, %(name)sv(_, _, _).Times(0);
5255 SpecializedSetup<cmds::%(name)s, 0>(false);
5258 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
5261 self
.WriteInvalidUnitTest(func
, file, invalid_test
, {
5262 'name': func
.GetInfo('name'),
5263 'count': func
.GetInfo('count'),
5267 class GLcharHandler(CustomHandler
):
5268 """Handler for functions that pass a single string ."""
5271 CustomHandler
.__init
__(self
)
5273 def WriteImmediateCmdComputeSize(self
, func
, file):
5274 """Overrriden from TypeHandler."""
5275 file.Write(" static uint32 ComputeSize(uint32 data_size) {\n")
5276 file.Write(" return static_cast<uint32>(\n")
5277 file.Write(" sizeof(ValueType) + data_size); // NOLINT\n")
5280 def WriteImmediateCmdSetHeader(self
, func
, file):
5281 """Overrriden from TypeHandler."""
5283 void SetHeader(uint32 data_size) {
5284 header.SetCmdBySize<ValueType>(data_size);
5289 def WriteImmediateCmdInit(self
, func
, file):
5290 """Overrriden from TypeHandler."""
5291 last_arg
= func
.GetLastOriginalArg()
5292 args
= func
.GetCmdArgs()
5295 set_code
.append(" %s = _%s;" % (arg
.name
, arg
.name
))
5297 void Init(%(typed_args)s, uint32 _data_size) {
5298 SetHeader(_data_size);
5300 memcpy(ImmediateDataAddress(this), _%(last_arg)s, _data_size);
5305 "typed_args": func
.MakeTypedOriginalArgString("_"),
5306 "set_code": "\n".join(set_code
),
5307 "last_arg": last_arg
.name
5310 def WriteImmediateCmdSet(self
, func
, file):
5311 """Overrriden from TypeHandler."""
5312 last_arg
= func
.GetLastOriginalArg()
5313 file.Write(" void* Set(void* cmd%s, uint32 _data_size) {\n" %
5314 func
.MakeTypedOriginalArgString("_", True))
5315 file.Write(" static_cast<ValueType*>(cmd)->Init(%s, _data_size);\n" %
5316 func
.MakeOriginalArgString("_"))
5317 file.Write(" return NextImmediateCmdAddress<ValueType>("
5318 "cmd, _data_size);\n")
5322 def WriteImmediateCmdHelper(self
, func
, file):
5323 """Overrriden from TypeHandler."""
5324 code
= """ void %(name)s(%(typed_args)s) {
5325 const uint32 data_size = strlen(name);
5326 gles2::cmds::%(name)s* c =
5327 GetImmediateCmdSpace<gles2::cmds::%(name)s>(data_size);
5329 c->Init(%(args)s, data_size);
5336 "typed_args": func
.MakeTypedOriginalArgString(""),
5337 "args": func
.MakeOriginalArgString(""),
5341 def WriteImmediateFormatTest(self
, func
, file):
5342 """Overrriden from TypeHandler."""
5345 all_but_last_arg
= func
.GetCmdArgs()[:-1]
5346 for value
, arg
in enumerate(all_but_last_arg
):
5347 init_code
.append(" static_cast<%s>(%d)," % (arg
.type, value
+ 11))
5348 for value
, arg
in enumerate(all_but_last_arg
):
5349 check_code
.append(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);" %
5350 (arg
.type, value
+ 11, arg
.name
))
5352 TEST_F(GLES2FormatTest, %(func_name)s) {
5353 cmds::%(func_name)s& cmd = *GetBufferAs<cmds::%(func_name)s>();
5354 static const char* const test_str = \"test string\";
5355 void* next_cmd = cmd.Set(
5360 EXPECT_EQ(static_cast<uint32>(cmds::%(func_name)s::kCmdId),
5361 cmd.header.command);
5362 EXPECT_EQ(sizeof(cmd) +
5363 RoundSizeToMultipleOfEntries(strlen(test_str)),
5364 cmd.header.size * 4u);
5365 EXPECT_EQ(static_cast<char*>(next_cmd),
5366 reinterpret_cast<char*>(&cmd) + sizeof(cmd) +
5367 RoundSizeToMultipleOfEntries(strlen(test_str)));
5369 EXPECT_EQ(static_cast<uint32>(strlen(test_str)), cmd.data_size);
5370 EXPECT_EQ(0, memcmp(test_str, ImmediateDataAddress(&cmd), strlen(test_str)));
5373 sizeof(cmd) + RoundSizeToMultipleOfEntries(strlen(test_str)),
5374 sizeof(cmd) + strlen(test_str));
5379 'func_name': func
.name
,
5380 'init_code': "\n".join(init_code
),
5381 'check_code': "\n".join(check_code
),
5385 class GLcharNHandler(CustomHandler
):
5386 """Handler for functions that pass a single string with an optional len."""
5389 CustomHandler
.__init
__(self
)
5391 def InitFunction(self
, func
):
5392 """Overrriden from TypeHandler."""
5394 func
.AddCmdArg(Argument('bucket_id', 'GLuint'))
5396 def AddImmediateFunction(self
, generator
, func
):
5397 """Overrriden from TypeHandler."""
5400 def AddBucketFunction(self
, generator
, func
):
5401 """Overrriden from TypeHandler."""
5404 def WriteServiceImplementation(self
, func
, file):
5405 """Overrriden from TypeHandler."""
5406 file.Write("""error::Error GLES2DecoderImpl::Handle%(name)s(
5407 uint32 immediate_data_size, const gles2::cmds::%(name)s& c) {
5408 GLuint bucket_id = static_cast<GLuint>(c.%(bucket_id)s);
5409 Bucket* bucket = GetBucket(bucket_id);
5410 if (!bucket || bucket->size() == 0) {
5411 return error::kInvalidArguments;
5414 if (!bucket->GetAsString(&str)) {
5415 return error::kInvalidArguments;
5417 %(gl_func_name)s(0, str.c_str());
5418 return error::kNoError;
5423 'gl_func_name': func
.GetGLFunctionName(),
5424 'bucket_id': func
.cmd_args
[0].name
,
5428 class IsHandler(TypeHandler
):
5429 """Handler for glIs____ type and glGetError functions."""
5432 TypeHandler
.__init
__(self
)
5434 def InitFunction(self
, func
):
5435 """Overrriden from TypeHandler."""
5436 func
.AddCmdArg(Argument("result_shm_id", 'uint32'))
5437 func
.AddCmdArg(Argument("result_shm_offset", 'uint32'))
5438 if func
.GetInfo('result') == None:
5439 func
.AddInfo('result', ['uint32'])
5441 def WriteServiceUnitTest(self
, func
, file):
5442 """Overrriden from TypeHandler."""
5444 TEST_F(%(test_name)s, %(name)sValidArgs) {
5445 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
5446 SpecializedSetup<cmds::%(name)s, 0>(true);
5448 cmd.Init(%(args)s%(comma)sshared_memory_id_, shared_memory_offset_);
5449 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5450 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5454 if len(func
.GetOriginalArgs()):
5456 self
.WriteValidUnitTest(func
, file, valid_test
, {
5461 TEST_F(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
5462 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
5463 SpecializedSetup<cmds::%(name)s, 0>(false);
5465 cmd.Init(%(args)s%(comma)sshared_memory_id_, shared_memory_offset_);
5466 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
5469 self
.WriteInvalidUnitTest(func
, file, invalid_test
, {
5474 TEST_F(%(test_name)s, %(name)sInvalidArgsBadSharedMemoryId) {
5475 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
5476 SpecializedSetup<cmds::%(name)s, 0>(false);
5478 cmd.Init(%(args)s%(comma)skInvalidSharedMemoryId, shared_memory_offset_);
5479 EXPECT_EQ(error::kOutOfBounds, ExecuteCmd(cmd));
5480 cmd.Init(%(args)s%(comma)sshared_memory_id_, kInvalidSharedMemoryOffset);
5481 EXPECT_EQ(error::kOutOfBounds, ExecuteCmd(cmd));
5484 self
.WriteValidUnitTest(func
, file, invalid_test
, {
5488 def WriteServiceImplementation(self
, func
, file):
5489 """Overrriden from TypeHandler."""
5491 "error::Error GLES2DecoderImpl::Handle%s(\n" % func
.name
)
5493 " uint32 immediate_data_size, const gles2::cmds::%s& c) {\n" %
5495 args
= func
.GetOriginalArgs()
5497 arg
.WriteGetCode(file)
5499 code
= """ typedef cmds::%(func_name)s::Result Result;
5500 Result* result_dst = GetSharedMemoryAs<Result*>(
5501 c.result_shm_id, c.result_shm_offset, sizeof(*result_dst));
5503 return error::kOutOfBounds;
5506 file.Write(code
% {'func_name': func
.name
})
5507 func
.WriteHandlerValidation(file)
5508 file.Write(" *result_dst = %s(%s);\n" %
5509 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
5510 file.Write(" return error::kNoError;\n")
5514 def WriteGLES2Implementation(self
, func
, file):
5515 """Overrriden from TypeHandler."""
5516 impl_func
= func
.GetInfo('impl_func')
5517 if impl_func
== None or impl_func
== True:
5518 error_value
= func
.GetInfo("error_value") or "GL_FALSE"
5519 file.Write("%s GLES2Implementation::%s(%s) {\n" %
5520 (func
.return_type
, func
.original_name
,
5521 func
.MakeTypedOriginalArgString("")))
5522 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
5523 self
.WriteTraceEvent(func
, file)
5524 func
.WriteDestinationInitalizationValidation(file)
5525 self
.WriteClientGLCallLog(func
, file)
5526 file.Write(" typedef cmds::%s::Result Result;\n" % func
.name
)
5527 file.Write(" Result* result = GetResultAs<Result*>();\n")
5528 file.Write(" if (!result) {\n")
5529 file.Write(" return %s;\n" % error_value
)
5531 file.Write(" *result = 0;\n")
5532 arg_string
= func
.MakeOriginalArgString("")
5534 if len(arg_string
) > 0:
5537 " helper_->%s(%s%sGetResultShmId(), GetResultShmOffset());\n" %
5538 (func
.name
, arg_string
, comma
))
5539 file.Write(" WaitForCmd();\n")
5540 file.Write(" %s result_value = *result;\n" % func
.return_type
)
5541 file.Write(' GPU_CLIENT_LOG("returned " << result_value);\n')
5542 file.Write(" CheckGLError();\n")
5543 file.Write(" return result_value;\n")
5547 def WriteGLES2ImplementationUnitTest(self
, func
, file):
5548 """Overrriden from TypeHandler."""
5549 client_test
= func
.GetInfo('client_test')
5550 if client_test
== None or client_test
== True:
5552 TEST_F(GLES2ImplementationTest, %(name)s) {
5557 typedef cmds::%(name)s::Result Result;
5559 ExpectedMemoryInfo result1 =
5560 GetExpectedResultMemory(sizeof(cmds::%(name)s::Result));
5561 expected.cmd.Init(1, result1.id, result1.offset);
5563 EXPECT_CALL(*command_buffer(), OnFlush())
5564 .WillOnce(SetMemory(result1.ptr, uint32(1)))
5565 .RetiresOnSaturation();
5567 GLboolean result = gl_->%(name)s(1);
5568 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
5569 EXPECT_TRUE(result);
5577 class STRnHandler(TypeHandler
):
5578 """Handler for GetProgramInfoLog, GetShaderInfoLog, GetShaderSource, and
5579 GetTranslatedShaderSourceANGLE."""
5582 TypeHandler
.__init
__(self
)
5584 def InitFunction(self
, func
):
5585 """Overrriden from TypeHandler."""
5586 # remove all but the first cmd args.
5587 cmd_args
= func
.GetCmdArgs()
5589 func
.AddCmdArg(cmd_args
[0])
5590 # add on a bucket id.
5591 func
.AddCmdArg(Argument('bucket_id', 'uint32'))
5593 def WriteGLES2Implementation(self
, func
, file):
5594 """Overrriden from TypeHandler."""
5595 code_1
= """%(return_type)s GLES2Implementation::%(func_name)s(%(args)s) {
5596 GPU_CLIENT_SINGLE_THREAD_CHECK();
5598 code_2
= """ GPU_CLIENT_LOG("[" << GetLogPrefix()
5599 << "] gl%(func_name)s" << "("
5602 << static_cast<void*>(%(arg2)s) << ", "
5603 << static_cast<void*>(%(arg3)s) << ")");
5604 helper_->SetBucketSize(kResultBucketId, 0);
5605 helper_->%(func_name)s(%(id_name)s, kResultBucketId);
5607 GLsizei max_size = 0;
5608 if (GetBucketAsString(kResultBucketId, &str)) {
5611 std::min(static_cast<size_t>(%(bufsize_name)s) - 1, str.size());
5612 memcpy(%(dest_name)s, str.c_str(), max_size);
5613 %(dest_name)s[max_size] = '\\0';
5614 GPU_CLIENT_LOG("------\\n" << %(dest_name)s << "\\n------");
5617 if (%(length_name)s != NULL) {
5618 *%(length_name)s = max_size;
5623 args
= func
.GetOriginalArgs()
5625 'return_type': func
.return_type
,
5626 'func_name': func
.original_name
,
5627 'args': func
.MakeTypedOriginalArgString(""),
5628 'id_name': args
[0].name
,
5629 'bufsize_name': args
[1].name
,
5630 'length_name': args
[2].name
,
5631 'dest_name': args
[3].name
,
5632 'arg0': args
[0].name
,
5633 'arg1': args
[1].name
,
5634 'arg2': args
[2].name
,
5635 'arg3': args
[3].name
,
5637 file.Write(code_1
% str_args
)
5638 func
.WriteDestinationInitalizationValidation(file)
5639 file.Write(code_2
% str_args
)
5641 def WriteServiceUnitTest(self
, func
, file):
5642 """Overrriden from TypeHandler."""
5644 TEST_F(%(test_name)s, %(name)sValidArgs) {
5645 const char* kInfo = "hello";
5646 const uint32 kBucketId = 123;
5647 SpecializedSetup<cmds::%(name)s, 0>(true);
5649 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s))
5650 .WillOnce(DoAll(SetArgumentPointee<2>(strlen(kInfo)),
5651 SetArrayArgument<3>(kInfo, kInfo + strlen(kInfo) + 1)));
5654 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5655 CommonDecoder::Bucket* bucket = decoder_->GetBucket(kBucketId);
5656 ASSERT_TRUE(bucket != NULL);
5657 EXPECT_EQ(strlen(kInfo) + 1, bucket->size());
5658 EXPECT_EQ(0, memcmp(bucket->GetData(0, bucket->size()), kInfo,
5660 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5663 args
= func
.GetOriginalArgs()
5664 id_name
= args
[0].GetValidGLArg(func
, 0, 0)
5665 get_len_func
= func
.GetInfo('get_len_func')
5666 get_len_enum
= func
.GetInfo('get_len_enum')
5669 'get_len_func': get_len_func
,
5670 'get_len_enum': get_len_enum
,
5671 'gl_args': '%s, strlen(kInfo) + 1, _, _' %
5672 args
[0].GetValidGLArg(func
, 0, 0),
5673 'args': '%s, kBucketId' % args
[0].GetValidArg(func
, 0, 0),
5674 'expect_len_code': '',
5676 if get_len_func
and get_len_func
[0:2] == 'gl':
5677 sub
['expect_len_code'] = (
5678 " EXPECT_CALL(*gl_, %s(%s, %s, _))\n"
5679 " .WillOnce(SetArgumentPointee<2>(strlen(kInfo) + 1));") % (
5680 get_len_func
[2:], id_name
, get_len_enum
)
5681 self
.WriteValidUnitTest(func
, file, valid_test
, sub
)
5684 TEST_F(%(test_name)s, %(name)sInvalidArgs) {
5685 const uint32 kBucketId = 123;
5686 EXPECT_CALL(*gl_, %(gl_func_name)s(_, _, _, _))
5689 cmd.Init(kInvalidClientId, kBucketId);
5690 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5691 EXPECT_EQ(GL_INVALID_VALUE, GetGLError());
5694 self
.WriteValidUnitTest(func
, file, invalid_test
)
5696 def WriteServiceImplementation(self
, func
, file):
5697 """Overrriden from TypeHandler."""
5701 class FunctionInfo(object):
5702 """Holds info about a function."""
5704 def __init__(self
, info
, type_handler
):
5706 setattr(self
, key
, info
[key
])
5707 self
.type_handler
= type_handler
5708 if not 'type' in info
:
5712 class Argument(object):
5713 """A class that represents a function argument."""
5718 'GLintptr': 'int32',
5720 'GLsizeiptr': 'int32',
5722 'GLclampf': 'float',
5724 need_validation_
= ['GLsizei*', 'GLboolean*', 'GLenum*', 'GLint*']
5726 def __init__(self
, name
, type):
5728 self
.optional
= type.endswith("Optional*")
5730 type = type[:-9] + "*"
5733 if type in self
.cmd_type_map_
:
5734 self
.cmd_type
= self
.cmd_type_map_
[type]
5736 self
.cmd_type
= 'uint32'
5738 def IsPointer(self
):
5739 """Returns true if argument is a pointer."""
5742 def AddCmdArgs(self
, args
):
5743 """Adds command arguments for this argument to the given list."""
5744 return args
.append(self
)
5746 def AddInitArgs(self
, args
):
5747 """Adds init arguments for this argument to the given list."""
5748 return args
.append(self
)
5750 def GetValidArg(self
, func
, offset
, index
):
5751 """Gets a valid value for this argument."""
5752 valid_arg
= func
.GetValidArg(offset
)
5753 if valid_arg
!= None:
5755 return str(offset
+ 1)
5757 def GetValidClientSideArg(self
, func
, offset
, index
):
5758 """Gets a valid value for this argument."""
5759 return str(offset
+ 1)
5761 def GetValidClientSideCmdArg(self
, func
, offset
, index
):
5762 """Gets a valid value for this argument."""
5763 return str(offset
+ 1)
5765 def GetValidGLArg(self
, func
, offset
, index
):
5766 """Gets a valid GL value for this argument."""
5767 valid_arg
= func
.GetValidArg(offset
)
5768 if valid_arg
!= None:
5770 return str(offset
+ 1)
5772 def GetNumInvalidValues(self
, func
):
5773 """returns the number of invalid values to be tested."""
5776 def GetInvalidArg(self
, offset
, index
):
5777 """returns an invalid value and expected parse result by index."""
5778 return ("---ERROR0---", "---ERROR2---", None)
5780 def GetLogArg(self
):
5781 """Get argument appropriate for LOG macro."""
5782 if self
.type == 'GLboolean':
5783 return 'GLES2Util::GetStringBool(%s)' % self
.name
5784 if self
.type == 'GLenum':
5785 return 'GLES2Util::GetStringEnum(%s)' % self
.name
5788 def WriteGetCode(self
, file):
5789 """Writes the code to get an argument from a command structure."""
5790 file.Write(" %s %s = static_cast<%s>(c.%s);\n" %
5791 (self
.type, self
.name
, self
.type, self
.name
))
5793 def WriteValidationCode(self
, file, func
):
5794 """Writes the validation code for an argument."""
5797 def WriteClientSideValidationCode(self
, file, func
):
5798 """Writes the validation code for an argument."""
5801 def WriteDestinationInitalizationValidation(self
, file, func
):
5802 """Writes the client side destintion initialization validation."""
5805 def WriteDestinationInitalizationValidatationIfNeeded(self
, file, func
):
5806 """Writes the client side destintion initialization validation if needed."""
5807 parts
= self
.type.split(" ")
5810 if parts
[0] in self
.need_validation_
:
5812 " GPU_CLIENT_VALIDATE_DESTINATION_%sINITALIZATION(%s, %s);\n" %
5813 ("OPTIONAL_" if self
.optional
else "", self
.type[:-1], self
.name
))
5816 def WriteGetAddress(self
, file):
5817 """Writes the code to get the address this argument refers to."""
5820 def GetImmediateVersion(self
):
5821 """Gets the immediate version of this argument."""
5824 def GetBucketVersion(self
):
5825 """Gets the bucket version of this argument."""
5829 class BoolArgument(Argument
):
5830 """class for GLboolean"""
5832 def __init__(self
, name
, type):
5833 Argument
.__init
__(self
, name
, 'GLboolean')
5835 def GetValidArg(self
, func
, offset
, index
):
5836 """Gets a valid value for this argument."""
5839 def GetValidClientSideArg(self
, func
, offset
, index
):
5840 """Gets a valid value for this argument."""
5843 def GetValidClientSideCmdArg(self
, func
, offset
, index
):
5844 """Gets a valid value for this argument."""
5847 def GetValidGLArg(self
, func
, offset
, index
):
5848 """Gets a valid GL value for this argument."""
5852 class UniformLocationArgument(Argument
):
5853 """class for uniform locations."""
5855 def __init__(self
, name
):
5856 Argument
.__init
__(self
, name
, "GLint")
5858 def WriteGetCode(self
, file):
5859 """Writes the code to get an argument from a command structure."""
5860 code
= """ %s %s = static_cast<%s>(c.%s);
5862 file.Write(code
% (self
.type, self
.name
, self
.type, self
.name
))
5864 def GetValidArg(self
, func
, offset
, index
):
5865 """Gets a valid value for this argument."""
5866 return "%d" % (offset
+ 1)
5869 class DataSizeArgument(Argument
):
5870 """class for data_size which Bucket commands do not need."""
5872 def __init__(self
, name
):
5873 Argument
.__init
__(self
, name
, "uint32")
5875 def GetBucketVersion(self
):
5879 class SizeArgument(Argument
):
5880 """class for GLsizei and GLsizeiptr."""
5882 def __init__(self
, name
, type):
5883 Argument
.__init
__(self
, name
, type)
5885 def GetNumInvalidValues(self
, func
):
5886 """overridden from Argument."""
5887 if func
.is_immediate
:
5891 def GetInvalidArg(self
, offset
, index
):
5892 """overridden from Argument."""
5893 return ("-1", "kNoError", "GL_INVALID_VALUE")
5895 def WriteValidationCode(self
, file, func
):
5896 """overridden from Argument."""
5897 file.Write(" if (%s < 0) {\n" % self
.name
)
5899 " LOCAL_SET_GL_ERROR(GL_INVALID_VALUE, \"gl%s\", \"%s < 0\");\n" %
5900 (func
.original_name
, self
.name
))
5901 file.Write(" return error::kNoError;\n")
5904 def WriteClientSideValidationCode(self
, file, func
):
5905 """overridden from Argument."""
5906 file.Write(" if (%s < 0) {\n" % self
.name
)
5908 " SetGLError(GL_INVALID_VALUE, \"gl%s\", \"%s < 0\");\n" %
5909 (func
.original_name
, self
.name
))
5910 file.Write(" return;\n")
5914 class SizeNotNegativeArgument(SizeArgument
):
5915 """class for GLsizeiNotNegative. It's NEVER allowed to be negative"""
5917 def __init__(self
, name
, type, gl_type
):
5918 SizeArgument
.__init
__(self
, name
, gl_type
)
5920 def GetInvalidArg(self
, offset
, index
):
5921 """overridden from SizeArgument."""
5922 return ("-1", "kOutOfBounds", "GL_NO_ERROR")
5924 def WriteValidationCode(self
, file, func
):
5925 """overridden from SizeArgument."""
5929 class EnumBaseArgument(Argument
):
5930 """Base class for EnumArgument, IntArgument and ValidatedBoolArgument"""
5932 def __init__(self
, name
, gl_type
, type, gl_error
):
5933 Argument
.__init
__(self
, name
, gl_type
)
5935 self
.local_type
= type
5936 self
.gl_error
= gl_error
5937 name
= type[len(gl_type
):]
5938 self
.type_name
= name
5939 self
.enum_info
= _ENUM_LISTS
[name
]
5941 def WriteValidationCode(self
, file, func
):
5942 file.Write(" if (!validators_->%s.IsValid(%s)) {\n" %
5943 (ToUnderscore(self
.type_name
), self
.name
))
5944 if self
.gl_error
== "GL_INVALID_ENUM":
5946 " LOCAL_SET_GL_ERROR_INVALID_ENUM(\"gl%s\", %s, \"%s\");\n" %
5947 (func
.original_name
, self
.name
, self
.name
))
5950 " LOCAL_SET_GL_ERROR(%s, \"gl%s\", \"%s %s\");\n" %
5951 (self
.gl_error
, func
.original_name
, self
.name
, self
.gl_error
))
5952 file.Write(" return error::kNoError;\n")
5955 def GetValidArg(self
, func
, offset
, index
):
5956 valid_arg
= func
.GetValidArg(offset
)
5957 if valid_arg
!= None:
5959 if 'valid' in self
.enum_info
:
5960 valid
= self
.enum_info
['valid']
5961 num_valid
= len(valid
)
5962 if index
>= num_valid
:
5963 index
= num_valid
- 1
5965 return str(offset
+ 1)
5967 def GetValidClientSideArg(self
, func
, offset
, index
):
5968 """Gets a valid value for this argument."""
5969 return self
.GetValidArg(func
, offset
, index
)
5971 def GetValidClientSideCmdArg(self
, func
, offset
, index
):
5972 """Gets a valid value for this argument."""
5973 return self
.GetValidArg(func
, offset
, index
)
5975 def GetValidGLArg(self
, func
, offset
, index
):
5976 """Gets a valid value for this argument."""
5977 return self
.GetValidArg(func
, offset
, index
)
5979 def GetNumInvalidValues(self
, func
):
5980 """returns the number of invalid values to be tested."""
5981 if 'invalid' in self
.enum_info
:
5982 invalid
= self
.enum_info
['invalid']
5986 def GetInvalidArg(self
, offset
, index
):
5987 """returns an invalid value by index."""
5988 if 'invalid' in self
.enum_info
:
5989 invalid
= self
.enum_info
['invalid']
5990 num_invalid
= len(invalid
)
5991 if index
>= num_invalid
:
5992 index
= num_invalid
- 1
5993 return (invalid
[index
], "kNoError", self
.gl_error
)
5994 return ("---ERROR1---", "kNoError", self
.gl_error
)
5997 class EnumArgument(EnumBaseArgument
):
5998 """A class that represents a GLenum argument"""
6000 def __init__(self
, name
, type):
6001 EnumBaseArgument
.__init
__(self
, name
, "GLenum", type, "GL_INVALID_ENUM")
6003 def GetLogArg(self
):
6004 """Overridden from Argument."""
6005 return ("GLES2Util::GetString%s(%s)" %
6006 (self
.type_name
, self
.name
))
6009 class IntArgument(EnumBaseArgument
):
6010 """A class for a GLint argument that can only except specific values.
6012 For example glTexImage2D takes a GLint for its internalformat
6013 argument instead of a GLenum.
6016 def __init__(self
, name
, type):
6017 EnumBaseArgument
.__init
__(self
, name
, "GLint", type, "GL_INVALID_VALUE")
6020 class ValidatedBoolArgument(EnumBaseArgument
):
6021 """A class for a GLboolean argument that can only except specific values.
6023 For example glUniformMatrix takes a GLboolean for it's transpose but it
6027 def __init__(self
, name
, type):
6028 EnumBaseArgument
.__init
__(self
, name
, "GLboolean", type, "GL_INVALID_VALUE")
6030 def GetLogArg(self
):
6031 """Overridden from Argument."""
6032 return 'GLES2Util::GetStringBool(%s)' % self
.name
6035 class ImmediatePointerArgument(Argument
):
6036 """A class that represents an immediate argument to a function.
6038 An immediate argument is one where the data follows the command.
6041 def __init__(self
, name
, type):
6042 Argument
.__init
__(self
, name
, type)
6044 def AddCmdArgs(self
, args
):
6045 """Overridden from Argument."""
6048 def WriteGetCode(self
, file):
6049 """Overridden from Argument."""
6051 " %s %s = GetImmediateDataAs<%s>(\n" %
6052 (self
.type, self
.name
, self
.type))
6053 file.Write(" c, data_size, immediate_data_size);\n")
6055 def WriteValidationCode(self
, file, func
):
6056 """Overridden from Argument."""
6057 file.Write(" if (%s == NULL) {\n" % self
.name
)
6058 file.Write(" return error::kOutOfBounds;\n")
6061 def GetImmediateVersion(self
):
6062 """Overridden from Argument."""
6065 def WriteDestinationInitalizationValidation(self
, file, func
):
6066 """Overridden from Argument."""
6067 self
.WriteDestinationInitalizationValidatationIfNeeded(file, func
)
6069 def GetLogArg(self
):
6070 """Overridden from Argument."""
6071 return "static_cast<const void*>(%s)" % self
.name
6074 class BucketPointerArgument(Argument
):
6075 """A class that represents an bucket argument to a function."""
6077 def __init__(self
, name
, type):
6078 Argument
.__init
__(self
, name
, type)
6080 def AddCmdArgs(self
, args
):
6081 """Overridden from Argument."""
6084 def WriteGetCode(self
, file):
6085 """Overridden from Argument."""
6087 " %s %s = bucket->GetData(0, data_size);\n" %
6088 (self
.type, self
.name
))
6090 def WriteValidationCode(self
, file, func
):
6091 """Overridden from Argument."""
6094 def GetImmediateVersion(self
):
6095 """Overridden from Argument."""
6098 def WriteDestinationInitalizationValidation(self
, file, func
):
6099 """Overridden from Argument."""
6100 self
.WriteDestinationInitalizationValidatationIfNeeded(file, func
)
6102 def GetLogArg(self
):
6103 """Overridden from Argument."""
6104 return "static_cast<const void*>(%s)" % self
.name
6107 class PointerArgument(Argument
):
6108 """A class that represents a pointer argument to a function."""
6110 def __init__(self
, name
, type):
6111 Argument
.__init
__(self
, name
, type)
6113 def IsPointer(self
):
6114 """Returns true if argument is a pointer."""
6117 def GetValidArg(self
, func
, offset
, index
):
6118 """Overridden from Argument."""
6119 return "shared_memory_id_, shared_memory_offset_"
6121 def GetValidGLArg(self
, func
, offset
, index
):
6122 """Overridden from Argument."""
6123 return "reinterpret_cast<%s>(shared_memory_address_)" % self
.type
6125 def GetNumInvalidValues(self
, func
):
6126 """Overridden from Argument."""
6129 def GetInvalidArg(self
, offset
, index
):
6130 """Overridden from Argument."""
6132 return ("kInvalidSharedMemoryId, 0", "kOutOfBounds", None)
6134 return ("shared_memory_id_, kInvalidSharedMemoryOffset",
6135 "kOutOfBounds", None)
6137 def GetLogArg(self
):
6138 """Overridden from Argument."""
6139 return "static_cast<const void*>(%s)" % self
.name
6141 def AddCmdArgs(self
, args
):
6142 """Overridden from Argument."""
6143 args
.append(Argument("%s_shm_id" % self
.name
, 'uint32'))
6144 args
.append(Argument("%s_shm_offset" % self
.name
, 'uint32'))
6146 def WriteGetCode(self
, file):
6147 """Overridden from Argument."""
6149 " %s %s = GetSharedMemoryAs<%s>(\n" %
6150 (self
.type, self
.name
, self
.type))
6152 " c.%s_shm_id, c.%s_shm_offset, data_size);\n" %
6153 (self
.name
, self
.name
))
6155 def WriteGetAddress(self
, file):
6156 """Overridden from Argument."""
6158 " %s %s = GetSharedMemoryAs<%s>(\n" %
6159 (self
.type, self
.name
, self
.type))
6161 " %s_shm_id, %s_shm_offset, %s_size);\n" %
6162 (self
.name
, self
.name
, self
.name
))
6164 def WriteValidationCode(self
, file, func
):
6165 """Overridden from Argument."""
6166 file.Write(" if (%s == NULL) {\n" % self
.name
)
6167 file.Write(" return error::kOutOfBounds;\n")
6170 def GetImmediateVersion(self
):
6171 """Overridden from Argument."""
6172 return ImmediatePointerArgument(self
.name
, self
.type)
6174 def GetBucketVersion(self
):
6175 """Overridden from Argument."""
6176 if self
.type == "const char*":
6177 return InputStringBucketArgument(self
.name
, self
.type)
6178 return BucketPointerArgument(self
.name
, self
.type)
6180 def WriteDestinationInitalizationValidation(self
, file, func
):
6181 """Overridden from Argument."""
6182 self
.WriteDestinationInitalizationValidatationIfNeeded(file, func
)
6185 class InputStringBucketArgument(Argument
):
6186 """An string input argument where the string is passed in a bucket."""
6188 def __init__(self
, name
, type):
6189 Argument
.__init
__(self
, name
+ "_bucket_id", "uint32")
6191 def WriteGetCode(self
, file):
6192 """Overridden from Argument."""
6194 Bucket* %(name)s_bucket = GetBucket(c.%(name)s);
6195 if (!%(name)s_bucket) {
6196 return error::kInvalidArguments;
6198 std::string %(name)s_str;
6199 if (!%(name)s_bucket->GetAsString(&%(name)s_str)) {
6200 return error::kInvalidArguments;
6202 const char* %(name)s = %(name)s_str.c_str();
6208 def GetValidArg(self
, func
, offset
, index
):
6209 return "kNameBucketId"
6211 def GetValidGLArg(self
, func
, offset
, index
):
6215 class NonImmediatePointerArgument(PointerArgument
):
6216 """A pointer argument that stays a pointer even in an immediate cmd."""
6218 def __init__(self
, name
, type):
6219 PointerArgument
.__init
__(self
, name
, type)
6221 def IsPointer(self
):
6222 """Returns true if argument is a pointer."""
6225 def GetImmediateVersion(self
):
6226 """Overridden from Argument."""
6230 class ResourceIdArgument(Argument
):
6231 """A class that represents a resource id argument to a function."""
6233 def __init__(self
, name
, type):
6234 match
= re
.match("(GLid\w+)", type)
6235 self
.resource_type
= match
.group(1)[4:]
6236 type = type.replace(match
.group(1), "GLuint")
6237 Argument
.__init
__(self
, name
, type)
6239 def WriteGetCode(self
, file):
6240 """Overridden from Argument."""
6241 file.Write(" %s %s = c.%s;\n" % (self
.type, self
.name
, self
.name
))
6243 def GetValidArg(self
, func
, offset
, index
):
6244 return "client_%s_id_" % self
.resource_type
.lower()
6246 def GetValidGLArg(self
, func
, offset
, index
):
6247 return "kService%sId" % self
.resource_type
6250 class ResourceIdBindArgument(Argument
):
6251 """Represents a resource id argument to a bind function."""
6253 def __init__(self
, name
, type):
6254 match
= re
.match("(GLidBind\w+)", type)
6255 self
.resource_type
= match
.group(1)[8:]
6256 type = type.replace(match
.group(1), "GLuint")
6257 Argument
.__init
__(self
, name
, type)
6259 def WriteGetCode(self
, file):
6260 """Overridden from Argument."""
6261 code
= """ %(type)s %(name)s = c.%(name)s;
6263 file.Write(code
% {'type': self
.type, 'name': self
.name
})
6265 def GetValidArg(self
, func
, offset
, index
):
6266 return "client_%s_id_" % self
.resource_type
.lower()
6268 def GetValidGLArg(self
, func
, offset
, index
):
6269 return "kService%sId" % self
.resource_type
6272 class ResourceIdZeroArgument(Argument
):
6273 """Represents a resource id argument to a function that can be zero."""
6275 def __init__(self
, name
, type):
6276 match
= re
.match("(GLidZero\w+)", type)
6277 self
.resource_type
= match
.group(1)[8:]
6278 type = type.replace(match
.group(1), "GLuint")
6279 Argument
.__init
__(self
, name
, type)
6281 def WriteGetCode(self
, file):
6282 """Overridden from Argument."""
6283 file.Write(" %s %s = c.%s;\n" % (self
.type, self
.name
, self
.name
))
6285 def GetValidArg(self
, func
, offset
, index
):
6286 return "client_%s_id_" % self
.resource_type
.lower()
6288 def GetValidGLArg(self
, func
, offset
, index
):
6289 return "kService%sId" % self
.resource_type
6291 def GetNumInvalidValues(self
, func
):
6292 """returns the number of invalid values to be tested."""
6295 def GetInvalidArg(self
, offset
, index
):
6296 """returns an invalid value by index."""
6297 return ("kInvalidClientId", "kNoError", "GL_INVALID_VALUE")
6300 class Function(object):
6301 """A class that represents a function."""
6303 def __init__(self
, original_name
, name
, info
, return_type
, original_args
,
6304 args_for_cmds
, cmd_args
, init_args
, num_pointer_args
):
6306 self
.original_name
= original_name
6308 self
.type_handler
= info
.type_handler
6309 self
.return_type
= return_type
6310 self
.original_args
= original_args
6311 self
.num_pointer_args
= num_pointer_args
6312 self
.can_auto_generate
= num_pointer_args
== 0 and return_type
== "void"
6313 self
.cmd_args
= cmd_args
6314 self
.init_args
= init_args
6316 self
.args_for_cmds
= args_for_cmds
6317 self
.is_immediate
= False
6319 def IsType(self
, type_name
):
6320 """Returns true if function is a certain type."""
6321 return self
.info
.type == type_name
6323 def InitFunction(self
):
6324 """Calls the init function for the type handler."""
6325 self
.type_handler
.InitFunction(self
)
6327 def GetInfo(self
, name
):
6328 """Returns a value from the function info for this function."""
6329 if hasattr(self
.info
, name
):
6330 return getattr(self
.info
, name
)
6333 def GetValidArg(self
, index
):
6334 """Gets a valid arg from the function info if one exists."""
6335 valid_args
= self
.GetInfo('valid_args')
6336 if valid_args
and str(index
) in valid_args
:
6337 return valid_args
[str(index
)]
6340 def AddInfo(self
, name
, value
):
6342 setattr(self
.info
, name
, value
)
6344 def IsCoreGLFunction(self
):
6345 return (not self
.GetInfo('extension') and
6346 not self
.GetInfo('pepper_interface'))
6348 def InPepperInterface(self
, interface
):
6349 ext
= self
.GetInfo('pepper_interface')
6350 if not interface
.GetName():
6351 return self
.IsCoreGLFunction()
6352 return ext
== interface
.GetName()
6354 def InAnyPepperExtension(self
):
6355 return self
.IsCoreGLFunction() or self
.GetInfo('pepper_interface')
6357 def GetGLFunctionName(self
):
6358 """Gets the function to call to execute GL for this command."""
6359 if self
.GetInfo('decoder_func'):
6360 return self
.GetInfo('decoder_func')
6361 return "gl%s" % self
.original_name
6363 def GetGLTestFunctionName(self
):
6364 gl_func_name
= self
.GetInfo('gl_test_func')
6365 if gl_func_name
== None:
6366 gl_func_name
= self
.GetGLFunctionName()
6367 if gl_func_name
.startswith("gl"):
6368 gl_func_name
= gl_func_name
[2:]
6370 gl_func_name
= self
.original_name
6373 def AddCmdArg(self
, arg
):
6374 """Adds a cmd argument to this function."""
6375 self
.cmd_args
.append(arg
)
6377 def GetCmdArgs(self
):
6378 """Gets the command args for this function."""
6379 return self
.cmd_args
6381 def ClearCmdArgs(self
):
6382 """Clears the command args for this function."""
6385 def GetInitArgs(self
):
6386 """Gets the init args for this function."""
6387 return self
.init_args
6389 def GetOriginalArgs(self
):
6390 """Gets the original arguments to this function."""
6391 return self
.original_args
6393 def GetLastOriginalArg(self
):
6394 """Gets the last original argument to this function."""
6395 return self
.original_args
[len(self
.original_args
) - 1]
6397 def __GetArgList(self
, arg_string
, add_comma
):
6398 """Adds a comma if arg_string is not empty and add_comma is true."""
6400 if add_comma
and len(arg_string
):
6402 return "%s%s" % (comma
, arg_string
)
6404 def MakeTypedOriginalArgString(self
, prefix
, add_comma
= False):
6405 """Gets a list of arguments as they arg in GL."""
6406 args
= self
.GetOriginalArgs()
6407 arg_string
= ", ".join(
6408 ["%s %s%s" % (arg
.type, prefix
, arg
.name
) for arg
in args
])
6409 return self
.__GetArgList
(arg_string
, add_comma
)
6411 def MakeOriginalArgString(self
, prefix
, add_comma
= False, separator
= ", "):
6412 """Gets the list of arguments as they are in GL."""
6413 args
= self
.GetOriginalArgs()
6414 arg_string
= separator
.join(
6415 ["%s%s" % (prefix
, arg
.name
) for arg
in args
])
6416 return self
.__GetArgList
(arg_string
, add_comma
)
6418 def MakeTypedCmdArgString(self
, prefix
, add_comma
= False):
6419 """Gets a typed list of arguments as they need to be for command buffers."""
6420 args
= self
.GetCmdArgs()
6421 arg_string
= ", ".join(
6422 ["%s %s%s" % (arg
.type, prefix
, arg
.name
) for arg
in args
])
6423 return self
.__GetArgList
(arg_string
, add_comma
)
6425 def MakeCmdArgString(self
, prefix
, add_comma
= False):
6426 """Gets the list of arguments as they need to be for command buffers."""
6427 args
= self
.GetCmdArgs()
6428 arg_string
= ", ".join(
6429 ["%s%s" % (prefix
, arg
.name
) for arg
in args
])
6430 return self
.__GetArgList
(arg_string
, add_comma
)
6432 def MakeTypedInitString(self
, prefix
, add_comma
= False):
6433 """Gets a typed list of arguments as they need to be for cmd Init/Set."""
6434 args
= self
.GetInitArgs()
6435 arg_string
= ", ".join(
6436 ["%s %s%s" % (arg
.type, prefix
, arg
.name
) for arg
in args
])
6437 return self
.__GetArgList
(arg_string
, add_comma
)
6439 def MakeInitString(self
, prefix
, add_comma
= False):
6440 """Gets the list of arguments as they need to be for cmd Init/Set."""
6441 args
= self
.GetInitArgs()
6442 arg_string
= ", ".join(
6443 ["%s%s" % (prefix
, arg
.name
) for arg
in args
])
6444 return self
.__GetArgList
(arg_string
, add_comma
)
6446 def MakeLogArgString(self
):
6447 """Makes a string of the arguments for the LOG macros"""
6448 args
= self
.GetOriginalArgs()
6449 return ' << ", " << '.join([arg
.GetLogArg() for arg
in args
])
6451 def WriteCommandDescription(self
, file):
6452 """Writes a description of the command."""
6453 file.Write("//! Command that corresponds to gl%s.\n" % self
.original_name
)
6455 def WriteHandlerValidation(self
, file):
6456 """Writes validation code for the function."""
6457 for arg
in self
.GetOriginalArgs():
6458 arg
.WriteValidationCode(file, self
)
6459 self
.WriteValidationCode(file)
6461 def WriteHandlerImplementation(self
, file):
6462 """Writes the handler implementation for this command."""
6463 self
.type_handler
.WriteHandlerImplementation(self
, file)
6465 def WriteValidationCode(self
, file):
6466 """Writes the validation code for a command."""
6469 def WriteCmdArgFlag(self
, file):
6470 """Writes the cmd kArgFlags constant."""
6471 file.Write(" static const cmd::ArgFlags kArgFlags = cmd::kFixed;\n")
6473 def WriteCmdComputeSize(self
, file):
6474 """Writes the ComputeSize function for the command."""
6475 file.Write(" static uint32 ComputeSize() {\n")
6477 " return static_cast<uint32>(sizeof(ValueType)); // NOLINT\n")
6481 def WriteCmdSetHeader(self
, file):
6482 """Writes the cmd's SetHeader function."""
6483 file.Write(" void SetHeader() {\n")
6484 file.Write(" header.SetCmd<ValueType>();\n")
6488 def WriteCmdInit(self
, file):
6489 """Writes the cmd's Init function."""
6490 file.Write(" void Init(%s) {\n" % self
.MakeTypedCmdArgString("_"))
6491 file.Write(" SetHeader();\n")
6492 args
= self
.GetCmdArgs()
6494 file.Write(" %s = _%s;\n" % (arg
.name
, arg
.name
))
6498 def WriteCmdSet(self
, file):
6499 """Writes the cmd's Set function."""
6500 copy_args
= self
.MakeCmdArgString("_", False)
6501 file.Write(" void* Set(void* cmd%s) {\n" %
6502 self
.MakeTypedCmdArgString("_", True))
6503 file.Write(" static_cast<ValueType*>(cmd)->Init(%s);\n" % copy_args
)
6504 file.Write(" return NextCmdAddress<ValueType>(cmd);\n")
6508 def WriteStruct(self
, file):
6509 self
.type_handler
.WriteStruct(self
, file)
6511 def WriteDocs(self
, file):
6512 self
.type_handler
.WriteDocs(self
, file)
6514 def WriteCmdHelper(self
, file):
6515 """Writes the cmd's helper."""
6516 self
.type_handler
.WriteCmdHelper(self
, file)
6518 def WriteServiceImplementation(self
, file):
6519 """Writes the service implementation for a command."""
6520 self
.type_handler
.WriteServiceImplementation(self
, file)
6522 def WriteServiceUnitTest(self
, file):
6523 """Writes the service implementation for a command."""
6524 self
.type_handler
.WriteServiceUnitTest(self
, file)
6526 def WriteGLES2CLibImplementation(self
, file):
6527 """Writes the GLES2 C Lib Implemention."""
6528 self
.type_handler
.WriteGLES2CLibImplementation(self
, file)
6530 def WriteGLES2InterfaceHeader(self
, file):
6531 """Writes the GLES2 Interface declaration."""
6532 self
.type_handler
.WriteGLES2InterfaceHeader(self
, file)
6534 def WriteGLES2InterfaceStub(self
, file):
6535 """Writes the GLES2 Interface Stub declaration."""
6536 self
.type_handler
.WriteGLES2InterfaceStub(self
, file)
6538 def WriteGLES2InterfaceStubImpl(self
, file):
6539 """Writes the GLES2 Interface Stub declaration."""
6540 self
.type_handler
.WriteGLES2InterfaceStubImpl(self
, file)
6542 def WriteGLES2ImplementationHeader(self
, file):
6543 """Writes the GLES2 Implemention declaration."""
6544 self
.type_handler
.WriteGLES2ImplementationHeader(self
, file)
6546 def WriteGLES2Implementation(self
, file):
6547 """Writes the GLES2 Implemention definition."""
6548 self
.type_handler
.WriteGLES2Implementation(self
, file)
6550 def WriteGLES2TraceImplementationHeader(self
, file):
6551 """Writes the GLES2 Trace Implemention declaration."""
6552 self
.type_handler
.WriteGLES2TraceImplementationHeader(self
, file)
6554 def WriteGLES2TraceImplementation(self
, file):
6555 """Writes the GLES2 Trace Implemention definition."""
6556 self
.type_handler
.WriteGLES2TraceImplementation(self
, file)
6558 def WriteGLES2Header(self
, file):
6559 """Writes the GLES2 Implemention unit test."""
6560 self
.type_handler
.WriteGLES2Header(self
, file)
6562 def WriteGLES2ImplementationUnitTest(self
, file):
6563 """Writes the GLES2 Implemention unit test."""
6564 self
.type_handler
.WriteGLES2ImplementationUnitTest(self
, file)
6566 def WriteDestinationInitalizationValidation(self
, file):
6567 """Writes the client side destintion initialization validation."""
6568 self
.type_handler
.WriteDestinationInitalizationValidation(self
, file)
6570 def WriteFormatTest(self
, file):
6571 """Writes the cmd's format test."""
6572 self
.type_handler
.WriteFormatTest(self
, file)
6575 class PepperInterface(object):
6576 """A class that represents a function."""
6578 def __init__(self
, info
):
6579 self
.name
= info
["name"]
6580 self
.dev
= info
["dev"]
6585 def GetInterfaceName(self
):
6589 upperint
= "_" + self
.name
.upper()
6592 return "PPB_OPENGLES2%s%s_INTERFACE" % (upperint
, dev
)
6594 def GetInterfaceString(self
):
6598 return "PPB_OpenGLES2%s%s" % (self
.name
, dev
)
6600 def GetStructName(self
):
6604 return "PPB_OpenGLES2%s%s" % (self
.name
, dev
)
6607 class ImmediateFunction(Function
):
6608 """A class that represnets an immediate function command."""
6610 def __init__(self
, func
):
6612 for arg
in func
.GetOriginalArgs():
6613 new_arg
= arg
.GetImmediateVersion()
6615 new_args
.append(new_arg
)
6618 new_args_for_cmds
= []
6619 for arg
in func
.args_for_cmds
:
6620 new_arg
= arg
.GetImmediateVersion()
6622 new_args_for_cmds
.append(new_arg
)
6623 new_arg
.AddCmdArgs(cmd_args
)
6626 for arg
in new_args_for_cmds
:
6627 arg
.AddInitArgs(new_init_args
)
6632 "%sImmediate" % func
.name
,
6640 self
.is_immediate
= True
6642 def WriteCommandDescription(self
, file):
6643 """Overridden from Function"""
6644 file.Write("//! Immediate version of command that corresponds to gl%s.\n" %
6647 def WriteServiceImplementation(self
, file):
6648 """Overridden from Function"""
6649 self
.type_handler
.WriteImmediateServiceImplementation(self
, file)
6651 def WriteHandlerImplementation(self
, file):
6652 """Overridden from Function"""
6653 self
.type_handler
.WriteImmediateHandlerImplementation(self
, file)
6655 def WriteServiceUnitTest(self
, file):
6656 """Writes the service implementation for a command."""
6657 self
.type_handler
.WriteImmediateServiceUnitTest(self
, file)
6659 def WriteValidationCode(self
, file):
6660 """Overridden from Function"""
6661 self
.type_handler
.WriteImmediateValidationCode(self
, file)
6663 def WriteCmdArgFlag(self
, file):
6664 """Overridden from Function"""
6665 file.Write(" static const cmd::ArgFlags kArgFlags = cmd::kAtLeastN;\n")
6667 def WriteCmdComputeSize(self
, file):
6668 """Overridden from Function"""
6669 self
.type_handler
.WriteImmediateCmdComputeSize(self
, file)
6671 def WriteCmdSetHeader(self
, file):
6672 """Overridden from Function"""
6673 self
.type_handler
.WriteImmediateCmdSetHeader(self
, file)
6675 def WriteCmdInit(self
, file):
6676 """Overridden from Function"""
6677 self
.type_handler
.WriteImmediateCmdInit(self
, file)
6679 def WriteCmdSet(self
, file):
6680 """Overridden from Function"""
6681 self
.type_handler
.WriteImmediateCmdSet(self
, file)
6683 def WriteCmdHelper(self
, file):
6684 """Overridden from Function"""
6685 self
.type_handler
.WriteImmediateCmdHelper(self
, file)
6687 def WriteFormatTest(self
, file):
6688 """Overridden from Function"""
6689 self
.type_handler
.WriteImmediateFormatTest(self
, file)
6692 class BucketFunction(Function
):
6693 """A class that represnets a bucket version of a function command."""
6695 def __init__(self
, func
):
6697 for arg
in func
.GetOriginalArgs():
6698 new_arg
= arg
.GetBucketVersion()
6700 new_args
.append(new_arg
)
6703 new_args_for_cmds
= []
6704 for arg
in func
.args_for_cmds
:
6705 new_arg
= arg
.GetBucketVersion()
6707 new_args_for_cmds
.append(new_arg
)
6708 new_arg
.AddCmdArgs(cmd_args
)
6711 for arg
in new_args_for_cmds
:
6712 arg
.AddInitArgs(new_init_args
)
6717 "%sBucket" % func
.name
,
6726 # def InitFunction(self):
6727 # """Overridden from Function"""
6730 def WriteCommandDescription(self
, file):
6731 """Overridden from Function"""
6732 file.Write("//! Bucket version of command that corresponds to gl%s.\n" %
6735 def WriteServiceImplementation(self
, file):
6736 """Overridden from Function"""
6737 self
.type_handler
.WriteBucketServiceImplementation(self
, file)
6739 def WriteHandlerImplementation(self
, file):
6740 """Overridden from Function"""
6741 self
.type_handler
.WriteBucketHandlerImplementation(self
, file)
6743 def WriteServiceUnitTest(self
, file):
6744 """Writes the service implementation for a command."""
6745 self
.type_handler
.WriteBucketServiceUnitTest(self
, file)
6748 def CreateArg(arg_string
):
6749 """Creates an Argument."""
6750 arg_parts
= arg_string
.split()
6751 if len(arg_parts
) == 1 and arg_parts
[0] == 'void':
6753 # Is this a pointer argument?
6754 elif arg_string
.find('*') >= 0:
6755 if arg_parts
[0] == 'NonImmediate':
6756 return NonImmediatePointerArgument(
6758 " ".join(arg_parts
[1:-1]))
6760 return PointerArgument(
6762 " ".join(arg_parts
[0:-1]))
6763 # Is this a resource argument? Must come after pointer check.
6764 elif arg_parts
[0].startswith('GLidBind'):
6765 return ResourceIdBindArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
6766 elif arg_parts
[0].startswith('GLidZero'):
6767 return ResourceIdZeroArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
6768 elif arg_parts
[0].startswith('GLid'):
6769 return ResourceIdArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
6770 elif arg_parts
[0].startswith('GLenum') and len(arg_parts
[0]) > 6:
6771 return EnumArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
6772 elif arg_parts
[0].startswith('GLboolean') and len(arg_parts
[0]) > 9:
6773 return ValidatedBoolArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
6774 elif arg_parts
[0].startswith('GLboolean'):
6775 return BoolArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
6776 elif arg_parts
[0].startswith('GLintUniformLocation'):
6777 return UniformLocationArgument(arg_parts
[-1])
6778 elif (arg_parts
[0].startswith('GLint') and len(arg_parts
[0]) > 5 and
6779 not arg_parts
[0].startswith('GLintptr')):
6780 return IntArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
6781 elif (arg_parts
[0].startswith('GLsizeiNotNegative') or
6782 arg_parts
[0].startswith('GLintptrNotNegative')):
6783 return SizeNotNegativeArgument(arg_parts
[-1],
6784 " ".join(arg_parts
[0:-1]),
6785 arg_parts
[0][0:-11])
6786 elif arg_parts
[0].startswith('GLsize'):
6787 return SizeArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
6789 return Argument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
6792 class GLGenerator(object):
6793 """A class to generate GL command buffers."""
6795 _function_re
= re
.compile(r
'GL_APICALL(.*?)GL_APIENTRY (.*?) \((.*?)\);')
6797 def __init__(self
, verbose
):
6798 self
.original_functions
= []
6800 self
.verbose
= verbose
6802 self
._function
_info
= {}
6803 self
._empty
_type
_handler
= TypeHandler()
6804 self
._empty
_function
_info
= FunctionInfo({}, self
._empty
_type
_handler
)
6805 self
.pepper_interfaces
= []
6806 self
.interface_info
= {}
6808 self
._type
_handlers
= {
6809 'Bind': BindHandler(),
6810 'Create': CreateHandler(),
6811 'Custom': CustomHandler(),
6812 'Data': DataHandler(),
6813 'Delete': DeleteHandler(),
6814 'DELn': DELnHandler(),
6815 'GENn': GENnHandler(),
6816 'GETn': GETnHandler(),
6817 'GLchar': GLcharHandler(),
6818 'GLcharN': GLcharNHandler(),
6819 'HandWritten': HandWrittenHandler(),
6821 'Manual': ManualHandler(),
6822 'PUT': PUTHandler(),
6823 'PUTn': PUTnHandler(),
6824 'PUTXn': PUTXnHandler(),
6825 'StateSet': StateSetHandler(),
6826 'StateSetRGBAlpha': StateSetRGBAlphaHandler(),
6827 'StateSetFrontBack': StateSetFrontBackHandler(),
6828 'StateSetFrontBackSeparate': StateSetFrontBackSeparateHandler(),
6829 'StateSetNamedParameter': StateSetNamedParameter(),
6830 'STRn': STRnHandler(),
6831 'Todo': TodoHandler(),
6834 for func_name
in _FUNCTION_INFO
:
6835 info
= _FUNCTION_INFO
[func_name
]
6839 self
._function
_info
[func_name
] = FunctionInfo(info
,
6840 self
.GetTypeHandler(type))
6841 for interface
in _PEPPER_INTERFACES
:
6842 interface
= PepperInterface(interface
)
6843 self
.pepper_interfaces
.append(interface
)
6844 self
.interface_info
[interface
.GetName()] = interface
6846 def AddFunction(self
, func
):
6847 """Adds a function."""
6848 self
.functions
.append(func
)
6850 def GetTypeHandler(self
, name
):
6851 """Gets a type info for the given type."""
6853 if name
in self
._type
_handlers
:
6854 return self
._type
_handlers
[name
]
6856 raise KeyError("no such type handler: %s" % name
)
6857 return self
._empty
_type
_handler
6859 def GetFunctionInfo(self
, name
):
6860 """Gets a type info for the given function name."""
6861 if name
in self
._function
_info
:
6862 return self
._function
_info
[name
]
6863 return self
._empty
_function
_info
6866 """Prints something if verbose is true."""
6870 def Error(self
, msg
):
6871 """Prints an error."""
6872 print "Error: %s" % msg
6875 def WriteLicense(self
, file):
6876 """Writes the license."""
6877 file.Write(_LICENSE
)
6879 def WriteNamespaceOpen(self
, file):
6880 """Writes the code for the namespace."""
6881 file.Write("namespace gpu {\n")
6882 file.Write("namespace gles2 {\n")
6885 def WriteNamespaceClose(self
, file):
6886 """Writes the code to close the namespace."""
6887 file.Write("} // namespace gles2\n")
6888 file.Write("} // namespace gpu\n")
6891 def ParseArgs(self
, arg_string
):
6892 """Parses a function arg string."""
6894 num_pointer_args
= 0
6895 parts
= arg_string
.split(',')
6897 for arg_string
in parts
:
6898 if arg_string
.startswith('GLenum '):
6900 arg
= CreateArg(arg_string
)
6904 num_pointer_args
+= 1
6905 return (args
, num_pointer_args
, is_gl_enum
)
6907 def ParseGLH(self
, filename
):
6908 """Parses the cmd_buffer_functions.txt file and extracts the functions"""
6909 f
= open("gpu/command_buffer/cmd_buffer_functions.txt", "r")
6910 functions
= f
.read()
6912 for line
in functions
.splitlines():
6913 match
= self
._function
_re
.match(line
)
6915 func_name
= match
.group(2)[2:]
6916 func_info
= self
.GetFunctionInfo(func_name
)
6917 if func_info
.type != 'Noop':
6918 return_type
= match
.group(1).strip()
6919 arg_string
= match
.group(3)
6920 (args
, num_pointer_args
, is_gl_enum
) = self
.ParseArgs(arg_string
)
6921 # comment in to find out which functions use bare enums.
6923 # self.Log("%s uses bare GLenum" % func_name)
6924 args_for_cmds
= args
6925 if hasattr(func_info
, 'cmd_args'):
6926 (args_for_cmds
, num_pointer_args
, is_gl_enum
) = (
6927 self
.ParseArgs(getattr(func_info
, 'cmd_args')))
6929 for arg
in args_for_cmds
:
6930 arg
.AddCmdArgs(cmd_args
)
6932 for arg
in args_for_cmds
:
6933 arg
.AddInitArgs(init_args
)
6934 return_arg
= CreateArg(return_type
+ " result")
6936 init_args
.append(return_arg
)
6937 f
= Function(func_name
, func_name
, func_info
, return_type
, args
,
6938 args_for_cmds
, cmd_args
, init_args
, num_pointer_args
)
6939 self
.original_functions
.append(f
)
6940 gen_cmd
= f
.GetInfo('gen_cmd')
6941 if gen_cmd
== True or gen_cmd
== None:
6943 f
.type_handler
.AddImmediateFunction(self
, f
)
6944 f
.type_handler
.AddBucketFunction(self
, f
)
6946 self
.Log("Auto Generated Functions : %d" %
6947 len([f
for f
in self
.functions
if f
.can_auto_generate
or
6948 (not f
.IsType('') and not f
.IsType('Custom') and
6949 not f
.IsType('Todo'))]))
6951 funcs
= [f
for f
in self
.functions
if not f
.can_auto_generate
and
6952 (f
.IsType('') or f
.IsType('Custom') or f
.IsType('Todo'))]
6953 self
.Log("Non Auto Generated Functions: %d" % len(funcs
))
6956 self
.Log(" %-10s %-20s gl%s" % (f
.info
.type, f
.return_type
, f
.name
))
6958 def WriteCommandIds(self
, filename
):
6959 """Writes the command buffer format"""
6960 file = CHeaderWriter(filename
)
6961 file.Write("#define GLES2_COMMAND_LIST(OP) \\\n")
6963 for func
in self
.functions
:
6964 file.Write(" %-60s /* %d */ \\\n" %
6965 ("OP(%s)" % func
.name
, id))
6969 file.Write("enum CommandId {\n")
6970 file.Write(" kStartPoint = cmd::kLastCommonId, "
6971 "// All GLES2 commands start after this.\n")
6972 file.Write("#define GLES2_CMD_OP(name) k ## name,\n")
6973 file.Write(" GLES2_COMMAND_LIST(GLES2_CMD_OP)\n")
6974 file.Write("#undef GLES2_CMD_OP\n")
6975 file.Write(" kNumCommands\n")
6980 def WriteFormat(self
, filename
):
6981 """Writes the command buffer format"""
6982 file = CHeaderWriter(filename
)
6983 for func
in self
.functions
:
6985 #gen_cmd = func.GetInfo('gen_cmd')
6986 #if gen_cmd == True or gen_cmd == None:
6987 func
.WriteStruct(file)
6991 def WriteDocs(self
, filename
):
6992 """Writes the command buffer doc version of the commands"""
6993 file = CWriter(filename
)
6994 for func
in self
.functions
:
6996 #gen_cmd = func.GetInfo('gen_cmd')
6997 #if gen_cmd == True or gen_cmd == None:
6998 func
.WriteDocs(file)
7002 def WriteFormatTest(self
, filename
):
7003 """Writes the command buffer format test."""
7004 file = CHeaderWriter(
7006 "// This file contains unit tests for gles2 commmands\n"
7007 "// It is included by gles2_cmd_format_test.cc\n"
7010 for func
in self
.functions
:
7012 #gen_cmd = func.GetInfo('gen_cmd')
7013 #if gen_cmd == True or gen_cmd == None:
7014 func
.WriteFormatTest(file)
7018 def WriteCmdHelperHeader(self
, filename
):
7019 """Writes the gles2 command helper."""
7020 file = CHeaderWriter(filename
)
7022 for func
in self
.functions
:
7024 #gen_cmd = func.GetInfo('gen_cmd')
7025 #if gen_cmd == True or gen_cmd == None:
7026 func
.WriteCmdHelper(file)
7030 def WriteServiceContextStateHeader(self
, filename
):
7031 """Writes the service context state header."""
7032 file = CHeaderWriter(
7034 "// It is included by context_state.h\n")
7035 file.Write("struct EnableFlags {\n")
7036 file.Write(" EnableFlags();\n")
7037 for capability
in _CAPABILITY_FLAGS
:
7038 file.Write(" bool %s;\n" % capability
['name'])
7039 file.Write("};\n\n")
7041 for state_name
in sorted(_STATES
.keys()):
7042 state
= _STATES
[state_name
]
7043 for item
in state
['states']:
7044 file.Write("%s %s;\n" % (item
['type'], item
['name']))
7049 def WriteClientContextStateHeader(self
, filename
):
7050 """Writes the client context state header."""
7051 file = CHeaderWriter(
7053 "// It is included by client_context_state.h\n")
7054 file.Write("struct EnableFlags {\n")
7055 file.Write(" EnableFlags();\n")
7056 for capability
in _CAPABILITY_FLAGS
:
7057 file.Write(" bool %s;\n" % capability
['name'])
7058 file.Write("};\n\n")
7062 def WriteContextStateGetters(self
, file, class_name
):
7063 """Writes the state getters."""
7064 for gl_type
in ["GLint", "GLfloat"]:
7066 bool %s::GetStateAs%s(
7067 GLenum pname, %s* params, GLsizei* num_written) const {
7069 """ % (class_name
, gl_type
, gl_type
))
7070 for state_name
in sorted(_STATES
.keys()):
7071 state
= _STATES
[state_name
]
7073 file.Write(" case %s:\n" % state
['enum'])
7074 file.Write(" *num_written = %d;\n" % len(state
['states']))
7075 file.Write(" if (params) {\n")
7076 for ndx
,item
in enumerate(state
['states']):
7077 file.Write(" params[%d] = static_cast<%s>(%s);\n" %
7078 (ndx
, gl_type
, item
['name']))
7080 file.Write(" return true;\n")
7082 for item
in state
['states']:
7083 file.Write(" case %s:\n" % item
['enum'])
7084 file.Write(" *num_written = 1;\n")
7085 file.Write(" if (params) {\n")
7086 file.Write(" params[0] = static_cast<%s>(%s);\n" %
7087 (gl_type
, item
['name']))
7089 file.Write(" return true;\n")
7090 for capability
in _CAPABILITY_FLAGS
:
7091 file.Write(" case GL_%s:\n" % capability
['name'].upper())
7092 file.Write(" *num_written = 1;\n")
7093 file.Write(" if (params) {\n")
7095 " params[0] = static_cast<%s>(enable_flags.%s);\n" %
7096 (gl_type
, capability
['name']))
7098 file.Write(" return true;\n")
7099 file.Write(""" default:
7105 def WriteServiceContextStateImpl(self
, filename
):
7106 """Writes the context state service implementation."""
7107 file = CHeaderWriter(
7109 "// It is included by context_state.cc\n")
7111 for capability
in _CAPABILITY_FLAGS
:
7112 code
.append("%s(%s)" %
7113 (capability
['name'],
7114 ('false', 'true')['default' in capability
]))
7115 file.Write("ContextState::EnableFlags::EnableFlags()\n : %s {\n}\n" %
7119 file.Write("void ContextState::Initialize() {\n")
7120 for state_name
in sorted(_STATES
.keys()):
7121 state
= _STATES
[state_name
]
7122 for item
in state
['states']:
7123 file.Write(" %s = %s;\n" % (item
['name'], item
['default']))
7127 void ContextState::InitCapabilities() const {
7129 for capability
in _CAPABILITY_FLAGS
:
7130 file.Write(" EnableDisable(GL_%s, enable_flags.%s);\n" %
7131 (capability
['name'].upper(), capability
['name']))
7134 void ContextState::InitState() const {
7137 # We need to sort the keys so the expectations match
7138 for state_name
in sorted(_STATES
.keys()):
7139 state
= _STATES
[state_name
]
7140 if state
['type'] == 'FrontBack':
7141 num_states
= len(state
['states'])
7142 for ndx
, group
in enumerate(Grouper(num_states
/ 2, state
['states'])):
7145 args
.append('%s' % item
['name'])
7147 " gl%s(%s, %s);\n" %
7148 (state
['func'], ('GL_FRONT', 'GL_BACK')[ndx
], ", ".join(args
)))
7149 elif state
['type'] == 'NamedParameter':
7150 for item
in state
['states']:
7151 if 'extension_flag' in item
:
7152 file.Write(" if (feature_info_->feature_flags().%s)\n " %
7153 item
['extension_flag'])
7154 file.Write(" gl%s(%s, %s);\n" %
7155 (state
['func'], item
['enum'], item
['name']))
7158 for item
in state
['states']:
7159 args
.append('%s' % item
['name'])
7160 file.Write(" gl%s(%s);\n" % (state
['func'], ", ".join(args
)))
7163 file.Write("""bool ContextState::GetEnabled(GLenum cap) const {
7166 for capability
in _CAPABILITY_FLAGS
:
7167 file.Write(" case GL_%s:\n" % capability
['name'].upper())
7168 file.Write(" return enable_flags.%s;\n" % capability
['name'])
7169 file.Write(""" default:
7176 self
.WriteContextStateGetters(file, "ContextState")
7179 def WriteClientContextStateImpl(self
, filename
):
7180 """Writes the context state client side implementation."""
7181 file = CHeaderWriter(
7183 "// It is included by client_context_state.cc\n")
7185 for capability
in _CAPABILITY_FLAGS
:
7186 code
.append("%s(%s)" %
7187 (capability
['name'],
7188 ('false', 'true')['default' in capability
]))
7190 "ClientContextState::EnableFlags::EnableFlags()\n : %s {\n}\n" %
7195 bool ClientContextState::SetCapabilityState(
7196 GLenum cap, bool enabled, bool* changed) {
7200 for capability
in _CAPABILITY_FLAGS
:
7201 file.Write(" case GL_%s:\n" % capability
['name'].upper())
7202 file.Write(""" if (enable_flags.%(name)s != enabled) {
7204 enable_flags.%(name)s = enabled;
7208 file.Write(""" default:
7213 file.Write("""bool ClientContextState::GetEnabled(
7214 GLenum cap, bool* enabled) const {
7217 for capability
in _CAPABILITY_FLAGS
:
7218 file.Write(" case GL_%s:\n" % capability
['name'].upper())
7219 file.Write(" *enabled = enable_flags.%s;\n" % capability
['name'])
7220 file.Write(" return true;\n")
7221 file.Write(""" default:
7228 def WriteServiceImplementation(self
, filename
):
7229 """Writes the service decorder implementation."""
7230 file = CHeaderWriter(
7232 "// It is included by gles2_cmd_decoder.cc\n")
7234 for func
in self
.functions
:
7236 #gen_cmd = func.GetInfo('gen_cmd')
7237 #if gen_cmd == True or gen_cmd == None:
7238 func
.WriteServiceImplementation(file)
7241 bool GLES2DecoderImpl::SetCapabilityState(GLenum cap, bool enabled) {
7244 for capability
in _CAPABILITY_FLAGS
:
7245 file.Write(" case GL_%s:\n" % capability
['name'].upper())
7246 if 'state_flag' in capability
:
7247 file.Write(""" if (state_.enable_flags.%(name)s != enabled) {
7248 state_.enable_flags.%(name)s = enabled;
7249 %(state_flag)s = true;
7254 file.Write(""" state_.enable_flags.%(name)s = enabled;
7257 file.Write(""" default:
7265 def WriteServiceUnitTests(self
, filename
):
7266 """Writes the service decorder unit tests."""
7267 num_tests
= len(self
.functions
)
7268 FUNCTIONS_PER_FILE
= 98 # hard code this so it doesn't change.
7270 for test_num
in range(0, num_tests
, FUNCTIONS_PER_FILE
):
7272 name
= filename
% count
7273 file = CHeaderWriter(
7275 "// It is included by gles2_cmd_decoder_unittest_%d.cc\n" % count
)
7276 file.SetFileNum(count
)
7277 end
= test_num
+ FUNCTIONS_PER_FILE
7280 for idx
in range(test_num
, end
):
7281 func
= self
.functions
[idx
]
7283 #gen_cmd = func.GetInfo('gen_cmd')
7284 #if gen_cmd == True or gen_cmd == None:
7285 if func
.GetInfo('unit_test') == False:
7286 file.Write("// TODO(gman): %s\n" % func
.name
)
7288 func
.WriteServiceUnitTest(file)
7291 file = CHeaderWriter(
7293 "// It is included by gles2_cmd_decoder_unittest_base.cc\n")
7295 """void GLES2DecoderTestBase::SetupInitCapabilitiesExpectations() {
7297 for capability
in _CAPABILITY_FLAGS
:
7298 file.Write(" ExpectEnableDisable(GL_%s, %s);\n" %
7299 (capability
['name'].upper(),
7300 ('false', 'true')['default' in capability
]))
7303 void GLES2DecoderTestBase::SetupInitStateExpectations() {
7306 # We need to sort the keys so the expectations match
7307 for state_name
in sorted(_STATES
.keys()):
7308 state
= _STATES
[state_name
]
7309 if state
['type'] == 'FrontBack':
7310 num_states
= len(state
['states'])
7311 for ndx
, group
in enumerate(Grouper(num_states
/ 2, state
['states'])):
7314 if 'expected' in item
:
7315 args
.append(item
['expected'])
7317 args
.append(item
['default'])
7319 " EXPECT_CALL(*gl_, %s(%s, %s))\n" %
7320 (state
['func'], ('GL_FRONT', 'GL_BACK')[ndx
], ", ".join(args
)))
7321 file.Write(" .Times(1)\n")
7322 file.Write(" .RetiresOnSaturation();\n")
7323 elif state
['type'] == 'NamedParameter':
7324 for item
in state
['states']:
7325 if 'extension_flag' in item
:
7328 " EXPECT_CALL(*gl_, %s(%s, %s))\n" %
7329 (state
['func'], item
['enum'], item
['default']))
7330 file.Write(" .Times(1)\n")
7331 file.Write(" .RetiresOnSaturation();\n")
7334 for item
in state
['states']:
7335 if 'expected' in item
:
7336 args
.append(item
['expected'])
7338 args
.append(item
['default'])
7339 file.Write(" EXPECT_CALL(*gl_, %s(%s))\n" %
7340 (state
['func'], ", ".join(args
)))
7341 file.Write(" .Times(1)\n")
7342 file.Write(" .RetiresOnSaturation();\n")
7347 def WriteGLES2Header(self
, filename
):
7348 """Writes the GLES2 header."""
7349 file = CHeaderWriter(
7351 "// This file contains Chromium-specific GLES2 declarations.\n\n")
7353 for func
in self
.original_functions
:
7354 func
.WriteGLES2Header(file)
7359 def WriteGLES2CLibImplementation(self
, filename
):
7360 """Writes the GLES2 c lib implementation."""
7361 file = CHeaderWriter(
7363 "// These functions emulate GLES2 over command buffers.\n")
7365 for func
in self
.original_functions
:
7366 func
.WriteGLES2CLibImplementation(file)
7371 extern const NameToFunc g_gles2_function_table[] = {
7373 for func
in self
.original_functions
:
7375 ' { "gl%s", reinterpret_cast<GLES2FunctionPointer>(gl%s), },\n' %
7376 (func
.name
, func
.name
))
7377 file.Write(""" { NULL, NULL, },
7380 } // namespace gles2
7384 def WriteGLES2InterfaceHeader(self
, filename
):
7385 """Writes the GLES2 interface header."""
7386 file = CHeaderWriter(
7388 "// This file is included by gles2_interface.h to declare the\n"
7389 "// GL api functions.\n")
7390 for func
in self
.original_functions
:
7391 func
.WriteGLES2InterfaceHeader(file)
7394 def WriteGLES2InterfaceStub(self
, filename
):
7395 """Writes the GLES2 interface stub header."""
7396 file = CHeaderWriter(
7398 "// This file is included by gles2_interface_stub.h.\n")
7399 for func
in self
.original_functions
:
7400 func
.WriteGLES2InterfaceStub(file)
7403 def WriteGLES2InterfaceStubImpl(self
, filename
):
7404 """Writes the GLES2 interface header."""
7405 file = CHeaderWriter(
7407 "// This file is included by gles2_interface_stub.cc.\n")
7408 for func
in self
.original_functions
:
7409 func
.WriteGLES2InterfaceStubImpl(file)
7412 def WriteGLES2ImplementationHeader(self
, filename
):
7413 """Writes the GLES2 Implementation header."""
7414 file = CHeaderWriter(
7416 "// This file is included by gles2_implementation.h to declare the\n"
7417 "// GL api functions.\n")
7418 for func
in self
.original_functions
:
7419 func
.WriteGLES2ImplementationHeader(file)
7422 def WriteGLES2Implementation(self
, filename
):
7423 """Writes the GLES2 Implementation."""
7424 file = CHeaderWriter(
7426 "// This file is included by gles2_implementation.cc to define the\n"
7427 "// GL api functions.\n")
7428 for func
in self
.original_functions
:
7429 func
.WriteGLES2Implementation(file)
7432 def WriteGLES2TraceImplementationHeader(self
, filename
):
7433 """Writes the GLES2 Trace Implementation header."""
7434 file = CHeaderWriter(
7436 "// This file is included by gles2_trace_implementation.h\n")
7437 for func
in self
.original_functions
:
7438 func
.WriteGLES2TraceImplementationHeader(file)
7441 def WriteGLES2TraceImplementation(self
, filename
):
7442 """Writes the GLES2 Trace Implementation."""
7443 file = CHeaderWriter(
7445 "// This file is included by gles2_trace_implementation.cc\n")
7446 for func
in self
.original_functions
:
7447 func
.WriteGLES2TraceImplementation(file)
7450 def WriteGLES2ImplementationUnitTests(self
, filename
):
7451 """Writes the GLES2 helper header."""
7452 file = CHeaderWriter(
7454 "// This file is included by gles2_implementation.h to declare the\n"
7455 "// GL api functions.\n")
7456 for func
in self
.original_functions
:
7457 func
.WriteGLES2ImplementationUnitTest(file)
7460 def WriteServiceUtilsHeader(self
, filename
):
7461 """Writes the gles2 auto generated utility header."""
7462 file = CHeaderWriter(filename
)
7463 for enum
in sorted(_ENUM_LISTS
.keys()):
7464 file.Write("ValueValidator<%s> %s;\n" %
7465 (_ENUM_LISTS
[enum
]['type'], ToUnderscore(enum
)))
7469 def WriteServiceUtilsImplementation(self
, filename
):
7470 """Writes the gles2 auto generated utility implementation."""
7471 file = CHeaderWriter(filename
)
7472 enums
= sorted(_ENUM_LISTS
.keys())
7474 if len(_ENUM_LISTS
[enum
]['valid']) > 0:
7475 file.Write("static const %s valid_%s_table[] = {\n" %
7476 (_ENUM_LISTS
[enum
]['type'], ToUnderscore(enum
)))
7477 for value
in _ENUM_LISTS
[enum
]['valid']:
7478 file.Write(" %s,\n" % value
)
7481 file.Write("Validators::Validators()\n")
7484 for count
, enum
in enumerate(enums
):
7485 if count
+ 1 == len(enums
):
7487 if len(_ENUM_LISTS
[enum
]['valid']) > 0:
7488 code
= """ %(pre)s%(name)s(
7489 valid_%(name)s_table, arraysize(valid_%(name)s_table))%(post)s
7492 code
= """ %(pre)s%(name)s()%(post)s
7495 'name': ToUnderscore(enum
),
7500 file.Write("}\n\n");
7503 def WriteCommonUtilsHeader(self
, filename
):
7504 """Writes the gles2 common utility header."""
7505 file = CHeaderWriter(filename
)
7506 enums
= sorted(_ENUM_LISTS
.keys())
7508 if _ENUM_LISTS
[enum
]['type'] == 'GLenum':
7509 file.Write("static std::string GetString%s(uint32 value);\n" % enum
)
7513 def WriteCommonUtilsImpl(self
, filename
):
7514 """Writes the gles2 common utility header."""
7515 enum_re
= re
.compile(r
'\#define\s+(GL_[a-zA-Z0-9_]+)\s+([0-9A-Fa-fx]+)')
7517 for fname
in ['../../third_party/khronos/GLES2/gl2.h',
7518 '../../third_party/khronos/GLES2/gl2ext.h',
7519 '../../gpu/GLES2/gl2chromium.h',
7520 '../../gpu/GLES2/gl2extchromium.h']:
7521 lines
= open(fname
).readlines()
7523 m
= enum_re
.match(line
)
7527 if len(value
) <= 10 and not value
in dict:
7530 file = CHeaderWriter(filename
)
7531 file.Write("static const GLES2Util::EnumToString "
7532 "enum_to_string_table[] = {\n")
7534 file.Write(' { %s, "%s", },\n' % (value
, dict[value
]))
7537 const GLES2Util::EnumToString* const GLES2Util::enum_to_string_table_ =
7538 enum_to_string_table;
7539 const size_t GLES2Util::enum_to_string_table_len_ =
7540 sizeof(enum_to_string_table) / sizeof(enum_to_string_table[0]);
7544 enums
= sorted(_ENUM_LISTS
.keys())
7546 if _ENUM_LISTS
[enum
]['type'] == 'GLenum':
7547 file.Write("std::string GLES2Util::GetString%s(uint32 value) {\n" %
7549 if len(_ENUM_LISTS
[enum
]['valid']) > 0:
7550 file.Write(" static const EnumToString string_table[] = {\n")
7551 for value
in _ENUM_LISTS
[enum
]['valid']:
7552 file.Write(' { %s, "%s" },\n' % (value
, value
))
7554 return GLES2Util::GetQualifiedEnumString(
7555 string_table, arraysize(string_table), value);
7560 file.Write(""" return GLES2Util::GetQualifiedEnumString(
7567 def WritePepperGLES2Interface(self
, filename
, dev
):
7568 """Writes the Pepper OpenGLES interface definition."""
7569 file = CHeaderWriter(
7571 "// OpenGL ES interface.\n",
7574 file.Write("#include \"ppapi/c/pp_resource.h\"\n")
7576 file.Write("#include \"ppapi/c/ppb_opengles2.h\"\n\n")
7578 file.Write("\n#ifndef __gl2_h_\n")
7579 for (k
, v
) in _GL_TYPES
.iteritems():
7580 file.Write("typedef %s %s;\n" % (v
, k
))
7581 file.Write("#endif // __gl2_h_\n\n")
7583 for interface
in self
.pepper_interfaces
:
7584 if interface
.dev
!= dev
:
7586 file.Write("#define %s_1_0 \"%s;1.0\"\n" %
7587 (interface
.GetInterfaceName(), interface
.GetInterfaceString()))
7588 file.Write("#define %s %s_1_0\n" %
7589 (interface
.GetInterfaceName(), interface
.GetInterfaceName()))
7591 file.Write("\nstruct %s {\n" % interface
.GetStructName())
7592 for func
in self
.original_functions
:
7593 if not func
.InPepperInterface(interface
):
7596 original_arg
= func
.MakeTypedOriginalArgString("")
7597 context_arg
= "PP_Resource context"
7598 if len(original_arg
):
7599 arg
= context_arg
+ ", " + original_arg
7602 file.Write(" %s (*%s)(%s);\n" % (func
.return_type
, func
.name
, arg
))
7603 file.Write("};\n\n")
7608 def WritePepperGLES2Implementation(self
, filename
):
7609 """Writes the Pepper OpenGLES interface implementation."""
7611 file = CWriter(filename
)
7612 file.Write(_LICENSE
)
7613 file.Write(_DO_NOT_EDIT_WARNING
)
7615 file.Write("#include \"ppapi/shared_impl/ppb_opengles2_shared.h\"\n\n")
7616 file.Write("#include \"base/logging.h\"\n")
7617 file.Write("#include \"gpu/command_buffer/client/gles2_implementation.h\"\n")
7618 file.Write("#include \"ppapi/shared_impl/ppb_graphics_3d_shared.h\"\n")
7619 file.Write("#include \"ppapi/thunk/enter.h\"\n\n")
7621 file.Write("namespace ppapi {\n\n")
7622 file.Write("namespace {\n\n")
7624 file.Write("gpu::gles2::GLES2Implementation*"
7625 " GetGLES(PP_Resource context) {\n")
7626 file.Write(" thunk::EnterResource<thunk::PPB_Graphics3D_API>"
7627 " enter_g3d(context, false);\n")
7628 file.Write(" DCHECK(enter_g3d.succeeded());\n")
7629 file.Write(" return static_cast<PPB_Graphics3D_Shared*>"
7630 "(enter_g3d.object())->gles2_impl();\n")
7633 for func
in self
.original_functions
:
7634 if not func
.InAnyPepperExtension():
7637 original_arg
= func
.MakeTypedOriginalArgString("")
7638 context_arg
= "PP_Resource context_id"
7639 if len(original_arg
):
7640 arg
= context_arg
+ ", " + original_arg
7643 file.Write("%s %s(%s) {\n" % (func
.return_type
, func
.name
, arg
))
7645 return_str
= "" if func
.return_type
== "void" else "return "
7646 file.Write(" %sGetGLES(context_id)->%s(%s);\n" %
7647 (return_str
, func
.original_name
,
7648 func
.MakeOriginalArgString("")))
7651 file.Write("} // namespace\n")
7653 for interface
in self
.pepper_interfaces
:
7654 file.Write("const %s* PPB_OpenGLES2_Shared::Get%sInterface() {\n" %
7655 (interface
.GetStructName(), interface
.GetName()))
7656 file.Write(" static const struct %s "
7657 "ppb_opengles2 = {\n" % interface
.GetStructName())
7659 file.Write(",\n &".join(
7660 f
.name
for f
in self
.original_functions
7661 if f
.InPepperInterface(interface
)))
7665 file.Write(" return &ppb_opengles2;\n")
7668 file.Write("} // namespace ppapi\n")
7671 def WriteGLES2ToPPAPIBridge(self
, filename
):
7672 """Connects GLES2 helper library to PPB_OpenGLES2 interface"""
7674 file = CWriter(filename
)
7675 file.Write(_LICENSE
)
7676 file.Write(_DO_NOT_EDIT_WARNING
)
7678 file.Write("#ifndef GL_GLEXT_PROTOTYPES\n")
7679 file.Write("#define GL_GLEXT_PROTOTYPES\n")
7680 file.Write("#endif\n")
7681 file.Write("#include <GLES2/gl2.h>\n")
7682 file.Write("#include <GLES2/gl2ext.h>\n")
7683 file.Write("#include \"ppapi/lib/gl/gles2/gl2ext_ppapi.h\"\n\n")
7685 for func
in self
.original_functions
:
7686 if not func
.InAnyPepperExtension():
7689 interface
= self
.interface_info
[func
.GetInfo('pepper_interface') or '']
7691 file.Write("%s GL_APIENTRY gl%s(%s) {\n" %
7692 (func
.return_type
, func
.name
,
7693 func
.MakeTypedOriginalArgString("")))
7694 return_str
= "" if func
.return_type
== "void" else "return "
7695 interface_str
= "glGet%sInterfacePPAPI()" % interface
.GetName()
7696 original_arg
= func
.MakeOriginalArgString("")
7697 context_arg
= "glGetCurrentContextPPAPI()"
7698 if len(original_arg
):
7699 arg
= context_arg
+ ", " + original_arg
7702 if interface
.GetName():
7703 file.Write(" const struct %s* ext = %s;\n" %
7704 (interface
.GetStructName(), interface_str
))
7705 file.Write(" if (ext)\n")
7706 file.Write(" %sext->%s(%s);\n" %
7707 (return_str
, func
.name
, arg
))
7709 file.Write(" %s0;\n" % return_str
)
7711 file.Write(" %s%s->%s(%s);\n" %
7712 (return_str
, interface_str
, func
.name
, arg
))
7717 """This is the main function."""
7718 parser
= OptionParser()
7720 "-g", "--generate-implementation-templates", action
="store_true",
7721 help="generates files that are generally hand edited..")
7723 "--alternate-mode", type="choice",
7724 choices
=("ppapi", "chrome_ppapi", "chrome_ppapi_proxy", "nacl_ppapi"),
7725 help="generate files for other projects. \"ppapi\" will generate ppapi "
7726 "bindings. \"chrome_ppapi\" generate chrome implementation for ppapi. "
7727 "\"chrome_ppapi_proxy\" will generate the glue for the chrome IPC ppapi"
7728 "proxy. \"nacl_ppapi\" will generate NaCl implementation for ppapi")
7731 help="base directory for resulting files, under chrome/src. default is "
7732 "empty. Use this if you want the result stored under gen.")
7734 "-v", "--verbose", action
="store_true",
7735 help="prints more output.")
7737 (options
, args
) = parser
.parse_args(args
=argv
)
7739 # Add in states and capabilites to GLState
7740 for state_name
in sorted(_STATES
.keys()):
7741 state
= _STATES
[state_name
]
7743 _ENUM_LISTS
['GLState']['valid'].append(state
['enum'])
7745 for item
in state
['states']:
7746 if 'extension_flag' in item
:
7748 _ENUM_LISTS
['GLState']['valid'].append(item
['enum'])
7749 for capability
in _CAPABILITY_FLAGS
:
7750 _ENUM_LISTS
['GLState']['valid'].append("GL_%s" % capability
['name'].upper())
7752 # This script lives under gpu/command_buffer, cd to base directory.
7753 os
.chdir(os
.path
.dirname(__file__
) + "/../..")
7755 gen
= GLGenerator(options
.verbose
)
7756 gen
.ParseGLH("common/GLES2/gl2.h")
7758 # Support generating files under gen/
7759 if options
.output_dir
!= None:
7760 os
.chdir(options
.output_dir
)
7762 if options
.alternate_mode
== "ppapi":
7763 # To trigger this action, do "make ppapi_gles_bindings"
7765 gen
.WritePepperGLES2Interface("c/ppb_opengles2.h", False)
7766 gen
.WritePepperGLES2Interface("c/dev/ppb_opengles2ext_dev.h", True)
7767 gen
.WriteGLES2ToPPAPIBridge("lib/gl/gles2/gles2.c")
7769 elif options
.alternate_mode
== "chrome_ppapi":
7770 # To trigger this action, do "make ppapi_gles_implementation"
7771 gen
.WritePepperGLES2Implementation(
7772 "ppapi/shared_impl/ppb_opengles2_shared.cc")
7775 os
.chdir("gpu/command_buffer")
7776 gen
.WriteCommandIds("common/gles2_cmd_ids_autogen.h")
7777 gen
.WriteFormat("common/gles2_cmd_format_autogen.h")
7778 gen
.WriteFormatTest("common/gles2_cmd_format_test_autogen.h")
7779 gen
.WriteGLES2InterfaceHeader("client/gles2_interface_autogen.h")
7780 gen
.WriteGLES2InterfaceStub("client/gles2_interface_stub_autogen.h")
7781 gen
.WriteGLES2InterfaceStubImpl(
7782 "client/gles2_interface_stub_impl_autogen.h")
7783 gen
.WriteGLES2ImplementationHeader("client/gles2_implementation_autogen.h")
7784 gen
.WriteGLES2Implementation("client/gles2_implementation_impl_autogen.h")
7785 gen
.WriteGLES2ImplementationUnitTests(
7786 "client/gles2_implementation_unittest_autogen.h")
7787 gen
.WriteGLES2TraceImplementationHeader(
7788 "client/gles2_trace_implementation_autogen.h")
7789 gen
.WriteGLES2TraceImplementation(
7790 "client/gles2_trace_implementation_impl_autogen.h")
7791 gen
.WriteGLES2CLibImplementation("client/gles2_c_lib_autogen.h")
7792 gen
.WriteCmdHelperHeader("client/gles2_cmd_helper_autogen.h")
7793 gen
.WriteServiceImplementation("service/gles2_cmd_decoder_autogen.h")
7794 gen
.WriteServiceContextStateHeader("service/context_state_autogen.h")
7795 gen
.WriteServiceContextStateImpl("service/context_state_impl_autogen.h")
7796 gen
.WriteClientContextStateHeader("client/client_context_state_autogen.h")
7797 gen
.WriteClientContextStateImpl(
7798 "client/client_context_state_impl_autogen.h")
7799 gen
.WriteServiceUnitTests("service/gles2_cmd_decoder_unittest_%d_autogen.h")
7800 gen
.WriteServiceUtilsHeader("service/gles2_cmd_validation_autogen.h")
7801 gen
.WriteServiceUtilsImplementation(
7802 "service/gles2_cmd_validation_implementation_autogen.h")
7803 gen
.WriteCommonUtilsHeader("common/gles2_cmd_utils_autogen.h")
7804 gen
.WriteCommonUtilsImpl("common/gles2_cmd_utils_implementation_autogen.h")
7805 gen
.WriteGLES2Header("../GLES2/gl2chromium_autogen.h")
7808 print "%d errors" % gen
.errors
7813 if __name__
== '__main__':
7814 sys
.exit(main(sys
.argv
[1:]))