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."""
14 from optparse
import OptionParser
15 from subprocess
import call
18 _SIZE_OF_COMMAND_HEADER
= 4
19 _FIRST_SPECIFIC_COMMAND_ID
= 256
21 _LICENSE
= """// Copyright 2014 The Chromium Authors. All rights reserved.
22 // Use of this source code is governed by a BSD-style license that can be
23 // found in the LICENSE file.
27 _DO_NOT_EDIT_WARNING
= """// This file is auto-generated from
28 // gpu/command_buffer/build_gles2_cmd_buffer.py
29 // It's formatted by clang-format using chromium coding style:
30 // clang-format -i -style=chromium filename
35 # This string is copied directly out of the gl2.h file from GLES2.0
39 # *) Any argument that is a resourceID has been changed to GLid<Type>.
40 # (not pointer arguments) and if it's allowed to be zero it's GLidZero<Type>
41 # If it's allowed to not exist it's GLidBind<Type>
43 # *) All GLenums have been changed to GLenumTypeOfEnum
46 'GLenum': 'unsigned int',
47 'GLboolean': 'unsigned char',
48 'GLbitfield': 'unsigned int',
49 'GLbyte': 'signed char',
53 'GLubyte': 'unsigned char',
54 'GLushort': 'unsigned short',
55 'GLuint': 'unsigned int',
64 'GLintptr': 'long int',
65 'GLsizeiptr': 'long int'
69 'GLintptr': 'long long int',
70 'GLsizeiptr': 'long long int'
73 # Capabilites selected with glEnable
76 {'name': 'cull_face'},
77 {'name': 'depth_test', 'state_flag': 'framebuffer_state_.clear_state_dirty'},
78 {'name': 'dither', 'default': True},
79 {'name': 'polygon_offset_fill'},
80 {'name': 'sample_alpha_to_coverage'},
81 {'name': 'sample_coverage'},
82 {'name': 'scissor_test'},
83 {'name': 'stencil_test',
84 'state_flag': 'framebuffer_state_.clear_state_dirty'},
91 'enum': 'GL_COLOR_CLEAR_VALUE',
93 {'name': 'color_clear_red', 'type': 'GLfloat', 'default': '0.0f'},
94 {'name': 'color_clear_green', 'type': 'GLfloat', 'default': '0.0f'},
95 {'name': 'color_clear_blue', 'type': 'GLfloat', 'default': '0.0f'},
96 {'name': 'color_clear_alpha', 'type': 'GLfloat', 'default': '0.0f'},
101 'func': 'ClearDepth',
102 'enum': 'GL_DEPTH_CLEAR_VALUE',
104 {'name': 'depth_clear', 'type': 'GLclampf', 'default': '1.0f'},
110 'enum': 'GL_COLOR_WRITEMASK',
113 'name': 'color_mask_red',
119 'name': 'color_mask_green',
125 'name': 'color_mask_blue',
131 'name': 'color_mask_alpha',
137 'state_flag': 'framebuffer_state_.clear_state_dirty',
141 'func': 'ClearStencil',
142 'enum': 'GL_STENCIL_CLEAR_VALUE',
144 {'name': 'stencil_clear', 'type': 'GLint', 'default': '0'},
149 'func': 'BlendColor',
150 'enum': 'GL_BLEND_COLOR',
152 {'name': 'blend_color_red', 'type': 'GLfloat', 'default': '0.0f'},
153 {'name': 'blend_color_green', 'type': 'GLfloat', 'default': '0.0f'},
154 {'name': 'blend_color_blue', 'type': 'GLfloat', 'default': '0.0f'},
155 {'name': 'blend_color_alpha', 'type': 'GLfloat', 'default': '0.0f'},
160 'func': 'BlendEquationSeparate',
163 'name': 'blend_equation_rgb',
165 'enum': 'GL_BLEND_EQUATION_RGB',
166 'default': 'GL_FUNC_ADD',
169 'name': 'blend_equation_alpha',
171 'enum': 'GL_BLEND_EQUATION_ALPHA',
172 'default': 'GL_FUNC_ADD',
178 'func': 'BlendFuncSeparate',
181 'name': 'blend_source_rgb',
183 'enum': 'GL_BLEND_SRC_RGB',
187 'name': 'blend_dest_rgb',
189 'enum': 'GL_BLEND_DST_RGB',
190 'default': 'GL_ZERO',
193 'name': 'blend_source_alpha',
195 'enum': 'GL_BLEND_SRC_ALPHA',
199 'name': 'blend_dest_alpha',
201 'enum': 'GL_BLEND_DST_ALPHA',
202 'default': 'GL_ZERO',
208 'func': 'PolygonOffset',
211 'name': 'polygon_offset_factor',
213 'enum': 'GL_POLYGON_OFFSET_FACTOR',
217 'name': 'polygon_offset_units',
219 'enum': 'GL_POLYGON_OFFSET_UNITS',
227 'enum': 'GL_CULL_FACE_MODE',
232 'default': 'GL_BACK',
239 'enum': 'GL_FRONT_FACE',
240 'states': [{'name': 'front_face', 'type': 'GLenum', 'default': 'GL_CCW'}],
245 'enum': 'GL_DEPTH_FUNC',
246 'states': [{'name': 'depth_func', 'type': 'GLenum', 'default': 'GL_LESS'}],
250 'func': 'DepthRange',
251 'enum': 'GL_DEPTH_RANGE',
253 {'name': 'z_near', 'type': 'GLclampf', 'default': '0.0f'},
254 {'name': 'z_far', 'type': 'GLclampf', 'default': '1.0f'},
259 'func': 'SampleCoverage',
262 'name': 'sample_coverage_value',
264 'enum': 'GL_SAMPLE_COVERAGE_VALUE',
268 'name': 'sample_coverage_invert',
270 'enum': 'GL_SAMPLE_COVERAGE_INVERT',
277 'func': 'StencilMaskSeparate',
278 'state_flag': 'framebuffer_state_.clear_state_dirty',
281 'name': 'stencil_front_writemask',
283 'enum': 'GL_STENCIL_WRITEMASK',
284 'default': '0xFFFFFFFFU',
288 'name': 'stencil_back_writemask',
290 'enum': 'GL_STENCIL_BACK_WRITEMASK',
291 'default': '0xFFFFFFFFU',
298 'func': 'StencilOpSeparate',
301 'name': 'stencil_front_fail_op',
303 'enum': 'GL_STENCIL_FAIL',
304 'default': 'GL_KEEP',
307 'name': 'stencil_front_z_fail_op',
309 'enum': 'GL_STENCIL_PASS_DEPTH_FAIL',
310 'default': 'GL_KEEP',
313 'name': 'stencil_front_z_pass_op',
315 'enum': 'GL_STENCIL_PASS_DEPTH_PASS',
316 'default': 'GL_KEEP',
319 'name': 'stencil_back_fail_op',
321 'enum': 'GL_STENCIL_BACK_FAIL',
322 'default': 'GL_KEEP',
325 'name': 'stencil_back_z_fail_op',
327 'enum': 'GL_STENCIL_BACK_PASS_DEPTH_FAIL',
328 'default': 'GL_KEEP',
331 'name': 'stencil_back_z_pass_op',
333 'enum': 'GL_STENCIL_BACK_PASS_DEPTH_PASS',
334 'default': 'GL_KEEP',
340 'func': 'StencilFuncSeparate',
343 'name': 'stencil_front_func',
345 'enum': 'GL_STENCIL_FUNC',
346 'default': 'GL_ALWAYS',
349 'name': 'stencil_front_ref',
351 'enum': 'GL_STENCIL_REF',
355 'name': 'stencil_front_mask',
357 'enum': 'GL_STENCIL_VALUE_MASK',
358 'default': '0xFFFFFFFFU',
361 'name': 'stencil_back_func',
363 'enum': 'GL_STENCIL_BACK_FUNC',
364 'default': 'GL_ALWAYS',
367 'name': 'stencil_back_ref',
369 'enum': 'GL_STENCIL_BACK_REF',
373 'name': 'stencil_back_mask',
375 'enum': 'GL_STENCIL_BACK_VALUE_MASK',
376 'default': '0xFFFFFFFFU',
381 'type': 'NamedParameter',
385 'name': 'hint_generate_mipmap',
387 'enum': 'GL_GENERATE_MIPMAP_HINT',
388 'default': 'GL_DONT_CARE'
391 'name': 'hint_fragment_shader_derivative',
393 'enum': 'GL_FRAGMENT_SHADER_DERIVATIVE_HINT_OES',
394 'default': 'GL_DONT_CARE',
395 'extension_flag': 'oes_standard_derivatives'
400 'type': 'NamedParameter',
401 'func': 'PixelStorei',
404 'name': 'pack_alignment',
406 'enum': 'GL_PACK_ALIGNMENT',
410 'name': 'unpack_alignment',
412 'enum': 'GL_UNPACK_ALIGNMENT',
417 # TODO: Consider implemenenting these states
422 'enum': 'GL_LINE_WIDTH',
425 'name': 'line_width',
428 'range_checks': [{'check': "<= 0.0f", 'test_value': "0.0f"}],
435 'enum': 'GL_DEPTH_WRITEMASK',
438 'name': 'depth_mask',
444 'state_flag': 'framebuffer_state_.clear_state_dirty',
449 'enum': 'GL_SCISSOR_BOX',
451 # NOTE: These defaults reset at GLES2DecoderImpl::Initialization.
456 'expected': 'kViewportX',
462 'expected': 'kViewportY',
465 'name': 'scissor_width',
468 'expected': 'kViewportWidth',
471 'name': 'scissor_height',
474 'expected': 'kViewportHeight',
481 'enum': 'GL_VIEWPORT',
483 # NOTE: These defaults reset at GLES2DecoderImpl::Initialization.
485 'name': 'viewport_x',
488 'expected': 'kViewportX',
491 'name': 'viewport_y',
494 'expected': 'kViewportY',
497 'name': 'viewport_width',
500 'expected': 'kViewportWidth',
503 'name': 'viewport_height',
506 'expected': 'kViewportHeight',
510 'MatrixValuesCHROMIUM': {
511 'type': 'NamedParameter',
512 'func': 'MatrixLoadfEXT',
514 { 'enum': 'GL_PATH_MODELVIEW_MATRIX_CHROMIUM',
515 'enum_set': 'GL_PATH_MODELVIEW_CHROMIUM',
516 'name': 'modelview_matrix',
519 '1.0f', '0.0f','0.0f','0.0f',
520 '0.0f', '1.0f','0.0f','0.0f',
521 '0.0f', '0.0f','1.0f','0.0f',
522 '0.0f', '0.0f','0.0f','1.0f',
524 'extension_flag': 'chromium_path_rendering',
526 { 'enum': 'GL_PATH_PROJECTION_MATRIX_CHROMIUM',
527 'enum_set': 'GL_PATH_PROJECTION_CHROMIUM',
528 'name': 'projection_matrix',
531 '1.0f', '0.0f','0.0f','0.0f',
532 '0.0f', '1.0f','0.0f','0.0f',
533 '0.0f', '0.0f','1.0f','0.0f',
534 '0.0f', '0.0f','0.0f','1.0f',
536 'extension_flag': 'chromium_path_rendering',
542 # Named type info object represents a named type that is used in OpenGL call
543 # arguments. Each named type defines a set of valid OpenGL call arguments. The
544 # named types are used in 'cmd_buffer_functions.txt'.
545 # type: The actual GL type of the named type.
546 # valid: The list of values that are valid for both the client and the service.
547 # invalid: Examples of invalid values for the type. At least these values
548 # should be tested to be invalid.
549 # is_complete: The list of valid values of type are final and will not be
550 # modified during runtime.
559 'GL_LINEAR_MIPMAP_LINEAR',
562 'FrameBufferTarget': {
568 'GL_DRAW_FRAMEBUFFER' ,
569 'GL_READ_FRAMEBUFFER' ,
572 'RenderBufferTarget': {
585 'GL_ELEMENT_ARRAY_BUFFER',
591 'IndexedBufferTarget': {
594 'GL_TRANSFORM_FEEDBACK_BUFFER',
650 'CompressedTextureFormat': {
658 # NOTE: State an Capability entries added later.
660 'GL_ALIASED_LINE_WIDTH_RANGE',
661 'GL_ALIASED_POINT_SIZE_RANGE',
663 'GL_ARRAY_BUFFER_BINDING',
665 'GL_COMPRESSED_TEXTURE_FORMATS',
666 'GL_CURRENT_PROGRAM',
669 'GL_ELEMENT_ARRAY_BUFFER_BINDING',
670 'GL_FRAMEBUFFER_BINDING',
671 'GL_GENERATE_MIPMAP_HINT',
673 'GL_IMPLEMENTATION_COLOR_READ_FORMAT',
674 'GL_IMPLEMENTATION_COLOR_READ_TYPE',
675 'GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS',
676 'GL_MAX_CUBE_MAP_TEXTURE_SIZE',
677 'GL_MAX_FRAGMENT_UNIFORM_VECTORS',
678 'GL_MAX_RENDERBUFFER_SIZE',
679 'GL_MAX_TEXTURE_IMAGE_UNITS',
680 'GL_MAX_TEXTURE_SIZE',
681 'GL_MAX_VARYING_VECTORS',
682 'GL_MAX_VERTEX_ATTRIBS',
683 'GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS',
684 'GL_MAX_VERTEX_UNIFORM_VECTORS',
685 'GL_MAX_VIEWPORT_DIMS',
686 'GL_NUM_COMPRESSED_TEXTURE_FORMATS',
687 'GL_NUM_SHADER_BINARY_FORMATS',
690 'GL_RENDERBUFFER_BINDING',
692 'GL_SAMPLE_COVERAGE_INVERT',
693 'GL_SAMPLE_COVERAGE_VALUE',
696 'GL_SHADER_BINARY_FORMATS',
697 'GL_SHADER_COMPILER',
700 'GL_TEXTURE_BINDING_2D',
701 'GL_TEXTURE_BINDING_CUBE_MAP',
702 'GL_UNPACK_ALIGNMENT',
703 'GL_UNPACK_FLIP_Y_CHROMIUM',
704 'GL_UNPACK_PREMULTIPLY_ALPHA_CHROMIUM',
705 'GL_UNPACK_UNPREMULTIPLY_ALPHA_CHROMIUM',
706 'GL_BIND_GENERATES_RESOURCE_CHROMIUM',
707 # we can add this because we emulate it if the driver does not support it.
708 'GL_VERTEX_ARRAY_BINDING_OES',
715 'GetTexParamTarget': {
719 'GL_TEXTURE_CUBE_MAP',
722 'GL_PROXY_TEXTURE_CUBE_MAP',
729 'GL_TEXTURE_CUBE_MAP_POSITIVE_X',
730 'GL_TEXTURE_CUBE_MAP_NEGATIVE_X',
731 'GL_TEXTURE_CUBE_MAP_POSITIVE_Y',
732 'GL_TEXTURE_CUBE_MAP_NEGATIVE_Y',
733 'GL_TEXTURE_CUBE_MAP_POSITIVE_Z',
734 'GL_TEXTURE_CUBE_MAP_NEGATIVE_Z',
737 'GL_PROXY_TEXTURE_CUBE_MAP',
744 'GL_TEXTURE_2D_ARRAY',
750 'TextureBindTarget': {
754 'GL_TEXTURE_CUBE_MAP',
761 'TransformFeedbackBindTarget': {
764 'GL_TRANSFORM_FEEDBACK',
770 'TransformFeedbackPrimitiveMode': {
785 'GL_FRAGMENT_SHADER',
788 'GL_GEOMETRY_SHADER',
824 'GL_FUNC_REVERSE_SUBTRACT',
837 'GL_ONE_MINUS_SRC_COLOR',
839 'GL_ONE_MINUS_DST_COLOR',
841 'GL_ONE_MINUS_SRC_ALPHA',
843 'GL_ONE_MINUS_DST_ALPHA',
845 'GL_ONE_MINUS_CONSTANT_COLOR',
847 'GL_ONE_MINUS_CONSTANT_ALPHA',
848 'GL_SRC_ALPHA_SATURATE',
857 'GL_ONE_MINUS_SRC_COLOR',
859 'GL_ONE_MINUS_DST_COLOR',
861 'GL_ONE_MINUS_SRC_ALPHA',
863 'GL_ONE_MINUS_DST_ALPHA',
865 'GL_ONE_MINUS_CONSTANT_COLOR',
867 'GL_ONE_MINUS_CONSTANT_ALPHA',
872 'valid': ["GL_%s" % cap
['name'].upper() for cap
in _CAPABILITY_FLAGS
],
919 'GL_COLOR_ATTACHMENT0',
920 'GL_DEPTH_ATTACHMENT',
921 'GL_STENCIL_ATTACHMENT',
924 'BackbufferAttachment': {
939 'GL_PIXEL_PACK_BUFFER',
945 'GL_INTERLEAVED_ATTRIBS',
946 'GL_SEPARATE_ATTRIBS',
949 'GL_PIXEL_PACK_BUFFER',
952 'FrameBufferParameter': {
955 'GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE',
956 'GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME',
957 'GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL',
958 'GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE',
964 'GL_PATH_PROJECTION_CHROMIUM',
965 'GL_PATH_MODELVIEW_CHROMIUM',
968 'ProgramParameter': {
973 'GL_VALIDATE_STATUS',
974 'GL_INFO_LOG_LENGTH',
975 'GL_ATTACHED_SHADERS',
976 'GL_ACTIVE_ATTRIBUTES',
977 'GL_ACTIVE_ATTRIBUTE_MAX_LENGTH',
978 'GL_ACTIVE_UNIFORMS',
979 'GL_ACTIVE_UNIFORM_MAX_LENGTH',
982 'QueryObjectParameter': {
985 'GL_QUERY_RESULT_EXT',
986 'GL_QUERY_RESULT_AVAILABLE_EXT',
992 'GL_CURRENT_QUERY_EXT',
998 'GL_ANY_SAMPLES_PASSED_EXT',
999 'GL_ANY_SAMPLES_PASSED_CONSERVATIVE_EXT',
1000 'GL_COMMANDS_ISSUED_CHROMIUM',
1001 'GL_LATENCY_QUERY_CHROMIUM',
1002 'GL_ASYNC_PIXEL_UNPACK_COMPLETED_CHROMIUM',
1003 'GL_ASYNC_PIXEL_PACK_COMPLETED_CHROMIUM',
1004 'GL_COMMANDS_COMPLETED_CHROMIUM',
1007 'RenderBufferParameter': {
1010 'GL_RENDERBUFFER_RED_SIZE',
1011 'GL_RENDERBUFFER_GREEN_SIZE',
1012 'GL_RENDERBUFFER_BLUE_SIZE',
1013 'GL_RENDERBUFFER_ALPHA_SIZE',
1014 'GL_RENDERBUFFER_DEPTH_SIZE',
1015 'GL_RENDERBUFFER_STENCIL_SIZE',
1016 'GL_RENDERBUFFER_WIDTH',
1017 'GL_RENDERBUFFER_HEIGHT',
1018 'GL_RENDERBUFFER_INTERNAL_FORMAT',
1021 'SamplerParameter': {
1024 'GL_TEXTURE_MAG_FILTER',
1025 'GL_TEXTURE_MIN_FILTER',
1026 'GL_TEXTURE_MIN_LOD',
1027 'GL_TEXTURE_MAX_LOD',
1028 'GL_TEXTURE_WRAP_S',
1029 'GL_TEXTURE_WRAP_T',
1030 'GL_TEXTURE_WRAP_R',
1031 'GL_TEXTURE_COMPARE_MODE',
1032 'GL_TEXTURE_COMPARE_FUNC',
1035 'GL_GENERATE_MIPMAP',
1038 'ShaderParameter': {
1043 'GL_COMPILE_STATUS',
1044 'GL_INFO_LOG_LENGTH',
1045 'GL_SHADER_SOURCE_LENGTH',
1046 'GL_TRANSLATED_SHADER_SOURCE_LENGTH_ANGLE',
1049 'ShaderPrecision': {
1066 'GL_SHADING_LANGUAGE_VERSION',
1070 'TextureParameter': {
1073 'GL_TEXTURE_MAG_FILTER',
1074 'GL_TEXTURE_MIN_FILTER',
1075 'GL_TEXTURE_POOL_CHROMIUM',
1076 'GL_TEXTURE_WRAP_S',
1077 'GL_TEXTURE_WRAP_T',
1080 'GL_GENERATE_MIPMAP',
1086 'GL_TEXTURE_POOL_MANAGED_CHROMIUM',
1087 'GL_TEXTURE_POOL_UNMANAGED_CHROMIUM',
1090 'TextureWrapMode': {
1094 'GL_MIRRORED_REPEAT',
1098 'TextureMinFilterMode': {
1103 'GL_NEAREST_MIPMAP_NEAREST',
1104 'GL_LINEAR_MIPMAP_NEAREST',
1105 'GL_NEAREST_MIPMAP_LINEAR',
1106 'GL_LINEAR_MIPMAP_LINEAR',
1109 'TextureMagFilterMode': {
1120 'GL_FRAMEBUFFER_ATTACHMENT_ANGLE',
1123 'VertexAttribute': {
1126 # some enum that the decoder actually passes through to GL needs
1127 # to be the first listed here since it's used in unit tests.
1128 'GL_VERTEX_ATTRIB_ARRAY_NORMALIZED',
1129 'GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING',
1130 'GL_VERTEX_ATTRIB_ARRAY_ENABLED',
1131 'GL_VERTEX_ATTRIB_ARRAY_SIZE',
1132 'GL_VERTEX_ATTRIB_ARRAY_STRIDE',
1133 'GL_VERTEX_ATTRIB_ARRAY_TYPE',
1134 'GL_CURRENT_VERTEX_ATTRIB',
1140 'GL_VERTEX_ATTRIB_ARRAY_POINTER',
1146 'GL_GENERATE_MIPMAP_HINT',
1149 'GL_PERSPECTIVE_CORRECTION_HINT',
1163 'GL_PACK_ALIGNMENT',
1164 'GL_UNPACK_ALIGNMENT',
1165 'GL_UNPACK_FLIP_Y_CHROMIUM',
1166 'GL_UNPACK_PREMULTIPLY_ALPHA_CHROMIUM',
1167 'GL_UNPACK_UNPREMULTIPLY_ALPHA_CHROMIUM',
1170 'GL_PACK_SWAP_BYTES',
1171 'GL_UNPACK_SWAP_BYTES',
1174 'PixelStoreAlignment': {
1187 'ReadPixelFormat': {
1199 'GL_UNSIGNED_SHORT_5_6_5',
1200 'GL_UNSIGNED_SHORT_4_4_4_4',
1201 'GL_UNSIGNED_SHORT_5_5_5_1',
1212 'GL_UNSIGNED_SHORT_5_6_5',
1213 'GL_UNSIGNED_SHORT_4_4_4_4',
1214 'GL_UNSIGNED_SHORT_5_5_5_1',
1221 'RenderBufferFormat': {
1227 'GL_DEPTH_COMPONENT16',
1228 'GL_STENCIL_INDEX8',
1231 'ShaderBinaryFormat': {
1254 'GL_LUMINANCE_ALPHA',
1263 'TextureInternalFormat': {
1268 'GL_LUMINANCE_ALPHA',
1277 'TextureInternalFormatStorage': {
1284 'GL_LUMINANCE8_EXT',
1285 'GL_LUMINANCE8_ALPHA8_EXT',
1290 'ImageInternalFormat': {
1301 'GL_SCANOUT_CHROMIUM'
1304 'ValueBufferTarget': {
1307 'GL_SUBSCRIBED_VALUES_BUFFER_CHROMIUM',
1310 'SubscriptionTarget': {
1313 'GL_MOUSE_POSITION_CHROMIUM',
1316 'UniformParameter': {
1321 'GL_UNIFORM_NAME_LENGTH',
1322 'GL_UNIFORM_BLOCK_INDEX',
1323 'GL_UNIFORM_OFFSET',
1324 'GL_UNIFORM_ARRAY_STRIDE',
1325 'GL_UNIFORM_MATRIX_STRIDE',
1326 'GL_UNIFORM_IS_ROW_MAJOR',
1329 'GL_UNIFORM_BLOCK_NAME_LENGTH',
1332 'UniformBlockParameter': {
1335 'GL_UNIFORM_BLOCK_BINDING',
1336 'GL_UNIFORM_BLOCK_DATA_SIZE',
1337 'GL_UNIFORM_BLOCK_NAME_LENGTH',
1338 'GL_UNIFORM_BLOCK_ACTIVE_UNIFORMS',
1339 'GL_UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES',
1340 'GL_UNIFORM_BLOCK_REFERENCED_BY_VERTEX_SHADER',
1341 'GL_UNIFORM_BLOCK_REFERENCED_BY_FRAGMENT_SHADER',
1347 'VertexAttribType': {
1353 'GL_UNSIGNED_SHORT',
1354 # 'GL_FIXED', // This is not available on Desktop GL.
1363 'is_complete': True,
1371 'VertexAttribSize': {
1386 'is_complete': True,
1395 'type': 'GLboolean',
1396 'is_complete': True,
1407 'GL_GUILTY_CONTEXT_RESET_ARB',
1408 'GL_INNOCENT_CONTEXT_RESET_ARB',
1409 'GL_UNKNOWN_CONTEXT_RESET_ARB',
1414 'is_complete': True,
1416 'GL_SYNC_GPU_COMMANDS_COMPLETE',
1423 'type': 'GLbitfield',
1424 'is_complete': True,
1433 'type': 'GLbitfield',
1435 'GL_SYNC_FLUSH_COMMANDS_BIT',
1445 'GL_SYNC_STATUS', # This needs to be the 1st; all others are cached.
1447 'GL_SYNC_CONDITION',
1456 # This table specifies the different pepper interfaces that are supported for
1457 # GL commands. 'dev' is true if it's a dev interface.
1458 _PEPPER_INTERFACES
= [
1459 {'name': '', 'dev': False},
1460 {'name': 'InstancedArrays', 'dev': False},
1461 {'name': 'FramebufferBlit', 'dev': False},
1462 {'name': 'FramebufferMultisample', 'dev': False},
1463 {'name': 'ChromiumEnableFeature', 'dev': False},
1464 {'name': 'ChromiumMapSub', 'dev': False},
1465 {'name': 'Query', 'dev': False},
1466 {'name': 'VertexArrayObject', 'dev': False},
1467 {'name': 'DrawBuffers', 'dev': True},
1470 # A function info object specifies the type and other special data for the
1471 # command that will be generated. A base function info object is generated by
1472 # parsing the "cmd_buffer_functions.txt", one for each function in the
1473 # file. These function info objects can be augmented and their values can be
1474 # overridden by adding an object to the table below.
1476 # Must match function names specified in "cmd_buffer_functions.txt".
1478 # cmd_comment: A comment added to the cmd format.
1479 # type: defines which handler will be used to generate code.
1480 # decoder_func: defines which function to call in the decoder to execute the
1481 # corresponding GL command. If not specified the GL command will
1482 # be called directly.
1483 # gl_test_func: GL function that is expected to be called when testing.
1484 # cmd_args: The arguments to use for the command. This overrides generating
1485 # them based on the GL function arguments.
1486 # gen_cmd: Whether or not this function geneates a command. Default = True.
1487 # data_transfer_methods: Array of methods that are used for transfering the
1488 # pointer data. Possible values: 'immediate', 'shm', 'bucket'.
1489 # The default is 'immediate' if the command has one pointer
1490 # argument, otherwise 'shm'. One command is generated for each
1491 # transfer method. Affects only commands which are not of type
1492 # 'HandWritten', 'GETn' or 'GLcharN'.
1493 # Note: the command arguments that affect this are the final args,
1494 # taking cmd_args override into consideration.
1495 # impl_func: Whether or not to generate the GLES2Implementation part of this
1497 # impl_decl: Whether or not to generate the GLES2Implementation declaration
1499 # needs_size: If True a data_size field is added to the command.
1500 # count: The number of units per element. For PUTn or PUT types.
1501 # use_count_func: If True the actual data count needs to be computed; the count
1502 # argument specifies the maximum count.
1503 # unit_test: If False no service side unit test will be generated.
1504 # client_test: If False no client side unit test will be generated.
1505 # expectation: If False the unit test will have no expected calls.
1506 # gen_func: Name of function that generates GL resource for corresponding
1508 # states: array of states that get set by this function corresponding to
1509 # the given arguments
1510 # state_flag: name of flag that is set to true when function is called.
1511 # no_gl: no GL function is called.
1512 # valid_args: A dictionary of argument indices to args to use in unit tests
1513 # when they can not be automatically determined.
1514 # pepper_interface: The pepper interface that is used for this extension
1515 # pepper_name: The name of the function as exposed to pepper.
1516 # pepper_args: A string representing the argument list (what would appear in
1517 # C/C++ between the parentheses for the function declaration)
1518 # that the Pepper API expects for this function. Use this only if
1519 # the stable Pepper API differs from the GLES2 argument list.
1520 # invalid_test: False if no invalid test needed.
1521 # shadowed: True = the value is shadowed so no glGetXXX call will be made.
1522 # first_element_only: For PUT types, True if only the first element of an
1523 # array is used and we end up calling the single value
1524 # corresponding function. eg. TexParameteriv -> TexParameteri
1525 # extension: Function is an extension to GL and should not be exposed to
1526 # pepper unless pepper_interface is defined.
1527 # extension_flag: Function is an extension and should be enabled only when
1528 # the corresponding feature info flag is enabled. Implies
1529 # 'extension': True.
1530 # not_shared: For GENn types, True if objects can't be shared between contexts
1531 # unsafe: True = no validation is implemented on the service side and the
1532 # command is only available with --enable-unsafe-es3-apis.
1533 # id_mapping: A list of resource type names whose client side IDs need to be
1534 # mapped to service side IDs. This is only used for unsafe APIs.
1538 'decoder_func': 'DoActiveTexture',
1541 'client_test': False,
1543 'AttachShader': {'decoder_func': 'DoAttachShader'},
1544 'BindAttribLocation': {
1546 'data_transfer_methods': ['bucket'],
1551 'decoder_func': 'DoBindBuffer',
1552 'gen_func': 'GenBuffersARB',
1556 'id_mapping': [ 'Buffer' ],
1557 'gen_func': 'GenBuffersARB',
1560 'BindBufferRange': {
1562 'id_mapping': [ 'Buffer' ],
1563 'gen_func': 'GenBuffersARB',
1570 'BindFramebuffer': {
1572 'decoder_func': 'DoBindFramebuffer',
1573 'gl_test_func': 'glBindFramebufferEXT',
1574 'gen_func': 'GenFramebuffersEXT',
1577 'BindRenderbuffer': {
1579 'decoder_func': 'DoBindRenderbuffer',
1580 'gl_test_func': 'glBindRenderbufferEXT',
1581 'gen_func': 'GenRenderbuffersEXT',
1585 'id_mapping': [ 'Sampler' ],
1590 'decoder_func': 'DoBindTexture',
1591 'gen_func': 'GenTextures',
1592 # TODO(gman): remove this once client side caching works.
1593 'client_test': False,
1596 'BindTransformFeedback': {
1598 'id_mapping': [ 'TransformFeedback' ],
1601 'BlitFramebufferCHROMIUM': {
1602 'decoder_func': 'DoBlitFramebufferCHROMIUM',
1604 'extension_flag': 'chromium_framebuffer_multisample',
1605 'pepper_interface': 'FramebufferBlit',
1606 'pepper_name': 'BlitFramebufferEXT',
1607 'defer_reads': True,
1608 'defer_draws': True,
1613 'data_transfer_methods': ['shm'],
1614 'client_test': False,
1618 'client_test': False,
1619 'decoder_func': 'DoBufferSubData',
1620 'data_transfer_methods': ['shm'],
1622 'CheckFramebufferStatus': {
1624 'decoder_func': 'DoCheckFramebufferStatus',
1625 'gl_test_func': 'glCheckFramebufferStatusEXT',
1626 'error_value': 'GL_FRAMEBUFFER_UNSUPPORTED',
1627 'result': ['GLenum'],
1630 'decoder_func': 'DoClear',
1631 'defer_draws': True,
1636 'use_count_func': True,
1647 'use_count_func': True,
1656 'state': 'ClearColor',
1660 'state': 'ClearDepthf',
1661 'decoder_func': 'glClearDepth',
1662 'gl_test_func': 'glClearDepth',
1669 'data_transfer_methods': ['shm'],
1670 'cmd_args': 'GLuint sync, GLbitfieldSyncFlushFlags flags, '
1671 'GLuint timeout_0, GLuint timeout_1, GLenum* result',
1673 'result': ['GLenum'],
1677 'state': 'ColorMask',
1679 'expectation': False,
1681 'ConsumeTextureCHROMIUM': {
1682 'decoder_func': 'DoConsumeTextureCHROMIUM',
1685 'count': 64, # GL_MAILBOX_SIZE_CHROMIUM
1687 'client_test': False,
1688 'extension': "CHROMIUM_texture_mailbox",
1692 'CopyBufferSubData': {
1695 'CreateAndConsumeTextureCHROMIUM': {
1696 'decoder_func': 'DoCreateAndConsumeTextureCHROMIUM',
1698 'type': 'HandWritten',
1699 'data_transfer_methods': ['immediate'],
1701 'client_test': False,
1702 'extension': "CHROMIUM_texture_mailbox",
1705 'GenValuebuffersCHROMIUM': {
1707 'gl_test_func': 'glGenValuebuffersCHROMIUM',
1708 'resource_type': 'Valuebuffer',
1709 'resource_types': 'Valuebuffers',
1714 'DeleteValuebuffersCHROMIUM': {
1716 'gl_test_func': 'glDeleteValuebuffersCHROMIUM',
1717 'resource_type': 'Valuebuffer',
1718 'resource_types': 'Valuebuffers',
1723 'IsValuebufferCHROMIUM': {
1725 'decoder_func': 'DoIsValuebufferCHROMIUM',
1726 'expectation': False,
1730 'BindValuebufferCHROMIUM': {
1732 'decoder_func': 'DoBindValueBufferCHROMIUM',
1733 'gen_func': 'GenValueBuffersCHROMIUM',
1738 'SubscribeValueCHROMIUM': {
1739 'decoder_func': 'DoSubscribeValueCHROMIUM',
1744 'PopulateSubscribedValuesCHROMIUM': {
1745 'decoder_func': 'DoPopulateSubscribedValuesCHROMIUM',
1750 'UniformValuebufferCHROMIUM': {
1751 'decoder_func': 'DoUniformValueBufferCHROMIUM',
1758 'state': 'ClearStencil',
1760 'EnableFeatureCHROMIUM': {
1762 'data_transfer_methods': ['shm'],
1763 'decoder_func': 'DoEnableFeatureCHROMIUM',
1764 'expectation': False,
1765 'cmd_args': 'GLuint bucket_id, GLint* result',
1766 'result': ['GLint'],
1769 'pepper_interface': 'ChromiumEnableFeature',
1771 'CompileShader': {'decoder_func': 'DoCompileShader', 'unit_test': False},
1772 'CompressedTexImage2D': {
1774 'data_transfer_methods': ['bucket', 'shm'],
1776 'CompressedTexSubImage2D': {
1778 'data_transfer_methods': ['bucket', 'shm'],
1779 'decoder_func': 'DoCompressedTexSubImage2D',
1782 'decoder_func': 'DoCopyTexImage2D',
1784 'defer_reads': True,
1786 'CopyTexSubImage2D': {
1787 'decoder_func': 'DoCopyTexSubImage2D',
1788 'defer_reads': True,
1790 'CopyTexSubImage3D': {
1791 'defer_reads': True,
1794 'CreateImageCHROMIUM': {
1797 'ClientBuffer buffer, GLsizei width, GLsizei height, '
1798 'GLenum internalformat',
1799 'result': ['GLuint'],
1800 'client_test': False,
1802 'expectation': False,
1806 'DestroyImageCHROMIUM': {
1808 'client_test': False,
1813 'CreateGpuMemoryBufferImageCHROMIUM': {
1816 'GLsizei width, GLsizei height, GLenum internalformat, GLenum usage',
1817 'result': ['GLuint'],
1818 'client_test': False,
1820 'expectation': False,
1826 'client_test': False,
1830 'client_test': False,
1834 'state': 'BlendColor',
1837 'type': 'StateSetRGBAlpha',
1838 'state': 'BlendEquation',
1840 '0': 'GL_FUNC_SUBTRACT'
1843 'BlendEquationSeparate': {
1845 'state': 'BlendEquation',
1847 '0': 'GL_FUNC_SUBTRACT'
1851 'type': 'StateSetRGBAlpha',
1852 'state': 'BlendFunc',
1854 'BlendFuncSeparate': {
1856 'state': 'BlendFunc',
1858 'BlendBarrierKHR': {
1859 'gl_test_func': 'glBlendBarrierKHR',
1861 'extension_flag': 'blend_equation_advanced',
1862 'client_test': False,
1864 'SampleCoverage': {'decoder_func': 'DoSampleCoverage'},
1866 'type': 'StateSetFrontBack',
1867 'state': 'StencilFunc',
1869 'StencilFuncSeparate': {
1870 'type': 'StateSetFrontBackSeparate',
1871 'state': 'StencilFunc',
1874 'type': 'StateSetFrontBack',
1875 'state': 'StencilOp',
1880 'StencilOpSeparate': {
1881 'type': 'StateSetFrontBackSeparate',
1882 'state': 'StencilOp',
1888 'type': 'StateSetNamedParameter',
1891 'CullFace': {'type': 'StateSet', 'state': 'CullFace'},
1892 'FrontFace': {'type': 'StateSet', 'state': 'FrontFace'},
1893 'DepthFunc': {'type': 'StateSet', 'state': 'DepthFunc'},
1896 'state': 'LineWidth',
1903 'state': 'PolygonOffset',
1907 'gl_test_func': 'glDeleteBuffersARB',
1908 'resource_type': 'Buffer',
1909 'resource_types': 'Buffers',
1911 'DeleteFramebuffers': {
1913 'gl_test_func': 'glDeleteFramebuffersEXT',
1914 'resource_type': 'Framebuffer',
1915 'resource_types': 'Framebuffers',
1917 'DeleteProgram': { 'type': 'Delete' },
1918 'DeleteRenderbuffers': {
1920 'gl_test_func': 'glDeleteRenderbuffersEXT',
1921 'resource_type': 'Renderbuffer',
1922 'resource_types': 'Renderbuffers',
1926 'resource_type': 'Sampler',
1927 'resource_types': 'Samplers',
1930 'DeleteShader': { 'type': 'Delete' },
1933 'cmd_args': 'GLuint sync',
1934 'resource_type': 'Sync',
1939 'resource_type': 'Texture',
1940 'resource_types': 'Textures',
1942 'DeleteTransformFeedbacks': {
1944 'resource_type': 'TransformFeedback',
1945 'resource_types': 'TransformFeedbacks',
1949 'decoder_func': 'DoDepthRangef',
1950 'gl_test_func': 'glDepthRange',
1954 'state': 'DepthMask',
1956 'expectation': False,
1958 'DetachShader': {'decoder_func': 'DoDetachShader'},
1960 'decoder_func': 'DoDisable',
1962 'client_test': False,
1964 'DisableVertexAttribArray': {
1965 'decoder_func': 'DoDisableVertexAttribArray',
1970 'cmd_args': 'GLenumDrawMode mode, GLint first, GLsizei count',
1971 'defer_draws': True,
1976 'cmd_args': 'GLenumDrawMode mode, GLsizei count, '
1977 'GLenumIndexType type, GLuint index_offset',
1978 'client_test': False,
1979 'defer_draws': True,
1983 'decoder_func': 'DoEnable',
1985 'client_test': False,
1987 'EnableVertexAttribArray': {
1988 'decoder_func': 'DoEnableVertexAttribArray',
1993 'client_test': False,
1998 'client_test': False,
1999 'decoder_func': 'DoFinish',
2000 'defer_reads': True,
2004 'decoder_func': 'DoFlush',
2006 'FramebufferRenderbuffer': {
2007 'decoder_func': 'DoFramebufferRenderbuffer',
2008 'gl_test_func': 'glFramebufferRenderbufferEXT',
2010 'FramebufferTexture2D': {
2011 'decoder_func': 'DoFramebufferTexture2D',
2012 'gl_test_func': 'glFramebufferTexture2DEXT',
2015 'FramebufferTexture2DMultisampleEXT': {
2016 'decoder_func': 'DoFramebufferTexture2DMultisample',
2017 'gl_test_func': 'glFramebufferTexture2DMultisampleEXT',
2018 'expectation': False,
2020 'extension_flag': 'multisampled_render_to_texture',
2023 'FramebufferTextureLayer': {
2024 'decoder_func': 'DoFramebufferTextureLayer',
2028 'decoder_func': 'DoGenerateMipmap',
2029 'gl_test_func': 'glGenerateMipmapEXT',
2033 'gl_test_func': 'glGenBuffersARB',
2034 'resource_type': 'Buffer',
2035 'resource_types': 'Buffers',
2037 'GenMailboxCHROMIUM': {
2038 'type': 'HandWritten',
2040 'extension': "CHROMIUM_texture_mailbox",
2043 'GenFramebuffers': {
2045 'gl_test_func': 'glGenFramebuffersEXT',
2046 'resource_type': 'Framebuffer',
2047 'resource_types': 'Framebuffers',
2049 'GenRenderbuffers': {
2050 'type': 'GENn', 'gl_test_func': 'glGenRenderbuffersEXT',
2051 'resource_type': 'Renderbuffer',
2052 'resource_types': 'Renderbuffers',
2056 'gl_test_func': 'glGenSamplers',
2057 'resource_type': 'Sampler',
2058 'resource_types': 'Samplers',
2063 'gl_test_func': 'glGenTextures',
2064 'resource_type': 'Texture',
2065 'resource_types': 'Textures',
2067 'GenTransformFeedbacks': {
2069 'gl_test_func': 'glGenTransformFeedbacks',
2070 'resource_type': 'TransformFeedback',
2071 'resource_types': 'TransformFeedbacks',
2074 'GetActiveAttrib': {
2076 'data_transfer_methods': ['shm'],
2078 'GLidProgram program, GLuint index, uint32_t name_bucket_id, '
2086 'GetActiveUniform': {
2088 'data_transfer_methods': ['shm'],
2090 'GLidProgram program, GLuint index, uint32_t name_bucket_id, '
2098 'GetActiveUniformBlockiv': {
2100 'data_transfer_methods': ['shm'],
2101 'result': ['SizedResult<GLint>'],
2104 'GetActiveUniformBlockName': {
2106 'data_transfer_methods': ['shm'],
2108 'GLidProgram program, GLuint index, uint32_t name_bucket_id, '
2110 'result': ['int32_t'],
2113 'GetActiveUniformsiv': {
2115 'data_transfer_methods': ['shm'],
2117 'GLidProgram program, uint32_t indices_bucket_id, GLenum pname, '
2119 'result': ['SizedResult<GLint>'],
2122 'GetAttachedShaders': {
2124 'data_transfer_methods': ['shm'],
2125 'cmd_args': 'GLidProgram program, void* result, uint32_t result_size',
2126 'result': ['SizedResult<GLuint>'],
2128 'GetAttribLocation': {
2130 'data_transfer_methods': ['shm'],
2132 'GLidProgram program, uint32_t name_bucket_id, GLint* location',
2133 'result': ['GLint'],
2136 'GetFragDataLocation': {
2138 'data_transfer_methods': ['shm'],
2140 'GLidProgram program, uint32_t name_bucket_id, GLint* location',
2141 'result': ['GLint'],
2147 'result': ['SizedResult<GLboolean>'],
2148 'decoder_func': 'DoGetBooleanv',
2149 'gl_test_func': 'glGetBooleanv',
2151 'GetBufferParameteriv': {
2153 'result': ['SizedResult<GLint>'],
2154 'decoder_func': 'DoGetBufferParameteriv',
2155 'expectation': False,
2160 'decoder_func': 'GetErrorState()->GetGLError',
2162 'result': ['GLenum'],
2163 'client_test': False,
2167 'result': ['SizedResult<GLfloat>'],
2168 'decoder_func': 'DoGetFloatv',
2169 'gl_test_func': 'glGetFloatv',
2171 'GetFramebufferAttachmentParameteriv': {
2173 'decoder_func': 'DoGetFramebufferAttachmentParameteriv',
2174 'gl_test_func': 'glGetFramebufferAttachmentParameterivEXT',
2175 'result': ['SizedResult<GLint>'],
2179 'result': ['SizedResult<GLint>'],
2180 'decoder_func': 'DoGetIntegerv',
2181 'client_test': False,
2183 'GetInternalformativ': {
2185 'result': ['SizedResult<GLint>'],
2188 'GetMaxValueInBufferCHROMIUM': {
2190 'decoder_func': 'DoGetMaxValueInBufferCHROMIUM',
2191 'result': ['GLuint'],
2193 'client_test': False,
2200 'decoder_func': 'DoGetProgramiv',
2201 'result': ['SizedResult<GLint>'],
2202 'expectation': False,
2204 'GetProgramInfoCHROMIUM': {
2206 'expectation': False,
2210 'client_test': False,
2211 'cmd_args': 'GLidProgram program, uint32_t bucket_id',
2213 'uint32_t link_status',
2214 'uint32_t num_attribs',
2215 'uint32_t num_uniforms',
2218 'GetProgramInfoLog': {
2220 'expectation': False,
2222 'GetRenderbufferParameteriv': {
2224 'decoder_func': 'DoGetRenderbufferParameteriv',
2225 'gl_test_func': 'glGetRenderbufferParameterivEXT',
2226 'result': ['SizedResult<GLint>'],
2228 'GetSamplerParameterfv': {
2230 'result': ['SizedResult<GLfloat>'],
2231 'id_mapping': [ 'Sampler' ],
2234 'GetSamplerParameteriv': {
2236 'result': ['SizedResult<GLint>'],
2237 'id_mapping': [ 'Sampler' ],
2242 'decoder_func': 'DoGetShaderiv',
2243 'result': ['SizedResult<GLint>'],
2245 'GetShaderInfoLog': {
2247 'get_len_func': 'glGetShaderiv',
2248 'get_len_enum': 'GL_INFO_LOG_LENGTH',
2251 'GetShaderPrecisionFormat': {
2253 'data_transfer_methods': ['shm'],
2255 'GLenumShaderType shadertype, GLenumShaderPrecision precisiontype, '
2259 'int32_t min_range',
2260 'int32_t max_range',
2261 'int32_t precision',
2264 'GetShaderSource': {
2266 'get_len_func': 'DoGetShaderiv',
2267 'get_len_enum': 'GL_SHADER_SOURCE_LENGTH',
2269 'client_test': False,
2273 'client_test': False,
2274 'cmd_args': 'GLenumStringType name, uint32_t bucket_id',
2278 'cmd_args': 'GLuint sync, GLenumSyncParameter pname, void* values',
2279 'result': ['SizedResult<GLint>'],
2280 'id_mapping': ['Sync'],
2283 'GetTexParameterfv': {
2285 'decoder_func': 'DoGetTexParameterfv',
2286 'result': ['SizedResult<GLfloat>']
2288 'GetTexParameteriv': {
2290 'decoder_func': 'DoGetTexParameteriv',
2291 'result': ['SizedResult<GLint>']
2293 'GetTranslatedShaderSourceANGLE': {
2295 'get_len_func': 'DoGetShaderiv',
2296 'get_len_enum': 'GL_TRANSLATED_SHADER_SOURCE_LENGTH_ANGLE',
2300 'GetUniformBlockIndex': {
2302 'data_transfer_methods': ['shm'],
2304 'GLidProgram program, uint32_t name_bucket_id, GLuint* index',
2305 'result': ['GLuint'],
2306 'error_return': 'GL_INVALID_INDEX',
2309 'GetUniformBlocksCHROMIUM': {
2311 'expectation': False,
2315 'client_test': False,
2316 'cmd_args': 'GLidProgram program, uint32_t bucket_id',
2317 'result': ['uint32_t'],
2320 'GetUniformsES3CHROMIUM': {
2322 'expectation': False,
2326 'client_test': False,
2327 'cmd_args': 'GLidProgram program, uint32_t bucket_id',
2328 'result': ['uint32_t'],
2331 'GetTransformFeedbackVarying': {
2333 'data_transfer_methods': ['shm'],
2335 'GLidProgram program, GLuint index, uint32_t name_bucket_id, '
2344 'GetTransformFeedbackVaryingsCHROMIUM': {
2346 'expectation': False,
2350 'client_test': False,
2351 'cmd_args': 'GLidProgram program, uint32_t bucket_id',
2352 'result': ['uint32_t'],
2357 'data_transfer_methods': ['shm'],
2358 'result': ['SizedResult<GLfloat>'],
2362 'data_transfer_methods': ['shm'],
2363 'result': ['SizedResult<GLint>'],
2365 'GetUniformIndices': {
2367 'data_transfer_methods': ['shm'],
2368 'result': ['SizedResult<GLuint>'],
2369 'cmd_args': 'GLidProgram program, uint32_t names_bucket_id, '
2373 'GetUniformLocation': {
2375 'data_transfer_methods': ['shm'],
2377 'GLidProgram program, uint32_t name_bucket_id, GLint* location',
2378 'result': ['GLint'],
2379 'error_return': -1, # http://www.opengl.org/sdk/docs/man/xhtml/glGetUniformLocation.xml
2381 'GetVertexAttribfv': {
2383 'result': ['SizedResult<GLfloat>'],
2385 'decoder_func': 'DoGetVertexAttribfv',
2386 'expectation': False,
2387 'client_test': False,
2389 'GetVertexAttribiv': {
2391 'result': ['SizedResult<GLint>'],
2393 'decoder_func': 'DoGetVertexAttribiv',
2394 'expectation': False,
2395 'client_test': False,
2397 'GetVertexAttribPointerv': {
2399 'data_transfer_methods': ['shm'],
2400 'result': ['SizedResult<GLuint>'],
2401 'client_test': False,
2403 'InvalidateFramebuffer': {
2406 'client_test': False,
2410 'InvalidateSubFramebuffer': {
2413 'client_test': False,
2419 'decoder_func': 'DoIsBuffer',
2420 'expectation': False,
2424 'decoder_func': 'DoIsEnabled',
2425 'client_test': False,
2427 'expectation': False,
2431 'decoder_func': 'DoIsFramebuffer',
2432 'expectation': False,
2436 'decoder_func': 'DoIsProgram',
2437 'expectation': False,
2441 'decoder_func': 'DoIsRenderbuffer',
2442 'expectation': False,
2446 'decoder_func': 'DoIsShader',
2447 'expectation': False,
2451 'id_mapping': [ 'Sampler' ],
2452 'expectation': False,
2457 'id_mapping': [ 'Sync' ],
2458 'cmd_args': 'GLuint sync',
2459 'expectation': False,
2464 'decoder_func': 'DoIsTexture',
2465 'expectation': False,
2467 'IsTransformFeedback': {
2469 'id_mapping': [ 'TransformFeedback' ],
2470 'expectation': False,
2474 'decoder_func': 'DoLinkProgram',
2477 'MapBufferCHROMIUM': {
2481 'client_test': False,
2483 'MapBufferSubDataCHROMIUM': {
2487 'client_test': False,
2488 'pepper_interface': 'ChromiumMapSub',
2490 'MapTexSubImage2DCHROMIUM': {
2494 'client_test': False,
2495 'pepper_interface': 'ChromiumMapSub',
2497 'PauseTransformFeedback': {
2500 'PixelStorei': {'type': 'Manual'},
2501 'PostSubBufferCHROMIUM': {
2505 'client_test': False,
2509 'ProduceTextureCHROMIUM': {
2510 'decoder_func': 'DoProduceTextureCHROMIUM',
2513 'count': 64, # GL_MAILBOX_SIZE_CHROMIUM
2515 'client_test': False,
2516 'extension': "CHROMIUM_texture_mailbox",
2520 'ProduceTextureDirectCHROMIUM': {
2521 'decoder_func': 'DoProduceTextureDirectCHROMIUM',
2524 'count': 64, # GL_MAILBOX_SIZE_CHROMIUM
2526 'client_test': False,
2527 'extension': "CHROMIUM_texture_mailbox",
2531 'RenderbufferStorage': {
2532 'decoder_func': 'DoRenderbufferStorage',
2533 'gl_test_func': 'glRenderbufferStorageEXT',
2534 'expectation': False,
2536 'RenderbufferStorageMultisampleCHROMIUM': {
2538 '// GL_CHROMIUM_framebuffer_multisample\n',
2539 'decoder_func': 'DoRenderbufferStorageMultisampleCHROMIUM',
2540 'gl_test_func': 'glRenderbufferStorageMultisampleCHROMIUM',
2541 'expectation': False,
2543 'extension_flag': 'chromium_framebuffer_multisample',
2544 'pepper_interface': 'FramebufferMultisample',
2545 'pepper_name': 'RenderbufferStorageMultisampleEXT',
2547 'RenderbufferStorageMultisampleEXT': {
2549 '// GL_EXT_multisampled_render_to_texture\n',
2550 'decoder_func': 'DoRenderbufferStorageMultisampleEXT',
2551 'gl_test_func': 'glRenderbufferStorageMultisampleEXT',
2552 'expectation': False,
2554 'extension_flag': 'multisampled_render_to_texture',
2561 '// ReadPixels has the result separated from the pixel buffer so that\n'
2562 '// it is easier to specify the result going to some specific place\n'
2563 '// that exactly fits the rectangle of pixels.\n',
2565 'data_transfer_methods': ['shm'],
2567 'client_test': False,
2569 'GLint x, GLint y, GLsizei width, GLsizei height, '
2570 'GLenumReadPixelFormat format, GLenumReadPixelType type, '
2571 'uint32_t pixels_shm_id, uint32_t pixels_shm_offset, '
2572 'uint32_t result_shm_id, uint32_t result_shm_offset, '
2574 'result': ['uint32_t'],
2575 'defer_reads': True,
2577 'ReleaseShaderCompiler': {
2578 'decoder_func': 'DoReleaseShaderCompiler',
2581 'ResumeTransformFeedback': {
2584 'SamplerParameterf': {
2588 'id_mapping': [ 'Sampler' ],
2591 'SamplerParameterfv': {
2593 'data_value': 'GL_NEAREST',
2595 'gl_test_func': 'glSamplerParameterf',
2596 'decoder_func': 'DoSamplerParameterfv',
2597 'first_element_only': True,
2598 'id_mapping': [ 'Sampler' ],
2601 'SamplerParameteri': {
2605 'id_mapping': [ 'Sampler' ],
2608 'SamplerParameteriv': {
2610 'data_value': 'GL_NEAREST',
2612 'gl_test_func': 'glSamplerParameteri',
2613 'decoder_func': 'DoSamplerParameteriv',
2614 'first_element_only': True,
2619 'client_test': False,
2623 'decoder_func': 'DoShaderSource',
2624 'expectation': False,
2625 'data_transfer_methods': ['bucket'],
2627 'GLuint shader, const char** str',
2629 'GLuint shader, GLsizei count, const char** str, const GLint* length',
2632 'type': 'StateSetFrontBack',
2633 'state': 'StencilMask',
2635 'expectation': False,
2637 'StencilMaskSeparate': {
2638 'type': 'StateSetFrontBackSeparate',
2639 'state': 'StencilMask',
2641 'expectation': False,
2645 'decoder_func': 'DoSwapBuffers',
2647 'client_test': False,
2653 'decoder_func': 'DoSwapInterval',
2655 'client_test': False,
2661 'data_transfer_methods': ['shm'],
2662 'client_test': False,
2666 'data_transfer_methods': ['shm'],
2667 'client_test': False,
2671 'decoder_func': 'DoTexParameterf',
2677 'decoder_func': 'DoTexParameteri',
2684 'data_value': 'GL_NEAREST',
2686 'decoder_func': 'DoTexParameterfv',
2687 'gl_test_func': 'glTexParameterf',
2688 'first_element_only': True,
2692 'data_value': 'GL_NEAREST',
2694 'decoder_func': 'DoTexParameteriv',
2695 'gl_test_func': 'glTexParameteri',
2696 'first_element_only': True,
2703 'data_transfer_methods': ['shm'],
2704 'client_test': False,
2705 'cmd_args': 'GLenumTextureTarget target, GLint level, '
2706 'GLint xoffset, GLint yoffset, '
2707 'GLsizei width, GLsizei height, '
2708 'GLenumTextureFormat format, GLenumPixelType type, '
2709 'const void* pixels, GLboolean internal'
2713 'data_transfer_methods': ['shm'],
2714 'client_test': False,
2715 'cmd_args': 'GLenumTextureTarget target, GLint level, '
2716 'GLint xoffset, GLint yoffset, GLint zoffset, '
2717 'GLsizei width, GLsizei height, GLsizei depth, '
2718 'GLenumTextureFormat format, GLenumPixelType type, '
2719 'const void* pixels, GLboolean internal',
2722 'TransformFeedbackVaryings': {
2724 'data_transfer_methods': ['bucket'],
2725 'decoder_func': 'DoTransformFeedbackVaryings',
2727 'GLuint program, const char** varyings, GLenum buffermode',
2730 'Uniform1f': {'type': 'PUTXn', 'count': 1},
2734 'decoder_func': 'DoUniform1fv',
2736 'Uniform1i': {'decoder_func': 'DoUniform1i', 'unit_test': False},
2740 'decoder_func': 'DoUniform1iv',
2753 'Uniform2i': {'type': 'PUTXn', 'count': 2},
2754 'Uniform2f': {'type': 'PUTXn', 'count': 2},
2758 'decoder_func': 'DoUniform2fv',
2763 'decoder_func': 'DoUniform2iv',
2775 'Uniform3i': {'type': 'PUTXn', 'count': 3},
2776 'Uniform3f': {'type': 'PUTXn', 'count': 3},
2780 'decoder_func': 'DoUniform3fv',
2785 'decoder_func': 'DoUniform3iv',
2797 'Uniform4i': {'type': 'PUTXn', 'count': 4},
2798 'Uniform4f': {'type': 'PUTXn', 'count': 4},
2802 'decoder_func': 'DoUniform4fv',
2807 'decoder_func': 'DoUniform4iv',
2819 'UniformMatrix2fv': {
2822 'decoder_func': 'DoUniformMatrix2fv',
2824 'UniformMatrix2x3fv': {
2829 'UniformMatrix2x4fv': {
2834 'UniformMatrix3fv': {
2837 'decoder_func': 'DoUniformMatrix3fv',
2839 'UniformMatrix3x2fv': {
2844 'UniformMatrix3x4fv': {
2849 'UniformMatrix4fv': {
2852 'decoder_func': 'DoUniformMatrix4fv',
2854 'UniformMatrix4x2fv': {
2859 'UniformMatrix4x3fv': {
2864 'UniformBlockBinding': {
2869 'UnmapBufferCHROMIUM': {
2873 'client_test': False,
2875 'UnmapBufferSubDataCHROMIUM': {
2879 'client_test': False,
2880 'pepper_interface': 'ChromiumMapSub',
2882 'UnmapTexSubImage2DCHROMIUM': {
2886 'client_test': False,
2887 'pepper_interface': 'ChromiumMapSub',
2891 'decoder_func': 'DoUseProgram',
2893 'ValidateProgram': {'decoder_func': 'DoValidateProgram'},
2894 'VertexAttrib1f': {'decoder_func': 'DoVertexAttrib1f'},
2895 'VertexAttrib1fv': {
2898 'decoder_func': 'DoVertexAttrib1fv',
2900 'VertexAttrib2f': {'decoder_func': 'DoVertexAttrib2f'},
2901 'VertexAttrib2fv': {
2904 'decoder_func': 'DoVertexAttrib2fv',
2906 'VertexAttrib3f': {'decoder_func': 'DoVertexAttrib3f'},
2907 'VertexAttrib3fv': {
2910 'decoder_func': 'DoVertexAttrib3fv',
2912 'VertexAttrib4f': {'decoder_func': 'DoVertexAttrib4f'},
2913 'VertexAttrib4fv': {
2916 'decoder_func': 'DoVertexAttrib4fv',
2918 'VertexAttribI4i': {
2921 'VertexAttribI4iv': {
2926 'VertexAttribI4ui': {
2929 'VertexAttribI4uiv': {
2934 'VertexAttribIPointer': {
2936 'cmd_args': 'GLuint indx, GLintVertexAttribSize size, '
2937 'GLenumVertexAttribType type, GLsizei stride, '
2939 'client_test': False,
2942 'VertexAttribPointer': {
2944 'cmd_args': 'GLuint indx, GLintVertexAttribSize size, '
2945 'GLenumVertexAttribType type, GLboolean normalized, '
2946 'GLsizei stride, GLuint offset',
2947 'client_test': False,
2951 'cmd_args': 'GLuint sync, GLbitfieldSyncFlushFlags flags, '
2952 'GLuint timeout_0, GLuint timeout_1',
2954 'client_test': False,
2962 'decoder_func': 'DoViewport',
2971 'GetRequestableExtensionsCHROMIUM': {
2974 'cmd_args': 'uint32_t bucket_id',
2978 'RequestExtensionCHROMIUM': {
2981 'client_test': False,
2982 'cmd_args': 'uint32_t bucket_id',
2986 'RateLimitOffscreenContextCHROMIUM': {
2990 'client_test': False,
2992 'CreateStreamTextureCHROMIUM': {
2993 'type': 'HandWritten',
2999 'TexImageIOSurface2DCHROMIUM': {
3000 'decoder_func': 'DoTexImageIOSurface2DCHROMIUM',
3005 'CopyTextureCHROMIUM': {
3006 'decoder_func': 'DoCopyTextureCHROMIUM',
3011 'TexStorage2DEXT': {
3014 'decoder_func': 'DoTexStorage2DEXT',
3016 'DrawArraysInstancedANGLE': {
3018 'cmd_args': 'GLenumDrawMode mode, GLint first, GLsizei count, '
3019 'GLsizei primcount',
3022 'pepper_interface': 'InstancedArrays',
3023 'defer_draws': True,
3027 'decoder_func': 'DoDrawBuffersEXT',
3029 'client_test': False,
3031 # could use 'extension_flag': 'ext_draw_buffers' but currently expected to
3034 'pepper_interface': 'DrawBuffers',
3036 'DrawElementsInstancedANGLE': {
3038 'cmd_args': 'GLenumDrawMode mode, GLsizei count, '
3039 'GLenumIndexType type, GLuint index_offset, GLsizei primcount',
3042 'client_test': False,
3043 'pepper_interface': 'InstancedArrays',
3044 'defer_draws': True,
3046 'VertexAttribDivisorANGLE': {
3048 'cmd_args': 'GLuint index, GLuint divisor',
3051 'pepper_interface': 'InstancedArrays',
3055 'gl_test_func': 'glGenQueriesARB',
3056 'resource_type': 'Query',
3057 'resource_types': 'Queries',
3059 'pepper_interface': 'Query',
3060 'not_shared': 'True',
3062 'DeleteQueriesEXT': {
3064 'gl_test_func': 'glDeleteQueriesARB',
3065 'resource_type': 'Query',
3066 'resource_types': 'Queries',
3068 'pepper_interface': 'Query',
3072 'client_test': False,
3073 'pepper_interface': 'Query',
3077 'cmd_args': 'GLenumQueryTarget target, GLidQuery id, void* sync_data',
3078 'data_transfer_methods': ['shm'],
3079 'gl_test_func': 'glBeginQuery',
3080 'pepper_interface': 'Query',
3082 'BeginTransformFeedback': {
3087 'cmd_args': 'GLenumQueryTarget target, GLuint submit_count',
3088 'gl_test_func': 'glEndnQuery',
3089 'client_test': False,
3090 'pepper_interface': 'Query',
3092 'EndTransformFeedback': {
3097 'client_test': False,
3098 'gl_test_func': 'glGetQueryiv',
3099 'pepper_interface': 'Query',
3101 'GetQueryObjectuivEXT': {
3103 'client_test': False,
3104 'gl_test_func': 'glGetQueryObjectuiv',
3105 'pepper_interface': 'Query',
3107 'BindUniformLocationCHROMIUM': {
3110 'data_transfer_methods': ['bucket'],
3112 'gl_test_func': 'DoBindUniformLocationCHROMIUM',
3114 'InsertEventMarkerEXT': {
3116 'decoder_func': 'DoInsertEventMarkerEXT',
3117 'expectation': False,
3120 'PushGroupMarkerEXT': {
3122 'decoder_func': 'DoPushGroupMarkerEXT',
3123 'expectation': False,
3126 'PopGroupMarkerEXT': {
3127 'decoder_func': 'DoPopGroupMarkerEXT',
3128 'expectation': False,
3133 'GenVertexArraysOES': {
3136 'gl_test_func': 'glGenVertexArraysOES',
3137 'resource_type': 'VertexArray',
3138 'resource_types': 'VertexArrays',
3140 'pepper_interface': 'VertexArrayObject',
3142 'BindVertexArrayOES': {
3145 'gl_test_func': 'glBindVertexArrayOES',
3146 'decoder_func': 'DoBindVertexArrayOES',
3147 'gen_func': 'GenVertexArraysOES',
3149 'client_test': False,
3150 'pepper_interface': 'VertexArrayObject',
3152 'DeleteVertexArraysOES': {
3155 'gl_test_func': 'glDeleteVertexArraysOES',
3156 'resource_type': 'VertexArray',
3157 'resource_types': 'VertexArrays',
3159 'pepper_interface': 'VertexArrayObject',
3161 'IsVertexArrayOES': {
3164 'gl_test_func': 'glIsVertexArrayOES',
3165 'decoder_func': 'DoIsVertexArrayOES',
3166 'expectation': False,
3168 'pepper_interface': 'VertexArrayObject',
3170 'BindTexImage2DCHROMIUM': {
3171 'decoder_func': 'DoBindTexImage2DCHROMIUM',
3176 'ReleaseTexImage2DCHROMIUM': {
3177 'decoder_func': 'DoReleaseTexImage2DCHROMIUM',
3182 'ShallowFinishCHROMIUM': {
3187 'client_test': False,
3189 'ShallowFlushCHROMIUM': {
3194 'client_test': False,
3196 'OrderingBarrierCHROMIUM': {
3201 'client_test': False,
3203 'TraceBeginCHROMIUM': {
3206 'client_test': False,
3207 'cmd_args': 'GLuint category_bucket_id, GLuint name_bucket_id',
3211 'TraceEndCHROMIUM': {
3213 'client_test': False,
3214 'decoder_func': 'DoTraceEndCHROMIUM',
3219 'AsyncTexImage2DCHROMIUM': {
3221 'data_transfer_methods': ['shm'],
3222 'client_test': False,
3223 'cmd_args': 'GLenumTextureTarget target, GLint level, '
3224 'GLintTextureInternalFormat internalformat, '
3225 'GLsizei width, GLsizei height, '
3226 'GLintTextureBorder border, '
3227 'GLenumTextureFormat format, GLenumPixelType type, '
3228 'const void* pixels, '
3229 'uint32_t async_upload_token, '
3234 'AsyncTexSubImage2DCHROMIUM': {
3236 'data_transfer_methods': ['shm'],
3237 'client_test': False,
3238 'cmd_args': 'GLenumTextureTarget target, GLint level, '
3239 'GLint xoffset, GLint yoffset, '
3240 'GLsizei width, GLsizei height, '
3241 'GLenumTextureFormat format, GLenumPixelType type, '
3242 'const void* data, '
3243 'uint32_t async_upload_token, '
3248 'WaitAsyncTexImage2DCHROMIUM': {
3250 'client_test': False,
3254 'WaitAllAsyncTexImage2DCHROMIUM': {
3256 'client_test': False,
3260 'DiscardFramebufferEXT': {
3263 'decoder_func': 'DoDiscardFramebufferEXT',
3265 'client_test': False,
3266 'extension_flag': 'ext_discard_framebuffer',
3268 'LoseContextCHROMIUM': {
3269 'decoder_func': 'DoLoseContextCHROMIUM',
3274 'InsertSyncPointCHROMIUM': {
3275 'type': 'HandWritten',
3277 'extension': "CHROMIUM_sync_point",
3280 'WaitSyncPointCHROMIUM': {
3283 'extension': "CHROMIUM_sync_point",
3287 'DiscardBackbufferCHROMIUM': {
3293 'ScheduleOverlayPlaneCHROMIUM': {
3297 'client_test': False,
3301 'MatrixLoadfCHROMIUM': {
3304 'data_type': 'GLfloat',
3305 'decoder_func': 'DoMatrixLoadfCHROMIUM',
3306 'gl_test_func': 'glMatrixLoadfEXT',
3309 'extension_flag': 'chromium_path_rendering',
3311 'MatrixLoadIdentityCHROMIUM': {
3312 'decoder_func': 'DoMatrixLoadIdentityCHROMIUM',
3313 'gl_test_func': 'glMatrixLoadIdentityEXT',
3316 'extension_flag': 'chromium_path_rendering',
3321 def Grouper(n
, iterable
, fillvalue
=None):
3322 """Collect data into fixed-length chunks or blocks"""
3323 args
= [iter(iterable
)] * n
3324 return itertools
.izip_longest(fillvalue
=fillvalue
, *args
)
3327 def SplitWords(input_string
):
3328 """Transforms a input_string into a list of lower-case components.
3331 input_string: the input string.
3334 a list of lower-case words.
3336 if input_string
.find('_') > -1:
3337 # 'some_TEXT_' -> 'some text'
3338 return input_string
.replace('_', ' ').strip().lower().split()
3340 if re
.search('[A-Z]', input_string
) and re
.search('[a-z]', input_string
):
3342 # look for capitalization to cut input_strings
3343 # 'SomeText' -> 'Some Text'
3344 input_string
= re
.sub('([A-Z])', r
' \1', input_string
).strip()
3345 # 'Vector3' -> 'Vector 3'
3346 input_string
= re
.sub('([^0-9])([0-9])', r
'\1 \2', input_string
)
3347 return input_string
.lower().split()
3351 """Makes a lower-case identifier from words.
3354 words: a list of lower-case words.
3357 the lower-case identifier.
3359 return '_'.join(words
)
3362 def ToUnderscore(input_string
):
3363 """converts CamelCase to camel_case."""
3364 words
= SplitWords(input_string
)
3367 def CachedStateName(item
):
3368 if item
.get('cached', False):
3369 return 'cached_' + item
['name']
3372 def ToGLExtensionString(extension_flag
):
3373 """Returns GL-type extension string of a extension flag."""
3374 if extension_flag
== "oes_compressed_etc1_rgb8_texture":
3375 return "OES_compressed_ETC1_RGB8_texture" # Fixup inconsitency with rgb8,
3377 uppercase_words
= [ 'img', 'ext', 'arb', 'chromium', 'oes', 'amd', 'bgra8888',
3378 'egl', 'atc', 'etc1', 'angle']
3379 parts
= extension_flag
.split('_')
3381 [part
.upper() if part
in uppercase_words
else part
for part
in parts
])
3383 def ToCamelCase(input_string
):
3384 """converts ABC_underscore_case to ABCUnderscoreCase."""
3385 return ''.join(w
[0].upper() + w
[1:] for w
in input_string
.split('_'))
3387 def GetGLGetTypeConversion(result_type
, value_type
, value
):
3388 """Makes a gl compatible type conversion string for accessing state variables.
3390 Useful when accessing state variables through glGetXXX calls.
3391 glGet documetation (for example, the manual pages):
3392 [...] If glGetIntegerv is called, [...] most floating-point values are
3393 rounded to the nearest integer value. [...]
3396 result_type: the gl type to be obtained
3397 value_type: the GL type of the state variable
3398 value: the name of the state variable
3401 String that converts the state variable to desired GL type according to GL
3405 if result_type
== 'GLint':
3406 if value_type
== 'GLfloat':
3407 return 'static_cast<GLint>(round(%s))' % value
3408 return 'static_cast<%s>(%s)' % (result_type
, value
)
3410 class CWriter(object):
3411 """Writes to a file formatting it for Google's style guidelines."""
3413 def __init__(self
, filename
):
3414 self
.filename
= filename
3417 def Write(self
, string
):
3418 """Writes a string to a file spliting if it's > 80 characters."""
3419 lines
= string
.splitlines()
3420 num_lines
= len(lines
)
3421 for ii
in range(0, num_lines
):
3422 self
.content
.append(lines
[ii
])
3423 if ii
< (num_lines
- 1) or string
[-1] == '\n':
3424 self
.content
.append('\n')
3427 """Close the file."""
3428 content
= "".join(self
.content
)
3430 if os
.path
.exists(self
.filename
):
3431 old_file
= open(self
.filename
, "rb");
3432 old_content
= old_file
.read()
3434 if content
== old_content
:
3437 file = open(self
.filename
, "wb")
3442 class CHeaderWriter(CWriter
):
3443 """Writes a C Header file."""
3445 _non_alnum_re
= re
.compile(r
'[^a-zA-Z0-9]')
3447 def __init__(self
, filename
, file_comment
= None):
3448 CWriter
.__init
__(self
, filename
)
3450 base
= os
.path
.abspath(filename
)
3451 while os
.path
.basename(base
) != 'src':
3452 new_base
= os
.path
.dirname(base
)
3453 assert new_base
!= base
# Prevent infinite loop.
3456 hpath
= os
.path
.relpath(filename
, base
)
3457 self
.guard
= self
._non
_alnum
_re
.sub('_', hpath
).upper() + '_'
3459 self
.Write(_LICENSE
)
3460 self
.Write(_DO_NOT_EDIT_WARNING
)
3461 if not file_comment
== None:
3462 self
.Write(file_comment
)
3463 self
.Write("#ifndef %s\n" % self
.guard
)
3464 self
.Write("#define %s\n\n" % self
.guard
)
3467 self
.Write("#endif // %s\n\n" % self
.guard
)
3470 class TypeHandler(object):
3471 """This class emits code for a particular type of function."""
3473 _remove_expected_call_re
= re
.compile(r
' EXPECT_CALL.*?;\n', re
.S
)
3478 def InitFunction(self
, func
):
3479 """Add or adjust anything type specific for this function."""
3480 if func
.GetInfo('needs_size') and not func
.name
.endswith('Bucket'):
3481 func
.AddCmdArg(DataSizeArgument('data_size'))
3483 def NeedsDataTransferFunction(self
, func
):
3484 """Overriden from TypeHandler."""
3485 return func
.num_pointer_args
>= 1
3487 def WriteStruct(self
, func
, file):
3488 """Writes a structure that matches the arguments to a function."""
3489 comment
= func
.GetInfo('cmd_comment')
3490 if not comment
== None:
3492 file.Write("struct %s {\n" % func
.name
)
3493 file.Write(" typedef %s ValueType;\n" % func
.name
)
3494 file.Write(" static const CommandId kCmdId = k%s;\n" % func
.name
)
3495 func
.WriteCmdArgFlag(file)
3496 func
.WriteCmdFlag(file)
3498 result
= func
.GetInfo('result')
3499 if not result
== None:
3500 if len(result
) == 1:
3501 file.Write(" typedef %s Result;\n\n" % result
[0])
3503 file.Write(" struct Result {\n")
3505 file.Write(" %s;\n" % line
)
3506 file.Write(" };\n\n")
3508 func
.WriteCmdComputeSize(file)
3509 func
.WriteCmdSetHeader(file)
3510 func
.WriteCmdInit(file)
3511 func
.WriteCmdSet(file)
3513 file.Write(" gpu::CommandHeader header;\n")
3514 args
= func
.GetCmdArgs()
3516 file.Write(" %s %s;\n" % (arg
.cmd_type
, arg
.name
))
3518 consts
= func
.GetCmdConstants()
3519 for const
in consts
:
3520 file.Write(" static const %s %s = %s;\n" %
3521 (const
.cmd_type
, const
.name
, const
.GetConstantValue()))
3526 size
= len(args
) * _SIZE_OF_UINT32
+ _SIZE_OF_COMMAND_HEADER
3527 file.Write("static_assert(sizeof(%s) == %d,\n" % (func
.name
, size
))
3528 file.Write(" \"size of %s should be %d\");\n" %
3530 file.Write("static_assert(offsetof(%s, header) == 0,\n" % func
.name
)
3531 file.Write(" \"offset of %s header should be 0\");\n" %
3533 offset
= _SIZE_OF_COMMAND_HEADER
3535 file.Write("static_assert(offsetof(%s, %s) == %d,\n" %
3536 (func
.name
, arg
.name
, offset
))
3537 file.Write(" \"offset of %s %s should be %d\");\n" %
3538 (func
.name
, arg
.name
, offset
))
3539 offset
+= _SIZE_OF_UINT32
3540 if not result
== None and len(result
) > 1:
3543 parts
= line
.split()
3546 static_assert(offsetof(%(cmd_name)s::Result, %(field_name)s) == %(offset)d,
3547 "offset of %(cmd_name)s Result %(field_name)s should be "
3550 file.Write((check
.strip() + "\n") % {
3551 'cmd_name': func
.name
,
3555 offset
+= _SIZE_OF_UINT32
3558 def WriteHandlerImplementation(self
, func
, file):
3559 """Writes the handler implementation for this command."""
3560 if func
.IsUnsafe() and func
.GetInfo('id_mapping'):
3561 code_no_gen
= """ if (!group_->Get%(type)sServiceId(
3562 %(var)s, &%(service_var)s)) {
3563 LOCAL_SET_GL_ERROR(GL_INVALID_OPERATION, "%(func)s", "invalid %(var)s id");
3564 return error::kNoError;
3567 code_gen
= """ if (!group_->Get%(type)sServiceId(
3568 %(var)s, &%(service_var)s)) {
3569 if (!group_->bind_generates_resource()) {
3571 GL_INVALID_OPERATION, "%(func)s", "invalid %(var)s id");
3572 return error::kNoError;
3574 GLuint client_id = %(var)s;
3575 gl%(gen_func)s(1, &%(service_var)s);
3576 Create%(type)s(client_id, %(service_var)s);
3579 gen_func
= func
.GetInfo('gen_func')
3580 for id_type
in func
.GetInfo('id_mapping'):
3581 service_var
= id_type
.lower()
3582 if id_type
== 'Sync':
3583 service_var
= "service_%s" % service_var
3584 file.Write(" GLsync %s = 0;\n" % service_var
)
3585 if gen_func
and id_type
in gen_func
:
3586 file.Write(code_gen
% { 'type': id_type
,
3587 'var': id_type
.lower(),
3588 'service_var': service_var
,
3589 'func': func
.GetGLFunctionName(),
3590 'gen_func': gen_func
})
3592 file.Write(code_no_gen
% { 'type': id_type
,
3593 'var': id_type
.lower(),
3594 'service_var': service_var
,
3595 'func': func
.GetGLFunctionName() })
3597 for arg
in func
.GetOriginalArgs():
3598 if arg
.type == "GLsync":
3599 args
.append("service_%s" % arg
.name
)
3600 elif arg
.name
.endswith("size") and arg
.type == "GLsizei":
3601 args
.append("num_%s" % func
.GetLastOriginalArg().name
)
3602 elif arg
.name
== "length":
3603 args
.append("nullptr")
3605 args
.append(arg
.name
)
3606 file.Write(" %s(%s);\n" %
3607 (func
.GetGLFunctionName(), ", ".join(args
)))
3609 def WriteCmdSizeTest(self
, func
, file):
3610 """Writes the size test for a command."""
3611 file.Write(" EXPECT_EQ(sizeof(cmd), cmd.header.size * 4u);\n")
3613 def WriteFormatTest(self
, func
, file):
3614 """Writes a format test for a command."""
3615 file.Write("TEST_F(GLES2FormatTest, %s) {\n" % func
.name
)
3616 file.Write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
3617 (func
.name
, func
.name
))
3618 file.Write(" void* next_cmd = cmd.Set(\n")
3620 args
= func
.GetCmdArgs()
3621 for value
, arg
in enumerate(args
):
3622 file.Write(",\n static_cast<%s>(%d)" % (arg
.type, value
+ 11))
3624 file.Write(" EXPECT_EQ(static_cast<uint32_t>(cmds::%s::kCmdId),\n" %
3626 file.Write(" cmd.header.command);\n")
3627 func
.type_handler
.WriteCmdSizeTest(func
, file)
3628 for value
, arg
in enumerate(args
):
3629 file.Write(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);\n" %
3630 (arg
.type, value
+ 11, arg
.name
))
3631 file.Write(" CheckBytesWrittenMatchesExpectedSize(\n")
3632 file.Write(" next_cmd, sizeof(cmd));\n")
3636 def WriteImmediateFormatTest(self
, func
, file):
3637 """Writes a format test for an immediate version of a command."""
3640 def WriteBucketFormatTest(self
, func
, file):
3641 """Writes a format test for a bucket version of a command."""
3644 def WriteGetDataSizeCode(self
, func
, file):
3645 """Writes the code to set data_size used in validation"""
3648 def WriteImmediateCmdSizeTest(self
, func
, file):
3649 """Writes a size test for an immediate version of a command."""
3650 file.Write(" // TODO(gman): Compute correct size.\n")
3651 file.Write(" EXPECT_EQ(sizeof(cmd), cmd.header.size * 4u);\n")
3653 def __WriteIdMapping(self
, func
, file):
3654 """Writes client side / service side ID mapping."""
3655 if not func
.IsUnsafe() or not func
.GetInfo('id_mapping'):
3657 for id_type
in func
.GetInfo('id_mapping'):
3658 file.Write(" group_->Get%sServiceId(%s, &%s);\n" %
3659 (id_type
, id_type
.lower(), id_type
.lower()))
3661 def WriteImmediateHandlerImplementation (self
, func
, file):
3662 """Writes the handler impl for the immediate version of a command."""
3663 self
.__WriteIdMapping
(func
, file)
3664 file.Write(" %s(%s);\n" %
3665 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
3667 def WriteBucketHandlerImplementation (self
, func
, file):
3668 """Writes the handler impl for the bucket version of a command."""
3669 self
.__WriteIdMapping
(func
, file)
3670 file.Write(" %s(%s);\n" %
3671 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
3673 def WriteServiceHandlerFunctionHeader(self
, func
, file):
3674 """Writes function header for service implementation handlers."""
3675 file.Write("""error::Error GLES2DecoderImpl::Handle%(name)s(
3676 uint32_t immediate_data_size, const void* cmd_data) {
3677 """ % {'name': func
.name
})
3679 file.Write("""if (!unsafe_es3_apis_enabled())
3680 return error::kUnknownCommand;
3682 file.Write("""const gles2::cmds::%(name)s& c =
3683 *static_cast<const gles2::cmds::%(name)s*>(cmd_data);
3685 """ % {'name': func
.name
})
3687 def WriteServiceImplementation(self
, func
, file):
3688 """Writes the service implementation for a command."""
3689 self
.WriteServiceHandlerFunctionHeader(func
, file)
3690 self
.WriteHandlerExtensionCheck(func
, file)
3691 self
.WriteHandlerDeferReadWrite(func
, file);
3692 if len(func
.GetOriginalArgs()) > 0:
3693 last_arg
= func
.GetLastOriginalArg()
3694 all_but_last_arg
= func
.GetOriginalArgs()[:-1]
3695 for arg
in all_but_last_arg
:
3696 arg
.WriteGetCode(file)
3697 self
.WriteGetDataSizeCode(func
, file)
3698 last_arg
.WriteGetCode(file)
3699 func
.WriteHandlerValidation(file)
3700 func
.WriteHandlerImplementation(file)
3701 file.Write(" return error::kNoError;\n")
3705 def WriteImmediateServiceImplementation(self
, func
, file):
3706 """Writes the service implementation for an immediate version of command."""
3707 self
.WriteServiceHandlerFunctionHeader(func
, file)
3708 self
.WriteHandlerExtensionCheck(func
, file)
3709 self
.WriteHandlerDeferReadWrite(func
, file);
3710 for arg
in func
.GetOriginalArgs():
3712 self
.WriteGetDataSizeCode(func
, file)
3713 arg
.WriteGetCode(file)
3714 func
.WriteHandlerValidation(file)
3715 func
.WriteHandlerImplementation(file)
3716 file.Write(" return error::kNoError;\n")
3720 def WriteBucketServiceImplementation(self
, func
, file):
3721 """Writes the service implementation for a bucket version of command."""
3722 self
.WriteServiceHandlerFunctionHeader(func
, file)
3723 self
.WriteHandlerExtensionCheck(func
, file)
3724 self
.WriteHandlerDeferReadWrite(func
, file);
3725 for arg
in func
.GetCmdArgs():
3726 arg
.WriteGetCode(file)
3727 func
.WriteHandlerValidation(file)
3728 func
.WriteHandlerImplementation(file)
3729 file.Write(" return error::kNoError;\n")
3733 def WriteHandlerExtensionCheck(self
, func
, file):
3734 if func
.GetInfo('extension_flag'):
3735 file.Write(" if (!features().%s) {\n" % func
.GetInfo('extension_flag'))
3736 file.Write(" LOCAL_SET_GL_ERROR(GL_INVALID_OPERATION, \"gl%s\","
3737 " \"function not available\");\n" % func
.original_name
)
3738 file.Write(" return error::kNoError;")
3739 file.Write(" }\n\n")
3741 def WriteHandlerDeferReadWrite(self
, func
, file):
3742 """Writes the code to handle deferring reads or writes."""
3743 defer_draws
= func
.GetInfo('defer_draws')
3744 defer_reads
= func
.GetInfo('defer_reads')
3745 if defer_draws
or defer_reads
:
3746 file.Write(" error::Error error;\n")
3748 file.Write(" error = WillAccessBoundFramebufferForDraw();\n")
3749 file.Write(" if (error != error::kNoError)\n")
3750 file.Write(" return error;\n")
3752 file.Write(" error = WillAccessBoundFramebufferForRead();\n")
3753 file.Write(" if (error != error::kNoError)\n")
3754 file.Write(" return error;\n")
3756 def WriteValidUnitTest(self
, func
, file, test
, *extras
):
3757 """Writes a valid unit test for the service implementation."""
3758 if func
.GetInfo('expectation') == False:
3759 test
= self
._remove
_expected
_call
_re
.sub('', test
)
3762 arg
.GetValidArg(func
) \
3763 for arg
in func
.GetOriginalArgs() if not arg
.IsConstant()
3766 arg
.GetValidGLArg(func
) \
3767 for arg
in func
.GetOriginalArgs()
3769 gl_func_name
= func
.GetGLTestFunctionName()
3772 'gl_func_name': gl_func_name
,
3773 'args': ", ".join(arg_strings
),
3774 'gl_args': ", ".join(gl_arg_strings
),
3776 for extra
in extras
:
3779 while (old_test
!= test
):
3782 file.Write(test
% vars)
3784 def WriteInvalidUnitTest(self
, func
, file, test
, *extras
):
3785 """Writes an invalid unit test for the service implementation."""
3788 for invalid_arg_index
, invalid_arg
in enumerate(func
.GetOriginalArgs()):
3789 # Service implementation does not test constants, as they are not part of
3790 # the call in the service side.
3791 if invalid_arg
.IsConstant():
3794 num_invalid_values
= invalid_arg
.GetNumInvalidValues(func
)
3795 for value_index
in range(0, num_invalid_values
):
3797 parse_result
= "kNoError"
3799 for arg
in func
.GetOriginalArgs():
3800 if arg
.IsConstant():
3802 if invalid_arg
is arg
:
3803 (arg_string
, parse_result
, gl_error
) = arg
.GetInvalidArg(
3806 arg_string
= arg
.GetValidArg(func
)
3807 arg_strings
.append(arg_string
)
3809 for arg
in func
.GetOriginalArgs():
3810 gl_arg_strings
.append("_")
3811 gl_func_name
= func
.GetGLTestFunctionName()
3813 if not gl_error
== None:
3814 gl_error_test
= '\n EXPECT_EQ(%s, GetGLError());' % gl_error
3818 'arg_index': invalid_arg_index
,
3819 'value_index': value_index
,
3820 'gl_func_name': gl_func_name
,
3821 'args': ", ".join(arg_strings
),
3822 'all_but_last_args': ", ".join(arg_strings
[:-1]),
3823 'gl_args': ", ".join(gl_arg_strings
),
3824 'parse_result': parse_result
,
3825 'gl_error_test': gl_error_test
,
3827 for extra
in extras
:
3829 file.Write(test
% vars)
3831 def WriteServiceUnitTest(self
, func
, file, *extras
):
3832 """Writes the service unit test for a command."""
3834 if func
.name
== 'Enable':
3836 TEST_P(%(test_name)s, %(name)sValidArgs) {
3837 SetupExpectationsForEnableDisable(%(gl_args)s, true);
3838 SpecializedSetup<cmds::%(name)s, 0>(true);
3840 cmd.Init(%(args)s);"""
3841 elif func
.name
== 'Disable':
3843 TEST_P(%(test_name)s, %(name)sValidArgs) {
3844 SetupExpectationsForEnableDisable(%(gl_args)s, false);
3845 SpecializedSetup<cmds::%(name)s, 0>(true);
3847 cmd.Init(%(args)s);"""
3850 TEST_P(%(test_name)s, %(name)sValidArgs) {
3851 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
3852 SpecializedSetup<cmds::%(name)s, 0>(true);
3854 cmd.Init(%(args)s);"""
3857 decoder_->set_unsafe_es3_apis_enabled(true);
3858 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
3859 EXPECT_EQ(GL_NO_ERROR, GetGLError());
3860 decoder_->set_unsafe_es3_apis_enabled(false);
3861 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));
3866 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
3867 EXPECT_EQ(GL_NO_ERROR, GetGLError());
3870 self
.WriteValidUnitTest(func
, file, valid_test
, *extras
)
3872 if not func
.IsUnsafe():
3874 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
3875 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
3876 SpecializedSetup<cmds::%(name)s, 0>(false);
3879 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
3882 self
.WriteInvalidUnitTest(func
, file, invalid_test
, *extras
)
3884 def WriteImmediateServiceUnitTest(self
, func
, file, *extras
):
3885 """Writes the service unit test for an immediate command."""
3886 file.Write("// TODO(gman): %s\n" % func
.name
)
3888 def WriteImmediateValidationCode(self
, func
, file):
3889 """Writes the validation code for an immediate version of a command."""
3892 def WriteBucketServiceUnitTest(self
, func
, file, *extras
):
3893 """Writes the service unit test for a bucket command."""
3894 file.Write("// TODO(gman): %s\n" % func
.name
)
3896 def WriteBucketValidationCode(self
, func
, file):
3897 """Writes the validation code for a bucket version of a command."""
3898 file.Write("// TODO(gman): %s\n" % func
.name
)
3900 def WriteGLES2ImplementationDeclaration(self
, func
, file):
3901 """Writes the GLES2 Implemention declaration."""
3902 impl_decl
= func
.GetInfo('impl_decl')
3903 if impl_decl
== None or impl_decl
== True:
3904 file.Write("%s %s(%s) override;\n" %
3905 (func
.return_type
, func
.original_name
,
3906 func
.MakeTypedOriginalArgString("")))
3909 def WriteGLES2CLibImplementation(self
, func
, file):
3910 file.Write("%s GLES2%s(%s) {\n" %
3911 (func
.return_type
, func
.name
,
3912 func
.MakeTypedOriginalArgString("")))
3913 result_string
= "return "
3914 if func
.return_type
== "void":
3916 file.Write(" %sgles2::GetGLContext()->%s(%s);\n" %
3917 (result_string
, func
.original_name
,
3918 func
.MakeOriginalArgString("")))
3921 def WriteGLES2Header(self
, func
, file):
3922 """Writes a re-write macro for GLES"""
3923 file.Write("#define gl%s GLES2_GET_FUN(%s)\n" %(func
.name
, func
.name
))
3925 def WriteClientGLCallLog(self
, func
, file):
3926 """Writes a logging macro for the client side code."""
3928 if len(func
.GetOriginalArgs()):
3931 ' GPU_CLIENT_LOG("[" << GetLogPrefix() << "] gl%s("%s%s << ")");\n' %
3932 (func
.original_name
, comma
, func
.MakeLogArgString()))
3934 def WriteClientGLReturnLog(self
, func
, file):
3935 """Writes the return value logging code."""
3936 if func
.return_type
!= "void":
3937 file.Write(' GPU_CLIENT_LOG("return:" << result)\n')
3939 def WriteGLES2ImplementationHeader(self
, func
, file):
3940 """Writes the GLES2 Implemention."""
3941 self
.WriteGLES2ImplementationDeclaration(func
, file)
3943 def WriteGLES2TraceImplementationHeader(self
, func
, file):
3944 """Writes the GLES2 Trace Implemention header."""
3945 file.Write("%s %s(%s) override;\n" %
3946 (func
.return_type
, func
.original_name
,
3947 func
.MakeTypedOriginalArgString("")))
3949 def WriteGLES2TraceImplementation(self
, func
, file):
3950 """Writes the GLES2 Trace Implemention."""
3951 file.Write("%s GLES2TraceImplementation::%s(%s) {\n" %
3952 (func
.return_type
, func
.original_name
,
3953 func
.MakeTypedOriginalArgString("")))
3954 result_string
= "return "
3955 if func
.return_type
== "void":
3957 file.Write(' TRACE_EVENT_BINARY_EFFICIENT0("gpu", "GLES2Trace::%s");\n' %
3959 file.Write(" %sgl_->%s(%s);\n" %
3960 (result_string
, func
.name
, func
.MakeOriginalArgString("")))
3964 def WriteGLES2Implementation(self
, func
, file):
3965 """Writes the GLES2 Implemention."""
3966 impl_func
= func
.GetInfo('impl_func')
3967 impl_decl
= func
.GetInfo('impl_decl')
3968 gen_cmd
= func
.GetInfo('gen_cmd')
3969 if (func
.can_auto_generate
and
3970 (impl_func
== None or impl_func
== True) and
3971 (impl_decl
== None or impl_decl
== True) and
3972 (gen_cmd
== None or gen_cmd
== True)):
3973 file.Write("%s GLES2Implementation::%s(%s) {\n" %
3974 (func
.return_type
, func
.original_name
,
3975 func
.MakeTypedOriginalArgString("")))
3976 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
3977 self
.WriteClientGLCallLog(func
, file)
3978 func
.WriteDestinationInitalizationValidation(file)
3979 for arg
in func
.GetOriginalArgs():
3980 arg
.WriteClientSideValidationCode(file, func
)
3981 file.Write(" helper_->%s(%s);\n" %
3982 (func
.name
, func
.MakeHelperArgString("")))
3983 file.Write(" CheckGLError();\n")
3984 self
.WriteClientGLReturnLog(func
, file)
3988 def WriteGLES2InterfaceHeader(self
, func
, file):
3989 """Writes the GLES2 Interface."""
3990 file.Write("virtual %s %s(%s) = 0;\n" %
3991 (func
.return_type
, func
.original_name
,
3992 func
.MakeTypedOriginalArgString("")))
3994 def WriteGLES2InterfaceStub(self
, func
, file):
3995 """Writes the GLES2 Interface stub declaration."""
3996 file.Write("%s %s(%s) override;\n" %
3997 (func
.return_type
, func
.original_name
,
3998 func
.MakeTypedOriginalArgString("")))
4000 def WriteGLES2InterfaceStubImpl(self
, func
, file):
4001 """Writes the GLES2 Interface stub declaration."""
4002 args
= func
.GetOriginalArgs()
4003 arg_string
= ", ".join(
4004 ["%s /* %s */" % (arg
.type, arg
.name
) for arg
in args
])
4005 file.Write("%s GLES2InterfaceStub::%s(%s) {\n" %
4006 (func
.return_type
, func
.original_name
, arg_string
))
4007 if func
.return_type
!= "void":
4008 file.Write(" return 0;\n")
4011 def WriteGLES2ImplementationUnitTest(self
, func
, file):
4012 """Writes the GLES2 Implemention unit test."""
4013 client_test
= func
.GetInfo('client_test')
4014 if (func
.can_auto_generate
and
4015 (client_test
== None or client_test
== True)):
4017 TEST_F(GLES2ImplementationTest, %(name)s) {
4022 expected.cmd.Init(%(cmd_args)s);
4024 gl_->%(name)s(%(args)s);
4025 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
4029 arg
.GetValidClientSideCmdArg(func
) for arg
in func
.GetCmdArgs()
4033 arg
.GetValidClientSideArg(func
) for arg
in func
.GetOriginalArgs()
4038 'args': ", ".join(gl_arg_strings
),
4039 'cmd_args': ", ".join(cmd_arg_strings
),
4042 # Test constants for invalid values, as they are not tested by the
4044 constants
= [arg
for arg
in func
.GetOriginalArgs() if arg
.IsConstant()]
4047 TEST_F(GLES2ImplementationTest, %(name)sInvalidConstantArg%(invalid_index)d) {
4048 gl_->%(name)s(%(args)s);
4049 EXPECT_TRUE(NoCommandsWritten());
4050 EXPECT_EQ(%(gl_error)s, CheckError());
4053 for invalid_arg
in constants
:
4055 invalid
= invalid_arg
.GetInvalidArg(func
)
4056 for arg
in func
.GetOriginalArgs():
4057 if arg
is invalid_arg
:
4058 gl_arg_strings
.append(invalid
[0])
4060 gl_arg_strings
.append(arg
.GetValidClientSideArg(func
))
4064 'invalid_index': func
.GetOriginalArgs().index(invalid_arg
),
4065 'args': ", ".join(gl_arg_strings
),
4066 'gl_error': invalid
[2],
4069 if client_test
!= False:
4070 file.Write("// TODO(zmo): Implement unit test for %s\n" % func
.name
)
4072 def WriteDestinationInitalizationValidation(self
, func
, file):
4073 """Writes the client side destintion initialization validation."""
4074 for arg
in func
.GetOriginalArgs():
4075 arg
.WriteDestinationInitalizationValidation(file, func
)
4077 def WriteTraceEvent(self
, func
, file):
4078 file.Write(' TRACE_EVENT0("gpu", "GLES2Implementation::%s");\n' %
4081 def WriteImmediateCmdComputeSize(self
, func
, file):
4082 """Writes the size computation code for the immediate version of a cmd."""
4083 file.Write(" static uint32_t ComputeSize(uint32_t size_in_bytes) {\n")
4084 file.Write(" return static_cast<uint32_t>(\n")
4085 file.Write(" sizeof(ValueType) + // NOLINT\n")
4086 file.Write(" RoundSizeToMultipleOfEntries(size_in_bytes));\n")
4090 def WriteImmediateCmdSetHeader(self
, func
, file):
4091 """Writes the SetHeader function for the immediate version of a cmd."""
4092 file.Write(" void SetHeader(uint32_t size_in_bytes) {\n")
4093 file.Write(" header.SetCmdByTotalSize<ValueType>(size_in_bytes);\n")
4097 def WriteImmediateCmdInit(self
, func
, file):
4098 """Writes the Init function for the immediate version of a command."""
4099 raise NotImplementedError(func
.name
)
4101 def WriteImmediateCmdSet(self
, func
, file):
4102 """Writes the Set function for the immediate version of a command."""
4103 raise NotImplementedError(func
.name
)
4105 def WriteCmdHelper(self
, func
, file):
4106 """Writes the cmd helper definition for a cmd."""
4107 code
= """ void %(name)s(%(typed_args)s) {
4108 gles2::cmds::%(name)s* c = GetCmdSpace<gles2::cmds::%(name)s>();
4117 "typed_args": func
.MakeTypedCmdArgString(""),
4118 "args": func
.MakeCmdArgString(""),
4121 def WriteImmediateCmdHelper(self
, func
, file):
4122 """Writes the cmd helper definition for the immediate version of a cmd."""
4123 code
= """ void %(name)s(%(typed_args)s) {
4124 const uint32_t s = 0; // TODO(gman): compute correct size
4125 gles2::cmds::%(name)s* c =
4126 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(s);
4135 "typed_args": func
.MakeTypedCmdArgString(""),
4136 "args": func
.MakeCmdArgString(""),
4140 class StateSetHandler(TypeHandler
):
4141 """Handler for commands that simply set state."""
4144 TypeHandler
.__init
__(self
)
4146 def WriteHandlerImplementation(self
, func
, file):
4147 """Overrriden from TypeHandler."""
4148 state_name
= func
.GetInfo('state')
4149 state
= _STATES
[state_name
]
4150 states
= state
['states']
4151 args
= func
.GetOriginalArgs()
4152 for ndx
,item
in enumerate(states
):
4154 if 'range_checks' in item
:
4155 for range_check
in item
['range_checks']:
4156 code
.append("%s %s" % (args
[ndx
].name
, range_check
['check']))
4157 if 'nan_check' in item
:
4158 # Drivers might generate an INVALID_VALUE error when a value is set
4159 # to NaN. This is allowed behavior under GLES 3.0 section 2.1.1 or
4160 # OpenGL 4.5 section 2.3.4.1 - providing NaN allows undefined results.
4161 # Make this behavior consistent within Chromium, and avoid leaking GL
4162 # errors by generating the error in the command buffer instead of
4163 # letting the GL driver generate it.
4164 code
.append("base::IsNaN(%s)" % args
[ndx
].name
)
4166 file.Write(" if (%s) {\n" % " ||\n ".join(code
))
4168 ' LOCAL_SET_GL_ERROR(GL_INVALID_VALUE,'
4169 ' "%s", "%s out of range");\n' %
4170 (func
.name
, args
[ndx
].name
))
4171 file.Write(" return error::kNoError;\n")
4174 for ndx
,item
in enumerate(states
):
4175 code
.append("state_.%s != %s" % (item
['name'], args
[ndx
].name
))
4176 file.Write(" if (%s) {\n" % " ||\n ".join(code
))
4177 for ndx
,item
in enumerate(states
):
4178 file.Write(" state_.%s = %s;\n" % (item
['name'], args
[ndx
].name
))
4179 if 'state_flag' in state
:
4180 file.Write(" %s = true;\n" % state
['state_flag'])
4181 if not func
.GetInfo("no_gl"):
4182 for ndx
,item
in enumerate(states
):
4183 if item
.get('cached', False):
4184 file.Write(" state_.%s = %s;\n" %
4185 (CachedStateName(item
), args
[ndx
].name
))
4186 file.Write(" %s(%s);\n" %
4187 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
4190 def WriteServiceUnitTest(self
, func
, file, *extras
):
4191 """Overrriden from TypeHandler."""
4192 TypeHandler
.WriteServiceUnitTest(self
, func
, file, *extras
)
4193 state_name
= func
.GetInfo('state')
4194 state
= _STATES
[state_name
]
4195 states
= state
['states']
4196 for ndx
,item
in enumerate(states
):
4197 if 'range_checks' in item
:
4198 for check_ndx
, range_check
in enumerate(item
['range_checks']):
4200 TEST_P(%(test_name)s, %(name)sInvalidValue%(ndx)d_%(check_ndx)d) {
4201 SpecializedSetup<cmds::%(name)s, 0>(false);
4204 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4205 EXPECT_EQ(GL_INVALID_VALUE, GetGLError());
4210 arg
.GetValidArg(func
) \
4211 for arg
in func
.GetOriginalArgs() if not arg
.IsConstant()
4214 arg_strings
[ndx
] = range_check
['test_value']
4218 'check_ndx': check_ndx
,
4219 'args': ", ".join(arg_strings
),
4221 for extra
in extras
:
4223 file.Write(valid_test
% vars)
4224 if 'nan_check' in item
:
4226 TEST_P(%(test_name)s, %(name)sNaNValue%(ndx)d) {
4227 SpecializedSetup<cmds::%(name)s, 0>(false);
4230 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4231 EXPECT_EQ(GL_INVALID_VALUE, GetGLError());
4236 arg
.GetValidArg(func
) \
4237 for arg
in func
.GetOriginalArgs() if not arg
.IsConstant()
4240 arg_strings
[ndx
] = 'nanf("")'
4244 'args': ", ".join(arg_strings
),
4246 for extra
in extras
:
4248 file.Write(valid_test
% vars)
4251 class StateSetRGBAlphaHandler(TypeHandler
):
4252 """Handler for commands that simply set state that have rgb/alpha."""
4255 TypeHandler
.__init
__(self
)
4257 def WriteHandlerImplementation(self
, func
, file):
4258 """Overrriden from TypeHandler."""
4259 state_name
= func
.GetInfo('state')
4260 state
= _STATES
[state_name
]
4261 states
= state
['states']
4262 args
= func
.GetOriginalArgs()
4263 num_args
= len(args
)
4265 for ndx
,item
in enumerate(states
):
4266 code
.append("state_.%s != %s" % (item
['name'], args
[ndx
% num_args
].name
))
4267 file.Write(" if (%s) {\n" % " ||\n ".join(code
))
4268 for ndx
, item
in enumerate(states
):
4269 file.Write(" state_.%s = %s;\n" %
4270 (item
['name'], args
[ndx
% num_args
].name
))
4271 if 'state_flag' in state
:
4272 file.Write(" %s = true;\n" % state
['state_flag'])
4273 if not func
.GetInfo("no_gl"):
4274 file.Write(" %s(%s);\n" %
4275 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
4279 class StateSetFrontBackSeparateHandler(TypeHandler
):
4280 """Handler for commands that simply set state that have front/back."""
4283 TypeHandler
.__init
__(self
)
4285 def WriteHandlerImplementation(self
, func
, file):
4286 """Overrriden from TypeHandler."""
4287 state_name
= func
.GetInfo('state')
4288 state
= _STATES
[state_name
]
4289 states
= state
['states']
4290 args
= func
.GetOriginalArgs()
4292 num_args
= len(args
)
4293 file.Write(" bool changed = false;\n")
4294 for group_ndx
, group
in enumerate(Grouper(num_args
- 1, states
)):
4295 file.Write(" if (%s == %s || %s == GL_FRONT_AND_BACK) {\n" %
4296 (face
, ('GL_FRONT', 'GL_BACK')[group_ndx
], face
))
4298 for ndx
, item
in enumerate(group
):
4299 code
.append("state_.%s != %s" % (item
['name'], args
[ndx
+ 1].name
))
4300 file.Write(" changed |= %s;\n" % " ||\n ".join(code
))
4302 file.Write(" if (changed) {\n")
4303 for group_ndx
, group
in enumerate(Grouper(num_args
- 1, states
)):
4304 file.Write(" if (%s == %s || %s == GL_FRONT_AND_BACK) {\n" %
4305 (face
, ('GL_FRONT', 'GL_BACK')[group_ndx
], face
))
4306 for ndx
, item
in enumerate(group
):
4307 file.Write(" state_.%s = %s;\n" %
4308 (item
['name'], args
[ndx
+ 1].name
))
4310 if 'state_flag' in state
:
4311 file.Write(" %s = true;\n" % state
['state_flag'])
4312 if not func
.GetInfo("no_gl"):
4313 file.Write(" %s(%s);\n" %
4314 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
4318 class StateSetFrontBackHandler(TypeHandler
):
4319 """Handler for commands that simply set state that set both front/back."""
4322 TypeHandler
.__init
__(self
)
4324 def WriteHandlerImplementation(self
, func
, file):
4325 """Overrriden from TypeHandler."""
4326 state_name
= func
.GetInfo('state')
4327 state
= _STATES
[state_name
]
4328 states
= state
['states']
4329 args
= func
.GetOriginalArgs()
4330 num_args
= len(args
)
4332 for group_ndx
, group
in enumerate(Grouper(num_args
, states
)):
4333 for ndx
, item
in enumerate(group
):
4334 code
.append("state_.%s != %s" % (item
['name'], args
[ndx
].name
))
4335 file.Write(" if (%s) {\n" % " ||\n ".join(code
))
4336 for group_ndx
, group
in enumerate(Grouper(num_args
, states
)):
4337 for ndx
, item
in enumerate(group
):
4338 file.Write(" state_.%s = %s;\n" % (item
['name'], args
[ndx
].name
))
4339 if 'state_flag' in state
:
4340 file.Write(" %s = true;\n" % state
['state_flag'])
4341 if not func
.GetInfo("no_gl"):
4342 file.Write(" %s(%s);\n" %
4343 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
4347 class StateSetNamedParameter(TypeHandler
):
4348 """Handler for commands that set a state chosen with an enum parameter."""
4351 TypeHandler
.__init
__(self
)
4353 def WriteHandlerImplementation(self
, func
, file):
4354 """Overridden from TypeHandler."""
4355 state_name
= func
.GetInfo('state')
4356 state
= _STATES
[state_name
]
4357 states
= state
['states']
4358 args
= func
.GetOriginalArgs()
4359 num_args
= len(args
)
4360 assert num_args
== 2
4361 file.Write(" switch (%s) {\n" % args
[0].name
)
4362 for state
in states
:
4363 file.Write(" case %s:\n" % state
['enum'])
4364 file.Write(" if (state_.%s != %s) {\n" %
4365 (state
['name'], args
[1].name
))
4366 file.Write(" state_.%s = %s;\n" % (state
['name'], args
[1].name
))
4367 if not func
.GetInfo("no_gl"):
4368 file.Write(" %s(%s);\n" %
4369 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
4371 file.Write(" break;\n")
4372 file.Write(" default:\n")
4373 file.Write(" NOTREACHED();\n")
4377 class CustomHandler(TypeHandler
):
4378 """Handler for commands that are auto-generated but require minor tweaks."""
4381 TypeHandler
.__init
__(self
)
4383 def WriteServiceImplementation(self
, func
, file):
4384 """Overrriden from TypeHandler."""
4387 def WriteImmediateServiceImplementation(self
, func
, file):
4388 """Overrriden from TypeHandler."""
4391 def WriteBucketServiceImplementation(self
, func
, file):
4392 """Overrriden from TypeHandler."""
4395 def WriteServiceUnitTest(self
, func
, file, *extras
):
4396 """Overrriden from TypeHandler."""
4397 file.Write("// TODO(gman): %s\n\n" % func
.name
)
4399 def WriteImmediateServiceUnitTest(self
, func
, file, *extras
):
4400 """Overrriden from TypeHandler."""
4401 file.Write("// TODO(gman): %s\n\n" % func
.name
)
4403 def WriteImmediateCmdGetTotalSize(self
, func
, file):
4404 """Overrriden from TypeHandler."""
4406 " uint32_t total_size = 0; // TODO(gman): get correct size.\n")
4408 def WriteImmediateCmdInit(self
, func
, file):
4409 """Overrriden from TypeHandler."""
4410 file.Write(" void Init(%s) {\n" % func
.MakeTypedCmdArgString("_"))
4411 self
.WriteImmediateCmdGetTotalSize(func
, file)
4412 file.Write(" SetHeader(total_size);\n")
4413 args
= func
.GetCmdArgs()
4415 file.Write(" %s = _%s;\n" % (arg
.name
, arg
.name
))
4419 def WriteImmediateCmdSet(self
, func
, file):
4420 """Overrriden from TypeHandler."""
4421 copy_args
= func
.MakeCmdArgString("_", False)
4422 file.Write(" void* Set(void* cmd%s) {\n" %
4423 func
.MakeTypedCmdArgString("_", True))
4424 self
.WriteImmediateCmdGetTotalSize(func
, file)
4425 file.Write(" static_cast<ValueType*>(cmd)->Init(%s);\n" % copy_args
)
4426 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
4427 "cmd, total_size);\n")
4432 class TodoHandler(CustomHandler
):
4433 """Handle for commands that are not yet implemented."""
4435 def NeedsDataTransferFunction(self
, func
):
4436 """Overriden from TypeHandler."""
4439 def WriteImmediateFormatTest(self
, func
, file):
4440 """Overrriden from TypeHandler."""
4443 def WriteGLES2ImplementationUnitTest(self
, func
, file):
4444 """Overrriden from TypeHandler."""
4447 def WriteGLES2Implementation(self
, func
, file):
4448 """Overrriden from TypeHandler."""
4449 file.Write("%s GLES2Implementation::%s(%s) {\n" %
4450 (func
.return_type
, func
.original_name
,
4451 func
.MakeTypedOriginalArgString("")))
4452 file.Write(" // TODO: for now this is a no-op\n")
4455 "GL_INVALID_OPERATION, \"gl%s\", \"not implemented\");\n" %
4457 if func
.return_type
!= "void":
4458 file.Write(" return 0;\n")
4462 def WriteServiceImplementation(self
, func
, file):
4463 """Overrriden from TypeHandler."""
4464 self
.WriteServiceHandlerFunctionHeader(func
, file)
4465 file.Write(" // TODO: for now this is a no-op\n")
4467 " LOCAL_SET_GL_ERROR("
4468 "GL_INVALID_OPERATION, \"gl%s\", \"not implemented\");\n" %
4470 file.Write(" return error::kNoError;\n")
4475 class HandWrittenHandler(CustomHandler
):
4476 """Handler for comands where everything must be written by hand."""
4478 def InitFunction(self
, func
):
4479 """Add or adjust anything type specific for this function."""
4480 CustomHandler
.InitFunction(self
, func
)
4481 func
.can_auto_generate
= False
4483 def NeedsDataTransferFunction(self
, func
):
4484 """Overriden from TypeHandler."""
4485 # If specified explicitly, force the data transfer method.
4486 if func
.GetInfo('data_transfer_methods'):
4490 def WriteStruct(self
, func
, file):
4491 """Overrriden from TypeHandler."""
4494 def WriteDocs(self
, func
, file):
4495 """Overrriden from TypeHandler."""
4498 def WriteServiceUnitTest(self
, func
, file, *extras
):
4499 """Overrriden from TypeHandler."""
4500 file.Write("// TODO(gman): %s\n\n" % func
.name
)
4502 def WriteImmediateServiceUnitTest(self
, func
, file, *extras
):
4503 """Overrriden from TypeHandler."""
4504 file.Write("// TODO(gman): %s\n\n" % func
.name
)
4506 def WriteBucketServiceUnitTest(self
, func
, file, *extras
):
4507 """Overrriden from TypeHandler."""
4508 file.Write("// TODO(gman): %s\n\n" % func
.name
)
4510 def WriteServiceImplementation(self
, func
, file):
4511 """Overrriden from TypeHandler."""
4514 def WriteImmediateServiceImplementation(self
, func
, file):
4515 """Overrriden from TypeHandler."""
4518 def WriteBucketServiceImplementation(self
, func
, file):
4519 """Overrriden from TypeHandler."""
4522 def WriteImmediateCmdHelper(self
, func
, file):
4523 """Overrriden from TypeHandler."""
4526 def WriteCmdHelper(self
, func
, file):
4527 """Overrriden from TypeHandler."""
4530 def WriteFormatTest(self
, func
, file):
4531 """Overrriden from TypeHandler."""
4532 file.Write("// TODO(gman): Write test for %s\n" % func
.name
)
4534 def WriteImmediateFormatTest(self
, func
, file):
4535 """Overrriden from TypeHandler."""
4536 file.Write("// TODO(gman): Write test for %s\n" % func
.name
)
4538 def WriteBucketFormatTest(self
, func
, file):
4539 """Overrriden from TypeHandler."""
4540 file.Write("// TODO(gman): Write test for %s\n" % func
.name
)
4544 class ManualHandler(CustomHandler
):
4545 """Handler for commands who's handlers must be written by hand."""
4548 CustomHandler
.__init
__(self
)
4550 def InitFunction(self
, func
):
4551 """Overrriden from TypeHandler."""
4552 if (func
.name
== 'CompressedTexImage2DBucket'):
4553 func
.cmd_args
= func
.cmd_args
[:-1]
4554 func
.AddCmdArg(Argument('bucket_id', 'GLuint'))
4556 CustomHandler
.InitFunction(self
, func
)
4558 def WriteServiceImplementation(self
, func
, file):
4559 """Overrriden from TypeHandler."""
4562 def WriteBucketServiceImplementation(self
, func
, file):
4563 """Overrriden from TypeHandler."""
4566 def WriteServiceUnitTest(self
, func
, file, *extras
):
4567 """Overrriden from TypeHandler."""
4568 file.Write("// TODO(gman): %s\n\n" % func
.name
)
4570 def WriteImmediateServiceUnitTest(self
, func
, file, *extras
):
4571 """Overrriden from TypeHandler."""
4572 file.Write("// TODO(gman): %s\n\n" % func
.name
)
4574 def WriteImmediateServiceImplementation(self
, func
, file):
4575 """Overrriden from TypeHandler."""
4578 def WriteImmediateFormatTest(self
, func
, file):
4579 """Overrriden from TypeHandler."""
4580 file.Write("// TODO(gman): Implement test for %s\n" % func
.name
)
4582 def WriteGLES2Implementation(self
, func
, file):
4583 """Overrriden from TypeHandler."""
4584 if func
.GetInfo('impl_func'):
4585 super(ManualHandler
, self
).WriteGLES2Implementation(func
, file)
4587 def WriteGLES2ImplementationHeader(self
, func
, file):
4588 """Overrriden from TypeHandler."""
4589 file.Write("%s %s(%s) override;\n" %
4590 (func
.return_type
, func
.original_name
,
4591 func
.MakeTypedOriginalArgString("")))
4594 def WriteImmediateCmdGetTotalSize(self
, func
, file):
4595 """Overrriden from TypeHandler."""
4596 # TODO(gman): Move this data to _FUNCTION_INFO?
4597 CustomHandler
.WriteImmediateCmdGetTotalSize(self
, func
, file)
4600 class DataHandler(TypeHandler
):
4601 """Handler for glBufferData, glBufferSubData, glTexImage2D, glTexSubImage2D,
4602 glCompressedTexImage2D, glCompressedTexImageSub2D."""
4604 TypeHandler
.__init
__(self
)
4606 def InitFunction(self
, func
):
4607 """Overrriden from TypeHandler."""
4608 if func
.name
== 'CompressedTexSubImage2DBucket':
4609 func
.cmd_args
= func
.cmd_args
[:-1]
4610 func
.AddCmdArg(Argument('bucket_id', 'GLuint'))
4612 def WriteGetDataSizeCode(self
, func
, file):
4613 """Overrriden from TypeHandler."""
4614 # TODO(gman): Move this data to _FUNCTION_INFO?
4616 if name
.endswith("Immediate"):
4618 if name
== 'BufferData' or name
== 'BufferSubData':
4619 file.Write(" uint32_t data_size = size;\n")
4620 elif (name
== 'CompressedTexImage2D' or
4621 name
== 'CompressedTexSubImage2D'):
4622 file.Write(" uint32_t data_size = imageSize;\n")
4623 elif (name
== 'CompressedTexSubImage2DBucket'):
4624 file.Write(" Bucket* bucket = GetBucket(c.bucket_id);\n")
4625 file.Write(" uint32_t data_size = bucket->size();\n")
4626 file.Write(" GLsizei imageSize = data_size;\n")
4627 elif name
== 'TexImage2D' or name
== 'TexSubImage2D':
4628 code
= """ uint32_t data_size;
4629 if (!GLES2Util::ComputeImageDataSize(
4630 width, height, format, type, unpack_alignment_, &data_size)) {
4631 return error::kOutOfBounds;
4637 "// uint32_t data_size = 0; // TODO(gman): get correct size!\n")
4639 def WriteImmediateCmdGetTotalSize(self
, func
, file):
4640 """Overrriden from TypeHandler."""
4643 def WriteImmediateCmdSizeTest(self
, func
, file):
4644 """Overrriden from TypeHandler."""
4645 file.Write(" EXPECT_EQ(sizeof(cmd), total_size);\n")
4647 def WriteImmediateCmdInit(self
, func
, file):
4648 """Overrriden from TypeHandler."""
4649 file.Write(" void Init(%s) {\n" % func
.MakeTypedCmdArgString("_"))
4650 self
.WriteImmediateCmdGetTotalSize(func
, file)
4651 file.Write(" SetHeader(total_size);\n")
4652 args
= func
.GetCmdArgs()
4654 file.Write(" %s = _%s;\n" % (arg
.name
, arg
.name
))
4658 def WriteImmediateCmdSet(self
, func
, file):
4659 """Overrriden from TypeHandler."""
4660 copy_args
= func
.MakeCmdArgString("_", False)
4661 file.Write(" void* Set(void* cmd%s) {\n" %
4662 func
.MakeTypedCmdArgString("_", True))
4663 self
.WriteImmediateCmdGetTotalSize(func
, file)
4664 file.Write(" static_cast<ValueType*>(cmd)->Init(%s);\n" % copy_args
)
4665 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
4666 "cmd, total_size);\n")
4670 def WriteImmediateFormatTest(self
, func
, file):
4671 """Overrriden from TypeHandler."""
4672 # TODO(gman): Remove this exception.
4673 file.Write("// TODO(gman): Implement test for %s\n" % func
.name
)
4676 def WriteServiceUnitTest(self
, func
, file, *extras
):
4677 """Overrriden from TypeHandler."""
4678 file.Write("// TODO(gman): %s\n\n" % func
.name
)
4680 def WriteImmediateServiceUnitTest(self
, func
, file, *extras
):
4681 """Overrriden from TypeHandler."""
4682 file.Write("// TODO(gman): %s\n\n" % func
.name
)
4684 def WriteBucketServiceImplementation(self
, func
, file):
4685 """Overrriden from TypeHandler."""
4686 if not func
.name
== 'CompressedTexSubImage2DBucket':
4687 TypeHandler
.WriteBucketServiceImplemenation(self
, func
, file)
4690 class BindHandler(TypeHandler
):
4691 """Handler for glBind___ type functions."""
4694 TypeHandler
.__init
__(self
)
4696 def WriteServiceUnitTest(self
, func
, file, *extras
):
4697 """Overrriden from TypeHandler."""
4699 if len(func
.GetOriginalArgs()) == 1:
4701 TEST_P(%(test_name)s, %(name)sValidArgs) {
4702 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
4703 SpecializedSetup<cmds::%(name)s, 0>(true);
4705 cmd.Init(%(args)s);"""
4708 decoder_->set_unsafe_es3_apis_enabled(true);
4709 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4710 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4711 decoder_->set_unsafe_es3_apis_enabled(false);
4712 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));
4717 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4718 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4721 if func
.GetInfo("gen_func"):
4723 TEST_P(%(test_name)s, %(name)sValidArgsNewId) {
4724 EXPECT_CALL(*gl_, %(gl_func_name)s(kNewServiceId));
4725 EXPECT_CALL(*gl_, %(gl_gen_func_name)s(1, _))
4726 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
4727 SpecializedSetup<cmds::%(name)s, 0>(true);
4729 cmd.Init(kNewClientId);
4730 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4731 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4732 EXPECT_TRUE(Get%(resource_type)s(kNewClientId) != NULL);
4735 self
.WriteValidUnitTest(func
, file, valid_test
, {
4736 'resource_type': func
.GetOriginalArgs()[0].resource_type
,
4737 'gl_gen_func_name': func
.GetInfo("gen_func"),
4741 TEST_P(%(test_name)s, %(name)sValidArgs) {
4742 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
4743 SpecializedSetup<cmds::%(name)s, 0>(true);
4745 cmd.Init(%(args)s);"""
4748 decoder_->set_unsafe_es3_apis_enabled(true);
4749 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4750 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4751 decoder_->set_unsafe_es3_apis_enabled(false);
4752 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));
4757 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4758 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4761 if func
.GetInfo("gen_func"):
4763 TEST_P(%(test_name)s, %(name)sValidArgsNewId) {
4765 %(gl_func_name)s(%(gl_args_with_new_id)s));
4766 EXPECT_CALL(*gl_, %(gl_gen_func_name)s(1, _))
4767 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
4768 SpecializedSetup<cmds::%(name)s, 0>(true);
4770 cmd.Init(%(args_with_new_id)s);"""
4773 decoder_->set_unsafe_es3_apis_enabled(true);
4774 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4775 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4776 EXPECT_TRUE(Get%(resource_type)s(kNewClientId) != NULL);
4777 decoder_->set_unsafe_es3_apis_enabled(false);
4778 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));
4783 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4784 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4785 EXPECT_TRUE(Get%(resource_type)s(kNewClientId) != NULL);
4789 gl_args_with_new_id
= []
4790 args_with_new_id
= []
4791 for arg
in func
.GetOriginalArgs():
4792 if hasattr(arg
, 'resource_type'):
4793 gl_args_with_new_id
.append('kNewServiceId')
4794 args_with_new_id
.append('kNewClientId')
4796 gl_args_with_new_id
.append(arg
.GetValidGLArg(func
))
4797 args_with_new_id
.append(arg
.GetValidArg(func
))
4798 self
.WriteValidUnitTest(func
, file, valid_test
, {
4799 'args_with_new_id': ", ".join(args_with_new_id
),
4800 'gl_args_with_new_id': ", ".join(gl_args_with_new_id
),
4801 'resource_type': func
.GetResourceIdArg().resource_type
,
4802 'gl_gen_func_name': func
.GetInfo("gen_func"),
4806 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
4807 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
4808 SpecializedSetup<cmds::%(name)s, 0>(false);
4811 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
4814 self
.WriteInvalidUnitTest(func
, file, invalid_test
, *extras
)
4816 def WriteGLES2Implementation(self
, func
, file):
4817 """Writes the GLES2 Implemention."""
4819 impl_func
= func
.GetInfo('impl_func')
4820 impl_decl
= func
.GetInfo('impl_decl')
4822 if (func
.can_auto_generate
and
4823 (impl_func
== None or impl_func
== True) and
4824 (impl_decl
== None or impl_decl
== True)):
4826 file.Write("%s GLES2Implementation::%s(%s) {\n" %
4827 (func
.return_type
, func
.original_name
,
4828 func
.MakeTypedOriginalArgString("")))
4829 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
4830 func
.WriteDestinationInitalizationValidation(file)
4831 self
.WriteClientGLCallLog(func
, file)
4832 for arg
in func
.GetOriginalArgs():
4833 arg
.WriteClientSideValidationCode(file, func
)
4835 code
= """ if (Is%(type)sReservedId(%(id)s)) {
4836 SetGLError(GL_INVALID_OPERATION, "%(name)s\", \"%(id)s reserved id");
4839 %(name)sHelper(%(arg_string)s);
4844 name_arg
= func
.GetResourceIdArg()
4847 'arg_string': func
.MakeOriginalArgString(""),
4848 'id': name_arg
.name
,
4849 'type': name_arg
.resource_type
,
4850 'lc_type': name_arg
.resource_type
.lower(),
4853 def WriteGLES2ImplementationUnitTest(self
, func
, file):
4854 """Overrriden from TypeHandler."""
4855 client_test
= func
.GetInfo('client_test')
4856 if client_test
== False:
4859 TEST_F(GLES2ImplementationTest, %(name)s) {
4864 expected.cmd.Init(%(cmd_args)s);
4866 gl_->%(name)s(%(args)s);
4867 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));"""
4868 if not func
.IsUnsafe():
4871 gl_->%(name)s(%(args)s);
4872 EXPECT_TRUE(NoCommandsWritten());"""
4877 arg
.GetValidClientSideCmdArg(func
) for arg
in func
.GetCmdArgs()
4880 arg
.GetValidClientSideArg(func
) for arg
in func
.GetOriginalArgs()
4885 'args': ", ".join(gl_arg_strings
),
4886 'cmd_args': ", ".join(cmd_arg_strings
),
4890 class GENnHandler(TypeHandler
):
4891 """Handler for glGen___ type functions."""
4894 TypeHandler
.__init
__(self
)
4896 def InitFunction(self
, func
):
4897 """Overrriden from TypeHandler."""
4900 def WriteGetDataSizeCode(self
, func
, file):
4901 """Overrriden from TypeHandler."""
4902 code
= """ uint32_t data_size;
4903 if (!SafeMultiplyUint32(n, sizeof(GLuint), &data_size)) {
4904 return error::kOutOfBounds;
4909 def WriteHandlerImplementation (self
, func
, file):
4910 """Overrriden from TypeHandler."""
4911 file.Write(" if (!%sHelper(n, %s)) {\n"
4912 " return error::kInvalidArguments;\n"
4914 (func
.name
, func
.GetLastOriginalArg().name
))
4916 def WriteImmediateHandlerImplementation(self
, func
, file):
4917 """Overrriden from TypeHandler."""
4919 file.Write(""" for (GLsizei ii = 0; ii < n; ++ii) {
4920 if (group_->Get%(resource_name)sServiceId(%(last_arg_name)s[ii], NULL)) {
4921 return error::kInvalidArguments;
4924 scoped_ptr<GLuint[]> service_ids(new GLuint[n]);
4925 gl%(func_name)s(n, service_ids.get());
4926 for (GLsizei ii = 0; ii < n; ++ii) {
4927 group_->Add%(resource_name)sId(%(last_arg_name)s[ii], service_ids[ii]);
4929 """ % { 'func_name': func
.original_name
,
4930 'last_arg_name': func
.GetLastOriginalArg().name
,
4931 'resource_name': func
.GetInfo('resource_type') })
4933 file.Write(" if (!%sHelper(n, %s)) {\n"
4934 " return error::kInvalidArguments;\n"
4936 (func
.original_name
, func
.GetLastOriginalArg().name
))
4938 def WriteGLES2Implementation(self
, func
, file):
4939 """Overrriden from TypeHandler."""
4940 log_code
= (""" GPU_CLIENT_LOG_CODE_BLOCK({
4941 for (GLsizei i = 0; i < n; ++i) {
4942 GPU_CLIENT_LOG(" " << i << ": " << %s[i]);
4944 });""" % func
.GetOriginalArgs()[1].name
)
4946 'log_code': log_code
,
4947 'return_type': func
.return_type
,
4948 'name': func
.original_name
,
4949 'typed_args': func
.MakeTypedOriginalArgString(""),
4950 'args': func
.MakeOriginalArgString(""),
4951 'resource_types': func
.GetInfo('resource_types'),
4952 'count_name': func
.GetOriginalArgs()[0].name
,
4955 "%(return_type)s GLES2Implementation::%(name)s(%(typed_args)s) {\n" %
4957 func
.WriteDestinationInitalizationValidation(file)
4958 self
.WriteClientGLCallLog(func
, file)
4959 for arg
in func
.GetOriginalArgs():
4960 arg
.WriteClientSideValidationCode(file, func
)
4961 not_shared
= func
.GetInfo('not_shared')
4965 """ IdAllocator* id_allocator = GetIdAllocator(id_namespaces::k%s);
4966 for (GLsizei ii = 0; ii < n; ++ii)
4967 %s[ii] = id_allocator->AllocateID();""" %
4968 (func
.GetInfo('resource_types'), func
.GetOriginalArgs()[1].name
))
4970 alloc_code
= (""" GetIdHandler(id_namespaces::k%(resource_types)s)->
4971 MakeIds(this, 0, %(args)s);""" % args
)
4972 args
['alloc_code'] = alloc_code
4974 code
= """ GPU_CLIENT_SINGLE_THREAD_CHECK();
4976 %(name)sHelper(%(args)s);
4977 helper_->%(name)sImmediate(%(args)s);
4978 if (share_group_->bind_generates_resource())
4979 helper_->CommandBufferHelper::Flush();
4985 file.Write(code
% args
)
4987 def WriteGLES2ImplementationUnitTest(self
, func
, file):
4988 """Overrriden from TypeHandler."""
4990 TEST_F(GLES2ImplementationTest, %(name)s) {
4991 GLuint ids[2] = { 0, };
4993 cmds::%(name)sImmediate gen;
4997 expected.gen.Init(arraysize(ids), &ids[0]);
4998 expected.data[0] = k%(types)sStartId;
4999 expected.data[1] = k%(types)sStartId + 1;
5000 gl_->%(name)s(arraysize(ids), &ids[0]);
5001 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
5002 EXPECT_EQ(k%(types)sStartId, ids[0]);
5003 EXPECT_EQ(k%(types)sStartId + 1, ids[1]);
5008 'types': func
.GetInfo('resource_types'),
5011 def WriteServiceUnitTest(self
, func
, file, *extras
):
5012 """Overrriden from TypeHandler."""
5014 TEST_P(%(test_name)s, %(name)sValidArgs) {
5015 EXPECT_CALL(*gl_, %(gl_func_name)s(1, _))
5016 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
5017 GetSharedMemoryAs<GLuint*>()[0] = kNewClientId;
5018 SpecializedSetup<cmds::%(name)s, 0>(true);
5021 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5022 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
5026 EXPECT_TRUE(Get%(resource_name)sServiceId(kNewClientId, &service_id));
5027 EXPECT_EQ(kNewServiceId, service_id)
5032 EXPECT_TRUE(Get%(resource_name)s(kNewClientId, &service_id) != NULL);
5035 self
.WriteValidUnitTest(func
, file, valid_test
, {
5036 'resource_name': func
.GetInfo('resource_type'),
5039 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
5040 EXPECT_CALL(*gl_, %(gl_func_name)s(_, _)).Times(0);
5041 GetSharedMemoryAs<GLuint*>()[0] = client_%(resource_name)s_id_;
5042 SpecializedSetup<cmds::%(name)s, 0>(false);
5045 EXPECT_EQ(error::kInvalidArguments, ExecuteCmd(cmd));
5048 self
.WriteValidUnitTest(func
, file, invalid_test
, {
5049 'resource_name': func
.GetInfo('resource_type').lower(),
5052 def WriteImmediateServiceUnitTest(self
, func
, file, *extras
):
5053 """Overrriden from TypeHandler."""
5055 TEST_P(%(test_name)s, %(name)sValidArgs) {
5056 EXPECT_CALL(*gl_, %(gl_func_name)s(1, _))
5057 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
5058 cmds::%(name)s* cmd = GetImmediateAs<cmds::%(name)s>();
5059 GLuint temp = kNewClientId;
5060 SpecializedSetup<cmds::%(name)s, 0>(true);"""
5063 decoder_->set_unsafe_es3_apis_enabled(true);"""
5065 cmd->Init(1, &temp);
5066 EXPECT_EQ(error::kNoError,
5067 ExecuteImmediateCmd(*cmd, sizeof(temp)));
5068 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
5072 EXPECT_TRUE(Get%(resource_name)sServiceId(kNewClientId, &service_id));
5073 EXPECT_EQ(kNewServiceId, service_id);
5074 decoder_->set_unsafe_es3_apis_enabled(false);
5075 EXPECT_EQ(error::kUnknownCommand,
5076 ExecuteImmediateCmd(*cmd, sizeof(temp)));
5081 EXPECT_TRUE(Get%(resource_name)s(kNewClientId) != NULL);
5084 self
.WriteValidUnitTest(func
, file, valid_test
, {
5085 'resource_name': func
.GetInfo('resource_type'),
5088 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
5089 EXPECT_CALL(*gl_, %(gl_func_name)s(_, _)).Times(0);
5090 cmds::%(name)s* cmd = GetImmediateAs<cmds::%(name)s>();
5091 SpecializedSetup<cmds::%(name)s, 0>(false);
5092 cmd->Init(1, &client_%(resource_name)s_id_);"""
5095 decoder_->set_unsafe_es3_apis_enabled(true);
5096 EXPECT_EQ(error::kInvalidArguments,
5097 ExecuteImmediateCmd(*cmd, sizeof(&client_%(resource_name)s_id_)));
5098 decoder_->set_unsafe_es3_apis_enabled(false);
5103 EXPECT_EQ(error::kInvalidArguments,
5104 ExecuteImmediateCmd(*cmd, sizeof(&client_%(resource_name)s_id_)));
5107 self
.WriteValidUnitTest(func
, file, invalid_test
, {
5108 'resource_name': func
.GetInfo('resource_type').lower(),
5111 def WriteImmediateCmdComputeSize(self
, func
, file):
5112 """Overrriden from TypeHandler."""
5113 file.Write(" static uint32_t ComputeDataSize(GLsizei n) {\n")
5115 " return static_cast<uint32_t>(sizeof(GLuint) * n); // NOLINT\n")
5118 file.Write(" static uint32_t ComputeSize(GLsizei n) {\n")
5119 file.Write(" return static_cast<uint32_t>(\n")
5120 file.Write(" sizeof(ValueType) + ComputeDataSize(n)); // NOLINT\n")
5124 def WriteImmediateCmdSetHeader(self
, func
, file):
5125 """Overrriden from TypeHandler."""
5126 file.Write(" void SetHeader(GLsizei n) {\n")
5127 file.Write(" header.SetCmdByTotalSize<ValueType>(ComputeSize(n));\n")
5131 def WriteImmediateCmdInit(self
, func
, file):
5132 """Overrriden from TypeHandler."""
5133 last_arg
= func
.GetLastOriginalArg()
5134 file.Write(" void Init(%s, %s _%s) {\n" %
5135 (func
.MakeTypedCmdArgString("_"),
5136 last_arg
.type, last_arg
.name
))
5137 file.Write(" SetHeader(_n);\n")
5138 args
= func
.GetCmdArgs()
5140 file.Write(" %s = _%s;\n" % (arg
.name
, arg
.name
))
5141 file.Write(" memcpy(ImmediateDataAddress(this),\n")
5142 file.Write(" _%s, ComputeDataSize(_n));\n" % last_arg
.name
)
5146 def WriteImmediateCmdSet(self
, func
, file):
5147 """Overrriden from TypeHandler."""
5148 last_arg
= func
.GetLastOriginalArg()
5149 copy_args
= func
.MakeCmdArgString("_", False)
5150 file.Write(" void* Set(void* cmd%s, %s _%s) {\n" %
5151 (func
.MakeTypedCmdArgString("_", True),
5152 last_arg
.type, last_arg
.name
))
5153 file.Write(" static_cast<ValueType*>(cmd)->Init(%s, _%s);\n" %
5154 (copy_args
, last_arg
.name
))
5155 file.Write(" const uint32_t size = ComputeSize(_n);\n")
5156 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
5161 def WriteImmediateCmdHelper(self
, func
, file):
5162 """Overrriden from TypeHandler."""
5163 code
= """ void %(name)s(%(typed_args)s) {
5164 const uint32_t size = gles2::cmds::%(name)s::ComputeSize(n);
5165 gles2::cmds::%(name)s* c =
5166 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
5175 "typed_args": func
.MakeTypedOriginalArgString(""),
5176 "args": func
.MakeOriginalArgString(""),
5179 def WriteImmediateFormatTest(self
, func
, file):
5180 """Overrriden from TypeHandler."""
5181 file.Write("TEST_F(GLES2FormatTest, %s) {\n" % func
.name
)
5182 file.Write(" static GLuint ids[] = { 12, 23, 34, };\n")
5183 file.Write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
5184 (func
.name
, func
.name
))
5185 file.Write(" void* next_cmd = cmd.Set(\n")
5186 file.Write(" &cmd, static_cast<GLsizei>(arraysize(ids)), ids);\n")
5187 file.Write(" EXPECT_EQ(static_cast<uint32_t>(cmds::%s::kCmdId),\n" %
5189 file.Write(" cmd.header.command);\n")
5190 file.Write(" EXPECT_EQ(sizeof(cmd) +\n")
5191 file.Write(" RoundSizeToMultipleOfEntries(cmd.n * 4u),\n")
5192 file.Write(" cmd.header.size * 4u);\n")
5193 file.Write(" EXPECT_EQ(static_cast<GLsizei>(arraysize(ids)), cmd.n);\n");
5194 file.Write(" CheckBytesWrittenMatchesExpectedSize(\n")
5195 file.Write(" next_cmd, sizeof(cmd) +\n")
5196 file.Write(" RoundSizeToMultipleOfEntries(arraysize(ids) * 4u));\n")
5197 file.Write(" // TODO(gman): Check that ids were inserted;\n")
5202 class CreateHandler(TypeHandler
):
5203 """Handler for glCreate___ type functions."""
5206 TypeHandler
.__init
__(self
)
5208 def InitFunction(self
, func
):
5209 """Overrriden from TypeHandler."""
5210 func
.AddCmdArg(Argument("client_id", 'uint32_t'))
5212 def __GetResourceType(self
, func
):
5213 if func
.return_type
== "GLsync":
5216 return func
.name
[6:] # Create*
5218 def WriteServiceUnitTest(self
, func
, file, *extras
):
5219 """Overrriden from TypeHandler."""
5221 TEST_P(%(test_name)s, %(name)sValidArgs) {
5222 %(id_type_cast)sEXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s))
5223 .WillOnce(Return(%(const_service_id)s));
5224 SpecializedSetup<cmds::%(name)s, 0>(true);
5226 cmd.Init(%(args)s%(comma)skNewClientId);"""
5229 decoder_->set_unsafe_es3_apis_enabled(true);"""
5231 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5232 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
5235 %(return_type)s service_id = 0;
5236 EXPECT_TRUE(Get%(resource_type)sServiceId(kNewClientId, &service_id));
5237 EXPECT_EQ(%(const_service_id)s, service_id);
5238 decoder_->set_unsafe_es3_apis_enabled(false);
5239 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));
5244 EXPECT_TRUE(Get%(resource_type)s(kNewClientId));
5249 for arg
in func
.GetOriginalArgs():
5250 if not arg
.IsConstant():
5254 if func
.return_type
== 'GLsync':
5255 id_type_cast
= ("const GLsync kNewServiceIdGLuint = reinterpret_cast"
5256 "<GLsync>(kNewServiceId);\n ")
5257 const_service_id
= "kNewServiceIdGLuint"
5260 const_service_id
= "kNewServiceId"
5261 self
.WriteValidUnitTest(func
, file, valid_test
, {
5263 'resource_type': self
.__GetResourceType
(func
),
5264 'return_type': func
.return_type
,
5265 'id_type_cast': id_type_cast
,
5266 'const_service_id': const_service_id
,
5269 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
5270 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
5271 SpecializedSetup<cmds::%(name)s, 0>(false);
5273 cmd.Init(%(args)s%(comma)skNewClientId);
5274 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));%(gl_error_test)s
5277 self
.WriteInvalidUnitTest(func
, file, invalid_test
, {
5281 def WriteHandlerImplementation (self
, func
, file):
5282 """Overrriden from TypeHandler."""
5284 code
= """ uint32_t client_id = c.client_id;
5285 %(return_type)s service_id = 0;
5286 if (group_->Get%(resource_name)sServiceId(client_id, &service_id)) {
5287 return error::kInvalidArguments;
5289 service_id = %(gl_func_name)s(%(gl_args)s);
5291 group_->Add%(resource_name)sId(client_id, service_id);
5295 code
= """ uint32_t client_id = c.client_id;
5296 if (Get%(resource_name)s(client_id)) {
5297 return error::kInvalidArguments;
5299 %(return_type)s service_id = %(gl_func_name)s(%(gl_args)s);
5301 Create%(resource_name)s(client_id, service_id%(gl_args_with_comma)s);
5305 'resource_name': self
.__GetResourceType
(func
),
5306 'return_type': func
.return_type
,
5307 'gl_func_name': func
.GetGLFunctionName(),
5308 'gl_args': func
.MakeOriginalArgString(""),
5309 'gl_args_with_comma': func
.MakeOriginalArgString("", True) })
5311 def WriteGLES2Implementation(self
, func
, file):
5312 """Overrriden from TypeHandler."""
5313 file.Write("%s GLES2Implementation::%s(%s) {\n" %
5314 (func
.return_type
, func
.original_name
,
5315 func
.MakeTypedOriginalArgString("")))
5316 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
5317 func
.WriteDestinationInitalizationValidation(file)
5318 self
.WriteClientGLCallLog(func
, file)
5319 for arg
in func
.GetOriginalArgs():
5320 arg
.WriteClientSideValidationCode(file, func
)
5321 file.Write(" GLuint client_id;\n")
5322 if func
.return_type
== "GLsync":
5324 " GetIdHandler(id_namespaces::kSyncs)->\n")
5327 " GetIdHandler(id_namespaces::kProgramsAndShaders)->\n")
5328 file.Write(" MakeIds(this, 0, 1, &client_id);\n")
5329 file.Write(" helper_->%s(%s);\n" %
5330 (func
.name
, func
.MakeCmdArgString("")))
5331 file.Write(' GPU_CLIENT_LOG("returned " << client_id);\n')
5332 file.Write(" CheckGLError();\n")
5333 if func
.return_type
== "GLsync":
5334 file.Write(" return reinterpret_cast<GLsync>(client_id);\n")
5336 file.Write(" return client_id;\n")
5341 class DeleteHandler(TypeHandler
):
5342 """Handler for glDelete___ single resource type functions."""
5345 TypeHandler
.__init
__(self
)
5347 def WriteServiceImplementation(self
, func
, file):
5348 """Overrriden from TypeHandler."""
5350 TypeHandler
.WriteServiceImplementation(self
, func
, file)
5351 # HandleDeleteShader and HandleDeleteProgram are manually written.
5354 def WriteGLES2Implementation(self
, func
, file):
5355 """Overrriden from TypeHandler."""
5356 file.Write("%s GLES2Implementation::%s(%s) {\n" %
5357 (func
.return_type
, func
.original_name
,
5358 func
.MakeTypedOriginalArgString("")))
5359 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
5360 func
.WriteDestinationInitalizationValidation(file)
5361 self
.WriteClientGLCallLog(func
, file)
5362 for arg
in func
.GetOriginalArgs():
5363 arg
.WriteClientSideValidationCode(file, func
)
5365 " GPU_CLIENT_DCHECK(%s != 0);\n" % func
.GetOriginalArgs()[-1].name
)
5366 file.Write(" %sHelper(%s);\n" %
5367 (func
.original_name
, func
.GetOriginalArgs()[-1].name
))
5368 file.Write(" CheckGLError();\n")
5372 def WriteHandlerImplementation (self
, func
, file):
5373 """Overrriden from TypeHandler."""
5374 assert len(func
.GetOriginalArgs()) == 1
5375 arg
= func
.GetOriginalArgs()[0]
5377 file.Write(""" %(arg_type)s service_id = 0;
5378 if (group_->Get%(resource_type)sServiceId(%(arg_name)s, &service_id)) {
5379 glDelete%(resource_type)s(service_id);
5380 group_->Remove%(resource_type)sId(%(arg_name)s);
5383 GL_INVALID_VALUE, "gl%(func_name)s", "unknown %(arg_name)s");
5385 """ % { 'resource_type': func
.GetInfo('resource_type'),
5386 'arg_name': arg
.name
,
5387 'arg_type': arg
.type,
5388 'func_name': func
.original_name
})
5390 file.Write(" %sHelper(%s);\n" % (func
.original_name
, arg
.name
))
5392 class DELnHandler(TypeHandler
):
5393 """Handler for glDelete___ type functions."""
5396 TypeHandler
.__init
__(self
)
5398 def WriteGetDataSizeCode(self
, func
, file):
5399 """Overrriden from TypeHandler."""
5400 code
= """ uint32_t data_size;
5401 if (!SafeMultiplyUint32(n, sizeof(GLuint), &data_size)) {
5402 return error::kOutOfBounds;
5407 def WriteGLES2ImplementationUnitTest(self
, func
, file):
5408 """Overrriden from TypeHandler."""
5410 TEST_F(GLES2ImplementationTest, %(name)s) {
5411 GLuint ids[2] = { k%(types)sStartId, k%(types)sStartId + 1 };
5413 cmds::%(name)sImmediate del;
5417 expected.del.Init(arraysize(ids), &ids[0]);
5418 expected.data[0] = k%(types)sStartId;
5419 expected.data[1] = k%(types)sStartId + 1;
5420 gl_->%(name)s(arraysize(ids), &ids[0]);
5421 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
5426 'types': func
.GetInfo('resource_types'),
5429 def WriteServiceUnitTest(self
, func
, file, *extras
):
5430 """Overrriden from TypeHandler."""
5432 TEST_P(%(test_name)s, %(name)sValidArgs) {
5435 %(gl_func_name)s(1, Pointee(kService%(upper_resource_name)sId)))
5437 GetSharedMemoryAs<GLuint*>()[0] = client_%(resource_name)s_id_;
5438 SpecializedSetup<cmds::%(name)s, 0>(true);
5441 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5442 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5444 Get%(upper_resource_name)s(client_%(resource_name)s_id_) == NULL);
5447 self
.WriteValidUnitTest(func
, file, valid_test
, {
5448 'resource_name': func
.GetInfo('resource_type').lower(),
5449 'upper_resource_name': func
.GetInfo('resource_type'),
5452 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
5453 GetSharedMemoryAs<GLuint*>()[0] = kInvalidClientId;
5454 SpecializedSetup<cmds::%(name)s, 0>(false);
5457 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5460 self
.WriteValidUnitTest(func
, file, invalid_test
, *extras
)
5462 def WriteImmediateServiceUnitTest(self
, func
, file, *extras
):
5463 """Overrriden from TypeHandler."""
5465 TEST_P(%(test_name)s, %(name)sValidArgs) {
5468 %(gl_func_name)s(1, Pointee(kService%(upper_resource_name)sId)))
5470 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
5471 SpecializedSetup<cmds::%(name)s, 0>(true);
5472 cmd.Init(1, &client_%(resource_name)s_id_);"""
5475 decoder_->set_unsafe_es3_apis_enabled(true);"""
5477 EXPECT_EQ(error::kNoError,
5478 ExecuteImmediateCmd(cmd, sizeof(client_%(resource_name)s_id_)));
5479 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
5482 EXPECT_FALSE(Get%(upper_resource_name)sServiceId(
5483 client_%(resource_name)s_id_, NULL));
5484 decoder_->set_unsafe_es3_apis_enabled(false);
5485 EXPECT_EQ(error::kUnknownCommand,
5486 ExecuteImmediateCmd(cmd, sizeof(client_%(resource_name)s_id_)));
5492 Get%(upper_resource_name)s(client_%(resource_name)s_id_) == NULL);
5495 self
.WriteValidUnitTest(func
, file, valid_test
, {
5496 'resource_name': func
.GetInfo('resource_type').lower(),
5497 'upper_resource_name': func
.GetInfo('resource_type'),
5500 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
5501 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
5502 SpecializedSetup<cmds::%(name)s, 0>(false);
5503 GLuint temp = kInvalidClientId;
5504 cmd.Init(1, &temp);"""
5507 decoder_->set_unsafe_es3_apis_enabled(true);
5508 EXPECT_EQ(error::kNoError,
5509 ExecuteImmediateCmd(cmd, sizeof(temp)));
5510 decoder_->set_unsafe_es3_apis_enabled(false);
5511 EXPECT_EQ(error::kUnknownCommand,
5512 ExecuteImmediateCmd(cmd, sizeof(temp)));
5517 EXPECT_EQ(error::kNoError,
5518 ExecuteImmediateCmd(cmd, sizeof(temp)));
5521 self
.WriteValidUnitTest(func
, file, invalid_test
, *extras
)
5523 def WriteHandlerImplementation (self
, func
, file):
5524 """Overrriden from TypeHandler."""
5525 file.Write(" %sHelper(n, %s);\n" %
5526 (func
.name
, func
.GetLastOriginalArg().name
))
5528 def WriteImmediateHandlerImplementation (self
, func
, file):
5529 """Overrriden from TypeHandler."""
5531 file.Write(""" for (GLsizei ii = 0; ii < n; ++ii) {
5532 GLuint service_id = 0;
5533 if (group_->Get%(resource_type)sServiceId(
5534 %(last_arg_name)s[ii], &service_id)) {
5535 glDelete%(resource_type)ss(1, &service_id);
5536 group_->Remove%(resource_type)sId(%(last_arg_name)s[ii]);
5539 """ % { 'resource_type': func
.GetInfo('resource_type'),
5540 'last_arg_name': func
.GetLastOriginalArg().name
})
5542 file.Write(" %sHelper(n, %s);\n" %
5543 (func
.original_name
, func
.GetLastOriginalArg().name
))
5545 def WriteGLES2Implementation(self
, func
, file):
5546 """Overrriden from TypeHandler."""
5547 impl_decl
= func
.GetInfo('impl_decl')
5548 if impl_decl
== None or impl_decl
== True:
5550 'return_type': func
.return_type
,
5551 'name': func
.original_name
,
5552 'typed_args': func
.MakeTypedOriginalArgString(""),
5553 'args': func
.MakeOriginalArgString(""),
5554 'resource_type': func
.GetInfo('resource_type').lower(),
5555 'count_name': func
.GetOriginalArgs()[0].name
,
5558 "%(return_type)s GLES2Implementation::%(name)s(%(typed_args)s) {\n" %
5560 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
5561 func
.WriteDestinationInitalizationValidation(file)
5562 self
.WriteClientGLCallLog(func
, file)
5563 file.Write(""" GPU_CLIENT_LOG_CODE_BLOCK({
5564 for (GLsizei i = 0; i < n; ++i) {
5565 GPU_CLIENT_LOG(" " << i << ": " << %s[i]);
5568 """ % func
.GetOriginalArgs()[1].name
)
5569 file.Write(""" GPU_CLIENT_DCHECK_CODE_BLOCK({
5570 for (GLsizei i = 0; i < n; ++i) {
5574 """ % func
.GetOriginalArgs()[1].name
)
5575 for arg
in func
.GetOriginalArgs():
5576 arg
.WriteClientSideValidationCode(file, func
)
5577 code
= """ %(name)sHelper(%(args)s);
5582 file.Write(code
% args
)
5584 def WriteImmediateCmdComputeSize(self
, func
, file):
5585 """Overrriden from TypeHandler."""
5586 file.Write(" static uint32_t ComputeDataSize(GLsizei n) {\n")
5588 " return static_cast<uint32_t>(sizeof(GLuint) * n); // NOLINT\n")
5591 file.Write(" static uint32_t ComputeSize(GLsizei n) {\n")
5592 file.Write(" return static_cast<uint32_t>(\n")
5593 file.Write(" sizeof(ValueType) + ComputeDataSize(n)); // NOLINT\n")
5597 def WriteImmediateCmdSetHeader(self
, func
, file):
5598 """Overrriden from TypeHandler."""
5599 file.Write(" void SetHeader(GLsizei n) {\n")
5600 file.Write(" header.SetCmdByTotalSize<ValueType>(ComputeSize(n));\n")
5604 def WriteImmediateCmdInit(self
, func
, file):
5605 """Overrriden from TypeHandler."""
5606 last_arg
= func
.GetLastOriginalArg()
5607 file.Write(" void Init(%s, %s _%s) {\n" %
5608 (func
.MakeTypedCmdArgString("_"),
5609 last_arg
.type, last_arg
.name
))
5610 file.Write(" SetHeader(_n);\n")
5611 args
= func
.GetCmdArgs()
5613 file.Write(" %s = _%s;\n" % (arg
.name
, arg
.name
))
5614 file.Write(" memcpy(ImmediateDataAddress(this),\n")
5615 file.Write(" _%s, ComputeDataSize(_n));\n" % last_arg
.name
)
5619 def WriteImmediateCmdSet(self
, func
, file):
5620 """Overrriden from TypeHandler."""
5621 last_arg
= func
.GetLastOriginalArg()
5622 copy_args
= func
.MakeCmdArgString("_", False)
5623 file.Write(" void* Set(void* cmd%s, %s _%s) {\n" %
5624 (func
.MakeTypedCmdArgString("_", True),
5625 last_arg
.type, last_arg
.name
))
5626 file.Write(" static_cast<ValueType*>(cmd)->Init(%s, _%s);\n" %
5627 (copy_args
, last_arg
.name
))
5628 file.Write(" const uint32_t size = ComputeSize(_n);\n")
5629 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
5634 def WriteImmediateCmdHelper(self
, func
, file):
5635 """Overrriden from TypeHandler."""
5636 code
= """ void %(name)s(%(typed_args)s) {
5637 const uint32_t size = gles2::cmds::%(name)s::ComputeSize(n);
5638 gles2::cmds::%(name)s* c =
5639 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
5648 "typed_args": func
.MakeTypedOriginalArgString(""),
5649 "args": func
.MakeOriginalArgString(""),
5652 def WriteImmediateFormatTest(self
, func
, file):
5653 """Overrriden from TypeHandler."""
5654 file.Write("TEST_F(GLES2FormatTest, %s) {\n" % func
.name
)
5655 file.Write(" static GLuint ids[] = { 12, 23, 34, };\n")
5656 file.Write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
5657 (func
.name
, func
.name
))
5658 file.Write(" void* next_cmd = cmd.Set(\n")
5659 file.Write(" &cmd, static_cast<GLsizei>(arraysize(ids)), ids);\n")
5660 file.Write(" EXPECT_EQ(static_cast<uint32_t>(cmds::%s::kCmdId),\n" %
5662 file.Write(" cmd.header.command);\n")
5663 file.Write(" EXPECT_EQ(sizeof(cmd) +\n")
5664 file.Write(" RoundSizeToMultipleOfEntries(cmd.n * 4u),\n")
5665 file.Write(" cmd.header.size * 4u);\n")
5666 file.Write(" EXPECT_EQ(static_cast<GLsizei>(arraysize(ids)), cmd.n);\n");
5667 file.Write(" CheckBytesWrittenMatchesExpectedSize(\n")
5668 file.Write(" next_cmd, sizeof(cmd) +\n")
5669 file.Write(" RoundSizeToMultipleOfEntries(arraysize(ids) * 4u));\n")
5670 file.Write(" // TODO(gman): Check that ids were inserted;\n")
5675 class GETnHandler(TypeHandler
):
5676 """Handler for GETn for glGetBooleanv, glGetFloatv, ... type functions."""
5679 TypeHandler
.__init
__(self
)
5681 def NeedsDataTransferFunction(self
, func
):
5682 """Overriden from TypeHandler."""
5685 def WriteServiceImplementation(self
, func
, file):
5686 """Overrriden from TypeHandler."""
5687 self
.WriteServiceHandlerFunctionHeader(func
, file)
5688 last_arg
= func
.GetLastOriginalArg()
5689 # All except shm_id and shm_offset.
5690 all_but_last_args
= func
.GetCmdArgs()[:-2]
5691 for arg
in all_but_last_args
:
5692 arg
.WriteGetCode(file)
5694 code
= """ typedef cmds::%(func_name)s::Result Result;
5695 GLsizei num_values = 0;
5696 GetNumValuesReturnedForGLGet(pname, &num_values);
5697 Result* result = GetSharedMemoryAs<Result*>(
5698 c.%(last_arg_name)s_shm_id, c.%(last_arg_name)s_shm_offset,
5699 Result::ComputeSize(num_values));
5700 %(last_arg_type)s %(last_arg_name)s = result ? result->GetData() : NULL;
5703 'last_arg_type': last_arg
.type,
5704 'last_arg_name': last_arg
.name
,
5705 'func_name': func
.name
,
5707 func
.WriteHandlerValidation(file)
5708 code
= """ // Check that the client initialized the result.
5709 if (result->size != 0) {
5710 return error::kInvalidArguments;
5713 shadowed
= func
.GetInfo('shadowed')
5715 file.Write(' LOCAL_COPY_REAL_GL_ERRORS_TO_WRAPPER("%s");\n' % func
.name
)
5717 func
.WriteHandlerImplementation(file)
5719 code
= """ result->SetNumResults(num_values);
5720 return error::kNoError;
5724 code
= """ GLenum error = glGetError();
5725 if (error == GL_NO_ERROR) {
5726 result->SetNumResults(num_values);
5728 LOCAL_SET_GL_ERROR(error, "%(func_name)s", "");
5730 return error::kNoError;
5734 file.Write(code
% {'func_name': func
.name
})
5736 def WriteGLES2Implementation(self
, func
, file):
5737 """Overrriden from TypeHandler."""
5738 impl_decl
= func
.GetInfo('impl_decl')
5739 if impl_decl
== None or impl_decl
== True:
5740 file.Write("%s GLES2Implementation::%s(%s) {\n" %
5741 (func
.return_type
, func
.original_name
,
5742 func
.MakeTypedOriginalArgString("")))
5743 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
5744 func
.WriteDestinationInitalizationValidation(file)
5745 self
.WriteClientGLCallLog(func
, file)
5746 for arg
in func
.GetOriginalArgs():
5747 arg
.WriteClientSideValidationCode(file, func
)
5748 all_but_last_args
= func
.GetOriginalArgs()[:-1]
5750 has_length_arg
= False
5751 for arg
in all_but_last_args
:
5752 if arg
.type == 'GLsync':
5753 args
.append('ToGLuint(%s)' % arg
.name
)
5754 elif arg
.name
.endswith('size') and arg
.type == 'GLsizei':
5756 elif arg
.name
== 'length':
5757 has_length_arg
= True
5760 args
.append(arg
.name
)
5761 arg_string
= ", ".join(args
)
5765 for arg
in func
.GetOriginalArgs() if not arg
.IsConstant()]))
5766 self
.WriteTraceEvent(func
, file)
5767 code
= """ if (%(func_name)sHelper(%(all_arg_string)s)) {
5770 typedef cmds::%(func_name)s::Result Result;
5771 Result* result = GetResultAs<Result*>();
5775 result->SetNumResults(0);
5776 helper_->%(func_name)s(%(arg_string)s,
5777 GetResultShmId(), GetResultShmOffset());
5779 result->CopyResult(%(last_arg_name)s);
5780 GPU_CLIENT_LOG_CODE_BLOCK({
5781 for (int32_t i = 0; i < result->GetNumResults(); ++i) {
5782 GPU_CLIENT_LOG(" " << i << ": " << result->GetData()[i]);
5788 *length = result->GetNumResults();
5795 'func_name': func
.name
,
5796 'arg_string': arg_string
,
5797 'all_arg_string': all_arg_string
,
5798 'last_arg_name': func
.GetLastOriginalArg().name
,
5801 def WriteGLES2ImplementationUnitTest(self
, func
, file):
5802 """Writes the GLES2 Implemention unit test."""
5804 TEST_F(GLES2ImplementationTest, %(name)s) {
5808 typedef cmds::%(name)s::Result Result;
5809 Result::Type result = 0;
5811 ExpectedMemoryInfo result1 = GetExpectedResultMemory(4);
5812 expected.cmd.Init(%(cmd_args)s, result1.id, result1.offset);
5813 EXPECT_CALL(*command_buffer(), OnFlush())
5814 .WillOnce(SetMemory(result1.ptr, SizedResultHelper<Result::Type>(1)))
5815 .RetiresOnSaturation();
5816 gl_->%(name)s(%(args)s, &result);
5817 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
5818 EXPECT_EQ(static_cast<Result::Type>(1), result);
5821 first_cmd_arg
= func
.GetCmdArgs()[0].GetValidNonCachedClientSideCmdArg(func
)
5822 if not first_cmd_arg
:
5825 first_gl_arg
= func
.GetOriginalArgs()[0].GetValidNonCachedClientSideArg(
5828 cmd_arg_strings
= [first_cmd_arg
]
5829 for arg
in func
.GetCmdArgs()[1:-2]:
5830 cmd_arg_strings
.append(arg
.GetValidClientSideCmdArg(func
))
5831 gl_arg_strings
= [first_gl_arg
]
5832 for arg
in func
.GetOriginalArgs()[1:-1]:
5833 gl_arg_strings
.append(arg
.GetValidClientSideArg(func
))
5837 'args': ", ".join(gl_arg_strings
),
5838 'cmd_args': ", ".join(cmd_arg_strings
),
5841 def WriteServiceUnitTest(self
, func
, file, *extras
):
5842 """Overrriden from TypeHandler."""
5844 TEST_P(%(test_name)s, %(name)sValidArgs) {
5845 EXPECT_CALL(*gl_, GetError())
5846 .WillOnce(Return(GL_NO_ERROR))
5847 .WillOnce(Return(GL_NO_ERROR))
5848 .RetiresOnSaturation();
5849 SpecializedSetup<cmds::%(name)s, 0>(true);
5850 typedef cmds::%(name)s::Result Result;
5851 Result* result = static_cast<Result*>(shared_memory_address_);
5852 EXPECT_CALL(*gl_, %(gl_func_name)s(%(local_gl_args)s));
5855 cmd.Init(%(cmd_args)s);"""
5858 decoder_->set_unsafe_es3_apis_enabled(true);"""
5860 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5861 EXPECT_EQ(decoder_->GetGLES2Util()->GLGetNumValuesReturned(
5863 result->GetNumResults());
5864 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
5867 decoder_->set_unsafe_es3_apis_enabled(false);
5868 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));"""
5873 cmd_arg_strings
= []
5875 for arg
in func
.GetOriginalArgs()[:-1]:
5876 if arg
.name
== 'length':
5877 gl_arg_value
= 'nullptr'
5878 elif arg
.name
.endswith('size'):
5879 gl_arg_value
= ("decoder_->GetGLES2Util()->GLGetNumValuesReturned(%s)" %
5881 elif arg
.type == 'GLsync':
5882 gl_arg_value
= 'reinterpret_cast<GLsync>(kServiceSyncId)'
5884 gl_arg_value
= arg
.GetValidGLArg(func
)
5885 gl_arg_strings
.append(gl_arg_value
)
5886 if arg
.name
== 'pname':
5887 valid_pname
= gl_arg_value
5888 if arg
.name
.endswith('size') or arg
.name
== 'length':
5890 if arg
.type == 'GLsync':
5891 arg_value
= 'client_sync_id_'
5893 arg_value
= arg
.GetValidArg(func
)
5894 cmd_arg_strings
.append(arg_value
)
5895 if func
.GetInfo('gl_test_func') == 'glGetIntegerv':
5896 gl_arg_strings
.append("_")
5898 gl_arg_strings
.append("result->GetData()")
5899 cmd_arg_strings
.append("shared_memory_id_")
5900 cmd_arg_strings
.append("shared_memory_offset_")
5902 self
.WriteValidUnitTest(func
, file, valid_test
, {
5903 'local_gl_args': ", ".join(gl_arg_strings
),
5904 'cmd_args': ", ".join(cmd_arg_strings
),
5905 'valid_pname': valid_pname
,
5908 if not func
.IsUnsafe():
5910 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
5911 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
5912 SpecializedSetup<cmds::%(name)s, 0>(false);
5913 cmds::%(name)s::Result* result =
5914 static_cast<cmds::%(name)s::Result*>(shared_memory_address_);
5918 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));
5919 EXPECT_EQ(0u, result->size);%(gl_error_test)s
5922 self
.WriteInvalidUnitTest(func
, file, invalid_test
, *extras
)
5924 class ArrayArgTypeHandler(TypeHandler
):
5925 """Base class for type handlers that handle args that are arrays"""
5928 TypeHandler
.__init
__(self
)
5930 def GetArrayType(self
, func
):
5931 """Returns the type of the element in the element array being PUT to."""
5932 for arg
in func
.GetOriginalArgs():
5934 element_type
= arg
.GetPointedType()
5937 # Special case: array type handler is used for a function that is forwarded
5938 # to the actual array type implementation
5939 element_type
= func
.GetOriginalArgs()[-1].type
5940 assert all(arg
.type == element_type \
5941 for arg
in func
.GetOriginalArgs()[-self
.GetArrayCount(func
):])
5944 def GetArrayCount(self
, func
):
5945 """Returns the count of the elements in the array being PUT to."""
5946 return func
.GetInfo('count')
5948 class PUTHandler(ArrayArgTypeHandler
):
5949 """Handler for glTexParameter_v, glVertexAttrib_v functions."""
5952 ArrayArgTypeHandler
.__init
__(self
)
5954 def WriteServiceUnitTest(self
, func
, file, *extras
):
5955 """Writes the service unit test for a command."""
5956 expected_call
= "EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));"
5957 if func
.GetInfo("first_element_only"):
5959 arg
.GetValidGLArg(func
) for arg
in func
.GetOriginalArgs()
5961 gl_arg_strings
[-1] = "*" + gl_arg_strings
[-1]
5962 expected_call
= ("EXPECT_CALL(*gl_, %%(gl_func_name)s(%s));" %
5963 ", ".join(gl_arg_strings
))
5965 TEST_P(%(test_name)s, %(name)sValidArgs) {
5966 SpecializedSetup<cmds::%(name)s, 0>(true);
5969 GetSharedMemoryAs<%(data_type)s*>()[0] = %(data_value)s;
5971 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5972 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5976 'data_type': self
.GetArrayType(func
),
5977 'data_value': func
.GetInfo('data_value') or '0',
5978 'expected_call': expected_call
,
5980 self
.WriteValidUnitTest(func
, file, valid_test
, extra
, *extras
)
5983 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
5984 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
5985 SpecializedSetup<cmds::%(name)s, 0>(false);
5988 GetSharedMemoryAs<%(data_type)s*>()[0] = %(data_value)s;
5989 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
5992 self
.WriteInvalidUnitTest(func
, file, invalid_test
, extra
, *extras
)
5994 def WriteImmediateServiceUnitTest(self
, func
, file, *extras
):
5995 """Writes the service unit test for a command."""
5997 TEST_P(%(test_name)s, %(name)sValidArgs) {
5998 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
5999 SpecializedSetup<cmds::%(name)s, 0>(true);
6000 %(data_type)s temp[%(data_count)s] = { %(data_value)s, };
6001 cmd.Init(%(gl_args)s, &temp[0]);
6004 %(gl_func_name)s(%(gl_args)s, %(data_ref)sreinterpret_cast<
6005 %(data_type)s*>(ImmediateDataAddress(&cmd))));"""
6008 decoder_->set_unsafe_es3_apis_enabled(true);"""
6010 EXPECT_EQ(error::kNoError,
6011 ExecuteImmediateCmd(cmd, sizeof(temp)));
6012 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
6015 decoder_->set_unsafe_es3_apis_enabled(false);
6016 EXPECT_EQ(error::kUnknownCommand,
6017 ExecuteImmediateCmd(cmd, sizeof(temp)));"""
6022 arg
.GetValidGLArg(func
) for arg
in func
.GetOriginalArgs()[0:-1]
6024 gl_any_strings
= ["_"] * len(gl_arg_strings
)
6027 'data_ref': ("*" if func
.GetInfo('first_element_only') else ""),
6028 'data_type': self
.GetArrayType(func
),
6029 'data_count': self
.GetArrayCount(func
),
6030 'data_value': func
.GetInfo('data_value') or '0',
6031 'gl_args': ", ".join(gl_arg_strings
),
6032 'gl_any_args': ", ".join(gl_any_strings
),
6034 self
.WriteValidUnitTest(func
, file, valid_test
, extra
, *extras
)
6037 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
6038 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();"""
6041 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_any_args)s, _)).Times(1);
6045 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_any_args)s, _)).Times(0);
6048 SpecializedSetup<cmds::%(name)s, 0>(false);
6049 %(data_type)s temp[%(data_count)s] = { %(data_value)s, };
6050 cmd.Init(%(all_but_last_args)s, &temp[0]);"""
6053 decoder_->set_unsafe_es3_apis_enabled(true);
6054 EXPECT_EQ(error::%(parse_result)s,
6055 ExecuteImmediateCmd(cmd, sizeof(temp)));
6056 decoder_->set_unsafe_es3_apis_enabled(false);
6061 EXPECT_EQ(error::%(parse_result)s,
6062 ExecuteImmediateCmd(cmd, sizeof(temp)));
6066 self
.WriteInvalidUnitTest(func
, file, invalid_test
, extra
, *extras
)
6068 def WriteGetDataSizeCode(self
, func
, file):
6069 """Overrriden from TypeHandler."""
6070 code
= """ uint32_t data_size;
6071 if (!ComputeDataSize(1, sizeof(%s), %d, &data_size)) {
6072 return error::kOutOfBounds;
6075 file.Write(code
% (self
.GetArrayType(func
), self
.GetArrayCount(func
)))
6076 if func
.IsImmediate():
6077 file.Write(" if (data_size > immediate_data_size) {\n")
6078 file.Write(" return error::kOutOfBounds;\n")
6081 def __NeedsToCalcDataCount(self
, func
):
6082 use_count_func
= func
.GetInfo('use_count_func')
6083 return use_count_func
!= None and use_count_func
!= False
6085 def WriteGLES2Implementation(self
, func
, file):
6086 """Overrriden from TypeHandler."""
6087 impl_func
= func
.GetInfo('impl_func')
6088 if (impl_func
!= None and impl_func
!= True):
6090 file.Write("%s GLES2Implementation::%s(%s) {\n" %
6091 (func
.return_type
, func
.original_name
,
6092 func
.MakeTypedOriginalArgString("")))
6093 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
6094 func
.WriteDestinationInitalizationValidation(file)
6095 self
.WriteClientGLCallLog(func
, file)
6097 if self
.__NeedsToCalcDataCount
(func
):
6098 file.Write(" size_t count = GLES2Util::Calc%sDataCount(%s);\n" %
6099 (func
.name
, func
.GetOriginalArgs()[0].name
))
6100 file.Write(" DCHECK_LE(count, %du);\n" % self
.GetArrayCount(func
))
6102 file.Write(" size_t count = %d;" % self
.GetArrayCount(func
))
6103 file.Write(" for (size_t ii = 0; ii < count; ++ii)\n")
6104 file.Write(' GPU_CLIENT_LOG("value[" << ii << "]: " << %s[ii]);\n' %
6105 func
.GetLastOriginalArg().name
)
6106 for arg
in func
.GetOriginalArgs():
6107 arg
.WriteClientSideValidationCode(file, func
)
6108 file.Write(" helper_->%sImmediate(%s);\n" %
6109 (func
.name
, func
.MakeOriginalArgString("")))
6110 file.Write(" CheckGLError();\n")
6114 def WriteGLES2ImplementationUnitTest(self
, func
, file):
6115 """Writes the GLES2 Implemention unit test."""
6116 client_test
= func
.GetInfo('client_test')
6117 if (client_test
!= None and client_test
!= True):
6120 TEST_F(GLES2ImplementationTest, %(name)s) {
6121 %(type)s data[%(count)d] = {0};
6123 cmds::%(name)sImmediate cmd;
6124 %(type)s data[%(count)d];
6127 for (int jj = 0; jj < %(count)d; ++jj) {
6128 data[jj] = static_cast<%(type)s>(jj);
6131 expected.cmd.Init(%(cmd_args)s, &data[0]);
6132 gl_->%(name)s(%(args)s, &data[0]);
6133 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
6137 arg
.GetValidClientSideCmdArg(func
) for arg
in func
.GetCmdArgs()[0:-2]
6140 arg
.GetValidClientSideArg(func
) for arg
in func
.GetOriginalArgs()[0:-1]
6145 'type': self
.GetArrayType(func
),
6146 'count': self
.GetArrayCount(func
),
6147 'args': ", ".join(gl_arg_strings
),
6148 'cmd_args': ", ".join(cmd_arg_strings
),
6151 def WriteImmediateCmdComputeSize(self
, func
, file):
6152 """Overrriden from TypeHandler."""
6153 file.Write(" static uint32_t ComputeDataSize() {\n")
6154 file.Write(" return static_cast<uint32_t>(\n")
6155 file.Write(" sizeof(%s) * %d);\n" %
6156 (self
.GetArrayType(func
), self
.GetArrayCount(func
)))
6159 if self
.__NeedsToCalcDataCount
(func
):
6160 file.Write(" static uint32_t ComputeEffectiveDataSize(%s %s) {\n" %
6161 (func
.GetOriginalArgs()[0].type,
6162 func
.GetOriginalArgs()[0].name
))
6163 file.Write(" return static_cast<uint32_t>(\n")
6164 file.Write(" sizeof(%s) * GLES2Util::Calc%sDataCount(%s));\n" %
6165 (self
.GetArrayType(func
), func
.original_name
,
6166 func
.GetOriginalArgs()[0].name
))
6169 file.Write(" static uint32_t ComputeSize() {\n")
6170 file.Write(" return static_cast<uint32_t>(\n")
6172 " sizeof(ValueType) + ComputeDataSize());\n")
6176 def WriteImmediateCmdSetHeader(self
, func
, file):
6177 """Overrriden from TypeHandler."""
6178 file.Write(" void SetHeader() {\n")
6180 " header.SetCmdByTotalSize<ValueType>(ComputeSize());\n")
6184 def WriteImmediateCmdInit(self
, func
, file):
6185 """Overrriden from TypeHandler."""
6186 last_arg
= func
.GetLastOriginalArg()
6187 file.Write(" void Init(%s, %s _%s) {\n" %
6188 (func
.MakeTypedCmdArgString("_"),
6189 last_arg
.type, last_arg
.name
))
6190 file.Write(" SetHeader();\n")
6191 args
= func
.GetCmdArgs()
6193 file.Write(" %s = _%s;\n" % (arg
.name
, arg
.name
))
6194 file.Write(" memcpy(ImmediateDataAddress(this),\n")
6195 if self
.__NeedsToCalcDataCount
(func
):
6196 file.Write(" _%s, ComputeEffectiveDataSize(%s));" %
6197 (last_arg
.name
, func
.GetOriginalArgs()[0].name
))
6199 DCHECK_GE(ComputeDataSize(), ComputeEffectiveDataSize(%(arg)s));
6200 char* pointer = reinterpret_cast<char*>(ImmediateDataAddress(this)) +
6201 ComputeEffectiveDataSize(%(arg)s);
6202 memset(pointer, 0, ComputeDataSize() - ComputeEffectiveDataSize(%(arg)s));
6203 """ % { 'arg': func
.GetOriginalArgs()[0].name
, })
6205 file.Write(" _%s, ComputeDataSize());\n" % last_arg
.name
)
6209 def WriteImmediateCmdSet(self
, func
, file):
6210 """Overrriden from TypeHandler."""
6211 last_arg
= func
.GetLastOriginalArg()
6212 copy_args
= func
.MakeCmdArgString("_", False)
6213 file.Write(" void* Set(void* cmd%s, %s _%s) {\n" %
6214 (func
.MakeTypedCmdArgString("_", True),
6215 last_arg
.type, last_arg
.name
))
6216 file.Write(" static_cast<ValueType*>(cmd)->Init(%s, _%s);\n" %
6217 (copy_args
, last_arg
.name
))
6218 file.Write(" const uint32_t size = ComputeSize();\n")
6219 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
6224 def WriteImmediateCmdHelper(self
, func
, file):
6225 """Overrriden from TypeHandler."""
6226 code
= """ void %(name)s(%(typed_args)s) {
6227 const uint32_t size = gles2::cmds::%(name)s::ComputeSize();
6228 gles2::cmds::%(name)s* c =
6229 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
6238 "typed_args": func
.MakeTypedOriginalArgString(""),
6239 "args": func
.MakeOriginalArgString(""),
6242 def WriteImmediateFormatTest(self
, func
, file):
6243 """Overrriden from TypeHandler."""
6244 file.Write("TEST_F(GLES2FormatTest, %s) {\n" % func
.name
)
6245 file.Write(" const int kSomeBaseValueToTestWith = 51;\n")
6246 file.Write(" static %s data[] = {\n" % self
.GetArrayType(func
))
6247 for v
in range(0, self
.GetArrayCount(func
)):
6248 file.Write(" static_cast<%s>(kSomeBaseValueToTestWith + %d),\n" %
6249 (self
.GetArrayType(func
), v
))
6251 file.Write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
6252 (func
.name
, func
.name
))
6253 file.Write(" void* next_cmd = cmd.Set(\n")
6255 args
= func
.GetCmdArgs()
6256 for value
, arg
in enumerate(args
):
6257 file.Write(",\n static_cast<%s>(%d)" % (arg
.type, value
+ 11))
6258 file.Write(",\n data);\n")
6259 args
= func
.GetCmdArgs()
6260 file.Write(" EXPECT_EQ(static_cast<uint32_t>(cmds::%s::kCmdId),\n"
6262 file.Write(" cmd.header.command);\n")
6263 file.Write(" EXPECT_EQ(sizeof(cmd) +\n")
6264 file.Write(" RoundSizeToMultipleOfEntries(sizeof(data)),\n")
6265 file.Write(" cmd.header.size * 4u);\n")
6266 for value
, arg
in enumerate(args
):
6267 file.Write(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);\n" %
6268 (arg
.type, value
+ 11, arg
.name
))
6269 file.Write(" CheckBytesWrittenMatchesExpectedSize(\n")
6270 file.Write(" next_cmd, sizeof(cmd) +\n")
6271 file.Write(" RoundSizeToMultipleOfEntries(sizeof(data)));\n")
6272 file.Write(" // TODO(gman): Check that data was inserted;\n")
6277 class PUTnHandler(ArrayArgTypeHandler
):
6278 """Handler for PUTn 'glUniform__v' type functions."""
6281 ArrayArgTypeHandler
.__init
__(self
)
6283 def WriteServiceUnitTest(self
, func
, file, *extras
):
6284 """Overridden from TypeHandler."""
6285 ArrayArgTypeHandler
.WriteServiceUnitTest(self
, func
, file, *extras
)
6288 TEST_P(%(test_name)s, %(name)sValidArgsCountTooLarge) {
6289 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
6290 SpecializedSetup<cmds::%(name)s, 0>(true);
6293 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
6294 EXPECT_EQ(GL_NO_ERROR, GetGLError());
6299 for count
, arg
in enumerate(func
.GetOriginalArgs()):
6300 # hardcoded to match unit tests.
6302 # the location of the second element of the 2nd uniform.
6303 # defined in GLES2DecoderBase::SetupShaderForUniform
6304 gl_arg_strings
.append("3")
6305 arg_strings
.append("ProgramManager::MakeFakeLocation(1, 1)")
6307 # the number of elements that gl will be called with.
6308 gl_arg_strings
.append("3")
6309 # the number of elements requested in the command.
6310 arg_strings
.append("5")
6312 gl_arg_strings
.append(arg
.GetValidGLArg(func
))
6313 if not arg
.IsConstant():
6314 arg_strings
.append(arg
.GetValidArg(func
))
6316 'gl_args': ", ".join(gl_arg_strings
),
6317 'args': ", ".join(arg_strings
),
6319 self
.WriteValidUnitTest(func
, file, valid_test
, extra
, *extras
)
6321 def WriteImmediateServiceUnitTest(self
, func
, file, *extras
):
6322 """Overridden from TypeHandler."""
6324 TEST_P(%(test_name)s, %(name)sValidArgs) {
6325 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
6328 %(gl_func_name)s(%(gl_args)s,
6329 reinterpret_cast<%(data_type)s*>(ImmediateDataAddress(&cmd))));
6330 SpecializedSetup<cmds::%(name)s, 0>(true);
6331 %(data_type)s temp[%(data_count)s * 2] = { 0, };
6332 cmd.Init(%(args)s, &temp[0]);"""
6335 decoder_->set_unsafe_es3_apis_enabled(true);"""
6337 EXPECT_EQ(error::kNoError,
6338 ExecuteImmediateCmd(cmd, sizeof(temp)));
6339 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
6342 decoder_->set_unsafe_es3_apis_enabled(false);
6343 EXPECT_EQ(error::kUnknownCommand,
6344 ExecuteImmediateCmd(cmd, sizeof(temp)));"""
6351 for arg
in func
.GetOriginalArgs()[0:-1]:
6352 gl_arg_strings
.append(arg
.GetValidGLArg(func
))
6353 gl_any_strings
.append("_")
6354 if not arg
.IsConstant():
6355 arg_strings
.append(arg
.GetValidArg(func
))
6357 'data_type': self
.GetArrayType(func
),
6358 'data_count': self
.GetArrayCount(func
),
6359 'args': ", ".join(arg_strings
),
6360 'gl_args': ", ".join(gl_arg_strings
),
6361 'gl_any_args': ", ".join(gl_any_strings
),
6363 self
.WriteValidUnitTest(func
, file, valid_test
, extra
, *extras
)
6366 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
6367 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
6368 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_any_args)s, _)).Times(0);
6369 SpecializedSetup<cmds::%(name)s, 0>(false);
6370 %(data_type)s temp[%(data_count)s * 2] = { 0, };
6371 cmd.Init(%(all_but_last_args)s, &temp[0]);
6372 EXPECT_EQ(error::%(parse_result)s,
6373 ExecuteImmediateCmd(cmd, sizeof(temp)));%(gl_error_test)s
6376 self
.WriteInvalidUnitTest(func
, file, invalid_test
, extra
, *extras
)
6378 def WriteGetDataSizeCode(self
, func
, file):
6379 """Overrriden from TypeHandler."""
6380 code
= """ uint32_t data_size;
6381 if (!ComputeDataSize(count, sizeof(%s), %d, &data_size)) {
6382 return error::kOutOfBounds;
6385 file.Write(code
% (self
.GetArrayType(func
), self
.GetArrayCount(func
)))
6386 if func
.IsImmediate():
6387 file.Write(" if (data_size > immediate_data_size) {\n")
6388 file.Write(" return error::kOutOfBounds;\n")
6391 def WriteGLES2Implementation(self
, func
, file):
6392 """Overrriden from TypeHandler."""
6393 file.Write("%s GLES2Implementation::%s(%s) {\n" %
6394 (func
.return_type
, func
.original_name
,
6395 func
.MakeTypedOriginalArgString("")))
6396 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
6397 func
.WriteDestinationInitalizationValidation(file)
6398 self
.WriteClientGLCallLog(func
, file)
6399 last_pointer_name
= func
.GetLastOriginalPointerArg().name
6400 file.Write(""" GPU_CLIENT_LOG_CODE_BLOCK({
6401 for (GLsizei i = 0; i < count; ++i) {
6403 values_str
= ' << ", " << '.join(
6404 ["%s[%d + i * %d]" % (
6405 last_pointer_name
, ndx
, self
.GetArrayCount(func
)) for ndx
in range(
6406 0, self
.GetArrayCount(func
))])
6407 file.Write(' GPU_CLIENT_LOG(" " << i << ": " << %s);\n' % values_str
)
6408 file.Write(" }\n });\n")
6409 for arg
in func
.GetOriginalArgs():
6410 arg
.WriteClientSideValidationCode(file, func
)
6411 file.Write(" helper_->%sImmediate(%s);\n" %
6412 (func
.name
, func
.MakeInitString("")))
6413 file.Write(" CheckGLError();\n")
6417 def WriteGLES2ImplementationUnitTest(self
, func
, file):
6418 """Writes the GLES2 Implemention unit test."""
6420 TEST_F(GLES2ImplementationTest, %(name)s) {
6421 %(type)s data[%(count_param)d][%(count)d] = {{0}};
6423 cmds::%(name)sImmediate cmd;
6424 %(type)s data[%(count_param)d][%(count)d];
6428 for (int ii = 0; ii < %(count_param)d; ++ii) {
6429 for (int jj = 0; jj < %(count)d; ++jj) {
6430 data[ii][jj] = static_cast<%(type)s>(ii * %(count)d + jj);
6433 expected.cmd.Init(%(cmd_args)s);
6434 gl_->%(name)s(%(args)s);
6435 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
6438 cmd_arg_strings
= []
6439 for arg
in func
.GetCmdArgs():
6440 if arg
.name
.endswith("_shm_id"):
6441 cmd_arg_strings
.append("&data[0][0]")
6442 elif arg
.name
.endswith("_shm_offset"):
6445 cmd_arg_strings
.append(arg
.GetValidClientSideCmdArg(func
))
6448 for arg
in func
.GetOriginalArgs():
6450 valid_value
= "&data[0][0]"
6452 valid_value
= arg
.GetValidClientSideArg(func
)
6453 gl_arg_strings
.append(valid_value
)
6454 if arg
.name
== "count":
6455 count_param
= int(valid_value
)
6458 'type': self
.GetArrayType(func
),
6459 'count': self
.GetArrayCount(func
),
6460 'args': ", ".join(gl_arg_strings
),
6461 'cmd_args': ", ".join(cmd_arg_strings
),
6462 'count_param': count_param
,
6465 # Test constants for invalid values, as they are not tested by the
6468 arg
for arg
in func
.GetOriginalArgs()[0:-1] if arg
.IsConstant()
6474 TEST_F(GLES2ImplementationTest, %(name)sInvalidConstantArg%(invalid_index)d) {
6475 %(type)s data[%(count_param)d][%(count)d] = {{0}};
6476 for (int ii = 0; ii < %(count_param)d; ++ii) {
6477 for (int jj = 0; jj < %(count)d; ++jj) {
6478 data[ii][jj] = static_cast<%(type)s>(ii * %(count)d + jj);
6481 gl_->%(name)s(%(args)s);
6482 EXPECT_TRUE(NoCommandsWritten());
6483 EXPECT_EQ(%(gl_error)s, CheckError());
6486 for invalid_arg
in constants
:
6488 invalid
= invalid_arg
.GetInvalidArg(func
)
6489 for arg
in func
.GetOriginalArgs():
6490 if arg
is invalid_arg
:
6491 gl_arg_strings
.append(invalid
[0])
6492 elif arg
.IsPointer():
6493 gl_arg_strings
.append("&data[0][0]")
6495 valid_value
= arg
.GetValidClientSideArg(func
)
6496 gl_arg_strings
.append(valid_value
)
6497 if arg
.name
== "count":
6498 count_param
= int(valid_value
)
6502 'invalid_index': func
.GetOriginalArgs().index(invalid_arg
),
6503 'type': self
.GetArrayType(func
),
6504 'count': self
.GetArrayCount(func
),
6505 'args': ", ".join(gl_arg_strings
),
6506 'gl_error': invalid
[2],
6507 'count_param': count_param
,
6511 def WriteImmediateCmdComputeSize(self
, func
, file):
6512 """Overrriden from TypeHandler."""
6513 file.Write(" static uint32_t ComputeDataSize(GLsizei count) {\n")
6514 file.Write(" return static_cast<uint32_t>(\n")
6515 file.Write(" sizeof(%s) * %d * count); // NOLINT\n" %
6516 (self
.GetArrayType(func
), self
.GetArrayCount(func
)))
6519 file.Write(" static uint32_t ComputeSize(GLsizei count) {\n")
6520 file.Write(" return static_cast<uint32_t>(\n")
6522 " sizeof(ValueType) + ComputeDataSize(count)); // NOLINT\n")
6526 def WriteImmediateCmdSetHeader(self
, func
, file):
6527 """Overrriden from TypeHandler."""
6528 file.Write(" void SetHeader(GLsizei count) {\n")
6530 " header.SetCmdByTotalSize<ValueType>(ComputeSize(count));\n")
6534 def WriteImmediateCmdInit(self
, func
, file):
6535 """Overrriden from TypeHandler."""
6536 file.Write(" void Init(%s) {\n" %
6537 func
.MakeTypedInitString("_"))
6538 file.Write(" SetHeader(_count);\n")
6539 args
= func
.GetCmdArgs()
6541 file.Write(" %s = _%s;\n" % (arg
.name
, arg
.name
))
6542 file.Write(" memcpy(ImmediateDataAddress(this),\n")
6543 pointer_arg
= func
.GetLastOriginalPointerArg()
6544 file.Write(" _%s, ComputeDataSize(_count));\n" % pointer_arg
.name
)
6548 def WriteImmediateCmdSet(self
, func
, file):
6549 """Overrriden from TypeHandler."""
6550 file.Write(" void* Set(void* cmd%s) {\n" %
6551 func
.MakeTypedInitString("_", True))
6552 file.Write(" static_cast<ValueType*>(cmd)->Init(%s);\n" %
6553 func
.MakeInitString("_"))
6554 file.Write(" const uint32_t size = ComputeSize(_count);\n")
6555 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
6560 def WriteImmediateCmdHelper(self
, func
, file):
6561 """Overrriden from TypeHandler."""
6562 code
= """ void %(name)s(%(typed_args)s) {
6563 const uint32_t size = gles2::cmds::%(name)s::ComputeSize(count);
6564 gles2::cmds::%(name)s* c =
6565 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
6574 "typed_args": func
.MakeTypedInitString(""),
6575 "args": func
.MakeInitString("")
6578 def WriteImmediateFormatTest(self
, func
, file):
6579 """Overrriden from TypeHandler."""
6580 args
= func
.GetOriginalArgs()
6583 if arg
.name
== "count":
6584 count_param
= int(arg
.GetValidClientSideCmdArg(func
))
6585 file.Write("TEST_F(GLES2FormatTest, %s) {\n" % func
.name
)
6586 file.Write(" const int kSomeBaseValueToTestWith = 51;\n")
6587 file.Write(" static %s data[] = {\n" % self
.GetArrayType(func
))
6588 for v
in range(0, self
.GetArrayCount(func
) * count_param
):
6589 file.Write(" static_cast<%s>(kSomeBaseValueToTestWith + %d),\n" %
6590 (self
.GetArrayType(func
), v
))
6592 file.Write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
6593 (func
.name
, func
.name
))
6594 file.Write(" const GLsizei kNumElements = %d;\n" % count_param
)
6595 file.Write(" const size_t kExpectedCmdSize =\n")
6596 file.Write(" sizeof(cmd) + kNumElements * sizeof(%s) * %d;\n" %
6597 (self
.GetArrayType(func
), self
.GetArrayCount(func
)))
6598 file.Write(" void* next_cmd = cmd.Set(\n")
6600 for value
, arg
in enumerate(args
):
6602 file.Write(",\n data")
6603 elif arg
.IsConstant():
6606 file.Write(",\n static_cast<%s>(%d)" % (arg
.type, value
+ 1))
6608 file.Write(" EXPECT_EQ(static_cast<uint32_t>(cmds::%s::kCmdId),\n" %
6610 file.Write(" cmd.header.command);\n")
6611 file.Write(" EXPECT_EQ(kExpectedCmdSize, cmd.header.size * 4u);\n")
6612 for value
, arg
in enumerate(args
):
6613 if arg
.IsPointer() or arg
.IsConstant():
6615 file.Write(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);\n" %
6616 (arg
.type, value
+ 1, arg
.name
))
6617 file.Write(" CheckBytesWrittenMatchesExpectedSize(\n")
6618 file.Write(" next_cmd, sizeof(cmd) +\n")
6619 file.Write(" RoundSizeToMultipleOfEntries(sizeof(data)));\n")
6620 file.Write(" // TODO(gman): Check that data was inserted;\n")
6624 class PUTSTRHandler(ArrayArgTypeHandler
):
6625 """Handler for functions that pass a string array."""
6628 ArrayArgTypeHandler
.__init
__(self
)
6630 def __GetDataArg(self
, func
):
6631 """Return the argument that points to the 2D char arrays"""
6632 for arg
in func
.GetOriginalArgs():
6633 if arg
.IsPointer2D():
6637 def __GetLengthArg(self
, func
):
6638 """Return the argument that holds length for each char array"""
6639 for arg
in func
.GetOriginalArgs():
6640 if arg
.IsPointer() and not arg
.IsPointer2D():
6644 def WriteGLES2Implementation(self
, func
, file):
6645 """Overrriden from TypeHandler."""
6646 file.Write("%s GLES2Implementation::%s(%s) {\n" %
6647 (func
.return_type
, func
.original_name
,
6648 func
.MakeTypedOriginalArgString("")))
6649 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
6650 func
.WriteDestinationInitalizationValidation(file)
6651 self
.WriteClientGLCallLog(func
, file)
6652 data_arg
= self
.__GetDataArg
(func
)
6653 length_arg
= self
.__GetLengthArg
(func
)
6654 log_code_block
= """ GPU_CLIENT_LOG_CODE_BLOCK({
6655 for (GLsizei ii = 0; ii < count; ++ii) {
6656 if (%(data)s[ii]) {"""
6657 if length_arg
== None:
6658 log_code_block
+= """
6659 GPU_CLIENT_LOG(" " << ii << ": ---\\n" << %(data)s[ii] << "\\n---");"""
6661 log_code_block
+= """
6662 if (%(length)s && %(length)s[ii] >= 0) {
6663 const std::string my_str(%(data)s[ii], %(length)s[ii]);
6664 GPU_CLIENT_LOG(" " << ii << ": ---\\n" << my_str << "\\n---");
6666 GPU_CLIENT_LOG(" " << ii << ": ---\\n" << %(data)s[ii] << "\\n---");
6668 log_code_block
+= """
6670 GPU_CLIENT_LOG(" " << ii << ": NULL");
6675 file.Write(log_code_block
% {
6676 'data': data_arg
.name
,
6677 'length': length_arg
.name
if not length_arg
== None else ''
6679 for arg
in func
.GetOriginalArgs():
6680 arg
.WriteClientSideValidationCode(file, func
)
6683 for arg
in func
.GetOriginalArgs():
6684 if arg
.name
== 'count' or arg
== self
.__GetLengthArg
(func
):
6686 if arg
== self
.__GetDataArg
(func
):
6687 bucket_args
.append('kResultBucketId')
6689 bucket_args
.append(arg
.name
)
6691 if (!PackStringsToBucket(count, %(data)s, %(length)s, "gl%(func_name)s")) {
6694 helper_->%(func_name)sBucket(%(bucket_args)s);
6695 helper_->SetBucketSize(kResultBucketId, 0);
6700 file.Write(code_block
% {
6701 'data': data_arg
.name
,
6702 'length': length_arg
.name
if not length_arg
== None else 'NULL',
6703 'func_name': func
.name
,
6704 'bucket_args': ', '.join(bucket_args
),
6707 def WriteGLES2ImplementationUnitTest(self
, func
, file):
6708 """Overrriden from TypeHandler."""
6710 TEST_F(GLES2ImplementationTest, %(name)s) {
6711 const uint32 kBucketId = GLES2Implementation::kResultBucketId;
6712 const char* kString1 = "happy";
6713 const char* kString2 = "ending";
6714 const size_t kString1Size = ::strlen(kString1) + 1;
6715 const size_t kString2Size = ::strlen(kString2) + 1;
6716 const size_t kHeaderSize = sizeof(GLint) * 3;
6717 const size_t kSourceSize = kHeaderSize + kString1Size + kString2Size;
6718 const size_t kPaddedHeaderSize =
6719 transfer_buffer_->RoundToAlignment(kHeaderSize);
6720 const size_t kPaddedString1Size =
6721 transfer_buffer_->RoundToAlignment(kString1Size);
6722 const size_t kPaddedString2Size =
6723 transfer_buffer_->RoundToAlignment(kString2Size);
6725 cmd::SetBucketSize set_bucket_size;
6726 cmd::SetBucketData set_bucket_header;
6727 cmd::SetToken set_token1;
6728 cmd::SetBucketData set_bucket_data1;
6729 cmd::SetToken set_token2;
6730 cmd::SetBucketData set_bucket_data2;
6731 cmd::SetToken set_token3;
6732 cmds::%(name)sBucket cmd_bucket;
6733 cmd::SetBucketSize clear_bucket_size;
6736 ExpectedMemoryInfo mem0 = GetExpectedMemory(kPaddedHeaderSize);
6737 ExpectedMemoryInfo mem1 = GetExpectedMemory(kPaddedString1Size);
6738 ExpectedMemoryInfo mem2 = GetExpectedMemory(kPaddedString2Size);
6741 expected.set_bucket_size.Init(kBucketId, kSourceSize);
6742 expected.set_bucket_header.Init(
6743 kBucketId, 0, kHeaderSize, mem0.id, mem0.offset);
6744 expected.set_token1.Init(GetNextToken());
6745 expected.set_bucket_data1.Init(
6746 kBucketId, kHeaderSize, kString1Size, mem1.id, mem1.offset);
6747 expected.set_token2.Init(GetNextToken());
6748 expected.set_bucket_data2.Init(
6749 kBucketId, kHeaderSize + kString1Size, kString2Size, mem2.id,
6751 expected.set_token3.Init(GetNextToken());
6752 expected.cmd_bucket.Init(%(bucket_args)s);
6753 expected.clear_bucket_size.Init(kBucketId, 0);
6754 const char* kStrings[] = { kString1, kString2 };
6755 gl_->%(name)s(%(gl_args)s);
6756 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
6761 for arg
in func
.GetOriginalArgs():
6762 if arg
== self
.__GetDataArg
(func
):
6763 gl_args
.append('kStrings')
6764 bucket_args
.append('kBucketId')
6765 elif arg
== self
.__GetLengthArg
(func
):
6766 gl_args
.append('NULL')
6767 elif arg
.name
== 'count':
6770 gl_args
.append(arg
.GetValidClientSideArg(func
))
6771 bucket_args
.append(arg
.GetValidClientSideArg(func
))
6774 'gl_args': ", ".join(gl_args
),
6775 'bucket_args': ", ".join(bucket_args
),
6778 if self
.__GetLengthArg
(func
) == None:
6781 TEST_F(GLES2ImplementationTest, %(name)sWithLength) {
6782 const uint32 kBucketId = GLES2Implementation::kResultBucketId;
6783 const char* kString = "foobar******";
6784 const size_t kStringSize = 6; // We only need "foobar".
6785 const size_t kHeaderSize = sizeof(GLint) * 2;
6786 const size_t kSourceSize = kHeaderSize + kStringSize + 1;
6787 const size_t kPaddedHeaderSize =
6788 transfer_buffer_->RoundToAlignment(kHeaderSize);
6789 const size_t kPaddedStringSize =
6790 transfer_buffer_->RoundToAlignment(kStringSize + 1);
6792 cmd::SetBucketSize set_bucket_size;
6793 cmd::SetBucketData set_bucket_header;
6794 cmd::SetToken set_token1;
6795 cmd::SetBucketData set_bucket_data;
6796 cmd::SetToken set_token2;
6797 cmds::ShaderSourceBucket shader_source_bucket;
6798 cmd::SetBucketSize clear_bucket_size;
6801 ExpectedMemoryInfo mem0 = GetExpectedMemory(kPaddedHeaderSize);
6802 ExpectedMemoryInfo mem1 = GetExpectedMemory(kPaddedStringSize);
6805 expected.set_bucket_size.Init(kBucketId, kSourceSize);
6806 expected.set_bucket_header.Init(
6807 kBucketId, 0, kHeaderSize, mem0.id, mem0.offset);
6808 expected.set_token1.Init(GetNextToken());
6809 expected.set_bucket_data.Init(
6810 kBucketId, kHeaderSize, kStringSize + 1, mem1.id, mem1.offset);
6811 expected.set_token2.Init(GetNextToken());
6812 expected.shader_source_bucket.Init(%(bucket_args)s);
6813 expected.clear_bucket_size.Init(kBucketId, 0);
6814 const char* kStrings[] = { kString };
6815 const GLint kLength[] = { kStringSize };
6816 gl_->%(name)s(%(gl_args)s);
6817 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
6821 for arg
in func
.GetOriginalArgs():
6822 if arg
== self
.__GetDataArg
(func
):
6823 gl_args
.append('kStrings')
6824 elif arg
== self
.__GetLengthArg
(func
):
6825 gl_args
.append('kLength')
6826 elif arg
.name
== 'count':
6829 gl_args
.append(arg
.GetValidClientSideArg(func
))
6832 'gl_args': ", ".join(gl_args
),
6833 'bucket_args': ", ".join(bucket_args
),
6836 def WriteBucketServiceUnitTest(self
, func
, file, *extras
):
6837 """Overrriden from TypeHandler."""
6839 cmd_args_with_invalid_id
= []
6841 for index
, arg
in enumerate(func
.GetOriginalArgs()):
6842 if arg
== self
.__GetLengthArg
(func
):
6844 elif arg
.name
== 'count':
6846 elif arg
== self
.__GetDataArg
(func
):
6847 cmd_args
.append('kBucketId')
6848 cmd_args_with_invalid_id
.append('kBucketId')
6850 elif index
== 0: # Resource ID arg
6851 cmd_args
.append(arg
.GetValidArg(func
))
6852 cmd_args_with_invalid_id
.append('kInvalidClientId')
6853 gl_args
.append(arg
.GetValidGLArg(func
))
6855 cmd_args
.append(arg
.GetValidArg(func
))
6856 cmd_args_with_invalid_id
.append(arg
.GetValidArg(func
))
6857 gl_args
.append(arg
.GetValidGLArg(func
))
6860 TEST_P(%(test_name)s, %(name)sValidArgs) {
6861 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
6862 const uint32 kBucketId = 123;
6863 const char kSource0[] = "hello";
6864 const char* kSource[] = { kSource0 };
6865 const char kValidStrEnd = 0;
6866 SetBucketAsCStrings(kBucketId, 1, kSource, 1, kValidStrEnd);
6868 cmd.Init(%(cmd_args)s);
6869 decoder_->set_unsafe_es3_apis_enabled(true);
6870 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));"""
6873 decoder_->set_unsafe_es3_apis_enabled(false);
6874 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));
6879 self
.WriteValidUnitTest(func
, file, test
, {
6880 'cmd_args': ", ".join(cmd_args
),
6881 'gl_args': ", ".join(gl_args
),
6885 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
6886 const uint32 kBucketId = 123;
6887 const char kSource0[] = "hello";
6888 const char* kSource[] = { kSource0 };
6889 const char kValidStrEnd = 0;
6890 decoder_->set_unsafe_es3_apis_enabled(true);
6893 cmd.Init(%(cmd_args)s);
6894 EXPECT_NE(error::kNoError, ExecuteCmd(cmd));
6895 // Test invalid client.
6896 SetBucketAsCStrings(kBucketId, 1, kSource, 1, kValidStrEnd);
6897 cmd.Init(%(cmd_args_with_invalid_id)s);
6898 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
6899 EXPECT_EQ(GL_INVALID_VALUE, GetGLError());
6902 self
.WriteValidUnitTest(func
, file, test
, {
6903 'cmd_args': ", ".join(cmd_args
),
6904 'cmd_args_with_invalid_id': ", ".join(cmd_args_with_invalid_id
),
6908 TEST_P(%(test_name)s, %(name)sInvalidHeader) {
6909 const uint32 kBucketId = 123;
6910 const char kSource0[] = "hello";
6911 const char* kSource[] = { kSource0 };
6912 const char kValidStrEnd = 0;
6913 const GLsizei kCount = static_cast<GLsizei>(arraysize(kSource));
6914 const GLsizei kTests[] = {
6917 std::numeric_limits<GLsizei>::max(),
6920 decoder_->set_unsafe_es3_apis_enabled(true);
6921 for (size_t ii = 0; ii < arraysize(kTests); ++ii) {
6922 SetBucketAsCStrings(kBucketId, 1, kSource, kTests[ii], kValidStrEnd);
6924 cmd.Init(%(cmd_args)s);
6925 EXPECT_EQ(error::kInvalidArguments, ExecuteCmd(cmd));
6929 self
.WriteValidUnitTest(func
, file, test
, {
6930 'cmd_args': ", ".join(cmd_args
),
6934 TEST_P(%(test_name)s, %(name)sInvalidStringEnding) {
6935 const uint32 kBucketId = 123;
6936 const char kSource0[] = "hello";
6937 const char* kSource[] = { kSource0 };
6938 const char kInvalidStrEnd = '*';
6939 SetBucketAsCStrings(kBucketId, 1, kSource, 1, kInvalidStrEnd);
6941 cmd.Init(%(cmd_args)s);
6942 decoder_->set_unsafe_es3_apis_enabled(true);
6943 EXPECT_EQ(error::kInvalidArguments, ExecuteCmd(cmd));
6946 self
.WriteValidUnitTest(func
, file, test
, {
6947 'cmd_args': ", ".join(cmd_args
),
6951 class PUTXnHandler(ArrayArgTypeHandler
):
6952 """Handler for glUniform?f functions."""
6954 ArrayArgTypeHandler
.__init
__(self
)
6956 def WriteHandlerImplementation(self
, func
, file):
6957 """Overrriden from TypeHandler."""
6958 code
= """ %(type)s temp[%(count)s] = { %(values)s};"""
6961 gl%(name)sv(%(location)s, 1, &temp[0]);
6965 Do%(name)sv(%(location)s, 1, &temp[0]);
6968 args
= func
.GetOriginalArgs()
6969 count
= int(self
.GetArrayCount(func
))
6970 num_args
= len(args
)
6971 for ii
in range(count
):
6972 values
+= "%s, " % args
[len(args
) - count
+ ii
].name
6976 'count': self
.GetArrayCount(func
),
6977 'type': self
.GetArrayType(func
),
6978 'location': args
[0].name
,
6979 'args': func
.MakeOriginalArgString(""),
6983 def WriteServiceUnitTest(self
, func
, file, *extras
):
6984 """Overrriden from TypeHandler."""
6986 TEST_P(%(test_name)s, %(name)sValidArgs) {
6987 EXPECT_CALL(*gl_, %(name)sv(%(local_args)s));
6988 SpecializedSetup<cmds::%(name)s, 0>(true);
6990 cmd.Init(%(args)s);"""
6993 decoder_->set_unsafe_es3_apis_enabled(true);"""
6995 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
6996 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
6999 decoder_->set_unsafe_es3_apis_enabled(false);
7000 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));"""
7004 args
= func
.GetOriginalArgs()
7005 local_args
= "%s, 1, _" % args
[0].GetValidGLArg(func
)
7006 self
.WriteValidUnitTest(func
, file, valid_test
, {
7008 'count': self
.GetArrayCount(func
),
7009 'local_args': local_args
,
7013 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
7014 EXPECT_CALL(*gl_, %(name)sv(_, _, _).Times(0);
7015 SpecializedSetup<cmds::%(name)s, 0>(false);
7018 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
7021 self
.WriteInvalidUnitTest(func
, file, invalid_test
, {
7022 'name': func
.GetInfo('name'),
7023 'count': self
.GetArrayCount(func
),
7027 class GLcharHandler(CustomHandler
):
7028 """Handler for functions that pass a single string ."""
7031 CustomHandler
.__init
__(self
)
7033 def WriteImmediateCmdComputeSize(self
, func
, file):
7034 """Overrriden from TypeHandler."""
7035 file.Write(" static uint32_t ComputeSize(uint32_t data_size) {\n")
7036 file.Write(" return static_cast<uint32_t>(\n")
7037 file.Write(" sizeof(ValueType) + data_size); // NOLINT\n")
7040 def WriteImmediateCmdSetHeader(self
, func
, file):
7041 """Overrriden from TypeHandler."""
7043 void SetHeader(uint32_t data_size) {
7044 header.SetCmdBySize<ValueType>(data_size);
7049 def WriteImmediateCmdInit(self
, func
, file):
7050 """Overrriden from TypeHandler."""
7051 last_arg
= func
.GetLastOriginalArg()
7052 args
= func
.GetCmdArgs()
7055 set_code
.append(" %s = _%s;" % (arg
.name
, arg
.name
))
7057 void Init(%(typed_args)s, uint32_t _data_size) {
7058 SetHeader(_data_size);
7060 memcpy(ImmediateDataAddress(this), _%(last_arg)s, _data_size);
7065 "typed_args": func
.MakeTypedArgString("_"),
7066 "set_code": "\n".join(set_code
),
7067 "last_arg": last_arg
.name
7070 def WriteImmediateCmdSet(self
, func
, file):
7071 """Overrriden from TypeHandler."""
7072 last_arg
= func
.GetLastOriginalArg()
7073 file.Write(" void* Set(void* cmd%s, uint32_t _data_size) {\n" %
7074 func
.MakeTypedCmdArgString("_", True))
7075 file.Write(" static_cast<ValueType*>(cmd)->Init(%s, _data_size);\n" %
7076 func
.MakeCmdArgString("_"))
7077 file.Write(" return NextImmediateCmdAddress<ValueType>("
7078 "cmd, _data_size);\n")
7082 def WriteImmediateCmdHelper(self
, func
, file):
7083 """Overrriden from TypeHandler."""
7084 code
= """ void %(name)s(%(typed_args)s) {
7085 const uint32_t data_size = strlen(name);
7086 gles2::cmds::%(name)s* c =
7087 GetImmediateCmdSpace<gles2::cmds::%(name)s>(data_size);
7089 c->Init(%(args)s, data_size);
7096 "typed_args": func
.MakeTypedOriginalArgString(""),
7097 "args": func
.MakeOriginalArgString(""),
7101 def WriteImmediateFormatTest(self
, func
, file):
7102 """Overrriden from TypeHandler."""
7105 all_but_last_arg
= func
.GetCmdArgs()[:-1]
7106 for value
, arg
in enumerate(all_but_last_arg
):
7107 init_code
.append(" static_cast<%s>(%d)," % (arg
.type, value
+ 11))
7108 for value
, arg
in enumerate(all_but_last_arg
):
7109 check_code
.append(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);" %
7110 (arg
.type, value
+ 11, arg
.name
))
7112 TEST_F(GLES2FormatTest, %(func_name)s) {
7113 cmds::%(func_name)s& cmd = *GetBufferAs<cmds::%(func_name)s>();
7114 static const char* const test_str = \"test string\";
7115 void* next_cmd = cmd.Set(
7120 EXPECT_EQ(static_cast<uint32_t>(cmds::%(func_name)s::kCmdId),
7121 cmd.header.command);
7122 EXPECT_EQ(sizeof(cmd) +
7123 RoundSizeToMultipleOfEntries(strlen(test_str)),
7124 cmd.header.size * 4u);
7125 EXPECT_EQ(static_cast<char*>(next_cmd),
7126 reinterpret_cast<char*>(&cmd) + sizeof(cmd) +
7127 RoundSizeToMultipleOfEntries(strlen(test_str)));
7129 EXPECT_EQ(static_cast<uint32_t>(strlen(test_str)), cmd.data_size);
7130 EXPECT_EQ(0, memcmp(test_str, ImmediateDataAddress(&cmd), strlen(test_str)));
7133 sizeof(cmd) + RoundSizeToMultipleOfEntries(strlen(test_str)),
7134 sizeof(cmd) + strlen(test_str));
7139 'func_name': func
.name
,
7140 'init_code': "\n".join(init_code
),
7141 'check_code': "\n".join(check_code
),
7145 class GLcharNHandler(CustomHandler
):
7146 """Handler for functions that pass a single string with an optional len."""
7149 CustomHandler
.__init
__(self
)
7151 def InitFunction(self
, func
):
7152 """Overrriden from TypeHandler."""
7154 func
.AddCmdArg(Argument('bucket_id', 'GLuint'))
7156 def NeedsDataTransferFunction(self
, func
):
7157 """Overriden from TypeHandler."""
7160 def AddBucketFunction(self
, generator
, func
):
7161 """Overrriden from TypeHandler."""
7164 def WriteServiceImplementation(self
, func
, file):
7165 """Overrriden from TypeHandler."""
7166 self
.WriteServiceHandlerFunctionHeader(func
, file)
7168 GLuint bucket_id = static_cast<GLuint>(c.%(bucket_id)s);
7169 Bucket* bucket = GetBucket(bucket_id);
7170 if (!bucket || bucket->size() == 0) {
7171 return error::kInvalidArguments;
7174 if (!bucket->GetAsString(&str)) {
7175 return error::kInvalidArguments;
7177 %(gl_func_name)s(0, str.c_str());
7178 return error::kNoError;
7183 'gl_func_name': func
.GetGLFunctionName(),
7184 'bucket_id': func
.cmd_args
[0].name
,
7188 class IsHandler(TypeHandler
):
7189 """Handler for glIs____ type and glGetError functions."""
7192 TypeHandler
.__init
__(self
)
7194 def InitFunction(self
, func
):
7195 """Overrriden from TypeHandler."""
7196 func
.AddCmdArg(Argument("result_shm_id", 'uint32_t'))
7197 func
.AddCmdArg(Argument("result_shm_offset", 'uint32_t'))
7198 if func
.GetInfo('result') == None:
7199 func
.AddInfo('result', ['uint32_t'])
7201 def WriteServiceUnitTest(self
, func
, file, *extras
):
7202 """Overrriden from TypeHandler."""
7204 TEST_P(%(test_name)s, %(name)sValidArgs) {
7205 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
7206 SpecializedSetup<cmds::%(name)s, 0>(true);
7208 cmd.Init(%(args)s%(comma)sshared_memory_id_, shared_memory_offset_);"""
7211 decoder_->set_unsafe_es3_apis_enabled(true);"""
7213 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
7214 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
7217 decoder_->set_unsafe_es3_apis_enabled(false);
7218 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));"""
7223 if len(func
.GetOriginalArgs()):
7225 self
.WriteValidUnitTest(func
, file, valid_test
, {
7230 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
7231 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
7232 SpecializedSetup<cmds::%(name)s, 0>(false);
7234 cmd.Init(%(args)s%(comma)sshared_memory_id_, shared_memory_offset_);
7235 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
7238 self
.WriteInvalidUnitTest(func
, file, invalid_test
, {
7243 TEST_P(%(test_name)s, %(name)sInvalidArgsBadSharedMemoryId) {
7244 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
7245 SpecializedSetup<cmds::%(name)s, 0>(false);"""
7248 decoder_->set_unsafe_es3_apis_enabled(true);"""
7251 cmd.Init(%(args)s%(comma)skInvalidSharedMemoryId, shared_memory_offset_);
7252 EXPECT_EQ(error::kOutOfBounds, ExecuteCmd(cmd));
7253 cmd.Init(%(args)s%(comma)sshared_memory_id_, kInvalidSharedMemoryOffset);
7254 EXPECT_EQ(error::kOutOfBounds, ExecuteCmd(cmd));"""
7257 decoder_->set_unsafe_es3_apis_enabled(true);"""
7261 self
.WriteValidUnitTest(func
, file, invalid_test
, {
7265 def WriteServiceImplementation(self
, func
, file):
7266 """Overrriden from TypeHandler."""
7267 self
.WriteServiceHandlerFunctionHeader(func
, file)
7268 args
= func
.GetOriginalArgs()
7270 arg
.WriteGetCode(file)
7272 code
= """ typedef cmds::%(func_name)s::Result Result;
7273 Result* result_dst = GetSharedMemoryAs<Result*>(
7274 c.result_shm_id, c.result_shm_offset, sizeof(*result_dst));
7276 return error::kOutOfBounds;
7279 file.Write(code
% {'func_name': func
.name
})
7280 func
.WriteHandlerValidation(file)
7282 assert func
.GetInfo('id_mapping')
7283 assert len(func
.GetInfo('id_mapping')) == 1
7284 assert len(args
) == 1
7285 id_type
= func
.GetInfo('id_mapping')[0]
7286 file.Write(" %s service_%s = 0;\n" % (args
[0].type, id_type
.lower()))
7287 file.Write(" *result_dst = group_->Get%sServiceId(%s, &service_%s);\n" %
7288 (id_type
, id_type
.lower(), id_type
.lower()))
7290 file.Write(" *result_dst = %s(%s);\n" %
7291 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
7292 file.Write(" return error::kNoError;\n")
7296 def WriteGLES2Implementation(self
, func
, file):
7297 """Overrriden from TypeHandler."""
7298 impl_func
= func
.GetInfo('impl_func')
7299 if impl_func
== None or impl_func
== True:
7300 error_value
= func
.GetInfo("error_value") or "GL_FALSE"
7301 file.Write("%s GLES2Implementation::%s(%s) {\n" %
7302 (func
.return_type
, func
.original_name
,
7303 func
.MakeTypedOriginalArgString("")))
7304 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
7305 self
.WriteTraceEvent(func
, file)
7306 func
.WriteDestinationInitalizationValidation(file)
7307 self
.WriteClientGLCallLog(func
, file)
7308 file.Write(" typedef cmds::%s::Result Result;\n" % func
.name
)
7309 file.Write(" Result* result = GetResultAs<Result*>();\n")
7310 file.Write(" if (!result) {\n")
7311 file.Write(" return %s;\n" % error_value
)
7313 file.Write(" *result = 0;\n")
7314 assert len(func
.GetOriginalArgs()) == 1
7315 id_arg
= func
.GetOriginalArgs()[0]
7316 if id_arg
.type == 'GLsync':
7317 arg_string
= "ToGLuint(%s)" % func
.MakeOriginalArgString("")
7319 arg_string
= func
.MakeOriginalArgString("")
7321 " helper_->%s(%s, GetResultShmId(), GetResultShmOffset());\n" %
7322 (func
.name
, arg_string
))
7323 file.Write(" WaitForCmd();\n")
7324 file.Write(" %s result_value = *result" % func
.return_type
)
7325 if func
.return_type
== "GLboolean":
7327 file.Write(';\n GPU_CLIENT_LOG("returned " << result_value);\n')
7328 file.Write(" CheckGLError();\n")
7329 file.Write(" return result_value;\n")
7333 def WriteGLES2ImplementationUnitTest(self
, func
, file):
7334 """Overrriden from TypeHandler."""
7335 client_test
= func
.GetInfo('client_test')
7336 if client_test
== None or client_test
== True:
7338 TEST_F(GLES2ImplementationTest, %(name)s) {
7344 ExpectedMemoryInfo result1 =
7345 GetExpectedResultMemory(sizeof(cmds::%(name)s::Result));
7346 expected.cmd.Init(%(cmd_id_value)s, result1.id, result1.offset);
7348 EXPECT_CALL(*command_buffer(), OnFlush())
7349 .WillOnce(SetMemory(result1.ptr, uint32_t(GL_TRUE)))
7350 .RetiresOnSaturation();
7352 GLboolean result = gl_->%(name)s(%(gl_id_value)s);
7353 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
7354 EXPECT_TRUE(result);
7357 args
= func
.GetOriginalArgs()
7358 assert len(args
) == 1
7361 'cmd_id_value': args
[0].GetValidClientSideCmdArg(func
),
7362 'gl_id_value': args
[0].GetValidClientSideArg(func
) })
7365 class STRnHandler(TypeHandler
):
7366 """Handler for GetProgramInfoLog, GetShaderInfoLog, GetShaderSource, and
7367 GetTranslatedShaderSourceANGLE."""
7370 TypeHandler
.__init
__(self
)
7372 def InitFunction(self
, func
):
7373 """Overrriden from TypeHandler."""
7374 # remove all but the first cmd args.
7375 cmd_args
= func
.GetCmdArgs()
7377 func
.AddCmdArg(cmd_args
[0])
7378 # add on a bucket id.
7379 func
.AddCmdArg(Argument('bucket_id', 'uint32_t'))
7381 def WriteGLES2Implementation(self
, func
, file):
7382 """Overrriden from TypeHandler."""
7383 code_1
= """%(return_type)s GLES2Implementation::%(func_name)s(%(args)s) {
7384 GPU_CLIENT_SINGLE_THREAD_CHECK();
7386 code_2
= """ GPU_CLIENT_LOG("[" << GetLogPrefix()
7387 << "] gl%(func_name)s" << "("
7390 << static_cast<void*>(%(arg2)s) << ", "
7391 << static_cast<void*>(%(arg3)s) << ")");
7392 helper_->SetBucketSize(kResultBucketId, 0);
7393 helper_->%(func_name)s(%(id_name)s, kResultBucketId);
7395 GLsizei max_size = 0;
7396 if (GetBucketAsString(kResultBucketId, &str)) {
7399 std::min(static_cast<size_t>(%(bufsize_name)s) - 1, str.size());
7400 memcpy(%(dest_name)s, str.c_str(), max_size);
7401 %(dest_name)s[max_size] = '\\0';
7402 GPU_CLIENT_LOG("------\\n" << %(dest_name)s << "\\n------");
7405 if (%(length_name)s != NULL) {
7406 *%(length_name)s = max_size;
7411 args
= func
.GetOriginalArgs()
7413 'return_type': func
.return_type
,
7414 'func_name': func
.original_name
,
7415 'args': func
.MakeTypedOriginalArgString(""),
7416 'id_name': args
[0].name
,
7417 'bufsize_name': args
[1].name
,
7418 'length_name': args
[2].name
,
7419 'dest_name': args
[3].name
,
7420 'arg0': args
[0].name
,
7421 'arg1': args
[1].name
,
7422 'arg2': args
[2].name
,
7423 'arg3': args
[3].name
,
7425 file.Write(code_1
% str_args
)
7426 func
.WriteDestinationInitalizationValidation(file)
7427 file.Write(code_2
% str_args
)
7429 def WriteServiceUnitTest(self
, func
, file, *extras
):
7430 """Overrriden from TypeHandler."""
7432 TEST_P(%(test_name)s, %(name)sValidArgs) {
7433 const char* kInfo = "hello";
7434 const uint32_t kBucketId = 123;
7435 SpecializedSetup<cmds::%(name)s, 0>(true);
7437 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s))
7438 .WillOnce(DoAll(SetArgumentPointee<2>(strlen(kInfo)),
7439 SetArrayArgument<3>(kInfo, kInfo + strlen(kInfo) + 1)));
7442 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
7443 CommonDecoder::Bucket* bucket = decoder_->GetBucket(kBucketId);
7444 ASSERT_TRUE(bucket != NULL);
7445 EXPECT_EQ(strlen(kInfo) + 1, bucket->size());
7446 EXPECT_EQ(0, memcmp(bucket->GetData(0, bucket->size()), kInfo,
7448 EXPECT_EQ(GL_NO_ERROR, GetGLError());
7451 args
= func
.GetOriginalArgs()
7452 id_name
= args
[0].GetValidGLArg(func
)
7453 get_len_func
= func
.GetInfo('get_len_func')
7454 get_len_enum
= func
.GetInfo('get_len_enum')
7457 'get_len_func': get_len_func
,
7458 'get_len_enum': get_len_enum
,
7459 'gl_args': '%s, strlen(kInfo) + 1, _, _' %
7460 args
[0].GetValidGLArg(func
),
7461 'args': '%s, kBucketId' % args
[0].GetValidArg(func
),
7462 'expect_len_code': '',
7464 if get_len_func
and get_len_func
[0:2] == 'gl':
7465 sub
['expect_len_code'] = (
7466 " EXPECT_CALL(*gl_, %s(%s, %s, _))\n"
7467 " .WillOnce(SetArgumentPointee<2>(strlen(kInfo) + 1));") % (
7468 get_len_func
[2:], id_name
, get_len_enum
)
7469 self
.WriteValidUnitTest(func
, file, valid_test
, sub
, *extras
)
7472 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
7473 const uint32_t kBucketId = 123;
7474 EXPECT_CALL(*gl_, %(gl_func_name)s(_, _, _, _))
7477 cmd.Init(kInvalidClientId, kBucketId);
7478 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
7479 EXPECT_EQ(GL_INVALID_VALUE, GetGLError());
7482 self
.WriteValidUnitTest(func
, file, invalid_test
, *extras
)
7484 def WriteServiceImplementation(self
, func
, file):
7485 """Overrriden from TypeHandler."""
7488 class NamedType(object):
7489 """A class that represents a type of an argument in a client function.
7491 A type of an argument that is to be passed through in the command buffer
7492 command. Currently used only for the arguments that are specificly named in
7493 the 'cmd_buffer_functions.txt' file, mostly enums.
7496 def __init__(self
, info
):
7497 assert not 'is_complete' in info
or info
['is_complete'] == True
7499 self
.valid
= info
['valid']
7500 if 'invalid' in info
:
7501 self
.invalid
= info
['invalid']
7506 return self
.info
['type']
7508 def GetInvalidValues(self
):
7511 def GetValidValues(self
):
7514 def IsConstant(self
):
7515 if not 'is_complete' in self
.info
:
7518 return len(self
.GetValidValues()) == 1
7520 def GetConstantValue(self
):
7521 return self
.GetValidValues()[0]
7523 class Argument(object):
7524 """A class that represents a function argument."""
7527 'GLenum': 'uint32_t',
7529 'GLintptr': 'int32_t',
7530 'GLsizei': 'int32_t',
7531 'GLsizeiptr': 'int32_t',
7533 'GLclampf': 'float',
7535 need_validation_
= ['GLsizei*', 'GLboolean*', 'GLenum*', 'GLint*']
7537 def __init__(self
, name
, type):
7539 self
.optional
= type.endswith("Optional*")
7541 type = type[:-9] + "*"
7544 if type in self
.cmd_type_map_
:
7545 self
.cmd_type
= self
.cmd_type_map_
[type]
7547 self
.cmd_type
= 'uint32_t'
7549 def IsPointer(self
):
7550 """Returns true if argument is a pointer."""
7553 def IsPointer2D(self
):
7554 """Returns true if argument is a 2D pointer."""
7557 def IsConstant(self
):
7558 """Returns true if the argument has only one valid value."""
7561 def AddCmdArgs(self
, args
):
7562 """Adds command arguments for this argument to the given list."""
7563 if not self
.IsConstant():
7564 return args
.append(self
)
7566 def AddInitArgs(self
, args
):
7567 """Adds init arguments for this argument to the given list."""
7568 if not self
.IsConstant():
7569 return args
.append(self
)
7571 def GetValidArg(self
, func
):
7572 """Gets a valid value for this argument."""
7573 valid_arg
= func
.GetValidArg(self
)
7574 if valid_arg
!= None:
7577 index
= func
.GetOriginalArgs().index(self
)
7578 return str(index
+ 1)
7580 def GetValidClientSideArg(self
, func
):
7581 """Gets a valid value for this argument."""
7582 valid_arg
= func
.GetValidArg(self
)
7583 if valid_arg
!= None:
7586 if self
.IsPointer():
7588 index
= func
.GetOriginalArgs().index(self
)
7589 if self
.type == 'GLsync':
7590 return ("reinterpret_cast<GLsync>(%d)" % (index
+ 1))
7591 return str(index
+ 1)
7593 def GetValidClientSideCmdArg(self
, func
):
7594 """Gets a valid value for this argument."""
7595 valid_arg
= func
.GetValidArg(self
)
7596 if valid_arg
!= None:
7599 index
= func
.GetOriginalArgs().index(self
)
7600 return str(index
+ 1)
7603 index
= func
.GetCmdArgs().index(self
)
7604 return str(index
+ 1)
7606 def GetValidGLArg(self
, func
):
7607 """Gets a valid GL value for this argument."""
7608 value
= self
.GetValidArg(func
)
7609 if self
.type == 'GLsync':
7610 return ("reinterpret_cast<GLsync>(%s)" % value
)
7613 def GetValidNonCachedClientSideArg(self
, func
):
7614 """Returns a valid value for this argument in a GL call.
7615 Using the value will produce a command buffer service invocation.
7616 Returns None if there is no such value."""
7618 if self
.type == 'GLsync':
7619 return ("reinterpret_cast<GLsync>(%s)" % value
)
7622 def GetValidNonCachedClientSideCmdArg(self
, func
):
7623 """Returns a valid value for this argument in a command buffer command.
7624 Calling the GL function with the value returned by
7625 GetValidNonCachedClientSideArg will result in a command buffer command
7626 that contains the value returned by this function. """
7629 def GetNumInvalidValues(self
, func
):
7630 """returns the number of invalid values to be tested."""
7633 def GetInvalidArg(self
, index
):
7634 """returns an invalid value and expected parse result by index."""
7635 return ("---ERROR0---", "---ERROR2---", None)
7637 def GetLogArg(self
):
7638 """Get argument appropriate for LOG macro."""
7639 if self
.type == 'GLboolean':
7640 return 'GLES2Util::GetStringBool(%s)' % self
.name
7641 if self
.type == 'GLenum':
7642 return 'GLES2Util::GetStringEnum(%s)' % self
.name
7645 def WriteGetCode(self
, file):
7646 """Writes the code to get an argument from a command structure."""
7647 if self
.type == 'GLsync':
7651 file.Write(" %s %s = static_cast<%s>(c.%s);\n" %
7652 (my_type
, self
.name
, my_type
, self
.name
))
7654 def WriteValidationCode(self
, file, func
):
7655 """Writes the validation code for an argument."""
7658 def WriteClientSideValidationCode(self
, file, func
):
7659 """Writes the validation code for an argument."""
7662 def WriteDestinationInitalizationValidation(self
, file, func
):
7663 """Writes the client side destintion initialization validation."""
7666 def WriteDestinationInitalizationValidatationIfNeeded(self
, file, func
):
7667 """Writes the client side destintion initialization validation if needed."""
7668 parts
= self
.type.split(" ")
7671 if parts
[0] in self
.need_validation_
:
7673 " GPU_CLIENT_VALIDATE_DESTINATION_%sINITALIZATION(%s, %s);\n" %
7674 ("OPTIONAL_" if self
.optional
else "", self
.type[:-1], self
.name
))
7677 def WriteGetAddress(self
, file):
7678 """Writes the code to get the address this argument refers to."""
7681 def GetImmediateVersion(self
):
7682 """Gets the immediate version of this argument."""
7685 def GetBucketVersion(self
):
7686 """Gets the bucket version of this argument."""
7690 class BoolArgument(Argument
):
7691 """class for GLboolean"""
7693 def __init__(self
, name
, type):
7694 Argument
.__init
__(self
, name
, 'GLboolean')
7696 def GetValidArg(self
, func
):
7697 """Gets a valid value for this argument."""
7700 def GetValidClientSideArg(self
, func
):
7701 """Gets a valid value for this argument."""
7704 def GetValidClientSideCmdArg(self
, func
):
7705 """Gets a valid value for this argument."""
7708 def GetValidGLArg(self
, func
):
7709 """Gets a valid GL value for this argument."""
7713 class UniformLocationArgument(Argument
):
7714 """class for uniform locations."""
7716 def __init__(self
, name
):
7717 Argument
.__init
__(self
, name
, "GLint")
7719 def WriteGetCode(self
, file):
7720 """Writes the code to get an argument from a command structure."""
7721 code
= """ %s %s = static_cast<%s>(c.%s);
7723 file.Write(code
% (self
.type, self
.name
, self
.type, self
.name
))
7725 class DataSizeArgument(Argument
):
7726 """class for data_size which Bucket commands do not need."""
7728 def __init__(self
, name
):
7729 Argument
.__init
__(self
, name
, "uint32_t")
7731 def GetBucketVersion(self
):
7735 class SizeArgument(Argument
):
7736 """class for GLsizei and GLsizeiptr."""
7738 def __init__(self
, name
, type):
7739 Argument
.__init
__(self
, name
, type)
7741 def GetNumInvalidValues(self
, func
):
7742 """overridden from Argument."""
7743 if func
.IsImmediate():
7747 def GetInvalidArg(self
, index
):
7748 """overridden from Argument."""
7749 return ("-1", "kNoError", "GL_INVALID_VALUE")
7751 def WriteValidationCode(self
, file, func
):
7752 """overridden from Argument."""
7755 code
= """ if (%(var_name)s < 0) {
7756 LOCAL_SET_GL_ERROR(GL_INVALID_VALUE, "gl%(func_name)s", "%(var_name)s < 0");
7757 return error::kNoError;
7761 "var_name": self
.name
,
7762 "func_name": func
.original_name
,
7765 def WriteClientSideValidationCode(self
, file, func
):
7766 """overridden from Argument."""
7767 code
= """ if (%(var_name)s < 0) {
7768 SetGLError(GL_INVALID_VALUE, "gl%(func_name)s", "%(var_name)s < 0");
7773 "var_name": self
.name
,
7774 "func_name": func
.original_name
,
7778 class SizeNotNegativeArgument(SizeArgument
):
7779 """class for GLsizeiNotNegative. It's NEVER allowed to be negative"""
7781 def __init__(self
, name
, type, gl_type
):
7782 SizeArgument
.__init
__(self
, name
, gl_type
)
7784 def GetInvalidArg(self
, index
):
7785 """overridden from SizeArgument."""
7786 return ("-1", "kOutOfBounds", "GL_NO_ERROR")
7788 def WriteValidationCode(self
, file, func
):
7789 """overridden from SizeArgument."""
7793 class EnumBaseArgument(Argument
):
7794 """Base class for EnumArgument, IntArgument, BitfieldArgument, and
7795 ValidatedBoolArgument."""
7797 def __init__(self
, name
, gl_type
, type, gl_error
):
7798 Argument
.__init
__(self
, name
, gl_type
)
7800 self
.local_type
= type
7801 self
.gl_error
= gl_error
7802 name
= type[len(gl_type
):]
7803 self
.type_name
= name
7804 self
.named_type
= NamedType(_NAMED_TYPE_INFO
[name
])
7806 def IsConstant(self
):
7807 return self
.named_type
.IsConstant()
7809 def GetConstantValue(self
):
7810 return self
.named_type
.GetConstantValue()
7812 def WriteValidationCode(self
, file, func
):
7815 if self
.named_type
.IsConstant():
7817 file.Write(" if (!validators_->%s.IsValid(%s)) {\n" %
7818 (ToUnderscore(self
.type_name
), self
.name
))
7819 if self
.gl_error
== "GL_INVALID_ENUM":
7821 " LOCAL_SET_GL_ERROR_INVALID_ENUM(\"gl%s\", %s, \"%s\");\n" %
7822 (func
.original_name
, self
.name
, self
.name
))
7825 " LOCAL_SET_GL_ERROR(%s, \"gl%s\", \"%s %s\");\n" %
7826 (self
.gl_error
, func
.original_name
, self
.name
, self
.gl_error
))
7827 file.Write(" return error::kNoError;\n")
7830 def WriteClientSideValidationCode(self
, file, func
):
7831 if not self
.named_type
.IsConstant():
7833 file.Write(" if (%s != %s) {" % (self
.name
,
7834 self
.GetConstantValue()))
7836 " SetGLError(%s, \"gl%s\", \"%s %s\");\n" %
7837 (self
.gl_error
, func
.original_name
, self
.name
, self
.gl_error
))
7838 if func
.return_type
== "void":
7839 file.Write(" return;\n")
7841 file.Write(" return %s;\n" % func
.GetErrorReturnString())
7844 def GetValidArg(self
, func
):
7845 valid_arg
= func
.GetValidArg(self
)
7846 if valid_arg
!= None:
7848 valid
= self
.named_type
.GetValidValues()
7850 num_valid
= len(valid
)
7853 index
= func
.GetOriginalArgs().index(self
)
7854 return str(index
+ 1)
7856 def GetValidClientSideArg(self
, func
):
7857 """Gets a valid value for this argument."""
7858 return self
.GetValidArg(func
)
7860 def GetValidClientSideCmdArg(self
, func
):
7861 """Gets a valid value for this argument."""
7862 valid_arg
= func
.GetValidArg(self
)
7863 if valid_arg
!= None:
7866 valid
= self
.named_type
.GetValidValues()
7868 num_valid
= len(valid
)
7872 index
= func
.GetOriginalArgs().index(self
)
7873 return str(index
+ 1)
7876 index
= func
.GetCmdArgs().index(self
)
7877 return str(index
+ 1)
7879 def GetValidGLArg(self
, func
):
7880 """Gets a valid value for this argument."""
7881 return self
.GetValidArg(func
)
7883 def GetNumInvalidValues(self
, func
):
7884 """returns the number of invalid values to be tested."""
7885 return len(self
.named_type
.GetInvalidValues())
7887 def GetInvalidArg(self
, index
):
7888 """returns an invalid value by index."""
7889 invalid
= self
.named_type
.GetInvalidValues()
7891 num_invalid
= len(invalid
)
7892 if index
>= num_invalid
:
7893 index
= num_invalid
- 1
7894 return (invalid
[index
], "kNoError", self
.gl_error
)
7895 return ("---ERROR1---", "kNoError", self
.gl_error
)
7898 class EnumArgument(EnumBaseArgument
):
7899 """A class that represents a GLenum argument"""
7901 def __init__(self
, name
, type):
7902 EnumBaseArgument
.__init
__(self
, name
, "GLenum", type, "GL_INVALID_ENUM")
7904 def GetLogArg(self
):
7905 """Overridden from Argument."""
7906 return ("GLES2Util::GetString%s(%s)" %
7907 (self
.type_name
, self
.name
))
7910 class IntArgument(EnumBaseArgument
):
7911 """A class for a GLint argument that can only accept specific values.
7913 For example glTexImage2D takes a GLint for its internalformat
7914 argument instead of a GLenum.
7917 def __init__(self
, name
, type):
7918 EnumBaseArgument
.__init
__(self
, name
, "GLint", type, "GL_INVALID_VALUE")
7921 class ValidatedBoolArgument(EnumBaseArgument
):
7922 """A class for a GLboolean argument that can only accept specific values.
7924 For example glUniformMatrix takes a GLboolean for it's transpose but it
7928 def __init__(self
, name
, type):
7929 EnumBaseArgument
.__init
__(self
, name
, "GLboolean", type, "GL_INVALID_VALUE")
7931 def GetLogArg(self
):
7932 """Overridden from Argument."""
7933 return 'GLES2Util::GetStringBool(%s)' % self
.name
7936 class BitFieldArgument(EnumBaseArgument
):
7937 """A class for a GLbitfield argument that can only accept specific values.
7939 For example glFenceSync takes a GLbitfield for its flags argument bit it
7943 def __init__(self
, name
, type):
7944 EnumBaseArgument
.__init
__(self
, name
, "GLbitfield", type,
7948 class ImmediatePointerArgument(Argument
):
7949 """A class that represents an immediate argument to a function.
7951 An immediate argument is one where the data follows the command.
7954 def __init__(self
, name
, type):
7955 Argument
.__init
__(self
, name
, type)
7957 def IsPointer(self
):
7960 def GetPointedType(self
):
7961 match
= re
.match('(const\s+)?(?P<element_type>[\w]+)\s*\*', self
.type)
7963 return match
.groupdict()['element_type']
7965 def AddCmdArgs(self
, args
):
7966 """Overridden from Argument."""
7969 def WriteGetCode(self
, file):
7970 """Overridden from Argument."""
7972 " %s %s = GetImmediateDataAs<%s>(\n" %
7973 (self
.type, self
.name
, self
.type))
7974 file.Write(" c, data_size, immediate_data_size);\n")
7976 def WriteValidationCode(self
, file, func
):
7977 """Overridden from Argument."""
7980 file.Write(" if (%s == NULL) {\n" % self
.name
)
7981 file.Write(" return error::kOutOfBounds;\n")
7984 def GetImmediateVersion(self
):
7985 """Overridden from Argument."""
7988 def WriteDestinationInitalizationValidation(self
, file, func
):
7989 """Overridden from Argument."""
7990 self
.WriteDestinationInitalizationValidatationIfNeeded(file, func
)
7992 def GetLogArg(self
):
7993 """Overridden from Argument."""
7994 return "static_cast<const void*>(%s)" % self
.name
7997 class PointerArgument(Argument
):
7998 """A class that represents a pointer argument to a function."""
8000 def __init__(self
, name
, type):
8001 Argument
.__init
__(self
, name
, type)
8003 def IsPointer(self
):
8004 """Overridden from Argument."""
8007 def IsPointer2D(self
):
8008 """Overridden from Argument."""
8009 return self
.type.count('*') == 2
8011 def GetPointedType(self
):
8012 match
= re
.match('(const\s+)?(?P<element_type>[\w]+)\s*\*', self
.type)
8014 return match
.groupdict()['element_type']
8016 def GetValidArg(self
, func
):
8017 """Overridden from Argument."""
8018 return "shared_memory_id_, shared_memory_offset_"
8020 def GetValidGLArg(self
, func
):
8021 """Overridden from Argument."""
8022 return "reinterpret_cast<%s>(shared_memory_address_)" % self
.type
8024 def GetNumInvalidValues(self
, func
):
8025 """Overridden from Argument."""
8028 def GetInvalidArg(self
, index
):
8029 """Overridden from Argument."""
8031 return ("kInvalidSharedMemoryId, 0", "kOutOfBounds", None)
8033 return ("shared_memory_id_, kInvalidSharedMemoryOffset",
8034 "kOutOfBounds", None)
8036 def GetLogArg(self
):
8037 """Overridden from Argument."""
8038 return "static_cast<const void*>(%s)" % self
.name
8040 def AddCmdArgs(self
, args
):
8041 """Overridden from Argument."""
8042 args
.append(Argument("%s_shm_id" % self
.name
, 'uint32_t'))
8043 args
.append(Argument("%s_shm_offset" % self
.name
, 'uint32_t'))
8045 def WriteGetCode(self
, file):
8046 """Overridden from Argument."""
8048 " %s %s = GetSharedMemoryAs<%s>(\n" %
8049 (self
.type, self
.name
, self
.type))
8051 " c.%s_shm_id, c.%s_shm_offset, data_size);\n" %
8052 (self
.name
, self
.name
))
8054 def WriteGetAddress(self
, file):
8055 """Overridden from Argument."""
8057 " %s %s = GetSharedMemoryAs<%s>(\n" %
8058 (self
.type, self
.name
, self
.type))
8060 " %s_shm_id, %s_shm_offset, %s_size);\n" %
8061 (self
.name
, self
.name
, self
.name
))
8063 def WriteValidationCode(self
, file, func
):
8064 """Overridden from Argument."""
8067 file.Write(" if (%s == NULL) {\n" % self
.name
)
8068 file.Write(" return error::kOutOfBounds;\n")
8071 def GetImmediateVersion(self
):
8072 """Overridden from Argument."""
8073 return ImmediatePointerArgument(self
.name
, self
.type)
8075 def GetBucketVersion(self
):
8076 """Overridden from Argument."""
8077 if self
.type.find('char') >= 0:
8078 if self
.IsPointer2D():
8079 return InputStringArrayBucketArgument(self
.name
, self
.type)
8080 return InputStringBucketArgument(self
.name
, self
.type)
8081 return BucketPointerArgument(self
.name
, self
.type)
8083 def WriteDestinationInitalizationValidation(self
, file, func
):
8084 """Overridden from Argument."""
8085 self
.WriteDestinationInitalizationValidatationIfNeeded(file, func
)
8088 class BucketPointerArgument(PointerArgument
):
8089 """A class that represents an bucket argument to a function."""
8091 def __init__(self
, name
, type):
8092 Argument
.__init
__(self
, name
, type)
8094 def AddCmdArgs(self
, args
):
8095 """Overridden from Argument."""
8098 def WriteGetCode(self
, file):
8099 """Overridden from Argument."""
8101 " %s %s = bucket->GetData(0, data_size);\n" %
8102 (self
.type, self
.name
))
8104 def WriteValidationCode(self
, file, func
):
8105 """Overridden from Argument."""
8108 def GetImmediateVersion(self
):
8109 """Overridden from Argument."""
8112 def WriteDestinationInitalizationValidation(self
, file, func
):
8113 """Overridden from Argument."""
8114 self
.WriteDestinationInitalizationValidatationIfNeeded(file, func
)
8116 def GetLogArg(self
):
8117 """Overridden from Argument."""
8118 return "static_cast<const void*>(%s)" % self
.name
8121 class InputStringBucketArgument(Argument
):
8122 """A string input argument where the string is passed in a bucket."""
8124 def __init__(self
, name
, type):
8125 Argument
.__init
__(self
, name
+ "_bucket_id", "uint32_t")
8127 def IsPointer(self
):
8128 """Overridden from Argument."""
8131 def IsPointer2D(self
):
8132 """Overridden from Argument."""
8136 class InputStringArrayBucketArgument(Argument
):
8137 """A string array input argument where the strings are passed in a bucket."""
8139 def __init__(self
, name
, type):
8140 Argument
.__init
__(self
, name
+ "_bucket_id", "uint32_t")
8141 self
._original
_name
= name
8143 def WriteGetCode(self
, file):
8144 """Overridden from Argument."""
8146 Bucket* bucket = GetBucket(c.%(name)s);
8148 return error::kInvalidArguments;
8151 std::vector<char*> strs;
8152 std::vector<GLint> len;
8153 if (!bucket->GetAsStrings(&count, &strs, &len)) {
8154 return error::kInvalidArguments;
8156 const char** %(original_name)s =
8157 strs.size() > 0 ? const_cast<const char**>(&strs[0]) : NULL;
8158 const GLint* length =
8159 len.size() > 0 ? const_cast<const GLint*>(&len[0]) : NULL;
8164 'original_name': self
._original
_name
,
8167 def GetValidArg(self
, func
):
8168 return "kNameBucketId"
8170 def GetValidGLArg(self
, func
):
8173 def IsPointer(self
):
8174 """Overridden from Argument."""
8177 def IsPointer2D(self
):
8178 """Overridden from Argument."""
8182 class ResourceIdArgument(Argument
):
8183 """A class that represents a resource id argument to a function."""
8185 def __init__(self
, name
, type):
8186 match
= re
.match("(GLid\w+)", type)
8187 self
.resource_type
= match
.group(1)[4:]
8188 if self
.resource_type
== "Sync":
8189 type = type.replace(match
.group(1), "GLsync")
8191 type = type.replace(match
.group(1), "GLuint")
8192 Argument
.__init
__(self
, name
, type)
8194 def WriteGetCode(self
, file):
8195 """Overridden from Argument."""
8196 if self
.type == "GLsync":
8200 file.Write(" %s %s = c.%s;\n" % (my_type
, self
.name
, self
.name
))
8202 def GetValidArg(self
, func
):
8203 return "client_%s_id_" % self
.resource_type
.lower()
8205 def GetValidGLArg(self
, func
):
8206 if self
.resource_type
== "Sync":
8207 return "reinterpret_cast<GLsync>(kService%sId)" % self
.resource_type
8208 return "kService%sId" % self
.resource_type
8211 class ResourceIdBindArgument(Argument
):
8212 """Represents a resource id argument to a bind function."""
8214 def __init__(self
, name
, type):
8215 match
= re
.match("(GLidBind\w+)", type)
8216 self
.resource_type
= match
.group(1)[8:]
8217 type = type.replace(match
.group(1), "GLuint")
8218 Argument
.__init
__(self
, name
, type)
8220 def WriteGetCode(self
, file):
8221 """Overridden from Argument."""
8222 code
= """ %(type)s %(name)s = c.%(name)s;
8224 file.Write(code
% {'type': self
.type, 'name': self
.name
})
8226 def GetValidArg(self
, func
):
8227 return "client_%s_id_" % self
.resource_type
.lower()
8229 def GetValidGLArg(self
, func
):
8230 return "kService%sId" % self
.resource_type
8233 class ResourceIdZeroArgument(Argument
):
8234 """Represents a resource id argument to a function that can be zero."""
8236 def __init__(self
, name
, type):
8237 match
= re
.match("(GLidZero\w+)", type)
8238 self
.resource_type
= match
.group(1)[8:]
8239 type = type.replace(match
.group(1), "GLuint")
8240 Argument
.__init
__(self
, name
, type)
8242 def WriteGetCode(self
, file):
8243 """Overridden from Argument."""
8244 file.Write(" %s %s = c.%s;\n" % (self
.type, self
.name
, self
.name
))
8246 def GetValidArg(self
, func
):
8247 return "client_%s_id_" % self
.resource_type
.lower()
8249 def GetValidGLArg(self
, func
):
8250 return "kService%sId" % self
.resource_type
8252 def GetNumInvalidValues(self
, func
):
8253 """returns the number of invalid values to be tested."""
8256 def GetInvalidArg(self
, index
):
8257 """returns an invalid value by index."""
8258 return ("kInvalidClientId", "kNoError", "GL_INVALID_VALUE")
8261 class Function(object):
8262 """A class that represents a function."""
8266 'Bind': BindHandler(),
8267 'Create': CreateHandler(),
8268 'Custom': CustomHandler(),
8269 'Data': DataHandler(),
8270 'Delete': DeleteHandler(),
8271 'DELn': DELnHandler(),
8272 'GENn': GENnHandler(),
8273 'GETn': GETnHandler(),
8274 'GLchar': GLcharHandler(),
8275 'GLcharN': GLcharNHandler(),
8276 'HandWritten': HandWrittenHandler(),
8278 'Manual': ManualHandler(),
8279 'PUT': PUTHandler(),
8280 'PUTn': PUTnHandler(),
8281 'PUTSTR': PUTSTRHandler(),
8282 'PUTXn': PUTXnHandler(),
8283 'StateSet': StateSetHandler(),
8284 'StateSetRGBAlpha': StateSetRGBAlphaHandler(),
8285 'StateSetFrontBack': StateSetFrontBackHandler(),
8286 'StateSetFrontBackSeparate': StateSetFrontBackSeparateHandler(),
8287 'StateSetNamedParameter': StateSetNamedParameter(),
8288 'STRn': STRnHandler(),
8289 'Todo': TodoHandler(),
8292 def __init__(self
, name
, info
):
8294 self
.original_name
= info
['original_name']
8296 self
.original_args
= self
.ParseArgs(info
['original_args'])
8298 if 'cmd_args' in info
:
8299 self
.args_for_cmds
= self
.ParseArgs(info
['cmd_args'])
8301 self
.args_for_cmds
= self
.original_args
[:]
8303 self
.return_type
= info
['return_type']
8304 if self
.return_type
!= 'void':
8305 self
.return_arg
= CreateArg(info
['return_type'] + " result")
8307 self
.return_arg
= None
8309 self
.num_pointer_args
= sum(
8310 [1 for arg
in self
.args_for_cmds
if arg
.IsPointer()])
8311 if self
.num_pointer_args
> 0:
8312 for arg
in reversed(self
.original_args
):
8314 self
.last_original_pointer_arg
= arg
8317 self
.last_original_pointer_arg
= None
8319 self
.type_handler
= self
.type_handlers
[info
['type']]
8320 self
.can_auto_generate
= (self
.num_pointer_args
== 0 and
8321 info
['return_type'] == "void")
8324 def ParseArgs(self
, arg_string
):
8325 """Parses a function arg string."""
8327 parts
= arg_string
.split(',')
8328 for arg_string
in parts
:
8329 arg
= CreateArg(arg_string
)
8334 def IsType(self
, type_name
):
8335 """Returns true if function is a certain type."""
8336 return self
.info
['type'] == type_name
8338 def InitFunction(self
):
8339 """Creates command args and calls the init function for the type handler.
8341 Creates argument lists for command buffer commands, eg. self.cmd_args and
8343 Calls the type function initialization.
8344 Override to create different kind of command buffer command argument lists.
8347 for arg
in self
.args_for_cmds
:
8348 arg
.AddCmdArgs(self
.cmd_args
)
8351 for arg
in self
.args_for_cmds
:
8352 arg
.AddInitArgs(self
.init_args
)
8355 self
.init_args
.append(self
.return_arg
)
8357 self
.type_handler
.InitFunction(self
)
8359 def IsImmediate(self
):
8360 """Returns whether the function is immediate data function or not."""
8364 """Returns whether the function has service side validation or not."""
8365 return self
.GetInfo('unsafe', False)
8367 def GetInfo(self
, name
, default
= None):
8368 """Returns a value from the function info for this function."""
8369 if name
in self
.info
:
8370 return self
.info
[name
]
8373 def GetValidArg(self
, arg
):
8374 """Gets a valid argument value for the parameter arg from the function info
8377 index
= self
.GetOriginalArgs().index(arg
)
8381 valid_args
= self
.GetInfo('valid_args')
8382 if valid_args
and str(index
) in valid_args
:
8383 return valid_args
[str(index
)]
8386 def AddInfo(self
, name
, value
):
8388 self
.info
[name
] = value
8390 def IsExtension(self
):
8391 return self
.GetInfo('extension') or self
.GetInfo('extension_flag')
8393 def IsCoreGLFunction(self
):
8394 return (not self
.IsExtension() and
8395 not self
.GetInfo('pepper_interface') and
8396 not self
.IsUnsafe())
8398 def InPepperInterface(self
, interface
):
8399 ext
= self
.GetInfo('pepper_interface')
8400 if not interface
.GetName():
8401 return self
.IsCoreGLFunction()
8402 return ext
== interface
.GetName()
8404 def InAnyPepperExtension(self
):
8405 return self
.IsCoreGLFunction() or self
.GetInfo('pepper_interface')
8407 def GetErrorReturnString(self
):
8408 if self
.GetInfo("error_return"):
8409 return self
.GetInfo("error_return")
8410 elif self
.return_type
== "GLboolean":
8412 elif "*" in self
.return_type
:
8416 def GetGLFunctionName(self
):
8417 """Gets the function to call to execute GL for this command."""
8418 if self
.GetInfo('decoder_func'):
8419 return self
.GetInfo('decoder_func')
8420 return "gl%s" % self
.original_name
8422 def GetGLTestFunctionName(self
):
8423 gl_func_name
= self
.GetInfo('gl_test_func')
8424 if gl_func_name
== None:
8425 gl_func_name
= self
.GetGLFunctionName()
8426 if gl_func_name
.startswith("gl"):
8427 gl_func_name
= gl_func_name
[2:]
8429 gl_func_name
= self
.original_name
8432 def GetDataTransferMethods(self
):
8433 return self
.GetInfo('data_transfer_methods',
8434 ['immediate' if self
.num_pointer_args
== 1 else 'shm'])
8436 def AddCmdArg(self
, arg
):
8437 """Adds a cmd argument to this function."""
8438 self
.cmd_args
.append(arg
)
8440 def GetCmdArgs(self
):
8441 """Gets the command args for this function."""
8442 return self
.cmd_args
8444 def ClearCmdArgs(self
):
8445 """Clears the command args for this function."""
8448 def GetCmdConstants(self
):
8449 """Gets the constants for this function."""
8450 return [arg
for arg
in self
.args_for_cmds
if arg
.IsConstant()]
8452 def GetInitArgs(self
):
8453 """Gets the init args for this function."""
8454 return self
.init_args
8456 def GetOriginalArgs(self
):
8457 """Gets the original arguments to this function."""
8458 return self
.original_args
8460 def GetLastOriginalArg(self
):
8461 """Gets the last original argument to this function."""
8462 return self
.original_args
[len(self
.original_args
) - 1]
8464 def GetLastOriginalPointerArg(self
):
8465 return self
.last_original_pointer_arg
8467 def GetResourceIdArg(self
):
8468 for arg
in self
.original_args
:
8469 if hasattr(arg
, 'resource_type'):
8473 def _MaybePrependComma(self
, arg_string
, add_comma
):
8474 """Adds a comma if arg_string is not empty and add_comma is true."""
8476 if add_comma
and len(arg_string
):
8478 return "%s%s" % (comma
, arg_string
)
8480 def MakeTypedOriginalArgString(self
, prefix
, add_comma
= False):
8481 """Gets a list of arguments as they are in GL."""
8482 args
= self
.GetOriginalArgs()
8483 arg_string
= ", ".join(
8484 ["%s %s%s" % (arg
.type, prefix
, arg
.name
) for arg
in args
])
8485 return self
._MaybePrependComma
(arg_string
, add_comma
)
8487 def MakeOriginalArgString(self
, prefix
, add_comma
= False, separator
= ", "):
8488 """Gets the list of arguments as they are in GL."""
8489 args
= self
.GetOriginalArgs()
8490 arg_string
= separator
.join(
8491 ["%s%s" % (prefix
, arg
.name
) for arg
in args
])
8492 return self
._MaybePrependComma
(arg_string
, add_comma
)
8494 def MakeTypedHelperArgString(self
, prefix
, add_comma
= False):
8495 """Gets a list of typed GL arguments after removing unneeded arguments."""
8496 args
= self
.GetOriginalArgs()
8497 arg_string
= ", ".join(
8502 ) for arg
in args
if not arg
.IsConstant()])
8503 return self
._MaybePrependComma
(arg_string
, add_comma
)
8505 def MakeHelperArgString(self
, prefix
, add_comma
= False, separator
= ", "):
8506 """Gets a list of GL arguments after removing unneeded arguments."""
8507 args
= self
.GetOriginalArgs()
8508 arg_string
= separator
.join(
8509 ["%s%s" % (prefix
, arg
.name
)
8510 for arg
in args
if not arg
.IsConstant()])
8511 return self
._MaybePrependComma
(arg_string
, add_comma
)
8513 def MakeTypedPepperArgString(self
, prefix
):
8514 """Gets a list of arguments as they need to be for Pepper."""
8515 if self
.GetInfo("pepper_args"):
8516 return self
.GetInfo("pepper_args")
8518 return self
.MakeTypedOriginalArgString(prefix
, False)
8520 def MapCTypeToPepperIdlType(self
, ctype
, is_for_return_type
=False):
8521 """Converts a C type name to the corresponding Pepper IDL type."""
8523 'char*': '[out] str_t',
8524 'const GLchar* const*': '[out] cstr_t',
8525 'const char*': 'cstr_t',
8526 'const void*': 'mem_t',
8527 'void*': '[out] mem_t',
8528 'void**': '[out] mem_ptr_t',
8530 # We use "GLxxx_ptr_t" for "GLxxx*".
8531 matched
= re
.match(r
'(const )?(GL\w+)\*$', ctype
)
8533 idltype
= matched
.group(2) + '_ptr_t'
8534 if not matched
.group(1):
8535 idltype
= '[out] ' + idltype
8536 # If an in/out specifier is not specified yet, prepend [in].
8537 if idltype
[0] != '[':
8538 idltype
= '[in] ' + idltype
8539 # Strip the in/out specifier for a return type.
8540 if is_for_return_type
:
8541 idltype
= re
.sub(r
'\[\w+\] ', '', idltype
)
8544 def MakeTypedPepperIdlArgStrings(self
):
8545 """Gets a list of arguments as they need to be for Pepper IDL."""
8546 args
= self
.GetOriginalArgs()
8547 return ["%s %s" % (self
.MapCTypeToPepperIdlType(arg
.type), arg
.name
)
8550 def GetPepperName(self
):
8551 if self
.GetInfo("pepper_name"):
8552 return self
.GetInfo("pepper_name")
8555 def MakeTypedCmdArgString(self
, prefix
, add_comma
= False):
8556 """Gets a typed list of arguments as they need to be for command buffers."""
8557 args
= self
.GetCmdArgs()
8558 arg_string
= ", ".join(
8559 ["%s %s%s" % (arg
.type, prefix
, arg
.name
) for arg
in args
])
8560 return self
._MaybePrependComma
(arg_string
, add_comma
)
8562 def MakeCmdArgString(self
, prefix
, add_comma
= False):
8563 """Gets the list of arguments as they need to be for command buffers."""
8564 args
= self
.GetCmdArgs()
8565 arg_string
= ", ".join(
8566 ["%s%s" % (prefix
, arg
.name
) for arg
in args
])
8567 return self
._MaybePrependComma
(arg_string
, add_comma
)
8569 def MakeTypedInitString(self
, prefix
, add_comma
= False):
8570 """Gets a typed list of arguments as they need to be for cmd Init/Set."""
8571 args
= self
.GetInitArgs()
8572 arg_string
= ", ".join(
8573 ["%s %s%s" % (arg
.type, prefix
, arg
.name
) for arg
in args
])
8574 return self
._MaybePrependComma
(arg_string
, add_comma
)
8576 def MakeInitString(self
, prefix
, add_comma
= False):
8577 """Gets the list of arguments as they need to be for cmd Init/Set."""
8578 args
= self
.GetInitArgs()
8579 arg_string
= ", ".join(
8580 ["%s%s" % (prefix
, arg
.name
) for arg
in args
])
8581 return self
._MaybePrependComma
(arg_string
, add_comma
)
8583 def MakeLogArgString(self
):
8584 """Makes a string of the arguments for the LOG macros"""
8585 args
= self
.GetOriginalArgs()
8586 return ' << ", " << '.join([arg
.GetLogArg() for arg
in args
])
8588 def WriteCommandDescription(self
, file):
8589 """Writes a description of the command."""
8590 file.Write("//! Command that corresponds to gl%s.\n" % self
.original_name
)
8592 def WriteHandlerValidation(self
, file):
8593 """Writes validation code for the function."""
8594 for arg
in self
.GetOriginalArgs():
8595 arg
.WriteValidationCode(file, self
)
8596 self
.WriteValidationCode(file)
8598 def WriteHandlerImplementation(self
, file):
8599 """Writes the handler implementation for this command."""
8600 self
.type_handler
.WriteHandlerImplementation(self
, file)
8602 def WriteValidationCode(self
, file):
8603 """Writes the validation code for a command."""
8606 def WriteCmdFlag(self
, file):
8607 """Writes the cmd cmd_flags constant."""
8609 # By default trace only at the highest level 3.
8610 trace_level
= int(self
.GetInfo('trace_level', default
= 3))
8611 if trace_level
not in xrange(0, 4):
8612 raise KeyError("Unhandled trace_level: %d" % trace_level
)
8614 flags
.append('CMD_FLAG_SET_TRACE_LEVEL(%d)' % trace_level
)
8617 cmd_flags
= ' | '.join(flags
)
8621 file.Write(" static const uint8 cmd_flags = %s;\n" % cmd_flags
)
8624 def WriteCmdArgFlag(self
, file):
8625 """Writes the cmd kArgFlags constant."""
8626 file.Write(" static const cmd::ArgFlags kArgFlags = cmd::kFixed;\n")
8628 def WriteCmdComputeSize(self
, file):
8629 """Writes the ComputeSize function for the command."""
8630 file.Write(" static uint32_t ComputeSize() {\n")
8632 " return static_cast<uint32_t>(sizeof(ValueType)); // NOLINT\n")
8636 def WriteCmdSetHeader(self
, file):
8637 """Writes the cmd's SetHeader function."""
8638 file.Write(" void SetHeader() {\n")
8639 file.Write(" header.SetCmd<ValueType>();\n")
8643 def WriteCmdInit(self
, file):
8644 """Writes the cmd's Init function."""
8645 file.Write(" void Init(%s) {\n" % self
.MakeTypedCmdArgString("_"))
8646 file.Write(" SetHeader();\n")
8647 args
= self
.GetCmdArgs()
8649 file.Write(" %s = _%s;\n" % (arg
.name
, arg
.name
))
8653 def WriteCmdSet(self
, file):
8654 """Writes the cmd's Set function."""
8655 copy_args
= self
.MakeCmdArgString("_", False)
8656 file.Write(" void* Set(void* cmd%s) {\n" %
8657 self
.MakeTypedCmdArgString("_", True))
8658 file.Write(" static_cast<ValueType*>(cmd)->Init(%s);\n" % copy_args
)
8659 file.Write(" return NextCmdAddress<ValueType>(cmd);\n")
8663 def WriteStruct(self
, file):
8664 self
.type_handler
.WriteStruct(self
, file)
8666 def WriteDocs(self
, file):
8667 self
.type_handler
.WriteDocs(self
, file)
8669 def WriteCmdHelper(self
, file):
8670 """Writes the cmd's helper."""
8671 self
.type_handler
.WriteCmdHelper(self
, file)
8673 def WriteServiceImplementation(self
, file):
8674 """Writes the service implementation for a command."""
8675 self
.type_handler
.WriteServiceImplementation(self
, file)
8677 def WriteServiceUnitTest(self
, file, *extras
):
8678 """Writes the service implementation for a command."""
8679 self
.type_handler
.WriteServiceUnitTest(self
, file, *extras
)
8681 def WriteGLES2CLibImplementation(self
, file):
8682 """Writes the GLES2 C Lib Implemention."""
8683 self
.type_handler
.WriteGLES2CLibImplementation(self
, file)
8685 def WriteGLES2InterfaceHeader(self
, file):
8686 """Writes the GLES2 Interface declaration."""
8687 self
.type_handler
.WriteGLES2InterfaceHeader(self
, file)
8689 def WriteGLES2InterfaceStub(self
, file):
8690 """Writes the GLES2 Interface Stub declaration."""
8691 self
.type_handler
.WriteGLES2InterfaceStub(self
, file)
8693 def WriteGLES2InterfaceStubImpl(self
, file):
8694 """Writes the GLES2 Interface Stub declaration."""
8695 self
.type_handler
.WriteGLES2InterfaceStubImpl(self
, file)
8697 def WriteGLES2ImplementationHeader(self
, file):
8698 """Writes the GLES2 Implemention declaration."""
8699 self
.type_handler
.WriteGLES2ImplementationHeader(self
, file)
8701 def WriteGLES2Implementation(self
, file):
8702 """Writes the GLES2 Implemention definition."""
8703 self
.type_handler
.WriteGLES2Implementation(self
, file)
8705 def WriteGLES2TraceImplementationHeader(self
, file):
8706 """Writes the GLES2 Trace Implemention declaration."""
8707 self
.type_handler
.WriteGLES2TraceImplementationHeader(self
, file)
8709 def WriteGLES2TraceImplementation(self
, file):
8710 """Writes the GLES2 Trace Implemention definition."""
8711 self
.type_handler
.WriteGLES2TraceImplementation(self
, file)
8713 def WriteGLES2Header(self
, file):
8714 """Writes the GLES2 Implemention unit test."""
8715 self
.type_handler
.WriteGLES2Header(self
, file)
8717 def WriteGLES2ImplementationUnitTest(self
, file):
8718 """Writes the GLES2 Implemention unit test."""
8719 self
.type_handler
.WriteGLES2ImplementationUnitTest(self
, file)
8721 def WriteDestinationInitalizationValidation(self
, file):
8722 """Writes the client side destintion initialization validation."""
8723 self
.type_handler
.WriteDestinationInitalizationValidation(self
, file)
8725 def WriteFormatTest(self
, file):
8726 """Writes the cmd's format test."""
8727 self
.type_handler
.WriteFormatTest(self
, file)
8730 class PepperInterface(object):
8731 """A class that represents a function."""
8733 def __init__(self
, info
):
8734 self
.name
= info
["name"]
8735 self
.dev
= info
["dev"]
8740 def GetInterfaceName(self
):
8744 upperint
= "_" + self
.name
.upper()
8747 return "PPB_OPENGLES2%s%s_INTERFACE" % (upperint
, dev
)
8749 def GetInterfaceString(self
):
8753 return "PPB_OpenGLES2%s%s" % (self
.name
, dev
)
8755 def GetStructName(self
):
8759 return "PPB_OpenGLES2%s%s" % (self
.name
, dev
)
8762 class ImmediateFunction(Function
):
8763 """A class that represnets an immediate function command."""
8765 def __init__(self
, func
):
8768 "%sImmediate" % func
.name
,
8771 def InitFunction(self
):
8772 # Override args in original_args and args_for_cmds with immediate versions
8775 new_original_args
= []
8776 for arg
in self
.original_args
:
8777 new_arg
= arg
.GetImmediateVersion()
8779 new_original_args
.append(new_arg
)
8780 self
.original_args
= new_original_args
8782 new_args_for_cmds
= []
8783 for arg
in self
.args_for_cmds
:
8784 new_arg
= arg
.GetImmediateVersion()
8786 new_args_for_cmds
.append(new_arg
)
8788 self
.args_for_cmds
= new_args_for_cmds
8790 Function
.InitFunction(self
)
8792 def IsImmediate(self
):
8795 def WriteCommandDescription(self
, file):
8796 """Overridden from Function"""
8797 file.Write("//! Immediate version of command that corresponds to gl%s.\n" %
8800 def WriteServiceImplementation(self
, file):
8801 """Overridden from Function"""
8802 self
.type_handler
.WriteImmediateServiceImplementation(self
, file)
8804 def WriteHandlerImplementation(self
, file):
8805 """Overridden from Function"""
8806 self
.type_handler
.WriteImmediateHandlerImplementation(self
, file)
8808 def WriteServiceUnitTest(self
, file, *extras
):
8809 """Writes the service implementation for a command."""
8810 self
.type_handler
.WriteImmediateServiceUnitTest(self
, file, *extras
)
8812 def WriteValidationCode(self
, file):
8813 """Overridden from Function"""
8814 self
.type_handler
.WriteImmediateValidationCode(self
, file)
8816 def WriteCmdArgFlag(self
, file):
8817 """Overridden from Function"""
8818 file.Write(" static const cmd::ArgFlags kArgFlags = cmd::kAtLeastN;\n")
8820 def WriteCmdComputeSize(self
, file):
8821 """Overridden from Function"""
8822 self
.type_handler
.WriteImmediateCmdComputeSize(self
, file)
8824 def WriteCmdSetHeader(self
, file):
8825 """Overridden from Function"""
8826 self
.type_handler
.WriteImmediateCmdSetHeader(self
, file)
8828 def WriteCmdInit(self
, file):
8829 """Overridden from Function"""
8830 self
.type_handler
.WriteImmediateCmdInit(self
, file)
8832 def WriteCmdSet(self
, file):
8833 """Overridden from Function"""
8834 self
.type_handler
.WriteImmediateCmdSet(self
, file)
8836 def WriteCmdHelper(self
, file):
8837 """Overridden from Function"""
8838 self
.type_handler
.WriteImmediateCmdHelper(self
, file)
8840 def WriteFormatTest(self
, file):
8841 """Overridden from Function"""
8842 self
.type_handler
.WriteImmediateFormatTest(self
, file)
8845 class BucketFunction(Function
):
8846 """A class that represnets a bucket version of a function command."""
8848 def __init__(self
, func
):
8851 "%sBucket" % func
.name
,
8854 def InitFunction(self
):
8855 # Override args in original_args and args_for_cmds with bucket versions
8858 new_original_args
= []
8859 for arg
in self
.original_args
:
8860 new_arg
= arg
.GetBucketVersion()
8862 new_original_args
.append(new_arg
)
8863 self
.original_args
= new_original_args
8865 new_args_for_cmds
= []
8866 for arg
in self
.args_for_cmds
:
8867 new_arg
= arg
.GetBucketVersion()
8869 new_args_for_cmds
.append(new_arg
)
8871 self
.args_for_cmds
= new_args_for_cmds
8873 Function
.InitFunction(self
)
8875 def WriteCommandDescription(self
, file):
8876 """Overridden from Function"""
8877 file.Write("//! Bucket version of command that corresponds to gl%s.\n" %
8880 def WriteServiceImplementation(self
, file):
8881 """Overridden from Function"""
8882 self
.type_handler
.WriteBucketServiceImplementation(self
, file)
8884 def WriteHandlerImplementation(self
, file):
8885 """Overridden from Function"""
8886 self
.type_handler
.WriteBucketHandlerImplementation(self
, file)
8888 def WriteServiceUnitTest(self
, file, *extras
):
8889 """Overridden from Function"""
8890 self
.type_handler
.WriteBucketServiceUnitTest(self
, file, *extras
)
8892 def MakeOriginalArgString(self
, prefix
, add_comma
= False, separator
= ", "):
8893 """Overridden from Function"""
8894 args
= self
.GetOriginalArgs()
8895 arg_string
= separator
.join(
8896 ["%s%s" % (prefix
, arg
.name
[0:-10] if arg
.name
.endswith("_bucket_id")
8897 else arg
.name
) for arg
in args
])
8898 return super(BucketFunction
, self
)._MaybePrependComma
(arg_string
, add_comma
)
8901 def CreateArg(arg_string
):
8902 """Creates an Argument."""
8903 arg_parts
= arg_string
.split()
8904 if len(arg_parts
) == 1 and arg_parts
[0] == 'void':
8906 # Is this a pointer argument?
8907 elif arg_string
.find('*') >= 0:
8908 return PointerArgument(
8910 " ".join(arg_parts
[0:-1]))
8911 # Is this a resource argument? Must come after pointer check.
8912 elif arg_parts
[0].startswith('GLidBind'):
8913 return ResourceIdBindArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
8914 elif arg_parts
[0].startswith('GLidZero'):
8915 return ResourceIdZeroArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
8916 elif arg_parts
[0].startswith('GLid'):
8917 return ResourceIdArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
8918 elif arg_parts
[0].startswith('GLenum') and len(arg_parts
[0]) > 6:
8919 return EnumArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
8920 elif arg_parts
[0].startswith('GLbitfield') and len(arg_parts
[0]) > 10:
8921 return BitFieldArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
8922 elif arg_parts
[0].startswith('GLboolean') and len(arg_parts
[0]) > 9:
8923 return ValidatedBoolArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
8924 elif arg_parts
[0].startswith('GLboolean'):
8925 return BoolArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
8926 elif arg_parts
[0].startswith('GLintUniformLocation'):
8927 return UniformLocationArgument(arg_parts
[-1])
8928 elif (arg_parts
[0].startswith('GLint') and len(arg_parts
[0]) > 5 and
8929 not arg_parts
[0].startswith('GLintptr')):
8930 return IntArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
8931 elif (arg_parts
[0].startswith('GLsizeiNotNegative') or
8932 arg_parts
[0].startswith('GLintptrNotNegative')):
8933 return SizeNotNegativeArgument(arg_parts
[-1],
8934 " ".join(arg_parts
[0:-1]),
8935 arg_parts
[0][0:-11])
8936 elif arg_parts
[0].startswith('GLsize'):
8937 return SizeArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
8939 return Argument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
8942 class GLGenerator(object):
8943 """A class to generate GL command buffers."""
8945 _function_re
= re
.compile(r
'GL_APICALL(.*?)GL_APIENTRY (.*?) \((.*?)\);')
8947 def __init__(self
, verbose
):
8948 self
.original_functions
= []
8950 self
.verbose
= verbose
8952 self
.pepper_interfaces
= []
8953 self
.interface_info
= {}
8954 self
.generated_cpp_filenames
= []
8956 for interface
in _PEPPER_INTERFACES
:
8957 interface
= PepperInterface(interface
)
8958 self
.pepper_interfaces
.append(interface
)
8959 self
.interface_info
[interface
.GetName()] = interface
8961 def AddFunction(self
, func
):
8962 """Adds a function."""
8963 self
.functions
.append(func
)
8965 def GetFunctionInfo(self
, name
):
8966 """Gets a type info for the given function name."""
8967 if name
in _FUNCTION_INFO
:
8968 func_info
= _FUNCTION_INFO
[name
].copy()
8972 if not 'type' in func_info
:
8973 func_info
['type'] = ''
8978 """Prints something if verbose is true."""
8982 def Error(self
, msg
):
8983 """Prints an error."""
8984 print "Error: %s" % msg
8987 def WriteLicense(self
, file):
8988 """Writes the license."""
8989 file.Write(_LICENSE
)
8991 def WriteNamespaceOpen(self
, file):
8992 """Writes the code for the namespace."""
8993 file.Write("namespace gpu {\n")
8994 file.Write("namespace gles2 {\n")
8997 def WriteNamespaceClose(self
, file):
8998 """Writes the code to close the namespace."""
8999 file.Write("} // namespace gles2\n")
9000 file.Write("} // namespace gpu\n")
9003 def ParseGLH(self
, filename
):
9004 """Parses the cmd_buffer_functions.txt file and extracts the functions"""
9005 f
= open(filename
, "r")
9006 functions
= f
.read()
9008 for line
in functions
.splitlines():
9009 match
= self
._function
_re
.match(line
)
9011 func_name
= match
.group(2)[2:]
9012 func_info
= self
.GetFunctionInfo(func_name
)
9013 if func_info
['type'] == 'Noop':
9016 parsed_func_info
= {
9017 'original_name': func_name
,
9018 'original_args': match
.group(3),
9019 'return_type': match
.group(1).strip(),
9022 for k
in parsed_func_info
.keys():
9023 if not k
in func_info
:
9024 func_info
[k
] = parsed_func_info
[k
]
9026 f
= Function(func_name
, func_info
)
9027 self
.original_functions
.append(f
)
9029 #for arg in f.GetOriginalArgs():
9030 # if not isinstance(arg, EnumArgument) and arg.type == 'GLenum':
9031 # self.Log("%s uses bare GLenum %s." % (func_name, arg.name))
9033 gen_cmd
= f
.GetInfo('gen_cmd')
9034 if gen_cmd
== True or gen_cmd
== None:
9035 if f
.type_handler
.NeedsDataTransferFunction(f
):
9036 methods
= f
.GetDataTransferMethods()
9037 if 'immediate' in methods
:
9038 self
.AddFunction(ImmediateFunction(f
))
9039 if 'bucket' in methods
:
9040 self
.AddFunction(BucketFunction(f
))
9041 if 'shm' in methods
:
9046 self
.Log("Auto Generated Functions : %d" %
9047 len([f
for f
in self
.functions
if f
.can_auto_generate
or
9048 (not f
.IsType('') and not f
.IsType('Custom') and
9049 not f
.IsType('Todo'))]))
9051 funcs
= [f
for f
in self
.functions
if not f
.can_auto_generate
and
9052 (f
.IsType('') or f
.IsType('Custom') or f
.IsType('Todo'))]
9053 self
.Log("Non Auto Generated Functions: %d" % len(funcs
))
9056 self
.Log(" %-10s %-20s gl%s" % (f
.info
['type'], f
.return_type
, f
.name
))
9058 def WriteCommandIds(self
, filename
):
9059 """Writes the command buffer format"""
9060 file = CHeaderWriter(filename
)
9061 file.Write("#define GLES2_COMMAND_LIST(OP) \\\n")
9063 for func
in self
.functions
:
9064 file.Write(" %-60s /* %d */ \\\n" %
9065 ("OP(%s)" % func
.name
, id))
9069 file.Write("enum CommandId {\n")
9070 file.Write(" kStartPoint = cmd::kLastCommonId, "
9071 "// All GLES2 commands start after this.\n")
9072 file.Write("#define GLES2_CMD_OP(name) k ## name,\n")
9073 file.Write(" GLES2_COMMAND_LIST(GLES2_CMD_OP)\n")
9074 file.Write("#undef GLES2_CMD_OP\n")
9075 file.Write(" kNumCommands\n")
9079 self
.generated_cpp_filenames
.append(file.filename
)
9081 def WriteFormat(self
, filename
):
9082 """Writes the command buffer format"""
9083 file = CHeaderWriter(filename
)
9084 # Forward declaration of a few enums used in constant argument
9085 # to avoid including GL header files.
9087 'GL_SYNC_GPU_COMMANDS_COMPLETE': '0x9117',
9088 'GL_SYNC_FLUSH_COMMANDS_BIT': '0x00000001',
9091 for enum
in enum_defines
:
9092 file.Write("#define %s %s\n" % (enum
, enum_defines
[enum
]))
9094 for func
in self
.functions
:
9096 #gen_cmd = func.GetInfo('gen_cmd')
9097 #if gen_cmd == True or gen_cmd == None:
9098 func
.WriteStruct(file)
9101 self
.generated_cpp_filenames
.append(file.filename
)
9103 def WriteDocs(self
, filename
):
9104 """Writes the command buffer doc version of the commands"""
9105 file = CWriter(filename
)
9106 for func
in self
.functions
:
9108 #gen_cmd = func.GetInfo('gen_cmd')
9109 #if gen_cmd == True or gen_cmd == None:
9110 func
.WriteDocs(file)
9113 self
.generated_cpp_filenames
.append(file.filename
)
9115 def WriteFormatTest(self
, filename
):
9116 """Writes the command buffer format test."""
9117 file = CHeaderWriter(
9119 "// This file contains unit tests for gles2 commmands\n"
9120 "// It is included by gles2_cmd_format_test.cc\n"
9123 for func
in self
.functions
:
9125 #gen_cmd = func.GetInfo('gen_cmd')
9126 #if gen_cmd == True or gen_cmd == None:
9127 func
.WriteFormatTest(file)
9130 self
.generated_cpp_filenames
.append(file.filename
)
9132 def WriteCmdHelperHeader(self
, filename
):
9133 """Writes the gles2 command helper."""
9134 file = CHeaderWriter(filename
)
9136 for func
in self
.functions
:
9138 #gen_cmd = func.GetInfo('gen_cmd')
9139 #if gen_cmd == True or gen_cmd == None:
9140 func
.WriteCmdHelper(file)
9143 self
.generated_cpp_filenames
.append(file.filename
)
9145 def WriteServiceContextStateHeader(self
, filename
):
9146 """Writes the service context state header."""
9147 file = CHeaderWriter(
9149 "// It is included by context_state.h\n")
9150 file.Write("struct EnableFlags {\n")
9151 file.Write(" EnableFlags();\n")
9152 for capability
in _CAPABILITY_FLAGS
:
9153 file.Write(" bool %s;\n" % capability
['name'])
9154 file.Write(" bool cached_%s;\n" % capability
['name'])
9155 file.Write("};\n\n")
9157 for state_name
in sorted(_STATES
.keys()):
9158 state
= _STATES
[state_name
]
9159 for item
in state
['states']:
9160 if isinstance(item
['default'], list):
9161 file.Write("%s %s[%d];\n" % (item
['type'], item
['name'],
9162 len(item
['default'])))
9164 file.Write("%s %s;\n" % (item
['type'], item
['name']))
9166 if item
.get('cached', False):
9167 if isinstance(item
['default'], list):
9168 file.Write("%s cached_%s[%d];\n" % (item
['type'], item
['name'],
9169 len(item
['default'])))
9171 file.Write("%s cached_%s;\n" % (item
['type'], item
['name']))
9176 inline void SetDeviceCapabilityState(GLenum cap, bool enable) {
9179 for capability
in _CAPABILITY_FLAGS
:
9182 """ % capability
['name'].upper())
9184 if (enable_flags.cached_%(name)s == enable &&
9185 !ignore_cached_state)
9187 enable_flags.cached_%(name)s = enable;
9204 self
.generated_cpp_filenames
.append(file.filename
)
9206 def WriteClientContextStateHeader(self
, filename
):
9207 """Writes the client context state header."""
9208 file = CHeaderWriter(
9210 "// It is included by client_context_state.h\n")
9211 file.Write("struct EnableFlags {\n")
9212 file.Write(" EnableFlags();\n")
9213 for capability
in _CAPABILITY_FLAGS
:
9214 file.Write(" bool %s;\n" % capability
['name'])
9215 file.Write("};\n\n")
9218 self
.generated_cpp_filenames
.append(file.filename
)
9220 def WriteContextStateGetters(self
, file, class_name
):
9221 """Writes the state getters."""
9222 for gl_type
in ["GLint", "GLfloat"]:
9224 bool %s::GetStateAs%s(
9225 GLenum pname, %s* params, GLsizei* num_written) const {
9227 """ % (class_name
, gl_type
, gl_type
))
9228 for state_name
in sorted(_STATES
.keys()):
9229 state
= _STATES
[state_name
]
9231 file.Write(" case %s:\n" % state
['enum'])
9232 file.Write(" *num_written = %d;\n" % len(state
['states']))
9233 file.Write(" if (params) {\n")
9234 for ndx
,item
in enumerate(state
['states']):
9235 file.Write(" params[%d] = static_cast<%s>(%s);\n" %
9236 (ndx
, gl_type
, item
['name']))
9238 file.Write(" return true;\n")
9240 for item
in state
['states']:
9241 file.Write(" case %s:\n" % item
['enum'])
9242 if isinstance(item
['default'], list):
9243 item_len
= len(item
['default'])
9244 file.Write(" *num_written = %d;\n" % item_len
)
9245 file.Write(" if (params) {\n")
9246 if item
['type'] == gl_type
:
9247 file.Write(" memcpy(params, %s, sizeof(%s) * %d);\n" %
9248 (item
['name'], item
['type'], item_len
))
9250 file.Write(" for (size_t i = 0; i < %s; ++i) {\n" %
9252 file.Write(" params[i] = %s;\n" %
9253 (GetGLGetTypeConversion(gl_type
, item
['type'],
9254 "%s[i]" % item
['name'])))
9257 file.Write(" *num_written = 1;\n")
9258 file.Write(" if (params) {\n")
9259 file.Write(" params[0] = %s;\n" %
9260 (GetGLGetTypeConversion(gl_type
, item
['type'],
9263 file.Write(" return true;\n")
9264 for capability
in _CAPABILITY_FLAGS
:
9265 file.Write(" case GL_%s:\n" % capability
['name'].upper())
9266 file.Write(" *num_written = 1;\n")
9267 file.Write(" if (params) {\n")
9269 " params[0] = static_cast<%s>(enable_flags.%s);\n" %
9270 (gl_type
, capability
['name']))
9272 file.Write(" return true;\n")
9273 file.Write(""" default:
9279 def WriteServiceContextStateImpl(self
, filename
):
9280 """Writes the context state service implementation."""
9281 file = CHeaderWriter(
9283 "// It is included by context_state.cc\n")
9285 for capability
in _CAPABILITY_FLAGS
:
9286 code
.append("%s(%s)" %
9287 (capability
['name'],
9288 ('false', 'true')['default' in capability
]))
9289 code
.append("cached_%s(%s)" %
9290 (capability
['name'],
9291 ('false', 'true')['default' in capability
]))
9292 file.Write("ContextState::EnableFlags::EnableFlags()\n : %s {\n}\n" %
9296 file.Write("void ContextState::Initialize() {\n")
9297 for state_name
in sorted(_STATES
.keys()):
9298 state
= _STATES
[state_name
]
9299 for item
in state
['states']:
9300 if isinstance(item
['default'], list):
9301 for ndx
, value
in enumerate(item
['default']):
9302 file.Write(" %s[%d] = %s;\n" % (item
['name'], ndx
, value
))
9304 file.Write(" %s = %s;\n" % (item
['name'], item
['default']))
9305 if item
.get('cached', False):
9306 if isinstance(item
['default'], list):
9307 for ndx
, value
in enumerate(item
['default']):
9308 file.Write(" cached_%s[%d] = %s;\n" % (item
['name'], ndx
, value
))
9310 file.Write(" cached_%s = %s;\n" % (item
['name'], item
['default']))
9314 void ContextState::InitCapabilities(const ContextState* prev_state) const {
9316 def WriteCapabilities(test_prev
):
9317 for capability
in _CAPABILITY_FLAGS
:
9318 capability_name
= capability
['name']
9320 file.Write(""" if (prev_state->enable_flags.cached_%s !=
9321 enable_flags.cached_%s)\n""" %
9322 (capability_name
, capability_name
))
9323 file.Write(" EnableDisable(GL_%s, enable_flags.cached_%s);\n" %
9324 (capability_name
.upper(), capability_name
))
9326 file.Write(" if (prev_state) {")
9327 WriteCapabilities(True)
9328 file.Write(" } else {")
9329 WriteCapabilities(False)
9334 void ContextState::InitState(const ContextState *prev_state) const {
9337 def WriteStates(test_prev
):
9338 # We need to sort the keys so the expectations match
9339 for state_name
in sorted(_STATES
.keys()):
9340 state
= _STATES
[state_name
]
9341 if state
['type'] == 'FrontBack':
9342 num_states
= len(state
['states'])
9343 for ndx
, group
in enumerate(Grouper(num_states
/ 2, state
['states'])):
9347 for place
, item
in enumerate(group
):
9348 item_name
= CachedStateName(item
)
9349 args
.append('%s' % item_name
)
9353 file.Write("(%s != prev_state->%s)" % (item_name
, item_name
))
9357 " gl%s(%s, %s);\n" %
9358 (state
['func'], ('GL_FRONT', 'GL_BACK')[ndx
], ", ".join(args
)))
9359 elif state
['type'] == 'NamedParameter':
9360 for item
in state
['states']:
9361 item_name
= CachedStateName(item
)
9363 if 'extension_flag' in item
:
9364 file.Write(" if (feature_info_->feature_flags().%s) {\n " %
9365 item
['extension_flag'])
9367 if isinstance(item
['default'], list):
9368 file.Write(" if (memcmp(prev_state->%s, %s, "
9369 "sizeof(%s) * %d)) {\n" %
9370 (item_name
, item_name
, item
['type'],
9371 len(item
['default'])))
9373 file.Write(" if (prev_state->%s != %s) {\n " %
9374 (item_name
, item_name
))
9375 file.Write(" gl%s(%s, %s);\n" %
9378 if 'enum_set' in item
else item
['enum']),
9381 if 'extension_flag' in item
:
9384 if 'extension_flag' in item
:
9387 if 'extension_flag' in state
:
9388 file.Write(" if (feature_info_->feature_flags().%s)\n " %
9389 state
['extension_flag'])
9393 for place
, item
in enumerate(state
['states']):
9394 item_name
= CachedStateName(item
)
9395 args
.append('%s' % item_name
)
9399 file.Write("(%s != prev_state->%s)" %
9400 (item_name
, item_name
))
9403 file.Write(" gl%s(%s);\n" % (state
['func'], ", ".join(args
)))
9405 file.Write(" if (prev_state) {")
9407 file.Write(" } else {")
9412 file.Write("""bool ContextState::GetEnabled(GLenum cap) const {
9415 for capability
in _CAPABILITY_FLAGS
:
9416 file.Write(" case GL_%s:\n" % capability
['name'].upper())
9417 file.Write(" return enable_flags.%s;\n" % capability
['name'])
9418 file.Write(""" default:
9425 self
.WriteContextStateGetters(file, "ContextState")
9427 self
.generated_cpp_filenames
.append(file.filename
)
9429 def WriteClientContextStateImpl(self
, filename
):
9430 """Writes the context state client side implementation."""
9431 file = CHeaderWriter(
9433 "// It is included by client_context_state.cc\n")
9435 for capability
in _CAPABILITY_FLAGS
:
9436 code
.append("%s(%s)" %
9437 (capability
['name'],
9438 ('false', 'true')['default' in capability
]))
9440 "ClientContextState::EnableFlags::EnableFlags()\n : %s {\n}\n" %
9445 bool ClientContextState::SetCapabilityState(
9446 GLenum cap, bool enabled, bool* changed) {
9450 for capability
in _CAPABILITY_FLAGS
:
9451 file.Write(" case GL_%s:\n" % capability
['name'].upper())
9452 file.Write(""" if (enable_flags.%(name)s != enabled) {
9454 enable_flags.%(name)s = enabled;
9458 file.Write(""" default:
9463 file.Write("""bool ClientContextState::GetEnabled(
9464 GLenum cap, bool* enabled) const {
9467 for capability
in _CAPABILITY_FLAGS
:
9468 file.Write(" case GL_%s:\n" % capability
['name'].upper())
9469 file.Write(" *enabled = enable_flags.%s;\n" % capability
['name'])
9470 file.Write(" return true;\n")
9471 file.Write(""" default:
9477 self
.generated_cpp_filenames
.append(file.filename
)
9479 def WriteServiceImplementation(self
, filename
):
9480 """Writes the service decorder implementation."""
9481 file = CHeaderWriter(
9483 "// It is included by gles2_cmd_decoder.cc\n")
9485 for func
in self
.functions
:
9487 #gen_cmd = func.GetInfo('gen_cmd')
9488 #if gen_cmd == True or gen_cmd == None:
9489 func
.WriteServiceImplementation(file)
9492 bool GLES2DecoderImpl::SetCapabilityState(GLenum cap, bool enabled) {
9495 for capability
in _CAPABILITY_FLAGS
:
9496 file.Write(" case GL_%s:\n" % capability
['name'].upper())
9497 if 'state_flag' in capability
:
9500 state_.enable_flags.%(name)s = enabled;
9501 if (state_.enable_flags.cached_%(name)s != enabled
9502 || state_.ignore_cached_state) {
9503 %(state_flag)s = true;
9509 state_.enable_flags.%(name)s = enabled;
9510 if (state_.enable_flags.cached_%(name)s != enabled
9511 || state_.ignore_cached_state) {
9512 state_.enable_flags.cached_%(name)s = enabled;
9517 file.Write(""" default:
9524 self
.generated_cpp_filenames
.append(file.filename
)
9526 def WriteServiceUnitTests(self
, filename
):
9527 """Writes the service decorder unit tests."""
9528 num_tests
= len(self
.functions
)
9529 FUNCTIONS_PER_FILE
= 98 # hard code this so it doesn't change.
9531 for test_num
in range(0, num_tests
, FUNCTIONS_PER_FILE
):
9533 name
= filename
% count
9534 file = CHeaderWriter(
9536 "// It is included by gles2_cmd_decoder_unittest_%d.cc\n" % count
)
9537 test_name
= 'GLES2DecoderTest%d' % count
9538 end
= test_num
+ FUNCTIONS_PER_FILE
9541 for idx
in range(test_num
, end
):
9542 func
= self
.functions
[idx
]
9544 # Do any filtering of the functions here, so that the functions
9545 # will not move between the numbered files if filtering properties
9547 if func
.GetInfo('extension_flag'):
9551 #gen_cmd = func.GetInfo('gen_cmd')
9552 #if gen_cmd == True or gen_cmd == None:
9553 if func
.GetInfo('unit_test') == False:
9554 file.Write("// TODO(gman): %s\n" % func
.name
)
9556 func
.WriteServiceUnitTest(file, {
9557 'test_name': test_name
9560 self
.generated_cpp_filenames
.append(file.filename
)
9561 file = CHeaderWriter(
9563 "// It is included by gles2_cmd_decoder_unittest_base.cc\n")
9565 """void GLES2DecoderTestBase::SetupInitCapabilitiesExpectations() {
9567 for capability
in _CAPABILITY_FLAGS
:
9568 file.Write(" ExpectEnableDisable(GL_%s, %s);\n" %
9569 (capability
['name'].upper(),
9570 ('false', 'true')['default' in capability
]))
9573 void GLES2DecoderTestBase::SetupInitStateExpectations() {
9576 # We need to sort the keys so the expectations match
9577 for state_name
in sorted(_STATES
.keys()):
9578 state
= _STATES
[state_name
]
9579 if state
['type'] == 'FrontBack':
9580 num_states
= len(state
['states'])
9581 for ndx
, group
in enumerate(Grouper(num_states
/ 2, state
['states'])):
9584 if 'expected' in item
:
9585 args
.append(item
['expected'])
9587 args
.append(item
['default'])
9589 " EXPECT_CALL(*gl_, %s(%s, %s))\n" %
9590 (state
['func'], ('GL_FRONT', 'GL_BACK')[ndx
], ", ".join(args
)))
9591 file.Write(" .Times(1)\n")
9592 file.Write(" .RetiresOnSaturation();\n")
9593 elif state
['type'] == 'NamedParameter':
9594 for item
in state
['states']:
9595 if 'extension_flag' in item
:
9596 file.Write(" if (group_->feature_info()->feature_flags().%s) {\n" %
9597 item
['extension_flag'])
9599 expect_value
= item
['default']
9600 if isinstance(expect_value
, list):
9601 # TODO: Currently we do not check array values.
9605 " EXPECT_CALL(*gl_, %s(%s, %s))\n" %
9608 if 'enum_set' in item
else item
['enum']),
9610 file.Write(" .Times(1)\n")
9611 file.Write(" .RetiresOnSaturation();\n")
9612 if 'extension_flag' in item
:
9615 if 'extension_flag' in state
:
9616 file.Write(" if (group_->feature_info()->feature_flags().%s) {\n" %
9617 state
['extension_flag'])
9620 for item
in state
['states']:
9621 if 'expected' in item
:
9622 args
.append(item
['expected'])
9624 args
.append(item
['default'])
9625 # TODO: Currently we do not check array values.
9626 args
= ["_" if isinstance(arg
, list) else arg
for arg
in args
]
9627 file.Write(" EXPECT_CALL(*gl_, %s(%s))\n" %
9628 (state
['func'], ", ".join(args
)))
9629 file.Write(" .Times(1)\n")
9630 file.Write(" .RetiresOnSaturation();\n")
9631 if 'extension_flag' in state
:
9636 self
.generated_cpp_filenames
.append(file.filename
)
9638 def WriteServiceUnitTestsForExtensions(self
, filename
):
9639 """Writes the service decorder unit tests for functions with extension_flag.
9641 The functions are special in that they need a specific unit test
9642 baseclass to turn on the extension.
9644 functions
= [f
for f
in self
.functions
if f
.GetInfo('extension_flag')]
9645 file = CHeaderWriter(
9647 "// It is included by gles2_cmd_decoder_unittest_extensions.cc\n")
9648 for func
in functions
:
9650 if func
.GetInfo('unit_test') == False:
9651 file.Write("// TODO(gman): %s\n" % func
.name
)
9653 extension
= ToCamelCase(
9654 ToGLExtensionString(func
.GetInfo('extension_flag')))
9655 func
.WriteServiceUnitTest(file, {
9656 'test_name': 'GLES2DecoderTestWith%s' % extension
9660 self
.generated_cpp_filenames
.append(file.filename
)
9662 def WriteGLES2Header(self
, filename
):
9663 """Writes the GLES2 header."""
9664 file = CHeaderWriter(
9666 "// This file contains Chromium-specific GLES2 declarations.\n\n")
9668 for func
in self
.original_functions
:
9669 func
.WriteGLES2Header(file)
9673 self
.generated_cpp_filenames
.append(file.filename
)
9675 def WriteGLES2CLibImplementation(self
, filename
):
9676 """Writes the GLES2 c lib implementation."""
9677 file = CHeaderWriter(
9679 "// These functions emulate GLES2 over command buffers.\n")
9681 for func
in self
.original_functions
:
9682 func
.WriteGLES2CLibImplementation(file)
9687 extern const NameToFunc g_gles2_function_table[] = {
9689 for func
in self
.original_functions
:
9691 ' { "gl%s", reinterpret_cast<GLES2FunctionPointer>(gl%s), },\n' %
9692 (func
.name
, func
.name
))
9693 file.Write(""" { NULL, NULL, },
9696 } // namespace gles2
9699 self
.generated_cpp_filenames
.append(file.filename
)
9701 def WriteGLES2InterfaceHeader(self
, filename
):
9702 """Writes the GLES2 interface header."""
9703 file = CHeaderWriter(
9705 "// This file is included by gles2_interface.h to declare the\n"
9706 "// GL api functions.\n")
9707 for func
in self
.original_functions
:
9708 func
.WriteGLES2InterfaceHeader(file)
9710 self
.generated_cpp_filenames
.append(file.filename
)
9712 def WriteGLES2InterfaceStub(self
, filename
):
9713 """Writes the GLES2 interface stub header."""
9714 file = CHeaderWriter(
9716 "// This file is included by gles2_interface_stub.h.\n")
9717 for func
in self
.original_functions
:
9718 func
.WriteGLES2InterfaceStub(file)
9720 self
.generated_cpp_filenames
.append(file.filename
)
9722 def WriteGLES2InterfaceStubImpl(self
, filename
):
9723 """Writes the GLES2 interface header."""
9724 file = CHeaderWriter(
9726 "// This file is included by gles2_interface_stub.cc.\n")
9727 for func
in self
.original_functions
:
9728 func
.WriteGLES2InterfaceStubImpl(file)
9730 self
.generated_cpp_filenames
.append(file.filename
)
9732 def WriteGLES2ImplementationHeader(self
, filename
):
9733 """Writes the GLES2 Implementation header."""
9734 file = CHeaderWriter(
9736 "// This file is included by gles2_implementation.h to declare the\n"
9737 "// GL api functions.\n")
9738 for func
in self
.original_functions
:
9739 func
.WriteGLES2ImplementationHeader(file)
9741 self
.generated_cpp_filenames
.append(file.filename
)
9743 def WriteGLES2Implementation(self
, filename
):
9744 """Writes the GLES2 Implementation."""
9745 file = CHeaderWriter(
9747 "// This file is included by gles2_implementation.cc to define the\n"
9748 "// GL api functions.\n")
9749 for func
in self
.original_functions
:
9750 func
.WriteGLES2Implementation(file)
9752 self
.generated_cpp_filenames
.append(file.filename
)
9754 def WriteGLES2TraceImplementationHeader(self
, filename
):
9755 """Writes the GLES2 Trace Implementation header."""
9756 file = CHeaderWriter(
9758 "// This file is included by gles2_trace_implementation.h\n")
9759 for func
in self
.original_functions
:
9760 func
.WriteGLES2TraceImplementationHeader(file)
9762 self
.generated_cpp_filenames
.append(file.filename
)
9764 def WriteGLES2TraceImplementation(self
, filename
):
9765 """Writes the GLES2 Trace Implementation."""
9766 file = CHeaderWriter(
9768 "// This file is included by gles2_trace_implementation.cc\n")
9769 for func
in self
.original_functions
:
9770 func
.WriteGLES2TraceImplementation(file)
9772 self
.generated_cpp_filenames
.append(file.filename
)
9774 def WriteGLES2ImplementationUnitTests(self
, filename
):
9775 """Writes the GLES2 helper header."""
9776 file = CHeaderWriter(
9778 "// This file is included by gles2_implementation.h to declare the\n"
9779 "// GL api functions.\n")
9780 for func
in self
.original_functions
:
9781 func
.WriteGLES2ImplementationUnitTest(file)
9783 self
.generated_cpp_filenames
.append(file.filename
)
9785 def WriteServiceUtilsHeader(self
, filename
):
9786 """Writes the gles2 auto generated utility header."""
9787 file = CHeaderWriter(filename
)
9788 for name
in sorted(_NAMED_TYPE_INFO
.keys()):
9789 named_type
= NamedType(_NAMED_TYPE_INFO
[name
])
9790 if named_type
.IsConstant():
9792 file.Write("ValueValidator<%s> %s;\n" %
9793 (named_type
.GetType(), ToUnderscore(name
)))
9796 self
.generated_cpp_filenames
.append(file.filename
)
9798 def WriteServiceUtilsImplementation(self
, filename
):
9799 """Writes the gles2 auto generated utility implementation."""
9800 file = CHeaderWriter(filename
)
9801 names
= sorted(_NAMED_TYPE_INFO
.keys())
9803 named_type
= NamedType(_NAMED_TYPE_INFO
[name
])
9804 if named_type
.IsConstant():
9806 if named_type
.GetValidValues():
9807 file.Write("static const %s valid_%s_table[] = {\n" %
9808 (named_type
.GetType(), ToUnderscore(name
)))
9809 for value
in named_type
.GetValidValues():
9810 file.Write(" %s,\n" % value
)
9813 file.Write("Validators::Validators()")
9815 for count
, name
in enumerate(names
):
9816 named_type
= NamedType(_NAMED_TYPE_INFO
[name
])
9817 if named_type
.IsConstant():
9819 if named_type
.GetValidValues():
9820 code
= """%(pre)s%(name)s(
9821 valid_%(name)s_table, arraysize(valid_%(name)s_table))"""
9823 code
= "%(pre)s%(name)s()"
9825 'name': ToUnderscore(name
),
9830 file.Write("}\n\n");
9832 self
.generated_cpp_filenames
.append(file.filename
)
9834 def WriteCommonUtilsHeader(self
, filename
):
9835 """Writes the gles2 common utility header."""
9836 file = CHeaderWriter(filename
)
9837 type_infos
= sorted(_NAMED_TYPE_INFO
.keys())
9838 for type_info
in type_infos
:
9839 if _NAMED_TYPE_INFO
[type_info
]['type'] == 'GLenum':
9840 file.Write("static std::string GetString%s(uint32_t value);\n" %
9844 self
.generated_cpp_filenames
.append(file.filename
)
9846 def WriteCommonUtilsImpl(self
, filename
):
9847 """Writes the gles2 common utility header."""
9848 enum_re
= re
.compile(r
'\#define\s+(GL_[a-zA-Z0-9_]+)\s+([0-9A-Fa-fx]+)')
9850 for fname
in ['third_party/khronos/GLES2/gl2.h',
9851 'third_party/khronos/GLES2/gl2ext.h',
9852 'third_party/khronos/GLES3/gl3.h',
9853 'gpu/GLES2/gl2chromium.h',
9854 'gpu/GLES2/gl2extchromium.h']:
9855 lines
= open(fname
).readlines()
9857 m
= enum_re
.match(line
)
9861 if len(value
) <= 10:
9862 if not value
in dict:
9864 # check our own _CHROMIUM macro conflicts with khronos GL headers.
9865 elif dict[value
] != name
and (name
.endswith('_CHROMIUM') or
9866 dict[value
].endswith('_CHROMIUM')):
9867 self
.Error("code collision: %s and %s have the same code %s" %
9868 (dict[value
], name
, value
))
9870 file = CHeaderWriter(filename
)
9871 file.Write("static const GLES2Util::EnumToString "
9872 "enum_to_string_table[] = {\n")
9874 file.Write(' { %s, "%s", },\n' % (value
, dict[value
]))
9877 const GLES2Util::EnumToString* const GLES2Util::enum_to_string_table_ =
9878 enum_to_string_table;
9879 const size_t GLES2Util::enum_to_string_table_len_ =
9880 sizeof(enum_to_string_table) / sizeof(enum_to_string_table[0]);
9884 enums
= sorted(_NAMED_TYPE_INFO
.keys())
9886 if _NAMED_TYPE_INFO
[enum
]['type'] == 'GLenum':
9887 file.Write("std::string GLES2Util::GetString%s(uint32_t value) {\n" %
9889 if len(_NAMED_TYPE_INFO
[enum
]['valid']) > 0:
9890 file.Write(" static const EnumToString string_table[] = {\n")
9891 for value
in _NAMED_TYPE_INFO
[enum
]['valid']:
9892 file.Write(' { %s, "%s" },\n' % (value
, value
))
9894 return GLES2Util::GetQualifiedEnumString(
9895 string_table, arraysize(string_table), value);
9900 file.Write(""" return GLES2Util::GetQualifiedEnumString(
9906 self
.generated_cpp_filenames
.append(file.filename
)
9908 def WritePepperGLES2Interface(self
, filename
, dev
):
9909 """Writes the Pepper OpenGLES interface definition."""
9910 file = CWriter(filename
)
9911 file.Write(_LICENSE
)
9912 file.Write(_DO_NOT_EDIT_WARNING
)
9914 file.Write("label Chrome {\n")
9915 file.Write(" M39 = 1.0\n")
9916 file.Write("};\n\n")
9920 file.Write("[version=1.0]\n")
9921 file.Write("describe {\n")
9922 for gltype
in ['GLbitfield', 'GLboolean', 'GLbyte', 'GLclampf',
9923 'GLclampx', 'GLenum', 'GLfixed', 'GLfloat', 'GLint',
9924 'GLintptr', 'GLshort', 'GLsizei', 'GLsizeiptr',
9925 'GLubyte', 'GLuint', 'GLushort']:
9926 file.Write(" %s;\n" % gltype
)
9927 file.Write(" %s_ptr_t;\n" % gltype
)
9928 file.Write("};\n\n")
9931 file.Write("#inline c\n")
9932 file.Write("#include \"ppapi/c/pp_resource.h\"\n")
9934 file.Write("#include \"ppapi/c/ppb_opengles2.h\"\n\n")
9936 file.Write("\n#ifndef __gl2_h_\n")
9937 for (k
, v
) in _GL_TYPES
.iteritems():
9938 file.Write("typedef %s %s;\n" % (v
, k
))
9939 file.Write("#ifdef _WIN64\n")
9940 for (k
, v
) in _GL_TYPES_64
.iteritems():
9941 file.Write("typedef %s %s;\n" % (v
, k
))
9942 file.Write("#else\n")
9943 for (k
, v
) in _GL_TYPES_32
.iteritems():
9944 file.Write("typedef %s %s;\n" % (v
, k
))
9945 file.Write("#endif // _WIN64\n")
9946 file.Write("#endif // __gl2_h_\n\n")
9947 file.Write("#endinl\n")
9949 for interface
in self
.pepper_interfaces
:
9950 if interface
.dev
!= dev
:
9952 # Historically, we provide OpenGLES2 interfaces with struct
9953 # namespace. Not to break code which uses the interface as
9954 # "struct OpenGLES2", we put it in struct namespace.
9955 file.Write('\n[macro="%s", force_struct_namespace]\n' %
9956 interface
.GetInterfaceName())
9957 file.Write("interface %s {\n" % interface
.GetStructName())
9958 for func
in self
.original_functions
:
9959 if not func
.InPepperInterface(interface
):
9962 ret_type
= func
.MapCTypeToPepperIdlType(func
.return_type
,
9963 is_for_return_type
=True)
9964 func_prefix
= " %s %s(" % (ret_type
, func
.GetPepperName())
9965 file.Write(func_prefix
)
9966 file.Write("[in] PP_Resource context")
9967 for arg
in func
.MakeTypedPepperIdlArgStrings():
9968 file.Write(",\n" + " " * len(func_prefix
) + arg
)
9970 file.Write("};\n\n")
9975 def WritePepperGLES2Implementation(self
, filename
):
9976 """Writes the Pepper OpenGLES interface implementation."""
9978 file = CWriter(filename
)
9979 file.Write(_LICENSE
)
9980 file.Write(_DO_NOT_EDIT_WARNING
)
9982 file.Write("#include \"ppapi/shared_impl/ppb_opengles2_shared.h\"\n\n")
9983 file.Write("#include \"base/logging.h\"\n")
9984 file.Write("#include \"gpu/command_buffer/client/gles2_implementation.h\"\n")
9985 file.Write("#include \"ppapi/shared_impl/ppb_graphics_3d_shared.h\"\n")
9986 file.Write("#include \"ppapi/thunk/enter.h\"\n\n")
9988 file.Write("namespace ppapi {\n\n")
9989 file.Write("namespace {\n\n")
9991 file.Write("typedef thunk::EnterResource<thunk::PPB_Graphics3D_API>"
9994 file.Write("gpu::gles2::GLES2Implementation* ToGles2Impl(Enter3D*"
9996 file.Write(" DCHECK(enter);\n")
9997 file.Write(" DCHECK(enter->succeeded());\n")
9998 file.Write(" return static_cast<PPB_Graphics3D_Shared*>(enter->object())->"
10000 file.Write("}\n\n");
10002 for func
in self
.original_functions
:
10003 if not func
.InAnyPepperExtension():
10006 original_arg
= func
.MakeTypedPepperArgString("")
10007 context_arg
= "PP_Resource context_id"
10008 if len(original_arg
):
10009 arg
= context_arg
+ ", " + original_arg
10012 file.Write("%s %s(%s) {\n" %
10013 (func
.return_type
, func
.GetPepperName(), arg
))
10014 file.Write(" Enter3D enter(context_id, true);\n")
10015 file.Write(" if (enter.succeeded()) {\n")
10017 return_str
= "" if func
.return_type
== "void" else "return "
10018 file.Write(" %sToGles2Impl(&enter)->%s(%s);\n" %
10019 (return_str
, func
.original_name
,
10020 func
.MakeOriginalArgString("")))
10022 if func
.return_type
== "void":
10025 file.Write(" else {\n")
10026 file.Write(" return %s;\n" % func
.GetErrorReturnString())
10028 file.Write("}\n\n")
10030 file.Write("} // namespace\n")
10032 for interface
in self
.pepper_interfaces
:
10033 file.Write("const %s* PPB_OpenGLES2_Shared::Get%sInterface() {\n" %
10034 (interface
.GetStructName(), interface
.GetName()))
10035 file.Write(" static const struct %s "
10036 "ppb_opengles2 = {\n" % interface
.GetStructName())
10038 file.Write(",\n &".join(
10039 f
.GetPepperName() for f
in self
.original_functions
10040 if f
.InPepperInterface(interface
)))
10043 file.Write(" };\n")
10044 file.Write(" return &ppb_opengles2;\n")
10047 file.Write("} // namespace ppapi\n")
10049 self
.generated_cpp_filenames
.append(file.filename
)
10051 def WriteGLES2ToPPAPIBridge(self
, filename
):
10052 """Connects GLES2 helper library to PPB_OpenGLES2 interface"""
10054 file = CWriter(filename
)
10055 file.Write(_LICENSE
)
10056 file.Write(_DO_NOT_EDIT_WARNING
)
10058 file.Write("#ifndef GL_GLEXT_PROTOTYPES\n")
10059 file.Write("#define GL_GLEXT_PROTOTYPES\n")
10060 file.Write("#endif\n")
10061 file.Write("#include <GLES2/gl2.h>\n")
10062 file.Write("#include <GLES2/gl2ext.h>\n")
10063 file.Write("#include \"ppapi/lib/gl/gles2/gl2ext_ppapi.h\"\n\n")
10065 for func
in self
.original_functions
:
10066 if not func
.InAnyPepperExtension():
10069 interface
= self
.interface_info
[func
.GetInfo('pepper_interface') or '']
10071 file.Write("%s GL_APIENTRY gl%s(%s) {\n" %
10072 (func
.return_type
, func
.GetPepperName(),
10073 func
.MakeTypedPepperArgString("")))
10074 return_str
= "" if func
.return_type
== "void" else "return "
10075 interface_str
= "glGet%sInterfacePPAPI()" % interface
.GetName()
10076 original_arg
= func
.MakeOriginalArgString("")
10077 context_arg
= "glGetCurrentContextPPAPI()"
10078 if len(original_arg
):
10079 arg
= context_arg
+ ", " + original_arg
10082 if interface
.GetName():
10083 file.Write(" const struct %s* ext = %s;\n" %
10084 (interface
.GetStructName(), interface_str
))
10085 file.Write(" if (ext)\n")
10086 file.Write(" %sext->%s(%s);\n" %
10087 (return_str
, func
.GetPepperName(), arg
))
10089 file.Write(" %s0;\n" % return_str
)
10091 file.Write(" %s%s->%s(%s);\n" %
10092 (return_str
, interface_str
, func
.GetPepperName(), arg
))
10093 file.Write("}\n\n")
10095 self
.generated_cpp_filenames
.append(file.filename
)
10097 def WriteMojoGLCallVisitor(self
, filename
):
10098 """Provides the GL implementation for mojo"""
10099 file = CWriter(filename
)
10100 file.Write(_LICENSE
)
10101 file.Write(_DO_NOT_EDIT_WARNING
)
10103 for func
in self
.original_functions
:
10104 if not func
.IsCoreGLFunction():
10106 file.Write("VISIT_GL_CALL(%s, %s, (%s), (%s))\n" %
10107 (func
.name
, func
.return_type
,
10108 func
.MakeTypedOriginalArgString(""),
10109 func
.MakeOriginalArgString("")))
10112 self
.generated_cpp_filenames
.append(file.filename
)
10114 def WriteMojoGLCallVisitorForExtension(self
, filename
, extension
):
10115 """Provides the GL implementation for mojo for a particular extension"""
10116 file = CWriter(filename
)
10117 file.Write(_LICENSE
)
10118 file.Write(_DO_NOT_EDIT_WARNING
)
10120 for func
in self
.original_functions
:
10121 if func
.GetInfo("extension") != extension
:
10123 file.Write("VISIT_GL_CALL(%s, %s, (%s), (%s))\n" %
10124 (func
.name
, func
.return_type
,
10125 func
.MakeTypedOriginalArgString(""),
10126 func
.MakeOriginalArgString("")))
10129 self
.generated_cpp_filenames
.append(file.filename
)
10131 def Format(generated_files
):
10132 formatter
= "clang-format"
10133 if platform
.system() == "Windows":
10134 formatter
+= ".bat"
10135 for filename
in generated_files
:
10136 call([formatter
, "-i", "-style=chromium", filename
])
10139 """This is the main function."""
10140 parser
= OptionParser()
10143 help="base directory for resulting files, under chrome/src. default is "
10144 "empty. Use this if you want the result stored under gen.")
10146 "-v", "--verbose", action
="store_true",
10147 help="prints more output.")
10149 (options
, args
) = parser
.parse_args(args
=argv
)
10151 # Add in states and capabilites to GLState
10152 gl_state_valid
= _NAMED_TYPE_INFO
['GLState']['valid']
10153 for state_name
in sorted(_STATES
.keys()):
10154 state
= _STATES
[state_name
]
10155 if 'extension_flag' in state
:
10157 if 'enum' in state
:
10158 if not state
['enum'] in gl_state_valid
:
10159 gl_state_valid
.append(state
['enum'])
10161 for item
in state
['states']:
10162 if 'extension_flag' in item
:
10164 if not item
['enum'] in gl_state_valid
:
10165 gl_state_valid
.append(item
['enum'])
10166 for capability
in _CAPABILITY_FLAGS
:
10167 valid_value
= "GL_%s" % capability
['name'].upper()
10168 if not valid_value
in gl_state_valid
:
10169 gl_state_valid
.append(valid_value
)
10171 # This script lives under gpu/command_buffer, cd to base directory.
10172 os
.chdir(os
.path
.dirname(__file__
) + "/../..")
10173 base_dir
= os
.getcwd()
10174 gen
= GLGenerator(options
.verbose
)
10175 gen
.ParseGLH("gpu/command_buffer/cmd_buffer_functions.txt")
10177 # Support generating files under gen/
10178 if options
.output_dir
!= None:
10179 os
.chdir(options
.output_dir
)
10181 gen
.WritePepperGLES2Interface("ppapi/api/ppb_opengles2.idl", False)
10182 gen
.WritePepperGLES2Interface("ppapi/api/dev/ppb_opengles2ext_dev.idl", True)
10183 gen
.WriteGLES2ToPPAPIBridge("ppapi/lib/gl/gles2/gles2.c")
10184 gen
.WritePepperGLES2Implementation(
10185 "ppapi/shared_impl/ppb_opengles2_shared.cc")
10187 gen
.WriteCommandIds("gpu/command_buffer/common/gles2_cmd_ids_autogen.h")
10188 gen
.WriteFormat("gpu/command_buffer/common/gles2_cmd_format_autogen.h")
10189 gen
.WriteFormatTest(
10190 "gpu/command_buffer/common/gles2_cmd_format_test_autogen.h")
10191 gen
.WriteGLES2InterfaceHeader(
10192 "gpu/command_buffer/client/gles2_interface_autogen.h")
10193 gen
.WriteGLES2InterfaceStub(
10194 "gpu/command_buffer/client/gles2_interface_stub_autogen.h")
10195 gen
.WriteGLES2InterfaceStubImpl(
10196 "gpu/command_buffer/client/gles2_interface_stub_impl_autogen.h")
10197 gen
.WriteGLES2ImplementationHeader(
10198 "gpu/command_buffer/client/gles2_implementation_autogen.h")
10199 gen
.WriteGLES2Implementation(
10200 "gpu/command_buffer/client/gles2_implementation_impl_autogen.h")
10201 gen
.WriteGLES2ImplementationUnitTests(
10202 "gpu/command_buffer/client/gles2_implementation_unittest_autogen.h")
10203 gen
.WriteGLES2TraceImplementationHeader(
10204 "gpu/command_buffer/client/gles2_trace_implementation_autogen.h")
10205 gen
.WriteGLES2TraceImplementation(
10206 "gpu/command_buffer/client/gles2_trace_implementation_impl_autogen.h")
10207 gen
.WriteGLES2CLibImplementation(
10208 "gpu/command_buffer/client/gles2_c_lib_autogen.h")
10209 gen
.WriteCmdHelperHeader(
10210 "gpu/command_buffer/client/gles2_cmd_helper_autogen.h")
10211 gen
.WriteServiceImplementation(
10212 "gpu/command_buffer/service/gles2_cmd_decoder_autogen.h")
10213 gen
.WriteServiceContextStateHeader(
10214 "gpu/command_buffer/service/context_state_autogen.h")
10215 gen
.WriteServiceContextStateImpl(
10216 "gpu/command_buffer/service/context_state_impl_autogen.h")
10217 gen
.WriteClientContextStateHeader(
10218 "gpu/command_buffer/client/client_context_state_autogen.h")
10219 gen
.WriteClientContextStateImpl(
10220 "gpu/command_buffer/client/client_context_state_impl_autogen.h")
10221 gen
.WriteServiceUnitTests(
10222 "gpu/command_buffer/service/gles2_cmd_decoder_unittest_%d_autogen.h")
10223 gen
.WriteServiceUnitTestsForExtensions(
10224 "gpu/command_buffer/service/"
10225 "gles2_cmd_decoder_unittest_extensions_autogen.h")
10226 gen
.WriteServiceUtilsHeader(
10227 "gpu/command_buffer/service/gles2_cmd_validation_autogen.h")
10228 gen
.WriteServiceUtilsImplementation(
10229 "gpu/command_buffer/service/"
10230 "gles2_cmd_validation_implementation_autogen.h")
10231 gen
.WriteCommonUtilsHeader(
10232 "gpu/command_buffer/common/gles2_cmd_utils_autogen.h")
10233 gen
.WriteCommonUtilsImpl(
10234 "gpu/command_buffer/common/gles2_cmd_utils_implementation_autogen.h")
10235 gen
.WriteGLES2Header("gpu/GLES2/gl2chromium_autogen.h")
10236 mojo_gles2_prefix
= ("third_party/mojo/src/mojo/public/c/gles2/"
10237 "gles2_call_visitor")
10238 gen
.WriteMojoGLCallVisitor(mojo_gles2_prefix
+ "_autogen.h")
10239 gen
.WriteMojoGLCallVisitorForExtension(
10240 mojo_gles2_prefix
+ "_chromium_texture_mailbox_autogen.h",
10241 "CHROMIUM_texture_mailbox")
10242 gen
.WriteMojoGLCallVisitorForExtension(
10243 mojo_gles2_prefix
+ "_chromium_sync_point_autogen.h",
10244 "CHROMIUM_sync_point")
10246 Format(gen
.generated_cpp_filenames
)
10249 print "%d errors" % gen
.errors
10254 if __name__
== '__main__':
10255 sys
.exit(main(sys
.argv
[1:]))