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'},
85 {'name': 'rasterizer_discard', 'es3': True},
86 {'name': 'primitive_restart_fixed_index', 'es3': True},
93 'enum': 'GL_COLOR_CLEAR_VALUE',
95 {'name': 'color_clear_red', 'type': 'GLfloat', 'default': '0.0f'},
96 {'name': 'color_clear_green', 'type': 'GLfloat', 'default': '0.0f'},
97 {'name': 'color_clear_blue', 'type': 'GLfloat', 'default': '0.0f'},
98 {'name': 'color_clear_alpha', 'type': 'GLfloat', 'default': '0.0f'},
103 'func': 'ClearDepth',
104 'enum': 'GL_DEPTH_CLEAR_VALUE',
106 {'name': 'depth_clear', 'type': 'GLclampf', 'default': '1.0f'},
112 'enum': 'GL_COLOR_WRITEMASK',
115 'name': 'color_mask_red',
121 'name': 'color_mask_green',
127 'name': 'color_mask_blue',
133 'name': 'color_mask_alpha',
139 'state_flag': 'framebuffer_state_.clear_state_dirty',
143 'func': 'ClearStencil',
144 'enum': 'GL_STENCIL_CLEAR_VALUE',
146 {'name': 'stencil_clear', 'type': 'GLint', 'default': '0'},
151 'func': 'BlendColor',
152 'enum': 'GL_BLEND_COLOR',
154 {'name': 'blend_color_red', 'type': 'GLfloat', 'default': '0.0f'},
155 {'name': 'blend_color_green', 'type': 'GLfloat', 'default': '0.0f'},
156 {'name': 'blend_color_blue', 'type': 'GLfloat', 'default': '0.0f'},
157 {'name': 'blend_color_alpha', 'type': 'GLfloat', 'default': '0.0f'},
162 'func': 'BlendEquationSeparate',
165 'name': 'blend_equation_rgb',
167 'enum': 'GL_BLEND_EQUATION_RGB',
168 'default': 'GL_FUNC_ADD',
171 'name': 'blend_equation_alpha',
173 'enum': 'GL_BLEND_EQUATION_ALPHA',
174 'default': 'GL_FUNC_ADD',
180 'func': 'BlendFuncSeparate',
183 'name': 'blend_source_rgb',
185 'enum': 'GL_BLEND_SRC_RGB',
189 'name': 'blend_dest_rgb',
191 'enum': 'GL_BLEND_DST_RGB',
192 'default': 'GL_ZERO',
195 'name': 'blend_source_alpha',
197 'enum': 'GL_BLEND_SRC_ALPHA',
201 'name': 'blend_dest_alpha',
203 'enum': 'GL_BLEND_DST_ALPHA',
204 'default': 'GL_ZERO',
210 'func': 'PolygonOffset',
213 'name': 'polygon_offset_factor',
215 'enum': 'GL_POLYGON_OFFSET_FACTOR',
219 'name': 'polygon_offset_units',
221 'enum': 'GL_POLYGON_OFFSET_UNITS',
229 'enum': 'GL_CULL_FACE_MODE',
234 'default': 'GL_BACK',
241 'enum': 'GL_FRONT_FACE',
242 'states': [{'name': 'front_face', 'type': 'GLenum', 'default': 'GL_CCW'}],
247 'enum': 'GL_DEPTH_FUNC',
248 'states': [{'name': 'depth_func', 'type': 'GLenum', 'default': 'GL_LESS'}],
252 'func': 'DepthRange',
253 'enum': 'GL_DEPTH_RANGE',
255 {'name': 'z_near', 'type': 'GLclampf', 'default': '0.0f'},
256 {'name': 'z_far', 'type': 'GLclampf', 'default': '1.0f'},
261 'func': 'SampleCoverage',
264 'name': 'sample_coverage_value',
266 'enum': 'GL_SAMPLE_COVERAGE_VALUE',
270 'name': 'sample_coverage_invert',
272 'enum': 'GL_SAMPLE_COVERAGE_INVERT',
279 'func': 'StencilMaskSeparate',
280 'state_flag': 'framebuffer_state_.clear_state_dirty',
283 'name': 'stencil_front_writemask',
285 'enum': 'GL_STENCIL_WRITEMASK',
286 'default': '0xFFFFFFFFU',
290 'name': 'stencil_back_writemask',
292 'enum': 'GL_STENCIL_BACK_WRITEMASK',
293 'default': '0xFFFFFFFFU',
300 'func': 'StencilOpSeparate',
303 'name': 'stencil_front_fail_op',
305 'enum': 'GL_STENCIL_FAIL',
306 'default': 'GL_KEEP',
309 'name': 'stencil_front_z_fail_op',
311 'enum': 'GL_STENCIL_PASS_DEPTH_FAIL',
312 'default': 'GL_KEEP',
315 'name': 'stencil_front_z_pass_op',
317 'enum': 'GL_STENCIL_PASS_DEPTH_PASS',
318 'default': 'GL_KEEP',
321 'name': 'stencil_back_fail_op',
323 'enum': 'GL_STENCIL_BACK_FAIL',
324 'default': 'GL_KEEP',
327 'name': 'stencil_back_z_fail_op',
329 'enum': 'GL_STENCIL_BACK_PASS_DEPTH_FAIL',
330 'default': 'GL_KEEP',
333 'name': 'stencil_back_z_pass_op',
335 'enum': 'GL_STENCIL_BACK_PASS_DEPTH_PASS',
336 'default': 'GL_KEEP',
342 'func': 'StencilFuncSeparate',
345 'name': 'stencil_front_func',
347 'enum': 'GL_STENCIL_FUNC',
348 'default': 'GL_ALWAYS',
351 'name': 'stencil_front_ref',
353 'enum': 'GL_STENCIL_REF',
357 'name': 'stencil_front_mask',
359 'enum': 'GL_STENCIL_VALUE_MASK',
360 'default': '0xFFFFFFFFU',
363 'name': 'stencil_back_func',
365 'enum': 'GL_STENCIL_BACK_FUNC',
366 'default': 'GL_ALWAYS',
369 'name': 'stencil_back_ref',
371 'enum': 'GL_STENCIL_BACK_REF',
375 'name': 'stencil_back_mask',
377 'enum': 'GL_STENCIL_BACK_VALUE_MASK',
378 'default': '0xFFFFFFFFU',
383 'type': 'NamedParameter',
387 'name': 'hint_generate_mipmap',
389 'enum': 'GL_GENERATE_MIPMAP_HINT',
390 'default': 'GL_DONT_CARE',
391 'gl_version_flag': '!is_desktop_core_profile'
394 'name': 'hint_fragment_shader_derivative',
396 'enum': 'GL_FRAGMENT_SHADER_DERIVATIVE_HINT_OES',
397 'default': 'GL_DONT_CARE',
398 'extension_flag': 'oes_standard_derivatives'
403 'type': 'NamedParameter',
404 'func': 'PixelStorei',
407 'name': 'pack_alignment',
409 'enum': 'GL_PACK_ALIGNMENT',
413 'name': 'unpack_alignment',
415 'enum': 'GL_UNPACK_ALIGNMENT',
420 # TODO: Consider implemenenting these states
425 'enum': 'GL_LINE_WIDTH',
428 'name': 'line_width',
431 'range_checks': [{'check': "<= 0.0f", 'test_value': "0.0f"}],
438 'enum': 'GL_DEPTH_WRITEMASK',
441 'name': 'depth_mask',
447 'state_flag': 'framebuffer_state_.clear_state_dirty',
452 'enum': 'GL_SCISSOR_BOX',
454 # NOTE: These defaults reset at GLES2DecoderImpl::Initialization.
459 'expected': 'kViewportX',
465 'expected': 'kViewportY',
468 'name': 'scissor_width',
471 'expected': 'kViewportWidth',
474 'name': 'scissor_height',
477 'expected': 'kViewportHeight',
484 'enum': 'GL_VIEWPORT',
486 # NOTE: These defaults reset at GLES2DecoderImpl::Initialization.
488 'name': 'viewport_x',
491 'expected': 'kViewportX',
494 'name': 'viewport_y',
497 'expected': 'kViewportY',
500 'name': 'viewport_width',
503 'expected': 'kViewportWidth',
506 'name': 'viewport_height',
509 'expected': 'kViewportHeight',
513 'MatrixValuesCHROMIUM': {
514 'type': 'NamedParameter',
515 'func': 'MatrixLoadfEXT',
517 { 'enum': 'GL_PATH_MODELVIEW_MATRIX_CHROMIUM',
518 'enum_set': 'GL_PATH_MODELVIEW_CHROMIUM',
519 'name': 'modelview_matrix',
522 '1.0f', '0.0f','0.0f','0.0f',
523 '0.0f', '1.0f','0.0f','0.0f',
524 '0.0f', '0.0f','1.0f','0.0f',
525 '0.0f', '0.0f','0.0f','1.0f',
527 'extension_flag': 'chromium_path_rendering',
529 { 'enum': 'GL_PATH_PROJECTION_MATRIX_CHROMIUM',
530 'enum_set': 'GL_PATH_PROJECTION_CHROMIUM',
531 'name': 'projection_matrix',
534 '1.0f', '0.0f','0.0f','0.0f',
535 '0.0f', '1.0f','0.0f','0.0f',
536 '0.0f', '0.0f','1.0f','0.0f',
537 '0.0f', '0.0f','0.0f','1.0f',
539 'extension_flag': 'chromium_path_rendering',
545 # Named type info object represents a named type that is used in OpenGL call
546 # arguments. Each named type defines a set of valid OpenGL call arguments. The
547 # named types are used in 'cmd_buffer_functions.txt'.
548 # type: The actual GL type of the named type.
549 # valid: The list of values that are valid for both the client and the service.
550 # valid_es3: The list of values that are valid in OpenGL ES 3, but not ES 2.
551 # invalid: Examples of invalid values for the type. At least these values
552 # should be tested to be invalid.
553 # deprecated_es3: The list of values that are valid in OpenGL ES 2, but
554 # deprecated in ES 3.
555 # is_complete: The list of valid values of type are final and will not be
556 # modified during runtime.
565 'GL_LINEAR_MIPMAP_LINEAR',
568 'FrameBufferTarget': {
574 'GL_DRAW_FRAMEBUFFER' ,
575 'GL_READ_FRAMEBUFFER' ,
578 'RenderBufferTarget': {
591 'GL_ELEMENT_ARRAY_BUFFER',
594 'GL_COPY_READ_BUFFER',
595 'GL_COPY_WRITE_BUFFER',
596 'GL_PIXEL_PACK_BUFFER',
597 'GL_PIXEL_UNPACK_BUFFER',
598 'GL_TRANSFORM_FEEDBACK_BUFFER',
605 'IndexedBufferTarget': {
608 'GL_TRANSFORM_FEEDBACK_BUFFER',
620 'GL_MAP_INVALIDATE_RANGE_BIT',
621 'GL_MAP_INVALIDATE_BUFFER_BIT',
622 'GL_MAP_FLUSH_EXPLICIT_BIT',
623 'GL_MAP_UNSYNCHRONIZED_BIT',
626 'GL_SYNC_FLUSH_COMMANDS_BIT',
678 'CompressedTextureFormat': {
683 'GL_COMPRESSED_R11_EAC',
684 'GL_COMPRESSED_SIGNED_R11_EAC',
685 'GL_COMPRESSED_RG11_EAC',
686 'GL_COMPRESSED_SIGNED_RG11_EAC',
687 'GL_COMPRESSED_RGB8_ETC2',
688 'GL_COMPRESSED_SRGB8_ETC2',
689 'GL_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2',
690 'GL_COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2',
691 'GL_COMPRESSED_RGBA8_ETC2_EAC',
692 'GL_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC',
698 # NOTE: State an Capability entries added later.
700 'GL_ALIASED_LINE_WIDTH_RANGE',
701 'GL_ALIASED_POINT_SIZE_RANGE',
703 'GL_ARRAY_BUFFER_BINDING',
705 'GL_COMPRESSED_TEXTURE_FORMATS',
706 'GL_CURRENT_PROGRAM',
709 'GL_ELEMENT_ARRAY_BUFFER_BINDING',
710 'GL_FRAMEBUFFER_BINDING',
711 'GL_GENERATE_MIPMAP_HINT',
713 'GL_IMPLEMENTATION_COLOR_READ_FORMAT',
714 'GL_IMPLEMENTATION_COLOR_READ_TYPE',
715 'GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS',
716 'GL_MAX_CUBE_MAP_TEXTURE_SIZE',
717 'GL_MAX_FRAGMENT_UNIFORM_VECTORS',
718 'GL_MAX_RENDERBUFFER_SIZE',
719 'GL_MAX_TEXTURE_IMAGE_UNITS',
720 'GL_MAX_TEXTURE_SIZE',
721 'GL_MAX_VARYING_VECTORS',
722 'GL_MAX_VERTEX_ATTRIBS',
723 'GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS',
724 'GL_MAX_VERTEX_UNIFORM_VECTORS',
725 'GL_MAX_VIEWPORT_DIMS',
726 'GL_NUM_COMPRESSED_TEXTURE_FORMATS',
727 'GL_NUM_SHADER_BINARY_FORMATS',
730 'GL_RENDERBUFFER_BINDING',
732 'GL_SAMPLE_COVERAGE_INVERT',
733 'GL_SAMPLE_COVERAGE_VALUE',
736 'GL_SHADER_BINARY_FORMATS',
737 'GL_SHADER_COMPILER',
740 'GL_TEXTURE_BINDING_2D',
741 'GL_TEXTURE_BINDING_CUBE_MAP',
742 'GL_UNPACK_ALIGNMENT',
743 'GL_UNPACK_FLIP_Y_CHROMIUM',
744 'GL_UNPACK_PREMULTIPLY_ALPHA_CHROMIUM',
745 'GL_UNPACK_UNPREMULTIPLY_ALPHA_CHROMIUM',
746 'GL_BIND_GENERATES_RESOURCE_CHROMIUM',
747 # we can add this because we emulate it if the driver does not support it.
748 'GL_VERTEX_ARRAY_BINDING_OES',
752 'GL_COPY_READ_BUFFER_BINDING',
753 'GL_COPY_WRITE_BUFFER_BINDING',
770 'GL_DRAW_FRAMEBUFFER_BINDING',
771 'GL_FRAGMENT_SHADER_DERIVATIVE_HINT',
773 'GL_MAX_3D_TEXTURE_SIZE',
774 'GL_MAX_ARRAY_TEXTURE_LAYERS',
775 'GL_MAX_COLOR_ATTACHMENTS',
776 'GL_MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS',
777 'GL_MAX_COMBINED_UNIFORM_BLOCKS',
778 'GL_MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS',
779 'GL_MAX_DRAW_BUFFERS',
780 'GL_MAX_ELEMENT_INDEX',
781 'GL_MAX_ELEMENTS_INDICES',
782 'GL_MAX_ELEMENTS_VERTICES',
783 'GL_MAX_FRAGMENT_INPUT_COMPONENTS',
784 'GL_MAX_FRAGMENT_UNIFORM_BLOCKS',
785 'GL_MAX_FRAGMENT_UNIFORM_COMPONENTS',
786 'GL_MAX_PROGRAM_TEXEL_OFFSET',
788 'GL_MAX_SERVER_WAIT_TIMEOUT',
789 'GL_MAX_TEXTURE_LOD_BIAS',
790 'GL_MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS',
791 'GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS',
792 'GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS',
793 'GL_MAX_UNIFORM_BLOCK_SIZE',
794 'GL_MAX_UNIFORM_BUFFER_BINDINGS',
795 'GL_MAX_VARYING_COMPONENTS',
796 'GL_MAX_VERTEX_OUTPUT_COMPONENTS',
797 'GL_MAX_VERTEX_UNIFORM_BLOCKS',
798 'GL_MAX_VERTEX_UNIFORM_COMPONENTS',
799 'GL_MIN_PROGRAM_TEXEL_OFFSET',
802 'GL_NUM_PROGRAM_BINARY_FORMATS',
803 'GL_PACK_ROW_LENGTH',
804 'GL_PACK_SKIP_PIXELS',
806 'GL_PIXEL_PACK_BUFFER_BINDING',
807 'GL_PIXEL_UNPACK_BUFFER_BINDING',
808 'GL_PROGRAM_BINARY_FORMATS',
810 'GL_READ_FRAMEBUFFER_BINDING',
811 'GL_SAMPLER_BINDING',
812 'GL_TEXTURE_BINDING_2D_ARRAY',
813 'GL_TEXTURE_BINDING_3D',
814 'GL_TRANSFORM_FEEDBACK_BINDING',
815 'GL_TRANSFORM_FEEDBACK_ACTIVE',
816 'GL_TRANSFORM_FEEDBACK_BUFFER_BINDING',
817 'GL_TRANSFORM_FEEDBACK_PAUSED',
818 'GL_TRANSFORM_FEEDBACK_BUFFER_SIZE',
819 'GL_TRANSFORM_FEEDBACK_BUFFER_START',
820 'GL_UNIFORM_BUFFER_BINDING',
821 'GL_UNIFORM_BUFFER_OFFSET_ALIGNMENT',
822 'GL_UNIFORM_BUFFER_SIZE',
823 'GL_UNIFORM_BUFFER_START',
824 'GL_UNPACK_IMAGE_HEIGHT',
825 'GL_UNPACK_ROW_LENGTH',
826 'GL_UNPACK_SKIP_IMAGES',
827 'GL_UNPACK_SKIP_PIXELS',
828 'GL_UNPACK_SKIP_ROWS',
829 # GL_VERTEX_ARRAY_BINDING is the same as GL_VERTEX_ARRAY_BINDING_OES
830 # 'GL_VERTEX_ARRAY_BINDING',
839 'GL_TRANSFORM_FEEDBACK_BUFFER_BINDING',
840 'GL_TRANSFORM_FEEDBACK_BUFFER_SIZE',
841 'GL_TRANSFORM_FEEDBACK_BUFFER_START',
842 'GL_UNIFORM_BUFFER_BINDING',
843 'GL_UNIFORM_BUFFER_SIZE',
844 'GL_UNIFORM_BUFFER_START',
850 'GetTexParamTarget': {
854 'GL_TEXTURE_CUBE_MAP',
857 'GL_PROXY_TEXTURE_CUBE_MAP',
864 'GL_TEXTURE_CUBE_MAP_POSITIVE_X',
865 'GL_TEXTURE_CUBE_MAP_NEGATIVE_X',
866 'GL_TEXTURE_CUBE_MAP_POSITIVE_Y',
867 'GL_TEXTURE_CUBE_MAP_NEGATIVE_Y',
868 'GL_TEXTURE_CUBE_MAP_POSITIVE_Z',
869 'GL_TEXTURE_CUBE_MAP_NEGATIVE_Z',
872 'GL_PROXY_TEXTURE_CUBE_MAP',
879 'GL_TEXTURE_2D_ARRAY',
885 'TextureBindTarget': {
889 'GL_TEXTURE_CUBE_MAP',
893 'GL_TEXTURE_2D_ARRAY',
900 'TransformFeedbackBindTarget': {
903 'GL_TRANSFORM_FEEDBACK',
909 'TransformFeedbackPrimitiveMode': {
924 'GL_FRAGMENT_SHADER',
927 'GL_GEOMETRY_SHADER',
963 'GL_FUNC_REVERSE_SUBTRACT',
976 'GL_ONE_MINUS_SRC_COLOR',
978 'GL_ONE_MINUS_DST_COLOR',
980 'GL_ONE_MINUS_SRC_ALPHA',
982 'GL_ONE_MINUS_DST_ALPHA',
984 'GL_ONE_MINUS_CONSTANT_COLOR',
986 'GL_ONE_MINUS_CONSTANT_ALPHA',
987 'GL_SRC_ALPHA_SATURATE',
996 'GL_ONE_MINUS_SRC_COLOR',
998 'GL_ONE_MINUS_DST_COLOR',
1000 'GL_ONE_MINUS_SRC_ALPHA',
1002 'GL_ONE_MINUS_DST_ALPHA',
1003 'GL_CONSTANT_COLOR',
1004 'GL_ONE_MINUS_CONSTANT_COLOR',
1005 'GL_CONSTANT_ALPHA',
1006 'GL_ONE_MINUS_CONSTANT_ALPHA',
1011 'valid': ["GL_%s" % cap
['name'].upper() for cap
in _CAPABILITY_FLAGS
1012 if 'es3' not in cap
or cap
['es3'] != True],
1013 'valid_es3': ["GL_%s" % cap
['name'].upper() for cap
in _CAPABILITY_FLAGS
1014 if 'es3' in cap
and cap
['es3'] == True],
1027 'GL_TRIANGLE_STRIP',
1040 'GL_UNSIGNED_SHORT',
1047 'GetMaxIndexType': {
1051 'GL_UNSIGNED_SHORT',
1061 'GL_COLOR_ATTACHMENT0',
1062 'GL_DEPTH_ATTACHMENT',
1063 'GL_STENCIL_ATTACHMENT',
1066 'BackbufferAttachment': {
1074 'BufferParameter': {
1081 'GL_PIXEL_PACK_BUFFER',
1087 'GL_INTERLEAVED_ATTRIBS',
1088 'GL_SEPARATE_ATTRIBS',
1091 'GL_PIXEL_PACK_BUFFER',
1094 'FrameBufferParameter': {
1097 'GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE',
1098 'GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME',
1099 'GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL',
1100 'GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE',
1106 'GL_PATH_PROJECTION_CHROMIUM',
1107 'GL_PATH_MODELVIEW_CHROMIUM',
1110 'ProgramParameter': {
1115 'GL_VALIDATE_STATUS',
1116 'GL_INFO_LOG_LENGTH',
1117 'GL_ATTACHED_SHADERS',
1118 'GL_ACTIVE_ATTRIBUTES',
1119 'GL_ACTIVE_ATTRIBUTE_MAX_LENGTH',
1120 'GL_ACTIVE_UNIFORMS',
1121 'GL_ACTIVE_UNIFORM_MAX_LENGTH',
1124 'QueryObjectParameter': {
1127 'GL_QUERY_RESULT_EXT',
1128 'GL_QUERY_RESULT_AVAILABLE_EXT',
1134 'GL_CURRENT_QUERY_EXT',
1140 'GL_ANY_SAMPLES_PASSED_EXT',
1141 'GL_ANY_SAMPLES_PASSED_CONSERVATIVE_EXT',
1142 'GL_COMMANDS_ISSUED_CHROMIUM',
1143 'GL_LATENCY_QUERY_CHROMIUM',
1144 'GL_ASYNC_PIXEL_UNPACK_COMPLETED_CHROMIUM',
1145 'GL_ASYNC_PIXEL_PACK_COMPLETED_CHROMIUM',
1146 'GL_COMMANDS_COMPLETED_CHROMIUM',
1149 'RenderBufferParameter': {
1152 'GL_RENDERBUFFER_RED_SIZE',
1153 'GL_RENDERBUFFER_GREEN_SIZE',
1154 'GL_RENDERBUFFER_BLUE_SIZE',
1155 'GL_RENDERBUFFER_ALPHA_SIZE',
1156 'GL_RENDERBUFFER_DEPTH_SIZE',
1157 'GL_RENDERBUFFER_STENCIL_SIZE',
1158 'GL_RENDERBUFFER_WIDTH',
1159 'GL_RENDERBUFFER_HEIGHT',
1160 'GL_RENDERBUFFER_INTERNAL_FORMAT',
1163 'SamplerParameter': {
1166 'GL_TEXTURE_MAG_FILTER',
1167 'GL_TEXTURE_MIN_FILTER',
1168 'GL_TEXTURE_MIN_LOD',
1169 'GL_TEXTURE_MAX_LOD',
1170 'GL_TEXTURE_WRAP_S',
1171 'GL_TEXTURE_WRAP_T',
1172 'GL_TEXTURE_WRAP_R',
1173 'GL_TEXTURE_COMPARE_MODE',
1174 'GL_TEXTURE_COMPARE_FUNC',
1177 'GL_GENERATE_MIPMAP',
1180 'ShaderParameter': {
1185 'GL_COMPILE_STATUS',
1186 'GL_INFO_LOG_LENGTH',
1187 'GL_SHADER_SOURCE_LENGTH',
1188 'GL_TRANSLATED_SHADER_SOURCE_LENGTH_ANGLE',
1191 'ShaderPrecision': {
1208 'GL_SHADING_LANGUAGE_VERSION',
1212 'TextureParameter': {
1215 'GL_TEXTURE_MAG_FILTER',
1216 'GL_TEXTURE_MIN_FILTER',
1217 'GL_TEXTURE_POOL_CHROMIUM',
1218 'GL_TEXTURE_WRAP_S',
1219 'GL_TEXTURE_WRAP_T',
1222 'GL_GENERATE_MIPMAP',
1228 'GL_TEXTURE_POOL_MANAGED_CHROMIUM',
1229 'GL_TEXTURE_POOL_UNMANAGED_CHROMIUM',
1232 'TextureWrapMode': {
1236 'GL_MIRRORED_REPEAT',
1240 'TextureMinFilterMode': {
1245 'GL_NEAREST_MIPMAP_NEAREST',
1246 'GL_LINEAR_MIPMAP_NEAREST',
1247 'GL_NEAREST_MIPMAP_LINEAR',
1248 'GL_LINEAR_MIPMAP_LINEAR',
1251 'TextureMagFilterMode': {
1262 'GL_FRAMEBUFFER_ATTACHMENT_ANGLE',
1265 'VertexAttribute': {
1268 # some enum that the decoder actually passes through to GL needs
1269 # to be the first listed here since it's used in unit tests.
1270 'GL_VERTEX_ATTRIB_ARRAY_NORMALIZED',
1271 'GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING',
1272 'GL_VERTEX_ATTRIB_ARRAY_ENABLED',
1273 'GL_VERTEX_ATTRIB_ARRAY_SIZE',
1274 'GL_VERTEX_ATTRIB_ARRAY_STRIDE',
1275 'GL_VERTEX_ATTRIB_ARRAY_TYPE',
1276 'GL_CURRENT_VERTEX_ATTRIB',
1282 'GL_VERTEX_ATTRIB_ARRAY_POINTER',
1288 'GL_GENERATE_MIPMAP_HINT',
1291 'GL_PERSPECTIVE_CORRECTION_HINT',
1305 'GL_PACK_ALIGNMENT',
1306 'GL_UNPACK_ALIGNMENT',
1307 'GL_UNPACK_FLIP_Y_CHROMIUM',
1308 'GL_UNPACK_PREMULTIPLY_ALPHA_CHROMIUM',
1309 'GL_UNPACK_UNPREMULTIPLY_ALPHA_CHROMIUM',
1312 'GL_PACK_SWAP_BYTES',
1313 'GL_UNPACK_SWAP_BYTES',
1316 'PixelStoreAlignment': {
1329 'ReadPixelFormat': {
1341 'GL_UNSIGNED_SHORT_5_6_5',
1342 'GL_UNSIGNED_SHORT_4_4_4_4',
1343 'GL_UNSIGNED_SHORT_5_5_5_1',
1347 'GL_UNSIGNED_SHORT',
1353 'GL_UNSIGNED_INT_2_10_10_10_REV',
1354 'GL_UNSIGNED_INT_10F_11F_11F_REV',
1355 'GL_UNSIGNED_INT_5_9_9_9_REV',
1356 'GL_UNSIGNED_INT_24_8',
1357 'GL_FLOAT_32_UNSIGNED_INT_24_8_REV',
1360 'GL_UNSIGNED_BYTE_3_3_2',
1367 'GL_UNSIGNED_SHORT_5_6_5',
1368 'GL_UNSIGNED_SHORT_4_4_4_4',
1369 'GL_UNSIGNED_SHORT_5_5_5_1',
1376 'RenderBufferFormat': {
1382 'GL_DEPTH_COMPONENT16',
1383 'GL_STENCIL_INDEX8',
1386 'ShaderBinaryFormat': {
1409 'GL_LUMINANCE_ALPHA',
1420 'GL_DEPTH_COMPONENT',
1428 'TextureInternalFormat': {
1433 'GL_LUMINANCE_ALPHA',
1462 'GL_R11F_G11F_B10F',
1487 # The DEPTH/STENCIL formats are not supported in CopyTexImage2D.
1488 # We will reject them dynamically in GPU command buffer.
1489 'GL_DEPTH_COMPONENT16',
1490 'GL_DEPTH_COMPONENT24',
1491 'GL_DEPTH_COMPONENT32F',
1492 'GL_DEPTH24_STENCIL8',
1493 'GL_DEPTH32F_STENCIL8',
1500 'TextureInternalFormatStorage': {
1507 'GL_LUMINANCE8_EXT',
1508 'GL_LUMINANCE8_ALPHA8_EXT',
1535 'GL_R11F_G11F_B10F',
1557 'GL_DEPTH_COMPONENT16',
1558 'GL_DEPTH_COMPONENT24',
1559 'GL_DEPTH_COMPONENT32F',
1560 'GL_DEPTH24_STENCIL8',
1561 'GL_DEPTH32F_STENCIL8',
1562 'GL_COMPRESSED_R11_EAC',
1563 'GL_COMPRESSED_SIGNED_R11_EAC',
1564 'GL_COMPRESSED_RG11_EAC',
1565 'GL_COMPRESSED_SIGNED_RG11_EAC',
1566 'GL_COMPRESSED_RGB8_ETC2',
1567 'GL_COMPRESSED_SRGB8_ETC2',
1568 'GL_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2',
1569 'GL_COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2',
1570 'GL_COMPRESSED_RGBA8_ETC2_EAC',
1571 'GL_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC',
1575 'GL_LUMINANCE8_EXT',
1576 'GL_LUMINANCE8_ALPHA8_EXT',
1578 'GL_LUMINANCE16F_EXT',
1579 'GL_LUMINANCE_ALPHA16F_EXT',
1581 'GL_LUMINANCE32F_EXT',
1582 'GL_LUMINANCE_ALPHA32F_EXT',
1585 'ImageInternalFormat': {
1589 'GL_RGB_YUV_420_CHROMIUM',
1597 'GL_SCANOUT_CHROMIUM'
1600 'ValueBufferTarget': {
1603 'GL_SUBSCRIBED_VALUES_BUFFER_CHROMIUM',
1606 'SubscriptionTarget': {
1609 'GL_MOUSE_POSITION_CHROMIUM',
1612 'UniformParameter': {
1617 'GL_UNIFORM_NAME_LENGTH',
1618 'GL_UNIFORM_BLOCK_INDEX',
1619 'GL_UNIFORM_OFFSET',
1620 'GL_UNIFORM_ARRAY_STRIDE',
1621 'GL_UNIFORM_MATRIX_STRIDE',
1622 'GL_UNIFORM_IS_ROW_MAJOR',
1625 'GL_UNIFORM_BLOCK_NAME_LENGTH',
1628 'UniformBlockParameter': {
1631 'GL_UNIFORM_BLOCK_BINDING',
1632 'GL_UNIFORM_BLOCK_DATA_SIZE',
1633 'GL_UNIFORM_BLOCK_NAME_LENGTH',
1634 'GL_UNIFORM_BLOCK_ACTIVE_UNIFORMS',
1635 'GL_UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES',
1636 'GL_UNIFORM_BLOCK_REFERENCED_BY_VERTEX_SHADER',
1637 'GL_UNIFORM_BLOCK_REFERENCED_BY_FRAGMENT_SHADER',
1643 'VertexAttribType': {
1649 'GL_UNSIGNED_SHORT',
1650 # 'GL_FIXED', // This is not available on Desktop GL.
1657 'VertexAttribIType': {
1663 'GL_UNSIGNED_SHORT',
1674 'is_complete': True,
1682 'VertexAttribSize': {
1697 'is_complete': True,
1706 'type': 'GLboolean',
1707 'is_complete': True,
1718 'GL_GUILTY_CONTEXT_RESET_ARB',
1719 'GL_INNOCENT_CONTEXT_RESET_ARB',
1720 'GL_UNKNOWN_CONTEXT_RESET_ARB',
1725 'is_complete': True,
1727 'GL_SYNC_GPU_COMMANDS_COMPLETE',
1734 'type': 'GLbitfield',
1735 'is_complete': True,
1744 'type': 'GLbitfield',
1746 'GL_SYNC_FLUSH_COMMANDS_BIT',
1756 'GL_SYNC_STATUS', # This needs to be the 1st; all others are cached.
1758 'GL_SYNC_CONDITION',
1767 # This table specifies the different pepper interfaces that are supported for
1768 # GL commands. 'dev' is true if it's a dev interface.
1769 _PEPPER_INTERFACES
= [
1770 {'name': '', 'dev': False},
1771 {'name': 'InstancedArrays', 'dev': False},
1772 {'name': 'FramebufferBlit', 'dev': False},
1773 {'name': 'FramebufferMultisample', 'dev': False},
1774 {'name': 'ChromiumEnableFeature', 'dev': False},
1775 {'name': 'ChromiumMapSub', 'dev': False},
1776 {'name': 'Query', 'dev': False},
1777 {'name': 'VertexArrayObject', 'dev': False},
1778 {'name': 'DrawBuffers', 'dev': True},
1781 # A function info object specifies the type and other special data for the
1782 # command that will be generated. A base function info object is generated by
1783 # parsing the "cmd_buffer_functions.txt", one for each function in the
1784 # file. These function info objects can be augmented and their values can be
1785 # overridden by adding an object to the table below.
1787 # Must match function names specified in "cmd_buffer_functions.txt".
1789 # cmd_comment: A comment added to the cmd format.
1790 # type: defines which handler will be used to generate code.
1791 # decoder_func: defines which function to call in the decoder to execute the
1792 # corresponding GL command. If not specified the GL command will
1793 # be called directly.
1794 # gl_test_func: GL function that is expected to be called when testing.
1795 # cmd_args: The arguments to use for the command. This overrides generating
1796 # them based on the GL function arguments.
1797 # gen_cmd: Whether or not this function geneates a command. Default = True.
1798 # data_transfer_methods: Array of methods that are used for transfering the
1799 # pointer data. Possible values: 'immediate', 'shm', 'bucket'.
1800 # The default is 'immediate' if the command has one pointer
1801 # argument, otherwise 'shm'. One command is generated for each
1802 # transfer method. Affects only commands which are not of type
1803 # 'HandWritten', 'GETn' or 'GLcharN'.
1804 # Note: the command arguments that affect this are the final args,
1805 # taking cmd_args override into consideration.
1806 # impl_func: Whether or not to generate the GLES2Implementation part of this
1808 # impl_decl: Whether or not to generate the GLES2Implementation declaration
1810 # needs_size: If True a data_size field is added to the command.
1811 # count: The number of units per element. For PUTn or PUT types.
1812 # use_count_func: If True the actual data count needs to be computed; the count
1813 # argument specifies the maximum count.
1814 # unit_test: If False no service side unit test will be generated.
1815 # client_test: If False no client side unit test will be generated.
1816 # expectation: If False the unit test will have no expected calls.
1817 # gen_func: Name of function that generates GL resource for corresponding
1819 # states: array of states that get set by this function corresponding to
1820 # the given arguments
1821 # state_flag: name of flag that is set to true when function is called.
1822 # no_gl: no GL function is called.
1823 # valid_args: A dictionary of argument indices to args to use in unit tests
1824 # when they can not be automatically determined.
1825 # pepper_interface: The pepper interface that is used for this extension
1826 # pepper_name: The name of the function as exposed to pepper.
1827 # pepper_args: A string representing the argument list (what would appear in
1828 # C/C++ between the parentheses for the function declaration)
1829 # that the Pepper API expects for this function. Use this only if
1830 # the stable Pepper API differs from the GLES2 argument list.
1831 # invalid_test: False if no invalid test needed.
1832 # shadowed: True = the value is shadowed so no glGetXXX call will be made.
1833 # first_element_only: For PUT types, True if only the first element of an
1834 # array is used and we end up calling the single value
1835 # corresponding function. eg. TexParameteriv -> TexParameteri
1836 # extension: Function is an extension to GL and should not be exposed to
1837 # pepper unless pepper_interface is defined.
1838 # extension_flag: Function is an extension and should be enabled only when
1839 # the corresponding feature info flag is enabled. Implies
1840 # 'extension': True.
1841 # not_shared: For GENn types, True if objects can't be shared between contexts
1842 # unsafe: True = no validation is implemented on the service side and the
1843 # command is only available with --enable-unsafe-es3-apis.
1844 # id_mapping: A list of resource type names whose client side IDs need to be
1845 # mapped to service side IDs. This is only used for unsafe APIs.
1849 'decoder_func': 'DoActiveTexture',
1852 'client_test': False,
1854 'AttachShader': {'decoder_func': 'DoAttachShader'},
1855 'BindAttribLocation': {
1857 'data_transfer_methods': ['bucket'],
1862 'decoder_func': 'DoBindBuffer',
1863 'gen_func': 'GenBuffersARB',
1867 'id_mapping': [ 'Buffer' ],
1868 'gen_func': 'GenBuffersARB',
1871 'BindBufferRange': {
1873 'id_mapping': [ 'Buffer' ],
1874 'gen_func': 'GenBuffersARB',
1881 'BindFramebuffer': {
1883 'decoder_func': 'DoBindFramebuffer',
1884 'gl_test_func': 'glBindFramebufferEXT',
1885 'gen_func': 'GenFramebuffersEXT',
1888 'BindRenderbuffer': {
1890 'decoder_func': 'DoBindRenderbuffer',
1891 'gl_test_func': 'glBindRenderbufferEXT',
1892 'gen_func': 'GenRenderbuffersEXT',
1896 'id_mapping': [ 'Sampler' ],
1901 'decoder_func': 'DoBindTexture',
1902 'gen_func': 'GenTextures',
1903 # TODO(gman): remove this once client side caching works.
1904 'client_test': False,
1907 'BindTransformFeedback': {
1909 'id_mapping': [ 'TransformFeedback' ],
1912 'BlitFramebufferCHROMIUM': {
1913 'decoder_func': 'DoBlitFramebufferCHROMIUM',
1915 'extension_flag': 'chromium_framebuffer_multisample',
1916 'pepper_interface': 'FramebufferBlit',
1917 'pepper_name': 'BlitFramebufferEXT',
1918 'defer_reads': True,
1919 'defer_draws': True,
1924 'data_transfer_methods': ['shm'],
1925 'client_test': False,
1929 'client_test': False,
1930 'decoder_func': 'DoBufferSubData',
1931 'data_transfer_methods': ['shm'],
1933 'CheckFramebufferStatus': {
1935 'decoder_func': 'DoCheckFramebufferStatus',
1936 'gl_test_func': 'glCheckFramebufferStatusEXT',
1937 'error_value': 'GL_FRAMEBUFFER_UNSUPPORTED',
1938 'result': ['GLenum'],
1941 'decoder_func': 'DoClear',
1942 'defer_draws': True,
1947 'use_count_func': True,
1958 'use_count_func': True,
1967 'state': 'ClearColor',
1971 'state': 'ClearDepthf',
1972 'decoder_func': 'glClearDepth',
1973 'gl_test_func': 'glClearDepth',
1980 'data_transfer_methods': ['shm'],
1981 'cmd_args': 'GLuint sync, GLbitfieldSyncFlushFlags flags, '
1982 'GLuint timeout_0, GLuint timeout_1, GLenum* result',
1984 'result': ['GLenum'],
1988 'state': 'ColorMask',
1990 'expectation': False,
1992 'ConsumeTextureCHROMIUM': {
1993 'decoder_func': 'DoConsumeTextureCHROMIUM',
1996 'count': 64, # GL_MAILBOX_SIZE_CHROMIUM
1998 'client_test': False,
1999 'extension': "CHROMIUM_texture_mailbox",
2003 'CopyBufferSubData': {
2006 'CreateAndConsumeTextureCHROMIUM': {
2007 'decoder_func': 'DoCreateAndConsumeTextureCHROMIUM',
2009 'type': 'HandWritten',
2010 'data_transfer_methods': ['immediate'],
2012 'client_test': False,
2013 'extension': "CHROMIUM_texture_mailbox",
2016 'GenValuebuffersCHROMIUM': {
2018 'gl_test_func': 'glGenValuebuffersCHROMIUM',
2019 'resource_type': 'Valuebuffer',
2020 'resource_types': 'Valuebuffers',
2025 'DeleteValuebuffersCHROMIUM': {
2027 'gl_test_func': 'glDeleteValuebuffersCHROMIUM',
2028 'resource_type': 'Valuebuffer',
2029 'resource_types': 'Valuebuffers',
2034 'IsValuebufferCHROMIUM': {
2036 'decoder_func': 'DoIsValuebufferCHROMIUM',
2037 'expectation': False,
2041 'BindValuebufferCHROMIUM': {
2043 'decoder_func': 'DoBindValueBufferCHROMIUM',
2044 'gen_func': 'GenValueBuffersCHROMIUM',
2049 'SubscribeValueCHROMIUM': {
2050 'decoder_func': 'DoSubscribeValueCHROMIUM',
2055 'PopulateSubscribedValuesCHROMIUM': {
2056 'decoder_func': 'DoPopulateSubscribedValuesCHROMIUM',
2061 'UniformValuebufferCHROMIUM': {
2062 'decoder_func': 'DoUniformValueBufferCHROMIUM',
2069 'state': 'ClearStencil',
2071 'EnableFeatureCHROMIUM': {
2073 'data_transfer_methods': ['shm'],
2074 'decoder_func': 'DoEnableFeatureCHROMIUM',
2075 'expectation': False,
2076 'cmd_args': 'GLuint bucket_id, GLint* result',
2077 'result': ['GLint'],
2080 'pepper_interface': 'ChromiumEnableFeature',
2082 'CompileShader': {'decoder_func': 'DoCompileShader', 'unit_test': False},
2083 'CompressedTexImage2D': {
2085 'data_transfer_methods': ['bucket', 'shm'],
2087 'CompressedTexSubImage2D': {
2089 'data_transfer_methods': ['bucket', 'shm'],
2090 'decoder_func': 'DoCompressedTexSubImage2D',
2093 'decoder_func': 'DoCopyTexImage2D',
2095 'defer_reads': True,
2097 'CopyTexSubImage2D': {
2098 'decoder_func': 'DoCopyTexSubImage2D',
2099 'defer_reads': True,
2101 'CompressedTexImage3D': {
2103 'data_transfer_methods': ['bucket', 'shm'],
2106 'CopyTexSubImage3D': {
2107 'defer_reads': True,
2110 'CreateImageCHROMIUM': {
2113 'ClientBuffer buffer, GLsizei width, GLsizei height, '
2114 'GLenum internalformat',
2115 'result': ['GLuint'],
2116 'client_test': False,
2118 'expectation': False,
2122 'DestroyImageCHROMIUM': {
2124 'client_test': False,
2129 'CreateGpuMemoryBufferImageCHROMIUM': {
2132 'GLsizei width, GLsizei height, GLenum internalformat, GLenum usage',
2133 'result': ['GLuint'],
2134 'client_test': False,
2136 'expectation': False,
2142 'client_test': False,
2146 'client_test': False,
2150 'state': 'BlendColor',
2153 'type': 'StateSetRGBAlpha',
2154 'state': 'BlendEquation',
2156 '0': 'GL_FUNC_SUBTRACT'
2159 'BlendEquationSeparate': {
2161 'state': 'BlendEquation',
2163 '0': 'GL_FUNC_SUBTRACT'
2167 'type': 'StateSetRGBAlpha',
2168 'state': 'BlendFunc',
2170 'BlendFuncSeparate': {
2172 'state': 'BlendFunc',
2174 'BlendBarrierKHR': {
2175 'gl_test_func': 'glBlendBarrierKHR',
2177 'extension_flag': 'blend_equation_advanced',
2178 'client_test': False,
2180 'SampleCoverage': {'decoder_func': 'DoSampleCoverage'},
2182 'type': 'StateSetFrontBack',
2183 'state': 'StencilFunc',
2185 'StencilFuncSeparate': {
2186 'type': 'StateSetFrontBackSeparate',
2187 'state': 'StencilFunc',
2190 'type': 'StateSetFrontBack',
2191 'state': 'StencilOp',
2196 'StencilOpSeparate': {
2197 'type': 'StateSetFrontBackSeparate',
2198 'state': 'StencilOp',
2204 'type': 'StateSetNamedParameter',
2207 'CullFace': {'type': 'StateSet', 'state': 'CullFace'},
2208 'FrontFace': {'type': 'StateSet', 'state': 'FrontFace'},
2209 'DepthFunc': {'type': 'StateSet', 'state': 'DepthFunc'},
2212 'state': 'LineWidth',
2219 'state': 'PolygonOffset',
2223 'gl_test_func': 'glDeleteBuffersARB',
2224 'resource_type': 'Buffer',
2225 'resource_types': 'Buffers',
2227 'DeleteFramebuffers': {
2229 'gl_test_func': 'glDeleteFramebuffersEXT',
2230 'resource_type': 'Framebuffer',
2231 'resource_types': 'Framebuffers',
2233 'DeleteProgram': { 'type': 'Delete' },
2234 'DeleteRenderbuffers': {
2236 'gl_test_func': 'glDeleteRenderbuffersEXT',
2237 'resource_type': 'Renderbuffer',
2238 'resource_types': 'Renderbuffers',
2242 'resource_type': 'Sampler',
2243 'resource_types': 'Samplers',
2246 'DeleteShader': { 'type': 'Delete' },
2249 'cmd_args': 'GLuint sync',
2250 'resource_type': 'Sync',
2255 'resource_type': 'Texture',
2256 'resource_types': 'Textures',
2258 'DeleteTransformFeedbacks': {
2260 'resource_type': 'TransformFeedback',
2261 'resource_types': 'TransformFeedbacks',
2265 'decoder_func': 'DoDepthRangef',
2266 'gl_test_func': 'glDepthRange',
2270 'state': 'DepthMask',
2272 'expectation': False,
2274 'DetachShader': {'decoder_func': 'DoDetachShader'},
2276 'decoder_func': 'DoDisable',
2278 'client_test': False,
2280 'DisableVertexAttribArray': {
2281 'decoder_func': 'DoDisableVertexAttribArray',
2286 'cmd_args': 'GLenumDrawMode mode, GLint first, GLsizei count',
2287 'defer_draws': True,
2292 'cmd_args': 'GLenumDrawMode mode, GLsizei count, '
2293 'GLenumIndexType type, GLuint index_offset',
2294 'client_test': False,
2295 'defer_draws': True,
2298 'DrawRangeElements': {
2304 'decoder_func': 'DoEnable',
2306 'client_test': False,
2308 'EnableVertexAttribArray': {
2309 'decoder_func': 'DoEnableVertexAttribArray',
2314 'client_test': False,
2319 'client_test': False,
2320 'decoder_func': 'DoFinish',
2321 'defer_reads': True,
2325 'decoder_func': 'DoFlush',
2327 'FramebufferRenderbuffer': {
2328 'decoder_func': 'DoFramebufferRenderbuffer',
2329 'gl_test_func': 'glFramebufferRenderbufferEXT',
2331 'FramebufferTexture2D': {
2332 'decoder_func': 'DoFramebufferTexture2D',
2333 'gl_test_func': 'glFramebufferTexture2DEXT',
2336 'FramebufferTexture2DMultisampleEXT': {
2337 'decoder_func': 'DoFramebufferTexture2DMultisample',
2338 'gl_test_func': 'glFramebufferTexture2DMultisampleEXT',
2339 'expectation': False,
2341 'extension_flag': 'multisampled_render_to_texture',
2344 'FramebufferTextureLayer': {
2345 'decoder_func': 'DoFramebufferTextureLayer',
2349 'decoder_func': 'DoGenerateMipmap',
2350 'gl_test_func': 'glGenerateMipmapEXT',
2354 'gl_test_func': 'glGenBuffersARB',
2355 'resource_type': 'Buffer',
2356 'resource_types': 'Buffers',
2358 'GenMailboxCHROMIUM': {
2359 'type': 'HandWritten',
2361 'extension': "CHROMIUM_texture_mailbox",
2364 'GenFramebuffers': {
2366 'gl_test_func': 'glGenFramebuffersEXT',
2367 'resource_type': 'Framebuffer',
2368 'resource_types': 'Framebuffers',
2370 'GenRenderbuffers': {
2371 'type': 'GENn', 'gl_test_func': 'glGenRenderbuffersEXT',
2372 'resource_type': 'Renderbuffer',
2373 'resource_types': 'Renderbuffers',
2377 'gl_test_func': 'glGenSamplers',
2378 'resource_type': 'Sampler',
2379 'resource_types': 'Samplers',
2384 'gl_test_func': 'glGenTextures',
2385 'resource_type': 'Texture',
2386 'resource_types': 'Textures',
2388 'GenTransformFeedbacks': {
2390 'gl_test_func': 'glGenTransformFeedbacks',
2391 'resource_type': 'TransformFeedback',
2392 'resource_types': 'TransformFeedbacks',
2395 'GetActiveAttrib': {
2397 'data_transfer_methods': ['shm'],
2399 'GLidProgram program, GLuint index, uint32_t name_bucket_id, '
2407 'GetActiveUniform': {
2409 'data_transfer_methods': ['shm'],
2411 'GLidProgram program, GLuint index, uint32_t name_bucket_id, '
2419 'GetActiveUniformBlockiv': {
2421 'data_transfer_methods': ['shm'],
2422 'result': ['SizedResult<GLint>'],
2425 'GetActiveUniformBlockName': {
2427 'data_transfer_methods': ['shm'],
2429 'GLidProgram program, GLuint index, uint32_t name_bucket_id, '
2431 'result': ['int32_t'],
2434 'GetActiveUniformsiv': {
2436 'data_transfer_methods': ['shm'],
2438 'GLidProgram program, uint32_t indices_bucket_id, GLenum pname, '
2440 'result': ['SizedResult<GLint>'],
2443 'GetAttachedShaders': {
2445 'data_transfer_methods': ['shm'],
2446 'cmd_args': 'GLidProgram program, void* result, uint32_t result_size',
2447 'result': ['SizedResult<GLuint>'],
2449 'GetAttribLocation': {
2451 'data_transfer_methods': ['shm'],
2453 'GLidProgram program, uint32_t name_bucket_id, GLint* location',
2454 'result': ['GLint'],
2457 'GetFragDataLocation': {
2459 'data_transfer_methods': ['shm'],
2461 'GLidProgram program, uint32_t name_bucket_id, GLint* location',
2462 'result': ['GLint'],
2468 'result': ['SizedResult<GLboolean>'],
2469 'decoder_func': 'DoGetBooleanv',
2470 'gl_test_func': 'glGetBooleanv',
2472 'GetBufferParameteriv': {
2474 'result': ['SizedResult<GLint>'],
2475 'decoder_func': 'DoGetBufferParameteriv',
2476 'expectation': False,
2481 'decoder_func': 'GetErrorState()->GetGLError',
2483 'result': ['GLenum'],
2484 'client_test': False,
2488 'result': ['SizedResult<GLfloat>'],
2489 'decoder_func': 'DoGetFloatv',
2490 'gl_test_func': 'glGetFloatv',
2492 'GetFramebufferAttachmentParameteriv': {
2494 'decoder_func': 'DoGetFramebufferAttachmentParameteriv',
2495 'gl_test_func': 'glGetFramebufferAttachmentParameterivEXT',
2496 'result': ['SizedResult<GLint>'],
2500 'result': ['SizedResult<GLint64>'],
2501 'client_test': False,
2502 'decoder_func': 'DoGetInteger64v',
2507 'result': ['SizedResult<GLint>'],
2508 'decoder_func': 'DoGetIntegerv',
2509 'client_test': False,
2511 'GetInteger64i_v': {
2513 'result': ['SizedResult<GLint64>'],
2514 'client_test': False,
2519 'result': ['SizedResult<GLint>'],
2520 'client_test': False,
2523 'GetInternalformativ': {
2525 'result': ['SizedResult<GLint>'],
2528 'GetMaxValueInBufferCHROMIUM': {
2530 'decoder_func': 'DoGetMaxValueInBufferCHROMIUM',
2531 'result': ['GLuint'],
2533 'client_test': False,
2540 'decoder_func': 'DoGetProgramiv',
2541 'result': ['SizedResult<GLint>'],
2542 'expectation': False,
2544 'GetProgramInfoCHROMIUM': {
2546 'expectation': False,
2550 'client_test': False,
2551 'cmd_args': 'GLidProgram program, uint32_t bucket_id',
2553 'uint32_t link_status',
2554 'uint32_t num_attribs',
2555 'uint32_t num_uniforms',
2558 'GetProgramInfoLog': {
2560 'expectation': False,
2562 'GetRenderbufferParameteriv': {
2564 'decoder_func': 'DoGetRenderbufferParameteriv',
2565 'gl_test_func': 'glGetRenderbufferParameterivEXT',
2566 'result': ['SizedResult<GLint>'],
2568 'GetSamplerParameterfv': {
2570 'result': ['SizedResult<GLfloat>'],
2571 'id_mapping': [ 'Sampler' ],
2574 'GetSamplerParameteriv': {
2576 'result': ['SizedResult<GLint>'],
2577 'id_mapping': [ 'Sampler' ],
2582 'decoder_func': 'DoGetShaderiv',
2583 'result': ['SizedResult<GLint>'],
2585 'GetShaderInfoLog': {
2587 'get_len_func': 'glGetShaderiv',
2588 'get_len_enum': 'GL_INFO_LOG_LENGTH',
2591 'GetShaderPrecisionFormat': {
2593 'data_transfer_methods': ['shm'],
2595 'GLenumShaderType shadertype, GLenumShaderPrecision precisiontype, '
2599 'int32_t min_range',
2600 'int32_t max_range',
2601 'int32_t precision',
2604 'GetShaderSource': {
2606 'get_len_func': 'DoGetShaderiv',
2607 'get_len_enum': 'GL_SHADER_SOURCE_LENGTH',
2609 'client_test': False,
2613 'client_test': False,
2614 'cmd_args': 'GLenumStringType name, uint32_t bucket_id',
2618 'cmd_args': 'GLuint sync, GLenumSyncParameter pname, void* values',
2619 'result': ['SizedResult<GLint>'],
2620 'id_mapping': ['Sync'],
2623 'GetTexParameterfv': {
2625 'decoder_func': 'DoGetTexParameterfv',
2626 'result': ['SizedResult<GLfloat>']
2628 'GetTexParameteriv': {
2630 'decoder_func': 'DoGetTexParameteriv',
2631 'result': ['SizedResult<GLint>']
2633 'GetTranslatedShaderSourceANGLE': {
2635 'get_len_func': 'DoGetShaderiv',
2636 'get_len_enum': 'GL_TRANSLATED_SHADER_SOURCE_LENGTH_ANGLE',
2640 'GetUniformBlockIndex': {
2642 'data_transfer_methods': ['shm'],
2644 'GLidProgram program, uint32_t name_bucket_id, GLuint* index',
2645 'result': ['GLuint'],
2646 'error_return': 'GL_INVALID_INDEX',
2649 'GetUniformBlocksCHROMIUM': {
2651 'expectation': False,
2655 'client_test': False,
2656 'cmd_args': 'GLidProgram program, uint32_t bucket_id',
2657 'result': ['uint32_t'],
2660 'GetUniformsES3CHROMIUM': {
2662 'expectation': False,
2666 'client_test': False,
2667 'cmd_args': 'GLidProgram program, uint32_t bucket_id',
2668 'result': ['uint32_t'],
2671 'GetTransformFeedbackVarying': {
2673 'data_transfer_methods': ['shm'],
2675 'GLidProgram program, GLuint index, uint32_t name_bucket_id, '
2684 'GetTransformFeedbackVaryingsCHROMIUM': {
2686 'expectation': False,
2690 'client_test': False,
2691 'cmd_args': 'GLidProgram program, uint32_t bucket_id',
2692 'result': ['uint32_t'],
2697 'data_transfer_methods': ['shm'],
2698 'result': ['SizedResult<GLfloat>'],
2702 'data_transfer_methods': ['shm'],
2703 'result': ['SizedResult<GLint>'],
2705 'GetUniformIndices': {
2707 'data_transfer_methods': ['shm'],
2708 'result': ['SizedResult<GLuint>'],
2709 'cmd_args': 'GLidProgram program, uint32_t names_bucket_id, '
2713 'GetUniformLocation': {
2715 'data_transfer_methods': ['shm'],
2717 'GLidProgram program, uint32_t name_bucket_id, GLint* location',
2718 'result': ['GLint'],
2719 'error_return': -1, # http://www.opengl.org/sdk/docs/man/xhtml/glGetUniformLocation.xml
2721 'GetVertexAttribfv': {
2723 'result': ['SizedResult<GLfloat>'],
2725 'decoder_func': 'DoGetVertexAttribfv',
2726 'expectation': False,
2727 'client_test': False,
2729 'GetVertexAttribiv': {
2731 'result': ['SizedResult<GLint>'],
2733 'decoder_func': 'DoGetVertexAttribiv',
2734 'expectation': False,
2735 'client_test': False,
2737 'GetVertexAttribPointerv': {
2739 'data_transfer_methods': ['shm'],
2740 'result': ['SizedResult<GLuint>'],
2741 'client_test': False,
2743 'InvalidateFramebuffer': {
2746 'client_test': False,
2750 'InvalidateSubFramebuffer': {
2753 'client_test': False,
2759 'decoder_func': 'DoIsBuffer',
2760 'expectation': False,
2764 'decoder_func': 'DoIsEnabled',
2765 'client_test': False,
2767 'expectation': False,
2771 'decoder_func': 'DoIsFramebuffer',
2772 'expectation': False,
2776 'decoder_func': 'DoIsProgram',
2777 'expectation': False,
2781 'decoder_func': 'DoIsRenderbuffer',
2782 'expectation': False,
2786 'decoder_func': 'DoIsShader',
2787 'expectation': False,
2791 'id_mapping': [ 'Sampler' ],
2792 'expectation': False,
2797 'id_mapping': [ 'Sync' ],
2798 'cmd_args': 'GLuint sync',
2799 'expectation': False,
2804 'decoder_func': 'DoIsTexture',
2805 'expectation': False,
2807 'IsTransformFeedback': {
2809 'id_mapping': [ 'TransformFeedback' ],
2810 'expectation': False,
2814 'decoder_func': 'DoLinkProgram',
2817 'MapBufferCHROMIUM': {
2821 'client_test': False,
2823 'MapBufferSubDataCHROMIUM': {
2827 'client_test': False,
2828 'pepper_interface': 'ChromiumMapSub',
2830 'MapTexSubImage2DCHROMIUM': {
2832 'extension': "CHROMIUM_sub_image",
2834 'client_test': False,
2835 'pepper_interface': 'ChromiumMapSub',
2839 'data_transfer_methods': ['shm'],
2840 'cmd_args': 'GLenumBufferTarget target, GLintptrNotNegative offset, '
2841 'GLsizeiptr size, GLbitfieldMapBufferAccess access, '
2842 'uint32_t data_shm_id, uint32_t data_shm_offset, '
2843 'uint32_t result_shm_id, uint32_t result_shm_offset',
2845 'result': ['uint32_t'],
2847 'PauseTransformFeedback': {
2850 'PixelStorei': {'type': 'Manual'},
2851 'PostSubBufferCHROMIUM': {
2855 'client_test': False,
2859 'ProduceTextureCHROMIUM': {
2860 'decoder_func': 'DoProduceTextureCHROMIUM',
2863 'count': 64, # GL_MAILBOX_SIZE_CHROMIUM
2865 'client_test': False,
2866 'extension': "CHROMIUM_texture_mailbox",
2870 'ProduceTextureDirectCHROMIUM': {
2871 'decoder_func': 'DoProduceTextureDirectCHROMIUM',
2874 'count': 64, # GL_MAILBOX_SIZE_CHROMIUM
2876 'client_test': False,
2877 'extension': "CHROMIUM_texture_mailbox",
2881 'RenderbufferStorage': {
2882 'decoder_func': 'DoRenderbufferStorage',
2883 'gl_test_func': 'glRenderbufferStorageEXT',
2884 'expectation': False,
2886 'RenderbufferStorageMultisampleCHROMIUM': {
2888 '// GL_CHROMIUM_framebuffer_multisample\n',
2889 'decoder_func': 'DoRenderbufferStorageMultisampleCHROMIUM',
2890 'gl_test_func': 'glRenderbufferStorageMultisampleCHROMIUM',
2891 'expectation': False,
2893 'extension_flag': 'chromium_framebuffer_multisample',
2894 'pepper_interface': 'FramebufferMultisample',
2895 'pepper_name': 'RenderbufferStorageMultisampleEXT',
2897 'RenderbufferStorageMultisampleEXT': {
2899 '// GL_EXT_multisampled_render_to_texture\n',
2900 'decoder_func': 'DoRenderbufferStorageMultisampleEXT',
2901 'gl_test_func': 'glRenderbufferStorageMultisampleEXT',
2902 'expectation': False,
2904 'extension_flag': 'multisampled_render_to_texture',
2911 '// ReadPixels has the result separated from the pixel buffer so that\n'
2912 '// it is easier to specify the result going to some specific place\n'
2913 '// that exactly fits the rectangle of pixels.\n',
2915 'data_transfer_methods': ['shm'],
2917 'client_test': False,
2919 'GLint x, GLint y, GLsizei width, GLsizei height, '
2920 'GLenumReadPixelFormat format, GLenumReadPixelType type, '
2921 'uint32_t pixels_shm_id, uint32_t pixels_shm_offset, '
2922 'uint32_t result_shm_id, uint32_t result_shm_offset, '
2924 'result': ['uint32_t'],
2925 'defer_reads': True,
2927 'ReleaseShaderCompiler': {
2928 'decoder_func': 'DoReleaseShaderCompiler',
2931 'ResumeTransformFeedback': {
2934 'SamplerParameterf': {
2938 'id_mapping': [ 'Sampler' ],
2941 'SamplerParameterfv': {
2943 'data_value': 'GL_NEAREST',
2945 'gl_test_func': 'glSamplerParameterf',
2946 'decoder_func': 'DoSamplerParameterfv',
2947 'first_element_only': True,
2948 'id_mapping': [ 'Sampler' ],
2951 'SamplerParameteri': {
2955 'id_mapping': [ 'Sampler' ],
2958 'SamplerParameteriv': {
2960 'data_value': 'GL_NEAREST',
2962 'gl_test_func': 'glSamplerParameteri',
2963 'decoder_func': 'DoSamplerParameteriv',
2964 'first_element_only': True,
2969 'client_test': False,
2973 'decoder_func': 'DoShaderSource',
2974 'expectation': False,
2975 'data_transfer_methods': ['bucket'],
2977 'GLuint shader, const char** str',
2979 'GLuint shader, GLsizei count, const char** str, const GLint* length',
2982 'type': 'StateSetFrontBack',
2983 'state': 'StencilMask',
2985 'expectation': False,
2987 'StencilMaskSeparate': {
2988 'type': 'StateSetFrontBackSeparate',
2989 'state': 'StencilMask',
2991 'expectation': False,
2995 'decoder_func': 'DoSwapBuffers',
2997 'client_test': False,
3003 'decoder_func': 'DoSwapInterval',
3005 'client_test': False,
3011 'data_transfer_methods': ['shm'],
3012 'client_test': False,
3016 'data_transfer_methods': ['shm'],
3017 'client_test': False,
3021 'decoder_func': 'DoTexParameterf',
3027 'decoder_func': 'DoTexParameteri',
3034 'data_value': 'GL_NEAREST',
3036 'decoder_func': 'DoTexParameterfv',
3037 'gl_test_func': 'glTexParameterf',
3038 'first_element_only': True,
3042 'data_value': 'GL_NEAREST',
3044 'decoder_func': 'DoTexParameteriv',
3045 'gl_test_func': 'glTexParameteri',
3046 'first_element_only': True,
3053 'data_transfer_methods': ['shm'],
3054 'client_test': False,
3055 'cmd_args': 'GLenumTextureTarget target, GLint level, '
3056 'GLint xoffset, GLint yoffset, '
3057 'GLsizei width, GLsizei height, '
3058 'GLenumTextureFormat format, GLenumPixelType type, '
3059 'const void* pixels, GLboolean internal'
3063 'data_transfer_methods': ['shm'],
3064 'client_test': False,
3065 'cmd_args': 'GLenumTextureTarget target, GLint level, '
3066 'GLint xoffset, GLint yoffset, GLint zoffset, '
3067 'GLsizei width, GLsizei height, GLsizei depth, '
3068 'GLenumTextureFormat format, GLenumPixelType type, '
3069 'const void* pixels, GLboolean internal',
3072 'TransformFeedbackVaryings': {
3074 'data_transfer_methods': ['bucket'],
3075 'decoder_func': 'DoTransformFeedbackVaryings',
3077 'GLuint program, const char** varyings, GLenum buffermode',
3080 'Uniform1f': {'type': 'PUTXn', 'count': 1},
3084 'decoder_func': 'DoUniform1fv',
3086 'Uniform1i': {'decoder_func': 'DoUniform1i', 'unit_test': False},
3090 'decoder_func': 'DoUniform1iv',
3103 'Uniform2i': {'type': 'PUTXn', 'count': 2},
3104 'Uniform2f': {'type': 'PUTXn', 'count': 2},
3108 'decoder_func': 'DoUniform2fv',
3113 'decoder_func': 'DoUniform2iv',
3125 'Uniform3i': {'type': 'PUTXn', 'count': 3},
3126 'Uniform3f': {'type': 'PUTXn', 'count': 3},
3130 'decoder_func': 'DoUniform3fv',
3135 'decoder_func': 'DoUniform3iv',
3147 'Uniform4i': {'type': 'PUTXn', 'count': 4},
3148 'Uniform4f': {'type': 'PUTXn', 'count': 4},
3152 'decoder_func': 'DoUniform4fv',
3157 'decoder_func': 'DoUniform4iv',
3169 'UniformMatrix2fv': {
3172 'decoder_func': 'DoUniformMatrix2fv',
3174 'UniformMatrix2x3fv': {
3179 'UniformMatrix2x4fv': {
3184 'UniformMatrix3fv': {
3187 'decoder_func': 'DoUniformMatrix3fv',
3189 'UniformMatrix3x2fv': {
3194 'UniformMatrix3x4fv': {
3199 'UniformMatrix4fv': {
3202 'decoder_func': 'DoUniformMatrix4fv',
3204 'UniformMatrix4x2fv': {
3209 'UniformMatrix4x3fv': {
3214 'UniformBlockBinding': {
3219 'UnmapBufferCHROMIUM': {
3223 'client_test': False,
3225 'UnmapBufferSubDataCHROMIUM': {
3229 'client_test': False,
3230 'pepper_interface': 'ChromiumMapSub',
3236 'UnmapTexSubImage2DCHROMIUM': {
3238 'extension': "CHROMIUM_sub_image",
3240 'client_test': False,
3241 'pepper_interface': 'ChromiumMapSub',
3245 'decoder_func': 'DoUseProgram',
3247 'ValidateProgram': {'decoder_func': 'DoValidateProgram'},
3248 'VertexAttrib1f': {'decoder_func': 'DoVertexAttrib1f'},
3249 'VertexAttrib1fv': {
3252 'decoder_func': 'DoVertexAttrib1fv',
3254 'VertexAttrib2f': {'decoder_func': 'DoVertexAttrib2f'},
3255 'VertexAttrib2fv': {
3258 'decoder_func': 'DoVertexAttrib2fv',
3260 'VertexAttrib3f': {'decoder_func': 'DoVertexAttrib3f'},
3261 'VertexAttrib3fv': {
3264 'decoder_func': 'DoVertexAttrib3fv',
3266 'VertexAttrib4f': {'decoder_func': 'DoVertexAttrib4f'},
3267 'VertexAttrib4fv': {
3270 'decoder_func': 'DoVertexAttrib4fv',
3272 'VertexAttribI4i': {
3275 'VertexAttribI4iv': {
3280 'VertexAttribI4ui': {
3283 'VertexAttribI4uiv': {
3288 'VertexAttribIPointer': {
3290 'cmd_args': 'GLuint indx, GLintVertexAttribSize size, '
3291 'GLenumVertexAttribIType type, GLsizei stride, '
3293 'client_test': False,
3296 'VertexAttribPointer': {
3298 'cmd_args': 'GLuint indx, GLintVertexAttribSize size, '
3299 'GLenumVertexAttribType type, GLboolean normalized, '
3300 'GLsizei stride, GLuint offset',
3301 'client_test': False,
3305 'cmd_args': 'GLuint sync, GLbitfieldSyncFlushFlags flags, '
3306 'GLuint timeout_0, GLuint timeout_1',
3308 'client_test': False,
3316 'decoder_func': 'DoViewport',
3325 'GetRequestableExtensionsCHROMIUM': {
3328 'cmd_args': 'uint32_t bucket_id',
3332 'RequestExtensionCHROMIUM': {
3335 'client_test': False,
3336 'cmd_args': 'uint32_t bucket_id',
3340 'RateLimitOffscreenContextCHROMIUM': {
3344 'client_test': False,
3346 'CreateStreamTextureCHROMIUM': {
3347 'type': 'HandWritten',
3353 'TexImageIOSurface2DCHROMIUM': {
3354 'decoder_func': 'DoTexImageIOSurface2DCHROMIUM',
3359 'CopyTextureCHROMIUM': {
3360 'decoder_func': 'DoCopyTextureCHROMIUM',
3365 'CopySubTextureCHROMIUM': {
3366 'decoder_func': 'DoCopySubTextureCHROMIUM',
3371 'TexStorage2DEXT': {
3374 'decoder_func': 'DoTexStorage2DEXT',
3376 'DrawArraysInstancedANGLE': {
3378 'cmd_args': 'GLenumDrawMode mode, GLint first, GLsizei count, '
3379 'GLsizei primcount',
3382 'pepper_interface': 'InstancedArrays',
3383 'defer_draws': True,
3387 'decoder_func': 'DoDrawBuffersEXT',
3389 'client_test': False,
3391 # could use 'extension_flag': 'ext_draw_buffers' but currently expected to
3394 'pepper_interface': 'DrawBuffers',
3396 'DrawElementsInstancedANGLE': {
3398 'cmd_args': 'GLenumDrawMode mode, GLsizei count, '
3399 'GLenumIndexType type, GLuint index_offset, GLsizei primcount',
3402 'client_test': False,
3403 'pepper_interface': 'InstancedArrays',
3404 'defer_draws': True,
3406 'VertexAttribDivisorANGLE': {
3408 'cmd_args': 'GLuint index, GLuint divisor',
3411 'pepper_interface': 'InstancedArrays',
3415 'gl_test_func': 'glGenQueriesARB',
3416 'resource_type': 'Query',
3417 'resource_types': 'Queries',
3419 'pepper_interface': 'Query',
3420 'not_shared': 'True',
3421 'extension': "occlusion_query_EXT",
3423 'DeleteQueriesEXT': {
3425 'gl_test_func': 'glDeleteQueriesARB',
3426 'resource_type': 'Query',
3427 'resource_types': 'Queries',
3429 'pepper_interface': 'Query',
3430 'extension': "occlusion_query_EXT",
3434 'client_test': False,
3435 'pepper_interface': 'Query',
3436 'extension': "occlusion_query_EXT",
3440 'cmd_args': 'GLenumQueryTarget target, GLidQuery id, void* sync_data',
3441 'data_transfer_methods': ['shm'],
3442 'gl_test_func': 'glBeginQuery',
3443 'pepper_interface': 'Query',
3444 'extension': "occlusion_query_EXT",
3446 'BeginTransformFeedback': {
3451 'cmd_args': 'GLenumQueryTarget target, GLuint submit_count',
3452 'gl_test_func': 'glEndnQuery',
3453 'client_test': False,
3454 'pepper_interface': 'Query',
3455 'extension': "occlusion_query_EXT",
3457 'EndTransformFeedback': {
3462 'client_test': False,
3463 'gl_test_func': 'glGetQueryiv',
3464 'pepper_interface': 'Query',
3465 'extension': "occlusion_query_EXT",
3467 'GetQueryObjectuivEXT': {
3469 'client_test': False,
3470 'gl_test_func': 'glGetQueryObjectuiv',
3471 'pepper_interface': 'Query',
3472 'extension': "occlusion_query_EXT",
3474 'BindUniformLocationCHROMIUM': {
3477 'data_transfer_methods': ['bucket'],
3479 'gl_test_func': 'DoBindUniformLocationCHROMIUM',
3481 'InsertEventMarkerEXT': {
3483 'decoder_func': 'DoInsertEventMarkerEXT',
3484 'expectation': False,
3487 'PushGroupMarkerEXT': {
3489 'decoder_func': 'DoPushGroupMarkerEXT',
3490 'expectation': False,
3493 'PopGroupMarkerEXT': {
3494 'decoder_func': 'DoPopGroupMarkerEXT',
3495 'expectation': False,
3500 'GenVertexArraysOES': {
3503 'gl_test_func': 'glGenVertexArraysOES',
3504 'resource_type': 'VertexArray',
3505 'resource_types': 'VertexArrays',
3507 'pepper_interface': 'VertexArrayObject',
3509 'BindVertexArrayOES': {
3512 'gl_test_func': 'glBindVertexArrayOES',
3513 'decoder_func': 'DoBindVertexArrayOES',
3514 'gen_func': 'GenVertexArraysOES',
3516 'client_test': False,
3517 'pepper_interface': 'VertexArrayObject',
3519 'DeleteVertexArraysOES': {
3522 'gl_test_func': 'glDeleteVertexArraysOES',
3523 'resource_type': 'VertexArray',
3524 'resource_types': 'VertexArrays',
3526 'pepper_interface': 'VertexArrayObject',
3528 'IsVertexArrayOES': {
3531 'gl_test_func': 'glIsVertexArrayOES',
3532 'decoder_func': 'DoIsVertexArrayOES',
3533 'expectation': False,
3535 'pepper_interface': 'VertexArrayObject',
3537 'BindTexImage2DCHROMIUM': {
3538 'decoder_func': 'DoBindTexImage2DCHROMIUM',
3543 'ReleaseTexImage2DCHROMIUM': {
3544 'decoder_func': 'DoReleaseTexImage2DCHROMIUM',
3549 'ShallowFinishCHROMIUM': {
3554 'client_test': False,
3556 'ShallowFlushCHROMIUM': {
3559 'extension': "CHROMIUM_miscellaneous",
3561 'client_test': False,
3563 'OrderingBarrierCHROMIUM': {
3568 'client_test': False,
3570 'TraceBeginCHROMIUM': {
3573 'client_test': False,
3574 'cmd_args': 'GLuint category_bucket_id, GLuint name_bucket_id',
3578 'TraceEndCHROMIUM': {
3580 'client_test': False,
3581 'decoder_func': 'DoTraceEndCHROMIUM',
3586 'AsyncTexImage2DCHROMIUM': {
3588 'data_transfer_methods': ['shm'],
3589 'client_test': False,
3590 'cmd_args': 'GLenumTextureTarget target, GLint level, '
3591 'GLintTextureInternalFormat internalformat, '
3592 'GLsizei width, GLsizei height, '
3593 'GLintTextureBorder border, '
3594 'GLenumTextureFormat format, GLenumPixelType type, '
3595 'const void* pixels, '
3596 'uint32_t async_upload_token, '
3601 'AsyncTexSubImage2DCHROMIUM': {
3603 'data_transfer_methods': ['shm'],
3604 'client_test': False,
3605 'cmd_args': 'GLenumTextureTarget target, GLint level, '
3606 'GLint xoffset, GLint yoffset, '
3607 'GLsizei width, GLsizei height, '
3608 'GLenumTextureFormat format, GLenumPixelType type, '
3609 'const void* data, '
3610 'uint32_t async_upload_token, '
3615 'WaitAsyncTexImage2DCHROMIUM': {
3617 'client_test': False,
3621 'WaitAllAsyncTexImage2DCHROMIUM': {
3623 'client_test': False,
3627 'DiscardFramebufferEXT': {
3630 'decoder_func': 'DoDiscardFramebufferEXT',
3632 'client_test': False,
3633 'extension_flag': 'ext_discard_framebuffer',
3635 'LoseContextCHROMIUM': {
3636 'decoder_func': 'DoLoseContextCHROMIUM',
3641 'InsertSyncPointCHROMIUM': {
3642 'type': 'HandWritten',
3644 'extension': "CHROMIUM_sync_point",
3647 'WaitSyncPointCHROMIUM': {
3650 'extension': "CHROMIUM_sync_point",
3654 'DiscardBackbufferCHROMIUM': {
3660 'ScheduleOverlayPlaneCHROMIUM': {
3664 'client_test': False,
3668 'MatrixLoadfCHROMIUM': {
3671 'data_type': 'GLfloat',
3672 'decoder_func': 'DoMatrixLoadfCHROMIUM',
3673 'gl_test_func': 'glMatrixLoadfEXT',
3676 'extension_flag': 'chromium_path_rendering',
3678 'MatrixLoadIdentityCHROMIUM': {
3679 'decoder_func': 'DoMatrixLoadIdentityCHROMIUM',
3680 'gl_test_func': 'glMatrixLoadIdentityEXT',
3683 'extension_flag': 'chromium_path_rendering',
3688 def Grouper(n
, iterable
, fillvalue
=None):
3689 """Collect data into fixed-length chunks or blocks"""
3690 args
= [iter(iterable
)] * n
3691 return itertools
.izip_longest(fillvalue
=fillvalue
, *args
)
3694 def SplitWords(input_string
):
3695 """Transforms a input_string into a list of lower-case components.
3698 input_string: the input string.
3701 a list of lower-case words.
3703 if input_string
.find('_') > -1:
3704 # 'some_TEXT_' -> 'some text'
3705 return input_string
.replace('_', ' ').strip().lower().split()
3707 if re
.search('[A-Z]', input_string
) and re
.search('[a-z]', input_string
):
3709 # look for capitalization to cut input_strings
3710 # 'SomeText' -> 'Some Text'
3711 input_string
= re
.sub('([A-Z])', r
' \1', input_string
).strip()
3712 # 'Vector3' -> 'Vector 3'
3713 input_string
= re
.sub('([^0-9])([0-9])', r
'\1 \2', input_string
)
3714 return input_string
.lower().split()
3718 """Makes a lower-case identifier from words.
3721 words: a list of lower-case words.
3724 the lower-case identifier.
3726 return '_'.join(words
)
3729 def ToUnderscore(input_string
):
3730 """converts CamelCase to camel_case."""
3731 words
= SplitWords(input_string
)
3734 def CachedStateName(item
):
3735 if item
.get('cached', False):
3736 return 'cached_' + item
['name']
3739 def ToGLExtensionString(extension_flag
):
3740 """Returns GL-type extension string of a extension flag."""
3741 if extension_flag
== "oes_compressed_etc1_rgb8_texture":
3742 return "OES_compressed_ETC1_RGB8_texture" # Fixup inconsitency with rgb8,
3744 uppercase_words
= [ 'img', 'ext', 'arb', 'chromium', 'oes', 'amd', 'bgra8888',
3745 'egl', 'atc', 'etc1', 'angle']
3746 parts
= extension_flag
.split('_')
3748 [part
.upper() if part
in uppercase_words
else part
for part
in parts
])
3750 def ToCamelCase(input_string
):
3751 """converts ABC_underscore_case to ABCUnderscoreCase."""
3752 return ''.join(w
[0].upper() + w
[1:] for w
in input_string
.split('_'))
3754 def GetGLGetTypeConversion(result_type
, value_type
, value
):
3755 """Makes a gl compatible type conversion string for accessing state variables.
3757 Useful when accessing state variables through glGetXXX calls.
3758 glGet documetation (for example, the manual pages):
3759 [...] If glGetIntegerv is called, [...] most floating-point values are
3760 rounded to the nearest integer value. [...]
3763 result_type: the gl type to be obtained
3764 value_type: the GL type of the state variable
3765 value: the name of the state variable
3768 String that converts the state variable to desired GL type according to GL
3772 if result_type
== 'GLint':
3773 if value_type
== 'GLfloat':
3774 return 'static_cast<GLint>(round(%s))' % value
3775 return 'static_cast<%s>(%s)' % (result_type
, value
)
3777 class CWriter(object):
3778 """Writes to a file formatting it for Google's style guidelines."""
3780 def __init__(self
, filename
):
3781 self
.filename
= filename
3784 def Write(self
, string
):
3785 """Writes a string to a file spliting if it's > 80 characters."""
3786 lines
= string
.splitlines()
3787 num_lines
= len(lines
)
3788 for ii
in range(0, num_lines
):
3789 self
.content
.append(lines
[ii
])
3790 if ii
< (num_lines
- 1) or string
[-1] == '\n':
3791 self
.content
.append('\n')
3794 """Close the file."""
3795 content
= "".join(self
.content
)
3797 if os
.path
.exists(self
.filename
):
3798 old_file
= open(self
.filename
, "rb");
3799 old_content
= old_file
.read()
3801 if content
== old_content
:
3804 file = open(self
.filename
, "wb")
3809 class CHeaderWriter(CWriter
):
3810 """Writes a C Header file."""
3812 _non_alnum_re
= re
.compile(r
'[^a-zA-Z0-9]')
3814 def __init__(self
, filename
, file_comment
= None):
3815 CWriter
.__init
__(self
, filename
)
3817 base
= os
.path
.abspath(filename
)
3818 while os
.path
.basename(base
) != 'src':
3819 new_base
= os
.path
.dirname(base
)
3820 assert new_base
!= base
# Prevent infinite loop.
3823 hpath
= os
.path
.relpath(filename
, base
)
3824 self
.guard
= self
._non
_alnum
_re
.sub('_', hpath
).upper() + '_'
3826 self
.Write(_LICENSE
)
3827 self
.Write(_DO_NOT_EDIT_WARNING
)
3828 if not file_comment
== None:
3829 self
.Write(file_comment
)
3830 self
.Write("#ifndef %s\n" % self
.guard
)
3831 self
.Write("#define %s\n\n" % self
.guard
)
3834 self
.Write("#endif // %s\n\n" % self
.guard
)
3837 class TypeHandler(object):
3838 """This class emits code for a particular type of function."""
3840 _remove_expected_call_re
= re
.compile(r
' EXPECT_CALL.*?;\n', re
.S
)
3845 def InitFunction(self
, func
):
3846 """Add or adjust anything type specific for this function."""
3847 if func
.GetInfo('needs_size') and not func
.name
.endswith('Bucket'):
3848 func
.AddCmdArg(DataSizeArgument('data_size'))
3850 def NeedsDataTransferFunction(self
, func
):
3851 """Overriden from TypeHandler."""
3852 return func
.num_pointer_args
>= 1
3854 def WriteStruct(self
, func
, file):
3855 """Writes a structure that matches the arguments to a function."""
3856 comment
= func
.GetInfo('cmd_comment')
3857 if not comment
== None:
3859 file.Write("struct %s {\n" % func
.name
)
3860 file.Write(" typedef %s ValueType;\n" % func
.name
)
3861 file.Write(" static const CommandId kCmdId = k%s;\n" % func
.name
)
3862 func
.WriteCmdArgFlag(file)
3863 func
.WriteCmdFlag(file)
3865 result
= func
.GetInfo('result')
3866 if not result
== None:
3867 if len(result
) == 1:
3868 file.Write(" typedef %s Result;\n\n" % result
[0])
3870 file.Write(" struct Result {\n")
3872 file.Write(" %s;\n" % line
)
3873 file.Write(" };\n\n")
3875 func
.WriteCmdComputeSize(file)
3876 func
.WriteCmdSetHeader(file)
3877 func
.WriteCmdInit(file)
3878 func
.WriteCmdSet(file)
3880 file.Write(" gpu::CommandHeader header;\n")
3881 args
= func
.GetCmdArgs()
3883 file.Write(" %s %s;\n" % (arg
.cmd_type
, arg
.name
))
3885 consts
= func
.GetCmdConstants()
3886 for const
in consts
:
3887 file.Write(" static const %s %s = %s;\n" %
3888 (const
.cmd_type
, const
.name
, const
.GetConstantValue()))
3893 size
= len(args
) * _SIZE_OF_UINT32
+ _SIZE_OF_COMMAND_HEADER
3894 file.Write("static_assert(sizeof(%s) == %d,\n" % (func
.name
, size
))
3895 file.Write(" \"size of %s should be %d\");\n" %
3897 file.Write("static_assert(offsetof(%s, header) == 0,\n" % func
.name
)
3898 file.Write(" \"offset of %s header should be 0\");\n" %
3900 offset
= _SIZE_OF_COMMAND_HEADER
3902 file.Write("static_assert(offsetof(%s, %s) == %d,\n" %
3903 (func
.name
, arg
.name
, offset
))
3904 file.Write(" \"offset of %s %s should be %d\");\n" %
3905 (func
.name
, arg
.name
, offset
))
3906 offset
+= _SIZE_OF_UINT32
3907 if not result
== None and len(result
) > 1:
3910 parts
= line
.split()
3913 static_assert(offsetof(%(cmd_name)s::Result, %(field_name)s) == %(offset)d,
3914 "offset of %(cmd_name)s Result %(field_name)s should be "
3917 file.Write((check
.strip() + "\n") % {
3918 'cmd_name': func
.name
,
3922 offset
+= _SIZE_OF_UINT32
3925 def WriteHandlerImplementation(self
, func
, file):
3926 """Writes the handler implementation for this command."""
3927 if func
.IsUnsafe() and func
.GetInfo('id_mapping'):
3928 code_no_gen
= """ if (!group_->Get%(type)sServiceId(
3929 %(var)s, &%(service_var)s)) {
3930 LOCAL_SET_GL_ERROR(GL_INVALID_OPERATION, "%(func)s", "invalid %(var)s id");
3931 return error::kNoError;
3934 code_gen
= """ if (!group_->Get%(type)sServiceId(
3935 %(var)s, &%(service_var)s)) {
3936 if (!group_->bind_generates_resource()) {
3938 GL_INVALID_OPERATION, "%(func)s", "invalid %(var)s id");
3939 return error::kNoError;
3941 GLuint client_id = %(var)s;
3942 gl%(gen_func)s(1, &%(service_var)s);
3943 Create%(type)s(client_id, %(service_var)s);
3946 gen_func
= func
.GetInfo('gen_func')
3947 for id_type
in func
.GetInfo('id_mapping'):
3948 service_var
= id_type
.lower()
3949 if id_type
== 'Sync':
3950 service_var
= "service_%s" % service_var
3951 file.Write(" GLsync %s = 0;\n" % service_var
)
3952 if gen_func
and id_type
in gen_func
:
3953 file.Write(code_gen
% { 'type': id_type
,
3954 'var': id_type
.lower(),
3955 'service_var': service_var
,
3956 'func': func
.GetGLFunctionName(),
3957 'gen_func': gen_func
})
3959 file.Write(code_no_gen
% { 'type': id_type
,
3960 'var': id_type
.lower(),
3961 'service_var': service_var
,
3962 'func': func
.GetGLFunctionName() })
3964 for arg
in func
.GetOriginalArgs():
3965 if arg
.type == "GLsync":
3966 args
.append("service_%s" % arg
.name
)
3967 elif arg
.name
.endswith("size") and arg
.type == "GLsizei":
3968 args
.append("num_%s" % func
.GetLastOriginalArg().name
)
3969 elif arg
.name
== "length":
3970 args
.append("nullptr")
3972 args
.append(arg
.name
)
3973 file.Write(" %s(%s);\n" %
3974 (func
.GetGLFunctionName(), ", ".join(args
)))
3976 def WriteCmdSizeTest(self
, func
, file):
3977 """Writes the size test for a command."""
3978 file.Write(" EXPECT_EQ(sizeof(cmd), cmd.header.size * 4u);\n")
3980 def WriteFormatTest(self
, func
, file):
3981 """Writes a format test for a command."""
3982 file.Write("TEST_F(GLES2FormatTest, %s) {\n" % func
.name
)
3983 file.Write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
3984 (func
.name
, func
.name
))
3985 file.Write(" void* next_cmd = cmd.Set(\n")
3987 args
= func
.GetCmdArgs()
3988 for value
, arg
in enumerate(args
):
3989 file.Write(",\n static_cast<%s>(%d)" % (arg
.type, value
+ 11))
3991 file.Write(" EXPECT_EQ(static_cast<uint32_t>(cmds::%s::kCmdId),\n" %
3993 file.Write(" cmd.header.command);\n")
3994 func
.type_handler
.WriteCmdSizeTest(func
, file)
3995 for value
, arg
in enumerate(args
):
3996 file.Write(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);\n" %
3997 (arg
.type, value
+ 11, arg
.name
))
3998 file.Write(" CheckBytesWrittenMatchesExpectedSize(\n")
3999 file.Write(" next_cmd, sizeof(cmd));\n")
4003 def WriteImmediateFormatTest(self
, func
, file):
4004 """Writes a format test for an immediate version of a command."""
4007 def WriteBucketFormatTest(self
, func
, file):
4008 """Writes a format test for a bucket version of a command."""
4011 def WriteGetDataSizeCode(self
, func
, file):
4012 """Writes the code to set data_size used in validation"""
4015 def WriteImmediateCmdSizeTest(self
, func
, file):
4016 """Writes a size test for an immediate version of a command."""
4017 file.Write(" // TODO(gman): Compute correct size.\n")
4018 file.Write(" EXPECT_EQ(sizeof(cmd), cmd.header.size * 4u);\n")
4020 def __WriteIdMapping(self
, func
, file):
4021 """Writes client side / service side ID mapping."""
4022 if not func
.IsUnsafe() or not func
.GetInfo('id_mapping'):
4024 for id_type
in func
.GetInfo('id_mapping'):
4025 file.Write(" group_->Get%sServiceId(%s, &%s);\n" %
4026 (id_type
, id_type
.lower(), id_type
.lower()))
4028 def WriteImmediateHandlerImplementation (self
, func
, file):
4029 """Writes the handler impl for the immediate version of a command."""
4030 self
.__WriteIdMapping
(func
, file)
4031 file.Write(" %s(%s);\n" %
4032 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
4034 def WriteBucketHandlerImplementation (self
, func
, file):
4035 """Writes the handler impl for the bucket version of a command."""
4036 self
.__WriteIdMapping
(func
, file)
4037 file.Write(" %s(%s);\n" %
4038 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
4040 def WriteServiceHandlerFunctionHeader(self
, func
, file):
4041 """Writes function header for service implementation handlers."""
4042 file.Write("""error::Error GLES2DecoderImpl::Handle%(name)s(
4043 uint32_t immediate_data_size, const void* cmd_data) {
4044 """ % {'name': func
.name
})
4046 file.Write("""if (!unsafe_es3_apis_enabled())
4047 return error::kUnknownCommand;
4049 file.Write("""const gles2::cmds::%(name)s& c =
4050 *static_cast<const gles2::cmds::%(name)s*>(cmd_data);
4052 """ % {'name': func
.name
})
4054 def WriteServiceImplementation(self
, func
, file):
4055 """Writes the service implementation for a command."""
4056 self
.WriteServiceHandlerFunctionHeader(func
, file)
4057 self
.WriteHandlerExtensionCheck(func
, file)
4058 self
.WriteHandlerDeferReadWrite(func
, file);
4059 if len(func
.GetOriginalArgs()) > 0:
4060 last_arg
= func
.GetLastOriginalArg()
4061 all_but_last_arg
= func
.GetOriginalArgs()[:-1]
4062 for arg
in all_but_last_arg
:
4063 arg
.WriteGetCode(file)
4064 self
.WriteGetDataSizeCode(func
, file)
4065 last_arg
.WriteGetCode(file)
4066 func
.WriteHandlerValidation(file)
4067 func
.WriteHandlerImplementation(file)
4068 file.Write(" return error::kNoError;\n")
4072 def WriteImmediateServiceImplementation(self
, func
, file):
4073 """Writes the service implementation for an immediate version of command."""
4074 self
.WriteServiceHandlerFunctionHeader(func
, file)
4075 self
.WriteHandlerExtensionCheck(func
, file)
4076 self
.WriteHandlerDeferReadWrite(func
, file);
4077 for arg
in func
.GetOriginalArgs():
4079 self
.WriteGetDataSizeCode(func
, file)
4080 arg
.WriteGetCode(file)
4081 func
.WriteHandlerValidation(file)
4082 func
.WriteHandlerImplementation(file)
4083 file.Write(" return error::kNoError;\n")
4087 def WriteBucketServiceImplementation(self
, func
, file):
4088 """Writes the service implementation for a bucket version of command."""
4089 self
.WriteServiceHandlerFunctionHeader(func
, file)
4090 self
.WriteHandlerExtensionCheck(func
, file)
4091 self
.WriteHandlerDeferReadWrite(func
, file);
4092 for arg
in func
.GetCmdArgs():
4093 arg
.WriteGetCode(file)
4094 func
.WriteHandlerValidation(file)
4095 func
.WriteHandlerImplementation(file)
4096 file.Write(" return error::kNoError;\n")
4100 def WriteHandlerExtensionCheck(self
, func
, file):
4101 if func
.GetInfo('extension_flag'):
4102 file.Write(" if (!features().%s) {\n" % func
.GetInfo('extension_flag'))
4103 file.Write(" LOCAL_SET_GL_ERROR(GL_INVALID_OPERATION, \"gl%s\","
4104 " \"function not available\");\n" % func
.original_name
)
4105 file.Write(" return error::kNoError;")
4106 file.Write(" }\n\n")
4108 def WriteHandlerDeferReadWrite(self
, func
, file):
4109 """Writes the code to handle deferring reads or writes."""
4110 defer_draws
= func
.GetInfo('defer_draws')
4111 defer_reads
= func
.GetInfo('defer_reads')
4112 if defer_draws
or defer_reads
:
4113 file.Write(" error::Error error;\n")
4115 file.Write(" error = WillAccessBoundFramebufferForDraw();\n")
4116 file.Write(" if (error != error::kNoError)\n")
4117 file.Write(" return error;\n")
4119 file.Write(" error = WillAccessBoundFramebufferForRead();\n")
4120 file.Write(" if (error != error::kNoError)\n")
4121 file.Write(" return error;\n")
4123 def WriteValidUnitTest(self
, func
, file, test
, *extras
):
4124 """Writes a valid unit test for the service implementation."""
4125 if func
.GetInfo('expectation') == False:
4126 test
= self
._remove
_expected
_call
_re
.sub('', test
)
4129 arg
.GetValidArg(func
) \
4130 for arg
in func
.GetOriginalArgs() if not arg
.IsConstant()
4133 arg
.GetValidGLArg(func
) \
4134 for arg
in func
.GetOriginalArgs()
4136 gl_func_name
= func
.GetGLTestFunctionName()
4139 'gl_func_name': gl_func_name
,
4140 'args': ", ".join(arg_strings
),
4141 'gl_args': ", ".join(gl_arg_strings
),
4143 for extra
in extras
:
4146 while (old_test
!= test
):
4149 file.Write(test
% vars)
4151 def WriteInvalidUnitTest(self
, func
, file, test
, *extras
):
4152 """Writes an invalid unit test for the service implementation."""
4155 for invalid_arg_index
, invalid_arg
in enumerate(func
.GetOriginalArgs()):
4156 # Service implementation does not test constants, as they are not part of
4157 # the call in the service side.
4158 if invalid_arg
.IsConstant():
4161 num_invalid_values
= invalid_arg
.GetNumInvalidValues(func
)
4162 for value_index
in range(0, num_invalid_values
):
4164 parse_result
= "kNoError"
4166 for arg
in func
.GetOriginalArgs():
4167 if arg
.IsConstant():
4169 if invalid_arg
is arg
:
4170 (arg_string
, parse_result
, gl_error
) = arg
.GetInvalidArg(
4173 arg_string
= arg
.GetValidArg(func
)
4174 arg_strings
.append(arg_string
)
4176 for arg
in func
.GetOriginalArgs():
4177 gl_arg_strings
.append("_")
4178 gl_func_name
= func
.GetGLTestFunctionName()
4180 if not gl_error
== None:
4181 gl_error_test
= '\n EXPECT_EQ(%s, GetGLError());' % gl_error
4185 'arg_index': invalid_arg_index
,
4186 'value_index': value_index
,
4187 'gl_func_name': gl_func_name
,
4188 'args': ", ".join(arg_strings
),
4189 'all_but_last_args': ", ".join(arg_strings
[:-1]),
4190 'gl_args': ", ".join(gl_arg_strings
),
4191 'parse_result': parse_result
,
4192 'gl_error_test': gl_error_test
,
4194 for extra
in extras
:
4196 file.Write(test
% vars)
4198 def WriteServiceUnitTest(self
, func
, file, *extras
):
4199 """Writes the service unit test for a command."""
4201 if func
.name
== 'Enable':
4203 TEST_P(%(test_name)s, %(name)sValidArgs) {
4204 SetupExpectationsForEnableDisable(%(gl_args)s, true);
4205 SpecializedSetup<cmds::%(name)s, 0>(true);
4207 cmd.Init(%(args)s);"""
4208 elif func
.name
== 'Disable':
4210 TEST_P(%(test_name)s, %(name)sValidArgs) {
4211 SetupExpectationsForEnableDisable(%(gl_args)s, false);
4212 SpecializedSetup<cmds::%(name)s, 0>(true);
4214 cmd.Init(%(args)s);"""
4217 TEST_P(%(test_name)s, %(name)sValidArgs) {
4218 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
4219 SpecializedSetup<cmds::%(name)s, 0>(true);
4221 cmd.Init(%(args)s);"""
4224 decoder_->set_unsafe_es3_apis_enabled(true);
4225 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4226 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4227 decoder_->set_unsafe_es3_apis_enabled(false);
4228 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));
4233 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4234 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4237 self
.WriteValidUnitTest(func
, file, valid_test
, *extras
)
4239 if not func
.IsUnsafe():
4241 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
4242 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
4243 SpecializedSetup<cmds::%(name)s, 0>(false);
4246 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
4249 self
.WriteInvalidUnitTest(func
, file, invalid_test
, *extras
)
4251 def WriteImmediateServiceUnitTest(self
, func
, file, *extras
):
4252 """Writes the service unit test for an immediate command."""
4253 file.Write("// TODO(gman): %s\n" % func
.name
)
4255 def WriteImmediateValidationCode(self
, func
, file):
4256 """Writes the validation code for an immediate version of a command."""
4259 def WriteBucketServiceUnitTest(self
, func
, file, *extras
):
4260 """Writes the service unit test for a bucket command."""
4261 file.Write("// TODO(gman): %s\n" % func
.name
)
4263 def WriteBucketValidationCode(self
, func
, file):
4264 """Writes the validation code for a bucket version of a command."""
4265 file.Write("// TODO(gman): %s\n" % func
.name
)
4267 def WriteGLES2ImplementationDeclaration(self
, func
, file):
4268 """Writes the GLES2 Implemention declaration."""
4269 impl_decl
= func
.GetInfo('impl_decl')
4270 if impl_decl
== None or impl_decl
== True:
4271 file.Write("%s %s(%s) override;\n" %
4272 (func
.return_type
, func
.original_name
,
4273 func
.MakeTypedOriginalArgString("")))
4276 def WriteGLES2CLibImplementation(self
, func
, file):
4277 file.Write("%s GLES2%s(%s) {\n" %
4278 (func
.return_type
, func
.name
,
4279 func
.MakeTypedOriginalArgString("")))
4280 result_string
= "return "
4281 if func
.return_type
== "void":
4283 file.Write(" %sgles2::GetGLContext()->%s(%s);\n" %
4284 (result_string
, func
.original_name
,
4285 func
.MakeOriginalArgString("")))
4288 def WriteGLES2Header(self
, func
, file):
4289 """Writes a re-write macro for GLES"""
4290 file.Write("#define gl%s GLES2_GET_FUN(%s)\n" %(func
.name
, func
.name
))
4292 def WriteClientGLCallLog(self
, func
, file):
4293 """Writes a logging macro for the client side code."""
4295 if len(func
.GetOriginalArgs()):
4298 ' GPU_CLIENT_LOG("[" << GetLogPrefix() << "] gl%s("%s%s << ")");\n' %
4299 (func
.original_name
, comma
, func
.MakeLogArgString()))
4301 def WriteClientGLReturnLog(self
, func
, file):
4302 """Writes the return value logging code."""
4303 if func
.return_type
!= "void":
4304 file.Write(' GPU_CLIENT_LOG("return:" << result)\n')
4306 def WriteGLES2ImplementationHeader(self
, func
, file):
4307 """Writes the GLES2 Implemention."""
4308 self
.WriteGLES2ImplementationDeclaration(func
, file)
4310 def WriteGLES2TraceImplementationHeader(self
, func
, file):
4311 """Writes the GLES2 Trace Implemention header."""
4312 file.Write("%s %s(%s) override;\n" %
4313 (func
.return_type
, func
.original_name
,
4314 func
.MakeTypedOriginalArgString("")))
4316 def WriteGLES2TraceImplementation(self
, func
, file):
4317 """Writes the GLES2 Trace Implemention."""
4318 file.Write("%s GLES2TraceImplementation::%s(%s) {\n" %
4319 (func
.return_type
, func
.original_name
,
4320 func
.MakeTypedOriginalArgString("")))
4321 result_string
= "return "
4322 if func
.return_type
== "void":
4324 file.Write(' TRACE_EVENT_BINARY_EFFICIENT0("gpu", "GLES2Trace::%s");\n' %
4326 file.Write(" %sgl_->%s(%s);\n" %
4327 (result_string
, func
.name
, func
.MakeOriginalArgString("")))
4331 def WriteGLES2Implementation(self
, func
, file):
4332 """Writes the GLES2 Implemention."""
4333 impl_func
= func
.GetInfo('impl_func')
4334 impl_decl
= func
.GetInfo('impl_decl')
4335 gen_cmd
= func
.GetInfo('gen_cmd')
4336 if (func
.can_auto_generate
and
4337 (impl_func
== None or impl_func
== True) and
4338 (impl_decl
== None or impl_decl
== True) and
4339 (gen_cmd
== None or gen_cmd
== True)):
4340 file.Write("%s GLES2Implementation::%s(%s) {\n" %
4341 (func
.return_type
, func
.original_name
,
4342 func
.MakeTypedOriginalArgString("")))
4343 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
4344 self
.WriteClientGLCallLog(func
, file)
4345 func
.WriteDestinationInitalizationValidation(file)
4346 for arg
in func
.GetOriginalArgs():
4347 arg
.WriteClientSideValidationCode(file, func
)
4348 file.Write(" helper_->%s(%s);\n" %
4349 (func
.name
, func
.MakeHelperArgString("")))
4350 file.Write(" CheckGLError();\n")
4351 self
.WriteClientGLReturnLog(func
, file)
4355 def WriteGLES2InterfaceHeader(self
, func
, file):
4356 """Writes the GLES2 Interface."""
4357 file.Write("virtual %s %s(%s) = 0;\n" %
4358 (func
.return_type
, func
.original_name
,
4359 func
.MakeTypedOriginalArgString("")))
4361 def WriteMojoGLES2ImplHeader(self
, func
, file):
4362 """Writes the Mojo GLES2 implementation header."""
4363 file.Write("%s %s(%s) override;\n" %
4364 (func
.return_type
, func
.original_name
,
4365 func
.MakeTypedOriginalArgString("")))
4367 def WriteMojoGLES2Impl(self
, func
, file):
4368 """Writes the Mojo GLES2 implementation."""
4369 file.Write("%s MojoGLES2Impl::%s(%s) {\n" %
4370 (func
.return_type
, func
.original_name
,
4371 func
.MakeTypedOriginalArgString("")))
4372 extensions
= ["CHROMIUM_sync_point", "CHROMIUM_texture_mailbox",
4373 "CHROMIUM_sub_image", "CHROMIUM_miscellaneous",
4374 "occlusion_query_EXT"]
4375 if func
.IsCoreGLFunction() or func
.GetInfo("extension") in extensions
:
4376 file.Write("MojoGLES2MakeCurrent(context_);");
4377 func_return
= "gl" + func
.original_name
+ "(" + \
4378 func
.MakeOriginalArgString("") + ");"
4379 if func
.return_type
== "void":
4380 file.Write(func_return
);
4382 file.Write("return " + func_return
);
4384 file.Write("NOTREACHED() << \"Unimplemented %s.\";\n" %
4385 func
.original_name
);
4386 if func
.return_type
!= "void":
4387 file.Write("return 0;")
4390 def WriteGLES2InterfaceStub(self
, func
, file):
4391 """Writes the GLES2 Interface stub declaration."""
4392 file.Write("%s %s(%s) override;\n" %
4393 (func
.return_type
, func
.original_name
,
4394 func
.MakeTypedOriginalArgString("")))
4396 def WriteGLES2InterfaceStubImpl(self
, func
, file):
4397 """Writes the GLES2 Interface stub declaration."""
4398 args
= func
.GetOriginalArgs()
4399 arg_string
= ", ".join(
4400 ["%s /* %s */" % (arg
.type, arg
.name
) for arg
in args
])
4401 file.Write("%s GLES2InterfaceStub::%s(%s) {\n" %
4402 (func
.return_type
, func
.original_name
, arg_string
))
4403 if func
.return_type
!= "void":
4404 file.Write(" return 0;\n")
4407 def WriteGLES2ImplementationUnitTest(self
, func
, file):
4408 """Writes the GLES2 Implemention unit test."""
4409 client_test
= func
.GetInfo('client_test')
4410 if (func
.can_auto_generate
and
4411 (client_test
== None or client_test
== True)):
4413 TEST_F(GLES2ImplementationTest, %(name)s) {
4418 expected.cmd.Init(%(cmd_args)s);
4420 gl_->%(name)s(%(args)s);
4421 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
4425 arg
.GetValidClientSideCmdArg(func
) for arg
in func
.GetCmdArgs()
4429 arg
.GetValidClientSideArg(func
) for arg
in func
.GetOriginalArgs()
4434 'args': ", ".join(gl_arg_strings
),
4435 'cmd_args': ", ".join(cmd_arg_strings
),
4438 # Test constants for invalid values, as they are not tested by the
4440 constants
= [arg
for arg
in func
.GetOriginalArgs() if arg
.IsConstant()]
4443 TEST_F(GLES2ImplementationTest, %(name)sInvalidConstantArg%(invalid_index)d) {
4444 gl_->%(name)s(%(args)s);
4445 EXPECT_TRUE(NoCommandsWritten());
4446 EXPECT_EQ(%(gl_error)s, CheckError());
4449 for invalid_arg
in constants
:
4451 invalid
= invalid_arg
.GetInvalidArg(func
)
4452 for arg
in func
.GetOriginalArgs():
4453 if arg
is invalid_arg
:
4454 gl_arg_strings
.append(invalid
[0])
4456 gl_arg_strings
.append(arg
.GetValidClientSideArg(func
))
4460 'invalid_index': func
.GetOriginalArgs().index(invalid_arg
),
4461 'args': ", ".join(gl_arg_strings
),
4462 'gl_error': invalid
[2],
4465 if client_test
!= False:
4466 file.Write("// TODO(zmo): Implement unit test for %s\n" % func
.name
)
4468 def WriteDestinationInitalizationValidation(self
, func
, file):
4469 """Writes the client side destintion initialization validation."""
4470 for arg
in func
.GetOriginalArgs():
4471 arg
.WriteDestinationInitalizationValidation(file, func
)
4473 def WriteTraceEvent(self
, func
, file):
4474 file.Write(' TRACE_EVENT0("gpu", "GLES2Implementation::%s");\n' %
4477 def WriteImmediateCmdComputeSize(self
, func
, file):
4478 """Writes the size computation code for the immediate version of a cmd."""
4479 file.Write(" static uint32_t ComputeSize(uint32_t size_in_bytes) {\n")
4480 file.Write(" return static_cast<uint32_t>(\n")
4481 file.Write(" sizeof(ValueType) + // NOLINT\n")
4482 file.Write(" RoundSizeToMultipleOfEntries(size_in_bytes));\n")
4486 def WriteImmediateCmdSetHeader(self
, func
, file):
4487 """Writes the SetHeader function for the immediate version of a cmd."""
4488 file.Write(" void SetHeader(uint32_t size_in_bytes) {\n")
4489 file.Write(" header.SetCmdByTotalSize<ValueType>(size_in_bytes);\n")
4493 def WriteImmediateCmdInit(self
, func
, file):
4494 """Writes the Init function for the immediate version of a command."""
4495 raise NotImplementedError(func
.name
)
4497 def WriteImmediateCmdSet(self
, func
, file):
4498 """Writes the Set function for the immediate version of a command."""
4499 raise NotImplementedError(func
.name
)
4501 def WriteCmdHelper(self
, func
, file):
4502 """Writes the cmd helper definition for a cmd."""
4503 code
= """ void %(name)s(%(typed_args)s) {
4504 gles2::cmds::%(name)s* c = GetCmdSpace<gles2::cmds::%(name)s>();
4513 "typed_args": func
.MakeTypedCmdArgString(""),
4514 "args": func
.MakeCmdArgString(""),
4517 def WriteImmediateCmdHelper(self
, func
, file):
4518 """Writes the cmd helper definition for the immediate version of a cmd."""
4519 code
= """ void %(name)s(%(typed_args)s) {
4520 const uint32_t s = 0; // TODO(gman): compute correct size
4521 gles2::cmds::%(name)s* c =
4522 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(s);
4531 "typed_args": func
.MakeTypedCmdArgString(""),
4532 "args": func
.MakeCmdArgString(""),
4536 class StateSetHandler(TypeHandler
):
4537 """Handler for commands that simply set state."""
4540 TypeHandler
.__init
__(self
)
4542 def WriteHandlerImplementation(self
, func
, file):
4543 """Overrriden from TypeHandler."""
4544 state_name
= func
.GetInfo('state')
4545 state
= _STATES
[state_name
]
4546 states
= state
['states']
4547 args
= func
.GetOriginalArgs()
4548 for ndx
,item
in enumerate(states
):
4550 if 'range_checks' in item
:
4551 for range_check
in item
['range_checks']:
4552 code
.append("%s %s" % (args
[ndx
].name
, range_check
['check']))
4553 if 'nan_check' in item
:
4554 # Drivers might generate an INVALID_VALUE error when a value is set
4555 # to NaN. This is allowed behavior under GLES 3.0 section 2.1.1 or
4556 # OpenGL 4.5 section 2.3.4.1 - providing NaN allows undefined results.
4557 # Make this behavior consistent within Chromium, and avoid leaking GL
4558 # errors by generating the error in the command buffer instead of
4559 # letting the GL driver generate it.
4560 code
.append("std::isnan(%s)" % args
[ndx
].name
)
4562 file.Write(" if (%s) {\n" % " ||\n ".join(code
))
4564 ' LOCAL_SET_GL_ERROR(GL_INVALID_VALUE,'
4565 ' "%s", "%s out of range");\n' %
4566 (func
.name
, args
[ndx
].name
))
4567 file.Write(" return error::kNoError;\n")
4570 for ndx
,item
in enumerate(states
):
4571 code
.append("state_.%s != %s" % (item
['name'], args
[ndx
].name
))
4572 file.Write(" if (%s) {\n" % " ||\n ".join(code
))
4573 for ndx
,item
in enumerate(states
):
4574 file.Write(" state_.%s = %s;\n" % (item
['name'], args
[ndx
].name
))
4575 if 'state_flag' in state
:
4576 file.Write(" %s = true;\n" % state
['state_flag'])
4577 if not func
.GetInfo("no_gl"):
4578 for ndx
,item
in enumerate(states
):
4579 if item
.get('cached', False):
4580 file.Write(" state_.%s = %s;\n" %
4581 (CachedStateName(item
), args
[ndx
].name
))
4582 file.Write(" %s(%s);\n" %
4583 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
4586 def WriteServiceUnitTest(self
, func
, file, *extras
):
4587 """Overrriden from TypeHandler."""
4588 TypeHandler
.WriteServiceUnitTest(self
, func
, file, *extras
)
4589 state_name
= func
.GetInfo('state')
4590 state
= _STATES
[state_name
]
4591 states
= state
['states']
4592 for ndx
,item
in enumerate(states
):
4593 if 'range_checks' in item
:
4594 for check_ndx
, range_check
in enumerate(item
['range_checks']):
4596 TEST_P(%(test_name)s, %(name)sInvalidValue%(ndx)d_%(check_ndx)d) {
4597 SpecializedSetup<cmds::%(name)s, 0>(false);
4600 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4601 EXPECT_EQ(GL_INVALID_VALUE, GetGLError());
4606 arg
.GetValidArg(func
) \
4607 for arg
in func
.GetOriginalArgs() if not arg
.IsConstant()
4610 arg_strings
[ndx
] = range_check
['test_value']
4614 'check_ndx': check_ndx
,
4615 'args': ", ".join(arg_strings
),
4617 for extra
in extras
:
4619 file.Write(valid_test
% vars)
4620 if 'nan_check' in item
:
4622 TEST_P(%(test_name)s, %(name)sNaNValue%(ndx)d) {
4623 SpecializedSetup<cmds::%(name)s, 0>(false);
4626 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4627 EXPECT_EQ(GL_INVALID_VALUE, GetGLError());
4632 arg
.GetValidArg(func
) \
4633 for arg
in func
.GetOriginalArgs() if not arg
.IsConstant()
4636 arg_strings
[ndx
] = 'nanf("")'
4640 'args': ", ".join(arg_strings
),
4642 for extra
in extras
:
4644 file.Write(valid_test
% vars)
4647 class StateSetRGBAlphaHandler(TypeHandler
):
4648 """Handler for commands that simply set state that have rgb/alpha."""
4651 TypeHandler
.__init
__(self
)
4653 def WriteHandlerImplementation(self
, func
, file):
4654 """Overrriden from TypeHandler."""
4655 state_name
= func
.GetInfo('state')
4656 state
= _STATES
[state_name
]
4657 states
= state
['states']
4658 args
= func
.GetOriginalArgs()
4659 num_args
= len(args
)
4661 for ndx
,item
in enumerate(states
):
4662 code
.append("state_.%s != %s" % (item
['name'], args
[ndx
% num_args
].name
))
4663 file.Write(" if (%s) {\n" % " ||\n ".join(code
))
4664 for ndx
, item
in enumerate(states
):
4665 file.Write(" state_.%s = %s;\n" %
4666 (item
['name'], args
[ndx
% num_args
].name
))
4667 if 'state_flag' in state
:
4668 file.Write(" %s = true;\n" % state
['state_flag'])
4669 if not func
.GetInfo("no_gl"):
4670 file.Write(" %s(%s);\n" %
4671 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
4675 class StateSetFrontBackSeparateHandler(TypeHandler
):
4676 """Handler for commands that simply set state that have front/back."""
4679 TypeHandler
.__init
__(self
)
4681 def WriteHandlerImplementation(self
, func
, file):
4682 """Overrriden from TypeHandler."""
4683 state_name
= func
.GetInfo('state')
4684 state
= _STATES
[state_name
]
4685 states
= state
['states']
4686 args
= func
.GetOriginalArgs()
4688 num_args
= len(args
)
4689 file.Write(" bool changed = false;\n")
4690 for group_ndx
, group
in enumerate(Grouper(num_args
- 1, states
)):
4691 file.Write(" if (%s == %s || %s == GL_FRONT_AND_BACK) {\n" %
4692 (face
, ('GL_FRONT', 'GL_BACK')[group_ndx
], face
))
4694 for ndx
, item
in enumerate(group
):
4695 code
.append("state_.%s != %s" % (item
['name'], args
[ndx
+ 1].name
))
4696 file.Write(" changed |= %s;\n" % " ||\n ".join(code
))
4698 file.Write(" if (changed) {\n")
4699 for group_ndx
, group
in enumerate(Grouper(num_args
- 1, states
)):
4700 file.Write(" if (%s == %s || %s == GL_FRONT_AND_BACK) {\n" %
4701 (face
, ('GL_FRONT', 'GL_BACK')[group_ndx
], face
))
4702 for ndx
, item
in enumerate(group
):
4703 file.Write(" state_.%s = %s;\n" %
4704 (item
['name'], args
[ndx
+ 1].name
))
4706 if 'state_flag' in state
:
4707 file.Write(" %s = true;\n" % state
['state_flag'])
4708 if not func
.GetInfo("no_gl"):
4709 file.Write(" %s(%s);\n" %
4710 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
4714 class StateSetFrontBackHandler(TypeHandler
):
4715 """Handler for commands that simply set state that set both front/back."""
4718 TypeHandler
.__init
__(self
)
4720 def WriteHandlerImplementation(self
, func
, file):
4721 """Overrriden from TypeHandler."""
4722 state_name
= func
.GetInfo('state')
4723 state
= _STATES
[state_name
]
4724 states
= state
['states']
4725 args
= func
.GetOriginalArgs()
4726 num_args
= len(args
)
4728 for group_ndx
, group
in enumerate(Grouper(num_args
, states
)):
4729 for ndx
, item
in enumerate(group
):
4730 code
.append("state_.%s != %s" % (item
['name'], args
[ndx
].name
))
4731 file.Write(" if (%s) {\n" % " ||\n ".join(code
))
4732 for group_ndx
, group
in enumerate(Grouper(num_args
, states
)):
4733 for ndx
, item
in enumerate(group
):
4734 file.Write(" state_.%s = %s;\n" % (item
['name'], args
[ndx
].name
))
4735 if 'state_flag' in state
:
4736 file.Write(" %s = true;\n" % state
['state_flag'])
4737 if not func
.GetInfo("no_gl"):
4738 file.Write(" %s(%s);\n" %
4739 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
4743 class StateSetNamedParameter(TypeHandler
):
4744 """Handler for commands that set a state chosen with an enum parameter."""
4747 TypeHandler
.__init
__(self
)
4749 def WriteHandlerImplementation(self
, func
, file):
4750 """Overridden from TypeHandler."""
4751 state_name
= func
.GetInfo('state')
4752 state
= _STATES
[state_name
]
4753 states
= state
['states']
4754 args
= func
.GetOriginalArgs()
4755 num_args
= len(args
)
4756 assert num_args
== 2
4757 file.Write(" switch (%s) {\n" % args
[0].name
)
4758 for state
in states
:
4759 file.Write(" case %s:\n" % state
['enum'])
4760 file.Write(" if (state_.%s != %s) {\n" %
4761 (state
['name'], args
[1].name
))
4762 file.Write(" state_.%s = %s;\n" % (state
['name'], args
[1].name
))
4763 if not func
.GetInfo("no_gl"):
4764 file.Write(" %s(%s);\n" %
4765 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
4767 file.Write(" break;\n")
4768 file.Write(" default:\n")
4769 file.Write(" NOTREACHED();\n")
4773 class CustomHandler(TypeHandler
):
4774 """Handler for commands that are auto-generated but require minor tweaks."""
4777 TypeHandler
.__init
__(self
)
4779 def WriteServiceImplementation(self
, func
, file):
4780 """Overrriden from TypeHandler."""
4783 def WriteImmediateServiceImplementation(self
, func
, file):
4784 """Overrriden from TypeHandler."""
4787 def WriteBucketServiceImplementation(self
, func
, file):
4788 """Overrriden from TypeHandler."""
4791 def WriteServiceUnitTest(self
, func
, file, *extras
):
4792 """Overrriden from TypeHandler."""
4793 file.Write("// TODO(gman): %s\n\n" % func
.name
)
4795 def WriteImmediateServiceUnitTest(self
, func
, file, *extras
):
4796 """Overrriden from TypeHandler."""
4797 file.Write("// TODO(gman): %s\n\n" % func
.name
)
4799 def WriteImmediateCmdGetTotalSize(self
, func
, file):
4800 """Overrriden from TypeHandler."""
4802 " uint32_t total_size = 0; // TODO(gman): get correct size.\n")
4804 def WriteImmediateCmdInit(self
, func
, file):
4805 """Overrriden from TypeHandler."""
4806 file.Write(" void Init(%s) {\n" % func
.MakeTypedCmdArgString("_"))
4807 self
.WriteImmediateCmdGetTotalSize(func
, file)
4808 file.Write(" SetHeader(total_size);\n")
4809 args
= func
.GetCmdArgs()
4811 file.Write(" %s = _%s;\n" % (arg
.name
, arg
.name
))
4815 def WriteImmediateCmdSet(self
, func
, file):
4816 """Overrriden from TypeHandler."""
4817 copy_args
= func
.MakeCmdArgString("_", False)
4818 file.Write(" void* Set(void* cmd%s) {\n" %
4819 func
.MakeTypedCmdArgString("_", True))
4820 self
.WriteImmediateCmdGetTotalSize(func
, file)
4821 file.Write(" static_cast<ValueType*>(cmd)->Init(%s);\n" % copy_args
)
4822 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
4823 "cmd, total_size);\n")
4828 class TodoHandler(CustomHandler
):
4829 """Handle for commands that are not yet implemented."""
4831 def NeedsDataTransferFunction(self
, func
):
4832 """Overriden from TypeHandler."""
4835 def WriteImmediateFormatTest(self
, func
, file):
4836 """Overrriden from TypeHandler."""
4839 def WriteGLES2ImplementationUnitTest(self
, func
, file):
4840 """Overrriden from TypeHandler."""
4843 def WriteGLES2Implementation(self
, func
, file):
4844 """Overrriden from TypeHandler."""
4845 file.Write("%s GLES2Implementation::%s(%s) {\n" %
4846 (func
.return_type
, func
.original_name
,
4847 func
.MakeTypedOriginalArgString("")))
4848 file.Write(" // TODO: for now this is a no-op\n")
4851 "GL_INVALID_OPERATION, \"gl%s\", \"not implemented\");\n" %
4853 if func
.return_type
!= "void":
4854 file.Write(" return 0;\n")
4858 def WriteServiceImplementation(self
, func
, file):
4859 """Overrriden from TypeHandler."""
4860 self
.WriteServiceHandlerFunctionHeader(func
, file)
4861 file.Write(" // TODO: for now this is a no-op\n")
4863 " LOCAL_SET_GL_ERROR("
4864 "GL_INVALID_OPERATION, \"gl%s\", \"not implemented\");\n" %
4866 file.Write(" return error::kNoError;\n")
4871 class HandWrittenHandler(CustomHandler
):
4872 """Handler for comands where everything must be written by hand."""
4874 def InitFunction(self
, func
):
4875 """Add or adjust anything type specific for this function."""
4876 CustomHandler
.InitFunction(self
, func
)
4877 func
.can_auto_generate
= False
4879 def NeedsDataTransferFunction(self
, func
):
4880 """Overriden from TypeHandler."""
4881 # If specified explicitly, force the data transfer method.
4882 if func
.GetInfo('data_transfer_methods'):
4886 def WriteStruct(self
, func
, file):
4887 """Overrriden from TypeHandler."""
4890 def WriteDocs(self
, func
, file):
4891 """Overrriden from TypeHandler."""
4894 def WriteServiceUnitTest(self
, func
, file, *extras
):
4895 """Overrriden from TypeHandler."""
4896 file.Write("// TODO(gman): %s\n\n" % func
.name
)
4898 def WriteImmediateServiceUnitTest(self
, func
, file, *extras
):
4899 """Overrriden from TypeHandler."""
4900 file.Write("// TODO(gman): %s\n\n" % func
.name
)
4902 def WriteBucketServiceUnitTest(self
, func
, file, *extras
):
4903 """Overrriden from TypeHandler."""
4904 file.Write("// TODO(gman): %s\n\n" % func
.name
)
4906 def WriteServiceImplementation(self
, func
, file):
4907 """Overrriden from TypeHandler."""
4910 def WriteImmediateServiceImplementation(self
, func
, file):
4911 """Overrriden from TypeHandler."""
4914 def WriteBucketServiceImplementation(self
, func
, file):
4915 """Overrriden from TypeHandler."""
4918 def WriteImmediateCmdHelper(self
, func
, file):
4919 """Overrriden from TypeHandler."""
4922 def WriteCmdHelper(self
, func
, file):
4923 """Overrriden from TypeHandler."""
4926 def WriteFormatTest(self
, func
, file):
4927 """Overrriden from TypeHandler."""
4928 file.Write("// TODO(gman): Write test for %s\n" % func
.name
)
4930 def WriteImmediateFormatTest(self
, func
, file):
4931 """Overrriden from TypeHandler."""
4932 file.Write("// TODO(gman): Write test for %s\n" % func
.name
)
4934 def WriteBucketFormatTest(self
, func
, file):
4935 """Overrriden from TypeHandler."""
4936 file.Write("// TODO(gman): Write test for %s\n" % func
.name
)
4940 class ManualHandler(CustomHandler
):
4941 """Handler for commands who's handlers must be written by hand."""
4944 CustomHandler
.__init
__(self
)
4946 def InitFunction(self
, func
):
4947 """Overrriden from TypeHandler."""
4948 if (func
.name
== 'CompressedTexImage2DBucket' or
4949 func
.name
== 'CompressedTexImage3DBucket'):
4950 func
.cmd_args
= func
.cmd_args
[:-1]
4951 func
.AddCmdArg(Argument('bucket_id', 'GLuint'))
4953 CustomHandler
.InitFunction(self
, func
)
4955 def WriteServiceImplementation(self
, func
, file):
4956 """Overrriden from TypeHandler."""
4959 def WriteBucketServiceImplementation(self
, func
, file):
4960 """Overrriden from TypeHandler."""
4963 def WriteServiceUnitTest(self
, func
, file, *extras
):
4964 """Overrriden from TypeHandler."""
4965 file.Write("// TODO(gman): %s\n\n" % func
.name
)
4967 def WriteImmediateServiceUnitTest(self
, func
, file, *extras
):
4968 """Overrriden from TypeHandler."""
4969 file.Write("// TODO(gman): %s\n\n" % func
.name
)
4971 def WriteImmediateServiceImplementation(self
, func
, file):
4972 """Overrriden from TypeHandler."""
4975 def WriteImmediateFormatTest(self
, func
, file):
4976 """Overrriden from TypeHandler."""
4977 file.Write("// TODO(gman): Implement test for %s\n" % func
.name
)
4979 def WriteGLES2Implementation(self
, func
, file):
4980 """Overrriden from TypeHandler."""
4981 if func
.GetInfo('impl_func'):
4982 super(ManualHandler
, self
).WriteGLES2Implementation(func
, file)
4984 def WriteGLES2ImplementationHeader(self
, func
, file):
4985 """Overrriden from TypeHandler."""
4986 file.Write("%s %s(%s) override;\n" %
4987 (func
.return_type
, func
.original_name
,
4988 func
.MakeTypedOriginalArgString("")))
4991 def WriteImmediateCmdGetTotalSize(self
, func
, file):
4992 """Overrriden from TypeHandler."""
4993 # TODO(gman): Move this data to _FUNCTION_INFO?
4994 CustomHandler
.WriteImmediateCmdGetTotalSize(self
, func
, file)
4997 class DataHandler(TypeHandler
):
4998 """Handler for glBufferData, glBufferSubData, glTexImage2D, glTexSubImage2D,
4999 glCompressedTexImage2D, glCompressedTexImageSub2D."""
5001 TypeHandler
.__init
__(self
)
5003 def InitFunction(self
, func
):
5004 """Overrriden from TypeHandler."""
5005 if func
.name
== 'CompressedTexSubImage2DBucket':
5006 func
.cmd_args
= func
.cmd_args
[:-1]
5007 func
.AddCmdArg(Argument('bucket_id', 'GLuint'))
5009 def WriteGetDataSizeCode(self
, func
, file):
5010 """Overrriden from TypeHandler."""
5011 # TODO(gman): Move this data to _FUNCTION_INFO?
5013 if name
.endswith("Immediate"):
5015 if name
== 'BufferData' or name
== 'BufferSubData':
5016 file.Write(" uint32_t data_size = size;\n")
5017 elif (name
== 'CompressedTexImage2D' or
5018 name
== 'CompressedTexSubImage2D'):
5019 file.Write(" uint32_t data_size = imageSize;\n")
5020 elif (name
== 'CompressedTexSubImage2DBucket'):
5021 file.Write(" Bucket* bucket = GetBucket(c.bucket_id);\n")
5022 file.Write(" uint32_t data_size = bucket->size();\n")
5023 file.Write(" GLsizei imageSize = data_size;\n")
5024 elif name
== 'TexImage2D' or name
== 'TexSubImage2D':
5025 code
= """ uint32_t data_size;
5026 if (!GLES2Util::ComputeImageDataSize(
5027 width, height, format, type, unpack_alignment_, &data_size)) {
5028 return error::kOutOfBounds;
5034 "// uint32_t data_size = 0; // TODO(gman): get correct size!\n")
5036 def WriteImmediateCmdGetTotalSize(self
, func
, file):
5037 """Overrriden from TypeHandler."""
5040 def WriteImmediateCmdSizeTest(self
, func
, file):
5041 """Overrriden from TypeHandler."""
5042 file.Write(" EXPECT_EQ(sizeof(cmd), total_size);\n")
5044 def WriteImmediateCmdInit(self
, func
, file):
5045 """Overrriden from TypeHandler."""
5046 file.Write(" void Init(%s) {\n" % func
.MakeTypedCmdArgString("_"))
5047 self
.WriteImmediateCmdGetTotalSize(func
, file)
5048 file.Write(" SetHeader(total_size);\n")
5049 args
= func
.GetCmdArgs()
5051 file.Write(" %s = _%s;\n" % (arg
.name
, arg
.name
))
5055 def WriteImmediateCmdSet(self
, func
, file):
5056 """Overrriden from TypeHandler."""
5057 copy_args
= func
.MakeCmdArgString("_", False)
5058 file.Write(" void* Set(void* cmd%s) {\n" %
5059 func
.MakeTypedCmdArgString("_", True))
5060 self
.WriteImmediateCmdGetTotalSize(func
, file)
5061 file.Write(" static_cast<ValueType*>(cmd)->Init(%s);\n" % copy_args
)
5062 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
5063 "cmd, total_size);\n")
5067 def WriteImmediateFormatTest(self
, func
, file):
5068 """Overrriden from TypeHandler."""
5069 # TODO(gman): Remove this exception.
5070 file.Write("// TODO(gman): Implement test for %s\n" % func
.name
)
5073 def WriteServiceUnitTest(self
, func
, file, *extras
):
5074 """Overrriden from TypeHandler."""
5075 file.Write("// TODO(gman): %s\n\n" % func
.name
)
5077 def WriteImmediateServiceUnitTest(self
, func
, file, *extras
):
5078 """Overrriden from TypeHandler."""
5079 file.Write("// TODO(gman): %s\n\n" % func
.name
)
5081 def WriteBucketServiceImplementation(self
, func
, file):
5082 """Overrriden from TypeHandler."""
5083 if not func
.name
== 'CompressedTexSubImage2DBucket':
5084 TypeHandler
.WriteBucketServiceImplemenation(self
, func
, file)
5087 class BindHandler(TypeHandler
):
5088 """Handler for glBind___ type functions."""
5091 TypeHandler
.__init
__(self
)
5093 def WriteServiceUnitTest(self
, func
, file, *extras
):
5094 """Overrriden from TypeHandler."""
5096 if len(func
.GetOriginalArgs()) == 1:
5098 TEST_P(%(test_name)s, %(name)sValidArgs) {
5099 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
5100 SpecializedSetup<cmds::%(name)s, 0>(true);
5102 cmd.Init(%(args)s);"""
5105 decoder_->set_unsafe_es3_apis_enabled(true);
5106 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5107 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5108 decoder_->set_unsafe_es3_apis_enabled(false);
5109 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));
5114 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5115 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5118 if func
.GetInfo("gen_func"):
5120 TEST_P(%(test_name)s, %(name)sValidArgsNewId) {
5121 EXPECT_CALL(*gl_, %(gl_func_name)s(kNewServiceId));
5122 EXPECT_CALL(*gl_, %(gl_gen_func_name)s(1, _))
5123 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
5124 SpecializedSetup<cmds::%(name)s, 0>(true);
5126 cmd.Init(kNewClientId);
5127 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5128 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5129 EXPECT_TRUE(Get%(resource_type)s(kNewClientId) != NULL);
5132 self
.WriteValidUnitTest(func
, file, valid_test
, {
5133 'resource_type': func
.GetOriginalArgs()[0].resource_type
,
5134 'gl_gen_func_name': func
.GetInfo("gen_func"),
5138 TEST_P(%(test_name)s, %(name)sValidArgs) {
5139 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
5140 SpecializedSetup<cmds::%(name)s, 0>(true);
5142 cmd.Init(%(args)s);"""
5145 decoder_->set_unsafe_es3_apis_enabled(true);
5146 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5147 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5148 decoder_->set_unsafe_es3_apis_enabled(false);
5149 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));
5154 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5155 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5158 if func
.GetInfo("gen_func"):
5160 TEST_P(%(test_name)s, %(name)sValidArgsNewId) {
5162 %(gl_func_name)s(%(gl_args_with_new_id)s));
5163 EXPECT_CALL(*gl_, %(gl_gen_func_name)s(1, _))
5164 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
5165 SpecializedSetup<cmds::%(name)s, 0>(true);
5167 cmd.Init(%(args_with_new_id)s);"""
5170 decoder_->set_unsafe_es3_apis_enabled(true);
5171 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5172 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5173 EXPECT_TRUE(Get%(resource_type)s(kNewClientId) != NULL);
5174 decoder_->set_unsafe_es3_apis_enabled(false);
5175 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));
5180 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5181 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5182 EXPECT_TRUE(Get%(resource_type)s(kNewClientId) != NULL);
5186 gl_args_with_new_id
= []
5187 args_with_new_id
= []
5188 for arg
in func
.GetOriginalArgs():
5189 if hasattr(arg
, 'resource_type'):
5190 gl_args_with_new_id
.append('kNewServiceId')
5191 args_with_new_id
.append('kNewClientId')
5193 gl_args_with_new_id
.append(arg
.GetValidGLArg(func
))
5194 args_with_new_id
.append(arg
.GetValidArg(func
))
5195 self
.WriteValidUnitTest(func
, file, valid_test
, {
5196 'args_with_new_id': ", ".join(args_with_new_id
),
5197 'gl_args_with_new_id': ", ".join(gl_args_with_new_id
),
5198 'resource_type': func
.GetResourceIdArg().resource_type
,
5199 'gl_gen_func_name': func
.GetInfo("gen_func"),
5203 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
5204 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
5205 SpecializedSetup<cmds::%(name)s, 0>(false);
5208 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
5211 self
.WriteInvalidUnitTest(func
, file, invalid_test
, *extras
)
5213 def WriteGLES2Implementation(self
, func
, file):
5214 """Writes the GLES2 Implemention."""
5216 impl_func
= func
.GetInfo('impl_func')
5217 impl_decl
= func
.GetInfo('impl_decl')
5219 if (func
.can_auto_generate
and
5220 (impl_func
== None or impl_func
== True) and
5221 (impl_decl
== None or impl_decl
== True)):
5223 file.Write("%s GLES2Implementation::%s(%s) {\n" %
5224 (func
.return_type
, func
.original_name
,
5225 func
.MakeTypedOriginalArgString("")))
5226 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
5227 func
.WriteDestinationInitalizationValidation(file)
5228 self
.WriteClientGLCallLog(func
, file)
5229 for arg
in func
.GetOriginalArgs():
5230 arg
.WriteClientSideValidationCode(file, func
)
5232 code
= """ if (Is%(type)sReservedId(%(id)s)) {
5233 SetGLError(GL_INVALID_OPERATION, "%(name)s\", \"%(id)s reserved id");
5236 %(name)sHelper(%(arg_string)s);
5241 name_arg
= func
.GetResourceIdArg()
5244 'arg_string': func
.MakeOriginalArgString(""),
5245 'id': name_arg
.name
,
5246 'type': name_arg
.resource_type
,
5247 'lc_type': name_arg
.resource_type
.lower(),
5250 def WriteGLES2ImplementationUnitTest(self
, func
, file):
5251 """Overrriden from TypeHandler."""
5252 client_test
= func
.GetInfo('client_test')
5253 if client_test
== False:
5256 TEST_F(GLES2ImplementationTest, %(name)s) {
5261 expected.cmd.Init(%(cmd_args)s);
5263 gl_->%(name)s(%(args)s);
5264 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));"""
5265 if not func
.IsUnsafe():
5268 gl_->%(name)s(%(args)s);
5269 EXPECT_TRUE(NoCommandsWritten());"""
5274 arg
.GetValidClientSideCmdArg(func
) for arg
in func
.GetCmdArgs()
5277 arg
.GetValidClientSideArg(func
) for arg
in func
.GetOriginalArgs()
5282 'args': ", ".join(gl_arg_strings
),
5283 'cmd_args': ", ".join(cmd_arg_strings
),
5287 class GENnHandler(TypeHandler
):
5288 """Handler for glGen___ type functions."""
5291 TypeHandler
.__init
__(self
)
5293 def InitFunction(self
, func
):
5294 """Overrriden from TypeHandler."""
5297 def WriteGetDataSizeCode(self
, func
, file):
5298 """Overrriden from TypeHandler."""
5299 code
= """ uint32_t data_size;
5300 if (!SafeMultiplyUint32(n, sizeof(GLuint), &data_size)) {
5301 return error::kOutOfBounds;
5306 def WriteHandlerImplementation (self
, func
, file):
5307 """Overrriden from TypeHandler."""
5308 file.Write(" if (!%sHelper(n, %s)) {\n"
5309 " return error::kInvalidArguments;\n"
5311 (func
.name
, func
.GetLastOriginalArg().name
))
5313 def WriteImmediateHandlerImplementation(self
, func
, file):
5314 """Overrriden from TypeHandler."""
5316 file.Write(""" for (GLsizei ii = 0; ii < n; ++ii) {
5317 if (group_->Get%(resource_name)sServiceId(%(last_arg_name)s[ii], NULL)) {
5318 return error::kInvalidArguments;
5321 scoped_ptr<GLuint[]> service_ids(new GLuint[n]);
5322 gl%(func_name)s(n, service_ids.get());
5323 for (GLsizei ii = 0; ii < n; ++ii) {
5324 group_->Add%(resource_name)sId(%(last_arg_name)s[ii], service_ids[ii]);
5326 """ % { 'func_name': func
.original_name
,
5327 'last_arg_name': func
.GetLastOriginalArg().name
,
5328 'resource_name': func
.GetInfo('resource_type') })
5330 file.Write(" if (!%sHelper(n, %s)) {\n"
5331 " return error::kInvalidArguments;\n"
5333 (func
.original_name
, func
.GetLastOriginalArg().name
))
5335 def WriteGLES2Implementation(self
, func
, file):
5336 """Overrriden from TypeHandler."""
5337 log_code
= (""" GPU_CLIENT_LOG_CODE_BLOCK({
5338 for (GLsizei i = 0; i < n; ++i) {
5339 GPU_CLIENT_LOG(" " << i << ": " << %s[i]);
5341 });""" % func
.GetOriginalArgs()[1].name
)
5343 'log_code': log_code
,
5344 'return_type': func
.return_type
,
5345 'name': func
.original_name
,
5346 'typed_args': func
.MakeTypedOriginalArgString(""),
5347 'args': func
.MakeOriginalArgString(""),
5348 'resource_types': func
.GetInfo('resource_types'),
5349 'count_name': func
.GetOriginalArgs()[0].name
,
5352 "%(return_type)s GLES2Implementation::%(name)s(%(typed_args)s) {\n" %
5354 func
.WriteDestinationInitalizationValidation(file)
5355 self
.WriteClientGLCallLog(func
, file)
5356 for arg
in func
.GetOriginalArgs():
5357 arg
.WriteClientSideValidationCode(file, func
)
5358 not_shared
= func
.GetInfo('not_shared')
5362 """ IdAllocator* id_allocator = GetIdAllocator(id_namespaces::k%s);
5363 for (GLsizei ii = 0; ii < n; ++ii)
5364 %s[ii] = id_allocator->AllocateID();""" %
5365 (func
.GetInfo('resource_types'), func
.GetOriginalArgs()[1].name
))
5367 alloc_code
= (""" GetIdHandler(id_namespaces::k%(resource_types)s)->
5368 MakeIds(this, 0, %(args)s);""" % args
)
5369 args
['alloc_code'] = alloc_code
5371 code
= """ GPU_CLIENT_SINGLE_THREAD_CHECK();
5373 %(name)sHelper(%(args)s);
5374 helper_->%(name)sImmediate(%(args)s);
5375 if (share_group_->bind_generates_resource())
5376 helper_->CommandBufferHelper::Flush();
5382 file.Write(code
% args
)
5384 def WriteGLES2ImplementationUnitTest(self
, func
, file):
5385 """Overrriden from TypeHandler."""
5387 TEST_F(GLES2ImplementationTest, %(name)s) {
5388 GLuint ids[2] = { 0, };
5390 cmds::%(name)sImmediate gen;
5394 expected.gen.Init(arraysize(ids), &ids[0]);
5395 expected.data[0] = k%(types)sStartId;
5396 expected.data[1] = k%(types)sStartId + 1;
5397 gl_->%(name)s(arraysize(ids), &ids[0]);
5398 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
5399 EXPECT_EQ(k%(types)sStartId, ids[0]);
5400 EXPECT_EQ(k%(types)sStartId + 1, ids[1]);
5405 'types': func
.GetInfo('resource_types'),
5408 def WriteServiceUnitTest(self
, func
, file, *extras
):
5409 """Overrriden from TypeHandler."""
5411 TEST_P(%(test_name)s, %(name)sValidArgs) {
5412 EXPECT_CALL(*gl_, %(gl_func_name)s(1, _))
5413 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
5414 GetSharedMemoryAs<GLuint*>()[0] = kNewClientId;
5415 SpecializedSetup<cmds::%(name)s, 0>(true);
5418 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5419 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
5423 EXPECT_TRUE(Get%(resource_name)sServiceId(kNewClientId, &service_id));
5424 EXPECT_EQ(kNewServiceId, service_id)
5429 EXPECT_TRUE(Get%(resource_name)s(kNewClientId, &service_id) != NULL);
5432 self
.WriteValidUnitTest(func
, file, valid_test
, {
5433 'resource_name': func
.GetInfo('resource_type'),
5436 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
5437 EXPECT_CALL(*gl_, %(gl_func_name)s(_, _)).Times(0);
5438 GetSharedMemoryAs<GLuint*>()[0] = client_%(resource_name)s_id_;
5439 SpecializedSetup<cmds::%(name)s, 0>(false);
5442 EXPECT_EQ(error::kInvalidArguments, ExecuteCmd(cmd));
5445 self
.WriteValidUnitTest(func
, file, invalid_test
, {
5446 'resource_name': func
.GetInfo('resource_type').lower(),
5449 def WriteImmediateServiceUnitTest(self
, func
, file, *extras
):
5450 """Overrriden from TypeHandler."""
5452 TEST_P(%(test_name)s, %(name)sValidArgs) {
5453 EXPECT_CALL(*gl_, %(gl_func_name)s(1, _))
5454 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
5455 cmds::%(name)s* cmd = GetImmediateAs<cmds::%(name)s>();
5456 GLuint temp = kNewClientId;
5457 SpecializedSetup<cmds::%(name)s, 0>(true);"""
5460 decoder_->set_unsafe_es3_apis_enabled(true);"""
5462 cmd->Init(1, &temp);
5463 EXPECT_EQ(error::kNoError,
5464 ExecuteImmediateCmd(*cmd, sizeof(temp)));
5465 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
5469 EXPECT_TRUE(Get%(resource_name)sServiceId(kNewClientId, &service_id));
5470 EXPECT_EQ(kNewServiceId, service_id);
5471 decoder_->set_unsafe_es3_apis_enabled(false);
5472 EXPECT_EQ(error::kUnknownCommand,
5473 ExecuteImmediateCmd(*cmd, sizeof(temp)));
5478 EXPECT_TRUE(Get%(resource_name)s(kNewClientId) != NULL);
5481 self
.WriteValidUnitTest(func
, file, valid_test
, {
5482 'resource_name': func
.GetInfo('resource_type'),
5485 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
5486 EXPECT_CALL(*gl_, %(gl_func_name)s(_, _)).Times(0);
5487 cmds::%(name)s* cmd = GetImmediateAs<cmds::%(name)s>();
5488 SpecializedSetup<cmds::%(name)s, 0>(false);
5489 cmd->Init(1, &client_%(resource_name)s_id_);"""
5492 decoder_->set_unsafe_es3_apis_enabled(true);
5493 EXPECT_EQ(error::kInvalidArguments,
5494 ExecuteImmediateCmd(*cmd, sizeof(&client_%(resource_name)s_id_)));
5495 decoder_->set_unsafe_es3_apis_enabled(false);
5500 EXPECT_EQ(error::kInvalidArguments,
5501 ExecuteImmediateCmd(*cmd, sizeof(&client_%(resource_name)s_id_)));
5504 self
.WriteValidUnitTest(func
, file, invalid_test
, {
5505 'resource_name': func
.GetInfo('resource_type').lower(),
5508 def WriteImmediateCmdComputeSize(self
, func
, file):
5509 """Overrriden from TypeHandler."""
5510 file.Write(" static uint32_t ComputeDataSize(GLsizei n) {\n")
5512 " return static_cast<uint32_t>(sizeof(GLuint) * n); // NOLINT\n")
5515 file.Write(" static uint32_t ComputeSize(GLsizei n) {\n")
5516 file.Write(" return static_cast<uint32_t>(\n")
5517 file.Write(" sizeof(ValueType) + ComputeDataSize(n)); // NOLINT\n")
5521 def WriteImmediateCmdSetHeader(self
, func
, file):
5522 """Overrriden from TypeHandler."""
5523 file.Write(" void SetHeader(GLsizei n) {\n")
5524 file.Write(" header.SetCmdByTotalSize<ValueType>(ComputeSize(n));\n")
5528 def WriteImmediateCmdInit(self
, func
, file):
5529 """Overrriden from TypeHandler."""
5530 last_arg
= func
.GetLastOriginalArg()
5531 file.Write(" void Init(%s, %s _%s) {\n" %
5532 (func
.MakeTypedCmdArgString("_"),
5533 last_arg
.type, last_arg
.name
))
5534 file.Write(" SetHeader(_n);\n")
5535 args
= func
.GetCmdArgs()
5537 file.Write(" %s = _%s;\n" % (arg
.name
, arg
.name
))
5538 file.Write(" memcpy(ImmediateDataAddress(this),\n")
5539 file.Write(" _%s, ComputeDataSize(_n));\n" % last_arg
.name
)
5543 def WriteImmediateCmdSet(self
, func
, file):
5544 """Overrriden from TypeHandler."""
5545 last_arg
= func
.GetLastOriginalArg()
5546 copy_args
= func
.MakeCmdArgString("_", False)
5547 file.Write(" void* Set(void* cmd%s, %s _%s) {\n" %
5548 (func
.MakeTypedCmdArgString("_", True),
5549 last_arg
.type, last_arg
.name
))
5550 file.Write(" static_cast<ValueType*>(cmd)->Init(%s, _%s);\n" %
5551 (copy_args
, last_arg
.name
))
5552 file.Write(" const uint32_t size = ComputeSize(_n);\n")
5553 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
5558 def WriteImmediateCmdHelper(self
, func
, file):
5559 """Overrriden from TypeHandler."""
5560 code
= """ void %(name)s(%(typed_args)s) {
5561 const uint32_t size = gles2::cmds::%(name)s::ComputeSize(n);
5562 gles2::cmds::%(name)s* c =
5563 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
5572 "typed_args": func
.MakeTypedOriginalArgString(""),
5573 "args": func
.MakeOriginalArgString(""),
5576 def WriteImmediateFormatTest(self
, func
, file):
5577 """Overrriden from TypeHandler."""
5578 file.Write("TEST_F(GLES2FormatTest, %s) {\n" % func
.name
)
5579 file.Write(" static GLuint ids[] = { 12, 23, 34, };\n")
5580 file.Write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
5581 (func
.name
, func
.name
))
5582 file.Write(" void* next_cmd = cmd.Set(\n")
5583 file.Write(" &cmd, static_cast<GLsizei>(arraysize(ids)), ids);\n")
5584 file.Write(" EXPECT_EQ(static_cast<uint32_t>(cmds::%s::kCmdId),\n" %
5586 file.Write(" cmd.header.command);\n")
5587 file.Write(" EXPECT_EQ(sizeof(cmd) +\n")
5588 file.Write(" RoundSizeToMultipleOfEntries(cmd.n * 4u),\n")
5589 file.Write(" cmd.header.size * 4u);\n")
5590 file.Write(" EXPECT_EQ(static_cast<GLsizei>(arraysize(ids)), cmd.n);\n");
5591 file.Write(" CheckBytesWrittenMatchesExpectedSize(\n")
5592 file.Write(" next_cmd, sizeof(cmd) +\n")
5593 file.Write(" RoundSizeToMultipleOfEntries(arraysize(ids) * 4u));\n")
5594 file.Write(" // TODO(gman): Check that ids were inserted;\n")
5599 class CreateHandler(TypeHandler
):
5600 """Handler for glCreate___ type functions."""
5603 TypeHandler
.__init
__(self
)
5605 def InitFunction(self
, func
):
5606 """Overrriden from TypeHandler."""
5607 func
.AddCmdArg(Argument("client_id", 'uint32_t'))
5609 def __GetResourceType(self
, func
):
5610 if func
.return_type
== "GLsync":
5613 return func
.name
[6:] # Create*
5615 def WriteServiceUnitTest(self
, func
, file, *extras
):
5616 """Overrriden from TypeHandler."""
5618 TEST_P(%(test_name)s, %(name)sValidArgs) {
5619 %(id_type_cast)sEXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s))
5620 .WillOnce(Return(%(const_service_id)s));
5621 SpecializedSetup<cmds::%(name)s, 0>(true);
5623 cmd.Init(%(args)s%(comma)skNewClientId);"""
5626 decoder_->set_unsafe_es3_apis_enabled(true);"""
5628 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5629 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
5632 %(return_type)s service_id = 0;
5633 EXPECT_TRUE(Get%(resource_type)sServiceId(kNewClientId, &service_id));
5634 EXPECT_EQ(%(const_service_id)s, service_id);
5635 decoder_->set_unsafe_es3_apis_enabled(false);
5636 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));
5641 EXPECT_TRUE(Get%(resource_type)s(kNewClientId));
5646 for arg
in func
.GetOriginalArgs():
5647 if not arg
.IsConstant():
5651 if func
.return_type
== 'GLsync':
5652 id_type_cast
= ("const GLsync kNewServiceIdGLuint = reinterpret_cast"
5653 "<GLsync>(kNewServiceId);\n ")
5654 const_service_id
= "kNewServiceIdGLuint"
5657 const_service_id
= "kNewServiceId"
5658 self
.WriteValidUnitTest(func
, file, valid_test
, {
5660 'resource_type': self
.__GetResourceType
(func
),
5661 'return_type': func
.return_type
,
5662 'id_type_cast': id_type_cast
,
5663 'const_service_id': const_service_id
,
5666 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
5667 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
5668 SpecializedSetup<cmds::%(name)s, 0>(false);
5670 cmd.Init(%(args)s%(comma)skNewClientId);
5671 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));%(gl_error_test)s
5674 self
.WriteInvalidUnitTest(func
, file, invalid_test
, {
5678 def WriteHandlerImplementation (self
, func
, file):
5679 """Overrriden from TypeHandler."""
5681 code
= """ uint32_t client_id = c.client_id;
5682 %(return_type)s service_id = 0;
5683 if (group_->Get%(resource_name)sServiceId(client_id, &service_id)) {
5684 return error::kInvalidArguments;
5686 service_id = %(gl_func_name)s(%(gl_args)s);
5688 group_->Add%(resource_name)sId(client_id, service_id);
5692 code
= """ uint32_t client_id = c.client_id;
5693 if (Get%(resource_name)s(client_id)) {
5694 return error::kInvalidArguments;
5696 %(return_type)s service_id = %(gl_func_name)s(%(gl_args)s);
5698 Create%(resource_name)s(client_id, service_id%(gl_args_with_comma)s);
5702 'resource_name': self
.__GetResourceType
(func
),
5703 'return_type': func
.return_type
,
5704 'gl_func_name': func
.GetGLFunctionName(),
5705 'gl_args': func
.MakeOriginalArgString(""),
5706 'gl_args_with_comma': func
.MakeOriginalArgString("", True) })
5708 def WriteGLES2Implementation(self
, func
, file):
5709 """Overrriden from TypeHandler."""
5710 file.Write("%s GLES2Implementation::%s(%s) {\n" %
5711 (func
.return_type
, func
.original_name
,
5712 func
.MakeTypedOriginalArgString("")))
5713 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
5714 func
.WriteDestinationInitalizationValidation(file)
5715 self
.WriteClientGLCallLog(func
, file)
5716 for arg
in func
.GetOriginalArgs():
5717 arg
.WriteClientSideValidationCode(file, func
)
5718 file.Write(" GLuint client_id;\n")
5719 if func
.return_type
== "GLsync":
5721 " GetIdHandler(id_namespaces::kSyncs)->\n")
5724 " GetIdHandler(id_namespaces::kProgramsAndShaders)->\n")
5725 file.Write(" MakeIds(this, 0, 1, &client_id);\n")
5726 file.Write(" helper_->%s(%s);\n" %
5727 (func
.name
, func
.MakeCmdArgString("")))
5728 file.Write(' GPU_CLIENT_LOG("returned " << client_id);\n')
5729 file.Write(" CheckGLError();\n")
5730 if func
.return_type
== "GLsync":
5731 file.Write(" return reinterpret_cast<GLsync>(client_id);\n")
5733 file.Write(" return client_id;\n")
5738 class DeleteHandler(TypeHandler
):
5739 """Handler for glDelete___ single resource type functions."""
5742 TypeHandler
.__init
__(self
)
5744 def WriteServiceImplementation(self
, func
, file):
5745 """Overrriden from TypeHandler."""
5747 TypeHandler
.WriteServiceImplementation(self
, func
, file)
5748 # HandleDeleteShader and HandleDeleteProgram are manually written.
5751 def WriteGLES2Implementation(self
, func
, file):
5752 """Overrriden from TypeHandler."""
5753 file.Write("%s GLES2Implementation::%s(%s) {\n" %
5754 (func
.return_type
, func
.original_name
,
5755 func
.MakeTypedOriginalArgString("")))
5756 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
5757 func
.WriteDestinationInitalizationValidation(file)
5758 self
.WriteClientGLCallLog(func
, file)
5759 for arg
in func
.GetOriginalArgs():
5760 arg
.WriteClientSideValidationCode(file, func
)
5762 " GPU_CLIENT_DCHECK(%s != 0);\n" % func
.GetOriginalArgs()[-1].name
)
5763 file.Write(" %sHelper(%s);\n" %
5764 (func
.original_name
, func
.GetOriginalArgs()[-1].name
))
5765 file.Write(" CheckGLError();\n")
5769 def WriteHandlerImplementation (self
, func
, file):
5770 """Overrriden from TypeHandler."""
5771 assert len(func
.GetOriginalArgs()) == 1
5772 arg
= func
.GetOriginalArgs()[0]
5774 file.Write(""" %(arg_type)s service_id = 0;
5775 if (group_->Get%(resource_type)sServiceId(%(arg_name)s, &service_id)) {
5776 glDelete%(resource_type)s(service_id);
5777 group_->Remove%(resource_type)sId(%(arg_name)s);
5780 GL_INVALID_VALUE, "gl%(func_name)s", "unknown %(arg_name)s");
5782 """ % { 'resource_type': func
.GetInfo('resource_type'),
5783 'arg_name': arg
.name
,
5784 'arg_type': arg
.type,
5785 'func_name': func
.original_name
})
5787 file.Write(" %sHelper(%s);\n" % (func
.original_name
, arg
.name
))
5789 class DELnHandler(TypeHandler
):
5790 """Handler for glDelete___ type functions."""
5793 TypeHandler
.__init
__(self
)
5795 def WriteGetDataSizeCode(self
, func
, file):
5796 """Overrriden from TypeHandler."""
5797 code
= """ uint32_t data_size;
5798 if (!SafeMultiplyUint32(n, sizeof(GLuint), &data_size)) {
5799 return error::kOutOfBounds;
5804 def WriteGLES2ImplementationUnitTest(self
, func
, file):
5805 """Overrriden from TypeHandler."""
5807 TEST_F(GLES2ImplementationTest, %(name)s) {
5808 GLuint ids[2] = { k%(types)sStartId, k%(types)sStartId + 1 };
5810 cmds::%(name)sImmediate del;
5814 expected.del.Init(arraysize(ids), &ids[0]);
5815 expected.data[0] = k%(types)sStartId;
5816 expected.data[1] = k%(types)sStartId + 1;
5817 gl_->%(name)s(arraysize(ids), &ids[0]);
5818 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
5823 'types': func
.GetInfo('resource_types'),
5826 def WriteServiceUnitTest(self
, func
, file, *extras
):
5827 """Overrriden from TypeHandler."""
5829 TEST_P(%(test_name)s, %(name)sValidArgs) {
5832 %(gl_func_name)s(1, Pointee(kService%(upper_resource_name)sId)))
5834 GetSharedMemoryAs<GLuint*>()[0] = client_%(resource_name)s_id_;
5835 SpecializedSetup<cmds::%(name)s, 0>(true);
5838 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5839 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5841 Get%(upper_resource_name)s(client_%(resource_name)s_id_) == NULL);
5844 self
.WriteValidUnitTest(func
, file, valid_test
, {
5845 'resource_name': func
.GetInfo('resource_type').lower(),
5846 'upper_resource_name': func
.GetInfo('resource_type'),
5849 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
5850 GetSharedMemoryAs<GLuint*>()[0] = kInvalidClientId;
5851 SpecializedSetup<cmds::%(name)s, 0>(false);
5854 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5857 self
.WriteValidUnitTest(func
, file, invalid_test
, *extras
)
5859 def WriteImmediateServiceUnitTest(self
, func
, file, *extras
):
5860 """Overrriden from TypeHandler."""
5862 TEST_P(%(test_name)s, %(name)sValidArgs) {
5865 %(gl_func_name)s(1, Pointee(kService%(upper_resource_name)sId)))
5867 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
5868 SpecializedSetup<cmds::%(name)s, 0>(true);
5869 cmd.Init(1, &client_%(resource_name)s_id_);"""
5872 decoder_->set_unsafe_es3_apis_enabled(true);"""
5874 EXPECT_EQ(error::kNoError,
5875 ExecuteImmediateCmd(cmd, sizeof(client_%(resource_name)s_id_)));
5876 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
5879 EXPECT_FALSE(Get%(upper_resource_name)sServiceId(
5880 client_%(resource_name)s_id_, NULL));
5881 decoder_->set_unsafe_es3_apis_enabled(false);
5882 EXPECT_EQ(error::kUnknownCommand,
5883 ExecuteImmediateCmd(cmd, sizeof(client_%(resource_name)s_id_)));
5889 Get%(upper_resource_name)s(client_%(resource_name)s_id_) == NULL);
5892 self
.WriteValidUnitTest(func
, file, valid_test
, {
5893 'resource_name': func
.GetInfo('resource_type').lower(),
5894 'upper_resource_name': func
.GetInfo('resource_type'),
5897 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
5898 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
5899 SpecializedSetup<cmds::%(name)s, 0>(false);
5900 GLuint temp = kInvalidClientId;
5901 cmd.Init(1, &temp);"""
5904 decoder_->set_unsafe_es3_apis_enabled(true);
5905 EXPECT_EQ(error::kNoError,
5906 ExecuteImmediateCmd(cmd, sizeof(temp)));
5907 decoder_->set_unsafe_es3_apis_enabled(false);
5908 EXPECT_EQ(error::kUnknownCommand,
5909 ExecuteImmediateCmd(cmd, sizeof(temp)));
5914 EXPECT_EQ(error::kNoError,
5915 ExecuteImmediateCmd(cmd, sizeof(temp)));
5918 self
.WriteValidUnitTest(func
, file, invalid_test
, *extras
)
5920 def WriteHandlerImplementation (self
, func
, file):
5921 """Overrriden from TypeHandler."""
5922 file.Write(" %sHelper(n, %s);\n" %
5923 (func
.name
, func
.GetLastOriginalArg().name
))
5925 def WriteImmediateHandlerImplementation (self
, func
, file):
5926 """Overrriden from TypeHandler."""
5928 file.Write(""" for (GLsizei ii = 0; ii < n; ++ii) {
5929 GLuint service_id = 0;
5930 if (group_->Get%(resource_type)sServiceId(
5931 %(last_arg_name)s[ii], &service_id)) {
5932 glDelete%(resource_type)ss(1, &service_id);
5933 group_->Remove%(resource_type)sId(%(last_arg_name)s[ii]);
5936 """ % { 'resource_type': func
.GetInfo('resource_type'),
5937 'last_arg_name': func
.GetLastOriginalArg().name
})
5939 file.Write(" %sHelper(n, %s);\n" %
5940 (func
.original_name
, func
.GetLastOriginalArg().name
))
5942 def WriteGLES2Implementation(self
, func
, file):
5943 """Overrriden from TypeHandler."""
5944 impl_decl
= func
.GetInfo('impl_decl')
5945 if impl_decl
== None or impl_decl
== True:
5947 'return_type': func
.return_type
,
5948 'name': func
.original_name
,
5949 'typed_args': func
.MakeTypedOriginalArgString(""),
5950 'args': func
.MakeOriginalArgString(""),
5951 'resource_type': func
.GetInfo('resource_type').lower(),
5952 'count_name': func
.GetOriginalArgs()[0].name
,
5955 "%(return_type)s GLES2Implementation::%(name)s(%(typed_args)s) {\n" %
5957 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
5958 func
.WriteDestinationInitalizationValidation(file)
5959 self
.WriteClientGLCallLog(func
, file)
5960 file.Write(""" GPU_CLIENT_LOG_CODE_BLOCK({
5961 for (GLsizei i = 0; i < n; ++i) {
5962 GPU_CLIENT_LOG(" " << i << ": " << %s[i]);
5965 """ % func
.GetOriginalArgs()[1].name
)
5966 file.Write(""" GPU_CLIENT_DCHECK_CODE_BLOCK({
5967 for (GLsizei i = 0; i < n; ++i) {
5971 """ % func
.GetOriginalArgs()[1].name
)
5972 for arg
in func
.GetOriginalArgs():
5973 arg
.WriteClientSideValidationCode(file, func
)
5974 code
= """ %(name)sHelper(%(args)s);
5979 file.Write(code
% args
)
5981 def WriteImmediateCmdComputeSize(self
, func
, file):
5982 """Overrriden from TypeHandler."""
5983 file.Write(" static uint32_t ComputeDataSize(GLsizei n) {\n")
5985 " return static_cast<uint32_t>(sizeof(GLuint) * n); // NOLINT\n")
5988 file.Write(" static uint32_t ComputeSize(GLsizei n) {\n")
5989 file.Write(" return static_cast<uint32_t>(\n")
5990 file.Write(" sizeof(ValueType) + ComputeDataSize(n)); // NOLINT\n")
5994 def WriteImmediateCmdSetHeader(self
, func
, file):
5995 """Overrriden from TypeHandler."""
5996 file.Write(" void SetHeader(GLsizei n) {\n")
5997 file.Write(" header.SetCmdByTotalSize<ValueType>(ComputeSize(n));\n")
6001 def WriteImmediateCmdInit(self
, func
, file):
6002 """Overrriden from TypeHandler."""
6003 last_arg
= func
.GetLastOriginalArg()
6004 file.Write(" void Init(%s, %s _%s) {\n" %
6005 (func
.MakeTypedCmdArgString("_"),
6006 last_arg
.type, last_arg
.name
))
6007 file.Write(" SetHeader(_n);\n")
6008 args
= func
.GetCmdArgs()
6010 file.Write(" %s = _%s;\n" % (arg
.name
, arg
.name
))
6011 file.Write(" memcpy(ImmediateDataAddress(this),\n")
6012 file.Write(" _%s, ComputeDataSize(_n));\n" % last_arg
.name
)
6016 def WriteImmediateCmdSet(self
, func
, file):
6017 """Overrriden from TypeHandler."""
6018 last_arg
= func
.GetLastOriginalArg()
6019 copy_args
= func
.MakeCmdArgString("_", False)
6020 file.Write(" void* Set(void* cmd%s, %s _%s) {\n" %
6021 (func
.MakeTypedCmdArgString("_", True),
6022 last_arg
.type, last_arg
.name
))
6023 file.Write(" static_cast<ValueType*>(cmd)->Init(%s, _%s);\n" %
6024 (copy_args
, last_arg
.name
))
6025 file.Write(" const uint32_t size = ComputeSize(_n);\n")
6026 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
6031 def WriteImmediateCmdHelper(self
, func
, file):
6032 """Overrriden from TypeHandler."""
6033 code
= """ void %(name)s(%(typed_args)s) {
6034 const uint32_t size = gles2::cmds::%(name)s::ComputeSize(n);
6035 gles2::cmds::%(name)s* c =
6036 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
6045 "typed_args": func
.MakeTypedOriginalArgString(""),
6046 "args": func
.MakeOriginalArgString(""),
6049 def WriteImmediateFormatTest(self
, func
, file):
6050 """Overrriden from TypeHandler."""
6051 file.Write("TEST_F(GLES2FormatTest, %s) {\n" % func
.name
)
6052 file.Write(" static GLuint ids[] = { 12, 23, 34, };\n")
6053 file.Write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
6054 (func
.name
, func
.name
))
6055 file.Write(" void* next_cmd = cmd.Set(\n")
6056 file.Write(" &cmd, static_cast<GLsizei>(arraysize(ids)), ids);\n")
6057 file.Write(" EXPECT_EQ(static_cast<uint32_t>(cmds::%s::kCmdId),\n" %
6059 file.Write(" cmd.header.command);\n")
6060 file.Write(" EXPECT_EQ(sizeof(cmd) +\n")
6061 file.Write(" RoundSizeToMultipleOfEntries(cmd.n * 4u),\n")
6062 file.Write(" cmd.header.size * 4u);\n")
6063 file.Write(" EXPECT_EQ(static_cast<GLsizei>(arraysize(ids)), cmd.n);\n");
6064 file.Write(" CheckBytesWrittenMatchesExpectedSize(\n")
6065 file.Write(" next_cmd, sizeof(cmd) +\n")
6066 file.Write(" RoundSizeToMultipleOfEntries(arraysize(ids) * 4u));\n")
6067 file.Write(" // TODO(gman): Check that ids were inserted;\n")
6072 class GETnHandler(TypeHandler
):
6073 """Handler for GETn for glGetBooleanv, glGetFloatv, ... type functions."""
6076 TypeHandler
.__init
__(self
)
6078 def NeedsDataTransferFunction(self
, func
):
6079 """Overriden from TypeHandler."""
6082 def WriteServiceImplementation(self
, func
, file):
6083 """Overrriden from TypeHandler."""
6084 self
.WriteServiceHandlerFunctionHeader(func
, file)
6085 last_arg
= func
.GetLastOriginalArg()
6086 # All except shm_id and shm_offset.
6087 all_but_last_args
= func
.GetCmdArgs()[:-2]
6088 for arg
in all_but_last_args
:
6089 arg
.WriteGetCode(file)
6091 code
= """ typedef cmds::%(func_name)s::Result Result;
6092 GLsizei num_values = 0;
6093 GetNumValuesReturnedForGLGet(pname, &num_values);
6094 Result* result = GetSharedMemoryAs<Result*>(
6095 c.%(last_arg_name)s_shm_id, c.%(last_arg_name)s_shm_offset,
6096 Result::ComputeSize(num_values));
6097 %(last_arg_type)s %(last_arg_name)s = result ? result->GetData() : NULL;
6100 'last_arg_type': last_arg
.type,
6101 'last_arg_name': last_arg
.name
,
6102 'func_name': func
.name
,
6104 func
.WriteHandlerValidation(file)
6105 code
= """ // Check that the client initialized the result.
6106 if (result->size != 0) {
6107 return error::kInvalidArguments;
6110 shadowed
= func
.GetInfo('shadowed')
6112 file.Write(' LOCAL_COPY_REAL_GL_ERRORS_TO_WRAPPER("%s");\n' % func
.name
)
6114 func
.WriteHandlerImplementation(file)
6116 code
= """ result->SetNumResults(num_values);
6117 return error::kNoError;
6121 code
= """ GLenum error = glGetError();
6122 if (error == GL_NO_ERROR) {
6123 result->SetNumResults(num_values);
6125 LOCAL_SET_GL_ERROR(error, "%(func_name)s", "");
6127 return error::kNoError;
6131 file.Write(code
% {'func_name': func
.name
})
6133 def WriteGLES2Implementation(self
, func
, file):
6134 """Overrriden from TypeHandler."""
6135 impl_decl
= func
.GetInfo('impl_decl')
6136 if impl_decl
== None or impl_decl
== True:
6137 file.Write("%s GLES2Implementation::%s(%s) {\n" %
6138 (func
.return_type
, func
.original_name
,
6139 func
.MakeTypedOriginalArgString("")))
6140 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
6141 func
.WriteDestinationInitalizationValidation(file)
6142 self
.WriteClientGLCallLog(func
, file)
6143 for arg
in func
.GetOriginalArgs():
6144 arg
.WriteClientSideValidationCode(file, func
)
6145 all_but_last_args
= func
.GetOriginalArgs()[:-1]
6147 has_length_arg
= False
6148 for arg
in all_but_last_args
:
6149 if arg
.type == 'GLsync':
6150 args
.append('ToGLuint(%s)' % arg
.name
)
6151 elif arg
.name
.endswith('size') and arg
.type == 'GLsizei':
6153 elif arg
.name
== 'length':
6154 has_length_arg
= True
6157 args
.append(arg
.name
)
6158 arg_string
= ", ".join(args
)
6162 for arg
in func
.GetOriginalArgs() if not arg
.IsConstant()]))
6163 self
.WriteTraceEvent(func
, file)
6164 code
= """ if (%(func_name)sHelper(%(all_arg_string)s)) {
6167 typedef cmds::%(func_name)s::Result Result;
6168 Result* result = GetResultAs<Result*>();
6172 result->SetNumResults(0);
6173 helper_->%(func_name)s(%(arg_string)s,
6174 GetResultShmId(), GetResultShmOffset());
6176 result->CopyResult(%(last_arg_name)s);
6177 GPU_CLIENT_LOG_CODE_BLOCK({
6178 for (int32_t i = 0; i < result->GetNumResults(); ++i) {
6179 GPU_CLIENT_LOG(" " << i << ": " << result->GetData()[i]);
6185 *length = result->GetNumResults();
6192 'func_name': func
.name
,
6193 'arg_string': arg_string
,
6194 'all_arg_string': all_arg_string
,
6195 'last_arg_name': func
.GetLastOriginalArg().name
,
6198 def WriteGLES2ImplementationUnitTest(self
, func
, file):
6199 """Writes the GLES2 Implemention unit test."""
6201 TEST_F(GLES2ImplementationTest, %(name)s) {
6205 typedef cmds::%(name)s::Result::Type ResultType;
6206 ResultType result = 0;
6208 ExpectedMemoryInfo result1 = GetExpectedResultMemory(
6209 sizeof(uint32_t) + sizeof(ResultType));
6210 expected.cmd.Init(%(cmd_args)s, result1.id, result1.offset);
6211 EXPECT_CALL(*command_buffer(), OnFlush())
6212 .WillOnce(SetMemory(result1.ptr, SizedResultHelper<ResultType>(1)))
6213 .RetiresOnSaturation();
6214 gl_->%(name)s(%(args)s, &result);
6215 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
6216 EXPECT_EQ(static_cast<ResultType>(1), result);
6219 first_cmd_arg
= func
.GetCmdArgs()[0].GetValidNonCachedClientSideCmdArg(func
)
6220 if not first_cmd_arg
:
6223 first_gl_arg
= func
.GetOriginalArgs()[0].GetValidNonCachedClientSideArg(
6226 cmd_arg_strings
= [first_cmd_arg
]
6227 for arg
in func
.GetCmdArgs()[1:-2]:
6228 cmd_arg_strings
.append(arg
.GetValidClientSideCmdArg(func
))
6229 gl_arg_strings
= [first_gl_arg
]
6230 for arg
in func
.GetOriginalArgs()[1:-1]:
6231 gl_arg_strings
.append(arg
.GetValidClientSideArg(func
))
6235 'args': ", ".join(gl_arg_strings
),
6236 'cmd_args': ", ".join(cmd_arg_strings
),
6239 def WriteServiceUnitTest(self
, func
, file, *extras
):
6240 """Overrriden from TypeHandler."""
6242 TEST_P(%(test_name)s, %(name)sValidArgs) {
6243 EXPECT_CALL(*gl_, GetError())
6244 .WillOnce(Return(GL_NO_ERROR))
6245 .WillOnce(Return(GL_NO_ERROR))
6246 .RetiresOnSaturation();
6247 SpecializedSetup<cmds::%(name)s, 0>(true);
6248 typedef cmds::%(name)s::Result Result;
6249 Result* result = static_cast<Result*>(shared_memory_address_);
6250 EXPECT_CALL(*gl_, %(gl_func_name)s(%(local_gl_args)s));
6253 cmd.Init(%(cmd_args)s);"""
6256 decoder_->set_unsafe_es3_apis_enabled(true);"""
6258 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
6259 EXPECT_EQ(decoder_->GetGLES2Util()->GLGetNumValuesReturned(
6261 result->GetNumResults());
6262 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
6265 decoder_->set_unsafe_es3_apis_enabled(false);
6266 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));"""
6271 cmd_arg_strings
= []
6273 for arg
in func
.GetOriginalArgs()[:-1]:
6274 if arg
.name
== 'length':
6275 gl_arg_value
= 'nullptr'
6276 elif arg
.name
.endswith('size'):
6277 gl_arg_value
= ("decoder_->GetGLES2Util()->GLGetNumValuesReturned(%s)" %
6279 elif arg
.type == 'GLsync':
6280 gl_arg_value
= 'reinterpret_cast<GLsync>(kServiceSyncId)'
6282 gl_arg_value
= arg
.GetValidGLArg(func
)
6283 gl_arg_strings
.append(gl_arg_value
)
6284 if arg
.name
== 'pname':
6285 valid_pname
= gl_arg_value
6286 if arg
.name
.endswith('size') or arg
.name
== 'length':
6288 if arg
.type == 'GLsync':
6289 arg_value
= 'client_sync_id_'
6291 arg_value
= arg
.GetValidArg(func
)
6292 cmd_arg_strings
.append(arg_value
)
6293 if func
.GetInfo('gl_test_func') == 'glGetIntegerv':
6294 gl_arg_strings
.append("_")
6296 gl_arg_strings
.append("result->GetData()")
6297 cmd_arg_strings
.append("shared_memory_id_")
6298 cmd_arg_strings
.append("shared_memory_offset_")
6300 self
.WriteValidUnitTest(func
, file, valid_test
, {
6301 'local_gl_args': ", ".join(gl_arg_strings
),
6302 'cmd_args': ", ".join(cmd_arg_strings
),
6303 'valid_pname': valid_pname
,
6306 if not func
.IsUnsafe():
6308 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
6309 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
6310 SpecializedSetup<cmds::%(name)s, 0>(false);
6311 cmds::%(name)s::Result* result =
6312 static_cast<cmds::%(name)s::Result*>(shared_memory_address_);
6316 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));
6317 EXPECT_EQ(0u, result->size);%(gl_error_test)s
6320 self
.WriteInvalidUnitTest(func
, file, invalid_test
, *extras
)
6322 class ArrayArgTypeHandler(TypeHandler
):
6323 """Base class for type handlers that handle args that are arrays"""
6326 TypeHandler
.__init
__(self
)
6328 def GetArrayType(self
, func
):
6329 """Returns the type of the element in the element array being PUT to."""
6330 for arg
in func
.GetOriginalArgs():
6332 element_type
= arg
.GetPointedType()
6335 # Special case: array type handler is used for a function that is forwarded
6336 # to the actual array type implementation
6337 element_type
= func
.GetOriginalArgs()[-1].type
6338 assert all(arg
.type == element_type \
6339 for arg
in func
.GetOriginalArgs()[-self
.GetArrayCount(func
):])
6342 def GetArrayCount(self
, func
):
6343 """Returns the count of the elements in the array being PUT to."""
6344 return func
.GetInfo('count')
6346 class PUTHandler(ArrayArgTypeHandler
):
6347 """Handler for glTexParameter_v, glVertexAttrib_v functions."""
6350 ArrayArgTypeHandler
.__init
__(self
)
6352 def WriteServiceUnitTest(self
, func
, file, *extras
):
6353 """Writes the service unit test for a command."""
6354 expected_call
= "EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));"
6355 if func
.GetInfo("first_element_only"):
6357 arg
.GetValidGLArg(func
) for arg
in func
.GetOriginalArgs()
6359 gl_arg_strings
[-1] = "*" + gl_arg_strings
[-1]
6360 expected_call
= ("EXPECT_CALL(*gl_, %%(gl_func_name)s(%s));" %
6361 ", ".join(gl_arg_strings
))
6363 TEST_P(%(test_name)s, %(name)sValidArgs) {
6364 SpecializedSetup<cmds::%(name)s, 0>(true);
6367 GetSharedMemoryAs<%(data_type)s*>()[0] = %(data_value)s;
6369 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
6370 EXPECT_EQ(GL_NO_ERROR, GetGLError());
6374 'data_type': self
.GetArrayType(func
),
6375 'data_value': func
.GetInfo('data_value') or '0',
6376 'expected_call': expected_call
,
6378 self
.WriteValidUnitTest(func
, file, valid_test
, extra
, *extras
)
6381 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
6382 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
6383 SpecializedSetup<cmds::%(name)s, 0>(false);
6386 GetSharedMemoryAs<%(data_type)s*>()[0] = %(data_value)s;
6387 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
6390 self
.WriteInvalidUnitTest(func
, file, invalid_test
, extra
, *extras
)
6392 def WriteImmediateServiceUnitTest(self
, func
, file, *extras
):
6393 """Writes the service unit test for a command."""
6395 TEST_P(%(test_name)s, %(name)sValidArgs) {
6396 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
6397 SpecializedSetup<cmds::%(name)s, 0>(true);
6398 %(data_type)s temp[%(data_count)s] = { %(data_value)s, };
6399 cmd.Init(%(gl_args)s, &temp[0]);
6402 %(gl_func_name)s(%(gl_args)s, %(data_ref)sreinterpret_cast<
6403 %(data_type)s*>(ImmediateDataAddress(&cmd))));"""
6406 decoder_->set_unsafe_es3_apis_enabled(true);"""
6408 EXPECT_EQ(error::kNoError,
6409 ExecuteImmediateCmd(cmd, sizeof(temp)));
6410 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
6413 decoder_->set_unsafe_es3_apis_enabled(false);
6414 EXPECT_EQ(error::kUnknownCommand,
6415 ExecuteImmediateCmd(cmd, sizeof(temp)));"""
6420 arg
.GetValidGLArg(func
) for arg
in func
.GetOriginalArgs()[0:-1]
6422 gl_any_strings
= ["_"] * len(gl_arg_strings
)
6425 'data_ref': ("*" if func
.GetInfo('first_element_only') else ""),
6426 'data_type': self
.GetArrayType(func
),
6427 'data_count': self
.GetArrayCount(func
),
6428 'data_value': func
.GetInfo('data_value') or '0',
6429 'gl_args': ", ".join(gl_arg_strings
),
6430 'gl_any_args': ", ".join(gl_any_strings
),
6432 self
.WriteValidUnitTest(func
, file, valid_test
, extra
, *extras
)
6435 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
6436 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();"""
6439 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_any_args)s, _)).Times(1);
6443 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_any_args)s, _)).Times(0);
6446 SpecializedSetup<cmds::%(name)s, 0>(false);
6447 %(data_type)s temp[%(data_count)s] = { %(data_value)s, };
6448 cmd.Init(%(all_but_last_args)s, &temp[0]);"""
6451 decoder_->set_unsafe_es3_apis_enabled(true);
6452 EXPECT_EQ(error::%(parse_result)s,
6453 ExecuteImmediateCmd(cmd, sizeof(temp)));
6454 decoder_->set_unsafe_es3_apis_enabled(false);
6459 EXPECT_EQ(error::%(parse_result)s,
6460 ExecuteImmediateCmd(cmd, sizeof(temp)));
6464 self
.WriteInvalidUnitTest(func
, file, invalid_test
, extra
, *extras
)
6466 def WriteGetDataSizeCode(self
, func
, file):
6467 """Overrriden from TypeHandler."""
6468 code
= """ uint32_t data_size;
6469 if (!ComputeDataSize(1, sizeof(%s), %d, &data_size)) {
6470 return error::kOutOfBounds;
6473 file.Write(code
% (self
.GetArrayType(func
), self
.GetArrayCount(func
)))
6474 if func
.IsImmediate():
6475 file.Write(" if (data_size > immediate_data_size) {\n")
6476 file.Write(" return error::kOutOfBounds;\n")
6479 def __NeedsToCalcDataCount(self
, func
):
6480 use_count_func
= func
.GetInfo('use_count_func')
6481 return use_count_func
!= None and use_count_func
!= False
6483 def WriteGLES2Implementation(self
, func
, file):
6484 """Overrriden from TypeHandler."""
6485 impl_func
= func
.GetInfo('impl_func')
6486 if (impl_func
!= None and impl_func
!= True):
6488 file.Write("%s GLES2Implementation::%s(%s) {\n" %
6489 (func
.return_type
, func
.original_name
,
6490 func
.MakeTypedOriginalArgString("")))
6491 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
6492 func
.WriteDestinationInitalizationValidation(file)
6493 self
.WriteClientGLCallLog(func
, file)
6495 if self
.__NeedsToCalcDataCount
(func
):
6496 file.Write(" size_t count = GLES2Util::Calc%sDataCount(%s);\n" %
6497 (func
.name
, func
.GetOriginalArgs()[0].name
))
6498 file.Write(" DCHECK_LE(count, %du);\n" % self
.GetArrayCount(func
))
6500 file.Write(" size_t count = %d;" % self
.GetArrayCount(func
))
6501 file.Write(" for (size_t ii = 0; ii < count; ++ii)\n")
6502 file.Write(' GPU_CLIENT_LOG("value[" << ii << "]: " << %s[ii]);\n' %
6503 func
.GetLastOriginalArg().name
)
6504 for arg
in func
.GetOriginalArgs():
6505 arg
.WriteClientSideValidationCode(file, func
)
6506 file.Write(" helper_->%sImmediate(%s);\n" %
6507 (func
.name
, func
.MakeOriginalArgString("")))
6508 file.Write(" CheckGLError();\n")
6512 def WriteGLES2ImplementationUnitTest(self
, func
, file):
6513 """Writes the GLES2 Implemention unit test."""
6514 client_test
= func
.GetInfo('client_test')
6515 if (client_test
!= None and client_test
!= True):
6518 TEST_F(GLES2ImplementationTest, %(name)s) {
6519 %(type)s data[%(count)d] = {0};
6521 cmds::%(name)sImmediate cmd;
6522 %(type)s data[%(count)d];
6525 for (int jj = 0; jj < %(count)d; ++jj) {
6526 data[jj] = static_cast<%(type)s>(jj);
6529 expected.cmd.Init(%(cmd_args)s, &data[0]);
6530 gl_->%(name)s(%(args)s, &data[0]);
6531 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
6535 arg
.GetValidClientSideCmdArg(func
) for arg
in func
.GetCmdArgs()[0:-2]
6538 arg
.GetValidClientSideArg(func
) for arg
in func
.GetOriginalArgs()[0:-1]
6543 'type': self
.GetArrayType(func
),
6544 'count': self
.GetArrayCount(func
),
6545 'args': ", ".join(gl_arg_strings
),
6546 'cmd_args': ", ".join(cmd_arg_strings
),
6549 def WriteImmediateCmdComputeSize(self
, func
, file):
6550 """Overrriden from TypeHandler."""
6551 file.Write(" static uint32_t ComputeDataSize() {\n")
6552 file.Write(" return static_cast<uint32_t>(\n")
6553 file.Write(" sizeof(%s) * %d);\n" %
6554 (self
.GetArrayType(func
), self
.GetArrayCount(func
)))
6557 if self
.__NeedsToCalcDataCount
(func
):
6558 file.Write(" static uint32_t ComputeEffectiveDataSize(%s %s) {\n" %
6559 (func
.GetOriginalArgs()[0].type,
6560 func
.GetOriginalArgs()[0].name
))
6561 file.Write(" return static_cast<uint32_t>(\n")
6562 file.Write(" sizeof(%s) * GLES2Util::Calc%sDataCount(%s));\n" %
6563 (self
.GetArrayType(func
), func
.original_name
,
6564 func
.GetOriginalArgs()[0].name
))
6567 file.Write(" static uint32_t ComputeSize() {\n")
6568 file.Write(" return static_cast<uint32_t>(\n")
6570 " sizeof(ValueType) + ComputeDataSize());\n")
6574 def WriteImmediateCmdSetHeader(self
, func
, file):
6575 """Overrriden from TypeHandler."""
6576 file.Write(" void SetHeader() {\n")
6578 " header.SetCmdByTotalSize<ValueType>(ComputeSize());\n")
6582 def WriteImmediateCmdInit(self
, func
, file):
6583 """Overrriden from TypeHandler."""
6584 last_arg
= func
.GetLastOriginalArg()
6585 file.Write(" void Init(%s, %s _%s) {\n" %
6586 (func
.MakeTypedCmdArgString("_"),
6587 last_arg
.type, last_arg
.name
))
6588 file.Write(" SetHeader();\n")
6589 args
= func
.GetCmdArgs()
6591 file.Write(" %s = _%s;\n" % (arg
.name
, arg
.name
))
6592 file.Write(" memcpy(ImmediateDataAddress(this),\n")
6593 if self
.__NeedsToCalcDataCount
(func
):
6594 file.Write(" _%s, ComputeEffectiveDataSize(%s));" %
6595 (last_arg
.name
, func
.GetOriginalArgs()[0].name
))
6597 DCHECK_GE(ComputeDataSize(), ComputeEffectiveDataSize(%(arg)s));
6598 char* pointer = reinterpret_cast<char*>(ImmediateDataAddress(this)) +
6599 ComputeEffectiveDataSize(%(arg)s);
6600 memset(pointer, 0, ComputeDataSize() - ComputeEffectiveDataSize(%(arg)s));
6601 """ % { 'arg': func
.GetOriginalArgs()[0].name
, })
6603 file.Write(" _%s, ComputeDataSize());\n" % last_arg
.name
)
6607 def WriteImmediateCmdSet(self
, func
, file):
6608 """Overrriden from TypeHandler."""
6609 last_arg
= func
.GetLastOriginalArg()
6610 copy_args
= func
.MakeCmdArgString("_", False)
6611 file.Write(" void* Set(void* cmd%s, %s _%s) {\n" %
6612 (func
.MakeTypedCmdArgString("_", True),
6613 last_arg
.type, last_arg
.name
))
6614 file.Write(" static_cast<ValueType*>(cmd)->Init(%s, _%s);\n" %
6615 (copy_args
, last_arg
.name
))
6616 file.Write(" const uint32_t size = ComputeSize();\n")
6617 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
6622 def WriteImmediateCmdHelper(self
, func
, file):
6623 """Overrriden from TypeHandler."""
6624 code
= """ void %(name)s(%(typed_args)s) {
6625 const uint32_t size = gles2::cmds::%(name)s::ComputeSize();
6626 gles2::cmds::%(name)s* c =
6627 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
6636 "typed_args": func
.MakeTypedOriginalArgString(""),
6637 "args": func
.MakeOriginalArgString(""),
6640 def WriteImmediateFormatTest(self
, func
, file):
6641 """Overrriden from TypeHandler."""
6642 file.Write("TEST_F(GLES2FormatTest, %s) {\n" % func
.name
)
6643 file.Write(" const int kSomeBaseValueToTestWith = 51;\n")
6644 file.Write(" static %s data[] = {\n" % self
.GetArrayType(func
))
6645 for v
in range(0, self
.GetArrayCount(func
)):
6646 file.Write(" static_cast<%s>(kSomeBaseValueToTestWith + %d),\n" %
6647 (self
.GetArrayType(func
), v
))
6649 file.Write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
6650 (func
.name
, func
.name
))
6651 file.Write(" void* next_cmd = cmd.Set(\n")
6653 args
= func
.GetCmdArgs()
6654 for value
, arg
in enumerate(args
):
6655 file.Write(",\n static_cast<%s>(%d)" % (arg
.type, value
+ 11))
6656 file.Write(",\n data);\n")
6657 args
= func
.GetCmdArgs()
6658 file.Write(" EXPECT_EQ(static_cast<uint32_t>(cmds::%s::kCmdId),\n"
6660 file.Write(" cmd.header.command);\n")
6661 file.Write(" EXPECT_EQ(sizeof(cmd) +\n")
6662 file.Write(" RoundSizeToMultipleOfEntries(sizeof(data)),\n")
6663 file.Write(" cmd.header.size * 4u);\n")
6664 for value
, arg
in enumerate(args
):
6665 file.Write(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);\n" %
6666 (arg
.type, value
+ 11, arg
.name
))
6667 file.Write(" CheckBytesWrittenMatchesExpectedSize(\n")
6668 file.Write(" next_cmd, sizeof(cmd) +\n")
6669 file.Write(" RoundSizeToMultipleOfEntries(sizeof(data)));\n")
6670 file.Write(" // TODO(gman): Check that data was inserted;\n")
6675 class PUTnHandler(ArrayArgTypeHandler
):
6676 """Handler for PUTn 'glUniform__v' type functions."""
6679 ArrayArgTypeHandler
.__init
__(self
)
6681 def WriteServiceUnitTest(self
, func
, file, *extras
):
6682 """Overridden from TypeHandler."""
6683 ArrayArgTypeHandler
.WriteServiceUnitTest(self
, func
, file, *extras
)
6686 TEST_P(%(test_name)s, %(name)sValidArgsCountTooLarge) {
6687 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
6688 SpecializedSetup<cmds::%(name)s, 0>(true);
6691 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
6692 EXPECT_EQ(GL_NO_ERROR, GetGLError());
6697 for count
, arg
in enumerate(func
.GetOriginalArgs()):
6698 # hardcoded to match unit tests.
6700 # the location of the second element of the 2nd uniform.
6701 # defined in GLES2DecoderBase::SetupShaderForUniform
6702 gl_arg_strings
.append("3")
6703 arg_strings
.append("ProgramManager::MakeFakeLocation(1, 1)")
6705 # the number of elements that gl will be called with.
6706 gl_arg_strings
.append("3")
6707 # the number of elements requested in the command.
6708 arg_strings
.append("5")
6710 gl_arg_strings
.append(arg
.GetValidGLArg(func
))
6711 if not arg
.IsConstant():
6712 arg_strings
.append(arg
.GetValidArg(func
))
6714 'gl_args': ", ".join(gl_arg_strings
),
6715 'args': ", ".join(arg_strings
),
6717 self
.WriteValidUnitTest(func
, file, valid_test
, extra
, *extras
)
6719 def WriteImmediateServiceUnitTest(self
, func
, file, *extras
):
6720 """Overridden from TypeHandler."""
6722 TEST_P(%(test_name)s, %(name)sValidArgs) {
6723 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
6726 %(gl_func_name)s(%(gl_args)s,
6727 reinterpret_cast<%(data_type)s*>(ImmediateDataAddress(&cmd))));
6728 SpecializedSetup<cmds::%(name)s, 0>(true);
6729 %(data_type)s temp[%(data_count)s * 2] = { 0, };
6730 cmd.Init(%(args)s, &temp[0]);"""
6733 decoder_->set_unsafe_es3_apis_enabled(true);"""
6735 EXPECT_EQ(error::kNoError,
6736 ExecuteImmediateCmd(cmd, sizeof(temp)));
6737 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
6740 decoder_->set_unsafe_es3_apis_enabled(false);
6741 EXPECT_EQ(error::kUnknownCommand,
6742 ExecuteImmediateCmd(cmd, sizeof(temp)));"""
6749 for arg
in func
.GetOriginalArgs()[0:-1]:
6750 gl_arg_strings
.append(arg
.GetValidGLArg(func
))
6751 gl_any_strings
.append("_")
6752 if not arg
.IsConstant():
6753 arg_strings
.append(arg
.GetValidArg(func
))
6755 'data_type': self
.GetArrayType(func
),
6756 'data_count': self
.GetArrayCount(func
),
6757 'args': ", ".join(arg_strings
),
6758 'gl_args': ", ".join(gl_arg_strings
),
6759 'gl_any_args': ", ".join(gl_any_strings
),
6761 self
.WriteValidUnitTest(func
, file, valid_test
, extra
, *extras
)
6764 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
6765 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
6766 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_any_args)s, _)).Times(0);
6767 SpecializedSetup<cmds::%(name)s, 0>(false);
6768 %(data_type)s temp[%(data_count)s * 2] = { 0, };
6769 cmd.Init(%(all_but_last_args)s, &temp[0]);
6770 EXPECT_EQ(error::%(parse_result)s,
6771 ExecuteImmediateCmd(cmd, sizeof(temp)));%(gl_error_test)s
6774 self
.WriteInvalidUnitTest(func
, file, invalid_test
, extra
, *extras
)
6776 def WriteGetDataSizeCode(self
, func
, file):
6777 """Overrriden from TypeHandler."""
6778 code
= """ uint32_t data_size;
6779 if (!ComputeDataSize(count, sizeof(%s), %d, &data_size)) {
6780 return error::kOutOfBounds;
6783 file.Write(code
% (self
.GetArrayType(func
), self
.GetArrayCount(func
)))
6784 if func
.IsImmediate():
6785 file.Write(" if (data_size > immediate_data_size) {\n")
6786 file.Write(" return error::kOutOfBounds;\n")
6789 def WriteGLES2Implementation(self
, func
, file):
6790 """Overrriden from TypeHandler."""
6791 file.Write("%s GLES2Implementation::%s(%s) {\n" %
6792 (func
.return_type
, func
.original_name
,
6793 func
.MakeTypedOriginalArgString("")))
6794 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
6795 func
.WriteDestinationInitalizationValidation(file)
6796 self
.WriteClientGLCallLog(func
, file)
6797 last_pointer_name
= func
.GetLastOriginalPointerArg().name
6798 file.Write(""" GPU_CLIENT_LOG_CODE_BLOCK({
6799 for (GLsizei i = 0; i < count; ++i) {
6801 values_str
= ' << ", " << '.join(
6802 ["%s[%d + i * %d]" % (
6803 last_pointer_name
, ndx
, self
.GetArrayCount(func
)) for ndx
in range(
6804 0, self
.GetArrayCount(func
))])
6805 file.Write(' GPU_CLIENT_LOG(" " << i << ": " << %s);\n' % values_str
)
6806 file.Write(" }\n });\n")
6807 for arg
in func
.GetOriginalArgs():
6808 arg
.WriteClientSideValidationCode(file, func
)
6809 file.Write(" helper_->%sImmediate(%s);\n" %
6810 (func
.name
, func
.MakeInitString("")))
6811 file.Write(" CheckGLError();\n")
6815 def WriteGLES2ImplementationUnitTest(self
, func
, file):
6816 """Writes the GLES2 Implemention unit test."""
6818 TEST_F(GLES2ImplementationTest, %(name)s) {
6819 %(type)s data[%(count_param)d][%(count)d] = {{0}};
6821 cmds::%(name)sImmediate cmd;
6822 %(type)s data[%(count_param)d][%(count)d];
6826 for (int ii = 0; ii < %(count_param)d; ++ii) {
6827 for (int jj = 0; jj < %(count)d; ++jj) {
6828 data[ii][jj] = static_cast<%(type)s>(ii * %(count)d + jj);
6831 expected.cmd.Init(%(cmd_args)s);
6832 gl_->%(name)s(%(args)s);
6833 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
6836 cmd_arg_strings
= []
6837 for arg
in func
.GetCmdArgs():
6838 if arg
.name
.endswith("_shm_id"):
6839 cmd_arg_strings
.append("&data[0][0]")
6840 elif arg
.name
.endswith("_shm_offset"):
6843 cmd_arg_strings
.append(arg
.GetValidClientSideCmdArg(func
))
6846 for arg
in func
.GetOriginalArgs():
6848 valid_value
= "&data[0][0]"
6850 valid_value
= arg
.GetValidClientSideArg(func
)
6851 gl_arg_strings
.append(valid_value
)
6852 if arg
.name
== "count":
6853 count_param
= int(valid_value
)
6856 'type': self
.GetArrayType(func
),
6857 'count': self
.GetArrayCount(func
),
6858 'args': ", ".join(gl_arg_strings
),
6859 'cmd_args': ", ".join(cmd_arg_strings
),
6860 'count_param': count_param
,
6863 # Test constants for invalid values, as they are not tested by the
6866 arg
for arg
in func
.GetOriginalArgs()[0:-1] if arg
.IsConstant()
6872 TEST_F(GLES2ImplementationTest, %(name)sInvalidConstantArg%(invalid_index)d) {
6873 %(type)s data[%(count_param)d][%(count)d] = {{0}};
6874 for (int ii = 0; ii < %(count_param)d; ++ii) {
6875 for (int jj = 0; jj < %(count)d; ++jj) {
6876 data[ii][jj] = static_cast<%(type)s>(ii * %(count)d + jj);
6879 gl_->%(name)s(%(args)s);
6880 EXPECT_TRUE(NoCommandsWritten());
6881 EXPECT_EQ(%(gl_error)s, CheckError());
6884 for invalid_arg
in constants
:
6886 invalid
= invalid_arg
.GetInvalidArg(func
)
6887 for arg
in func
.GetOriginalArgs():
6888 if arg
is invalid_arg
:
6889 gl_arg_strings
.append(invalid
[0])
6890 elif arg
.IsPointer():
6891 gl_arg_strings
.append("&data[0][0]")
6893 valid_value
= arg
.GetValidClientSideArg(func
)
6894 gl_arg_strings
.append(valid_value
)
6895 if arg
.name
== "count":
6896 count_param
= int(valid_value
)
6900 'invalid_index': func
.GetOriginalArgs().index(invalid_arg
),
6901 'type': self
.GetArrayType(func
),
6902 'count': self
.GetArrayCount(func
),
6903 'args': ", ".join(gl_arg_strings
),
6904 'gl_error': invalid
[2],
6905 'count_param': count_param
,
6909 def WriteImmediateCmdComputeSize(self
, func
, file):
6910 """Overrriden from TypeHandler."""
6911 file.Write(" static uint32_t ComputeDataSize(GLsizei count) {\n")
6912 file.Write(" return static_cast<uint32_t>(\n")
6913 file.Write(" sizeof(%s) * %d * count); // NOLINT\n" %
6914 (self
.GetArrayType(func
), self
.GetArrayCount(func
)))
6917 file.Write(" static uint32_t ComputeSize(GLsizei count) {\n")
6918 file.Write(" return static_cast<uint32_t>(\n")
6920 " sizeof(ValueType) + ComputeDataSize(count)); // NOLINT\n")
6924 def WriteImmediateCmdSetHeader(self
, func
, file):
6925 """Overrriden from TypeHandler."""
6926 file.Write(" void SetHeader(GLsizei count) {\n")
6928 " header.SetCmdByTotalSize<ValueType>(ComputeSize(count));\n")
6932 def WriteImmediateCmdInit(self
, func
, file):
6933 """Overrriden from TypeHandler."""
6934 file.Write(" void Init(%s) {\n" %
6935 func
.MakeTypedInitString("_"))
6936 file.Write(" SetHeader(_count);\n")
6937 args
= func
.GetCmdArgs()
6939 file.Write(" %s = _%s;\n" % (arg
.name
, arg
.name
))
6940 file.Write(" memcpy(ImmediateDataAddress(this),\n")
6941 pointer_arg
= func
.GetLastOriginalPointerArg()
6942 file.Write(" _%s, ComputeDataSize(_count));\n" % pointer_arg
.name
)
6946 def WriteImmediateCmdSet(self
, func
, file):
6947 """Overrriden from TypeHandler."""
6948 file.Write(" void* Set(void* cmd%s) {\n" %
6949 func
.MakeTypedInitString("_", True))
6950 file.Write(" static_cast<ValueType*>(cmd)->Init(%s);\n" %
6951 func
.MakeInitString("_"))
6952 file.Write(" const uint32_t size = ComputeSize(_count);\n")
6953 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
6958 def WriteImmediateCmdHelper(self
, func
, file):
6959 """Overrriden from TypeHandler."""
6960 code
= """ void %(name)s(%(typed_args)s) {
6961 const uint32_t size = gles2::cmds::%(name)s::ComputeSize(count);
6962 gles2::cmds::%(name)s* c =
6963 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
6972 "typed_args": func
.MakeTypedInitString(""),
6973 "args": func
.MakeInitString("")
6976 def WriteImmediateFormatTest(self
, func
, file):
6977 """Overrriden from TypeHandler."""
6978 args
= func
.GetOriginalArgs()
6981 if arg
.name
== "count":
6982 count_param
= int(arg
.GetValidClientSideCmdArg(func
))
6983 file.Write("TEST_F(GLES2FormatTest, %s) {\n" % func
.name
)
6984 file.Write(" const int kSomeBaseValueToTestWith = 51;\n")
6985 file.Write(" static %s data[] = {\n" % self
.GetArrayType(func
))
6986 for v
in range(0, self
.GetArrayCount(func
) * count_param
):
6987 file.Write(" static_cast<%s>(kSomeBaseValueToTestWith + %d),\n" %
6988 (self
.GetArrayType(func
), v
))
6990 file.Write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
6991 (func
.name
, func
.name
))
6992 file.Write(" const GLsizei kNumElements = %d;\n" % count_param
)
6993 file.Write(" const size_t kExpectedCmdSize =\n")
6994 file.Write(" sizeof(cmd) + kNumElements * sizeof(%s) * %d;\n" %
6995 (self
.GetArrayType(func
), self
.GetArrayCount(func
)))
6996 file.Write(" void* next_cmd = cmd.Set(\n")
6998 for value
, arg
in enumerate(args
):
7000 file.Write(",\n data")
7001 elif arg
.IsConstant():
7004 file.Write(",\n static_cast<%s>(%d)" % (arg
.type, value
+ 1))
7006 file.Write(" EXPECT_EQ(static_cast<uint32_t>(cmds::%s::kCmdId),\n" %
7008 file.Write(" cmd.header.command);\n")
7009 file.Write(" EXPECT_EQ(kExpectedCmdSize, cmd.header.size * 4u);\n")
7010 for value
, arg
in enumerate(args
):
7011 if arg
.IsPointer() or arg
.IsConstant():
7013 file.Write(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);\n" %
7014 (arg
.type, value
+ 1, arg
.name
))
7015 file.Write(" CheckBytesWrittenMatchesExpectedSize(\n")
7016 file.Write(" next_cmd, sizeof(cmd) +\n")
7017 file.Write(" RoundSizeToMultipleOfEntries(sizeof(data)));\n")
7018 file.Write(" // TODO(gman): Check that data was inserted;\n")
7022 class PUTSTRHandler(ArrayArgTypeHandler
):
7023 """Handler for functions that pass a string array."""
7026 ArrayArgTypeHandler
.__init
__(self
)
7028 def __GetDataArg(self
, func
):
7029 """Return the argument that points to the 2D char arrays"""
7030 for arg
in func
.GetOriginalArgs():
7031 if arg
.IsPointer2D():
7035 def __GetLengthArg(self
, func
):
7036 """Return the argument that holds length for each char array"""
7037 for arg
in func
.GetOriginalArgs():
7038 if arg
.IsPointer() and not arg
.IsPointer2D():
7042 def WriteGLES2Implementation(self
, func
, file):
7043 """Overrriden from TypeHandler."""
7044 file.Write("%s GLES2Implementation::%s(%s) {\n" %
7045 (func
.return_type
, func
.original_name
,
7046 func
.MakeTypedOriginalArgString("")))
7047 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
7048 func
.WriteDestinationInitalizationValidation(file)
7049 self
.WriteClientGLCallLog(func
, file)
7050 data_arg
= self
.__GetDataArg
(func
)
7051 length_arg
= self
.__GetLengthArg
(func
)
7052 log_code_block
= """ GPU_CLIENT_LOG_CODE_BLOCK({
7053 for (GLsizei ii = 0; ii < count; ++ii) {
7054 if (%(data)s[ii]) {"""
7055 if length_arg
== None:
7056 log_code_block
+= """
7057 GPU_CLIENT_LOG(" " << ii << ": ---\\n" << %(data)s[ii] << "\\n---");"""
7059 log_code_block
+= """
7060 if (%(length)s && %(length)s[ii] >= 0) {
7061 const std::string my_str(%(data)s[ii], %(length)s[ii]);
7062 GPU_CLIENT_LOG(" " << ii << ": ---\\n" << my_str << "\\n---");
7064 GPU_CLIENT_LOG(" " << ii << ": ---\\n" << %(data)s[ii] << "\\n---");
7066 log_code_block
+= """
7068 GPU_CLIENT_LOG(" " << ii << ": NULL");
7073 file.Write(log_code_block
% {
7074 'data': data_arg
.name
,
7075 'length': length_arg
.name
if not length_arg
== None else ''
7077 for arg
in func
.GetOriginalArgs():
7078 arg
.WriteClientSideValidationCode(file, func
)
7081 for arg
in func
.GetOriginalArgs():
7082 if arg
.name
== 'count' or arg
== self
.__GetLengthArg
(func
):
7084 if arg
== self
.__GetDataArg
(func
):
7085 bucket_args
.append('kResultBucketId')
7087 bucket_args
.append(arg
.name
)
7089 if (!PackStringsToBucket(count, %(data)s, %(length)s, "gl%(func_name)s")) {
7092 helper_->%(func_name)sBucket(%(bucket_args)s);
7093 helper_->SetBucketSize(kResultBucketId, 0);
7098 file.Write(code_block
% {
7099 'data': data_arg
.name
,
7100 'length': length_arg
.name
if not length_arg
== None else 'NULL',
7101 'func_name': func
.name
,
7102 'bucket_args': ', '.join(bucket_args
),
7105 def WriteGLES2ImplementationUnitTest(self
, func
, file):
7106 """Overrriden from TypeHandler."""
7108 TEST_F(GLES2ImplementationTest, %(name)s) {
7109 const uint32 kBucketId = GLES2Implementation::kResultBucketId;
7110 const char* kString1 = "happy";
7111 const char* kString2 = "ending";
7112 const size_t kString1Size = ::strlen(kString1) + 1;
7113 const size_t kString2Size = ::strlen(kString2) + 1;
7114 const size_t kHeaderSize = sizeof(GLint) * 3;
7115 const size_t kSourceSize = kHeaderSize + kString1Size + kString2Size;
7116 const size_t kPaddedHeaderSize =
7117 transfer_buffer_->RoundToAlignment(kHeaderSize);
7118 const size_t kPaddedString1Size =
7119 transfer_buffer_->RoundToAlignment(kString1Size);
7120 const size_t kPaddedString2Size =
7121 transfer_buffer_->RoundToAlignment(kString2Size);
7123 cmd::SetBucketSize set_bucket_size;
7124 cmd::SetBucketData set_bucket_header;
7125 cmd::SetToken set_token1;
7126 cmd::SetBucketData set_bucket_data1;
7127 cmd::SetToken set_token2;
7128 cmd::SetBucketData set_bucket_data2;
7129 cmd::SetToken set_token3;
7130 cmds::%(name)sBucket cmd_bucket;
7131 cmd::SetBucketSize clear_bucket_size;
7134 ExpectedMemoryInfo mem0 = GetExpectedMemory(kPaddedHeaderSize);
7135 ExpectedMemoryInfo mem1 = GetExpectedMemory(kPaddedString1Size);
7136 ExpectedMemoryInfo mem2 = GetExpectedMemory(kPaddedString2Size);
7139 expected.set_bucket_size.Init(kBucketId, kSourceSize);
7140 expected.set_bucket_header.Init(
7141 kBucketId, 0, kHeaderSize, mem0.id, mem0.offset);
7142 expected.set_token1.Init(GetNextToken());
7143 expected.set_bucket_data1.Init(
7144 kBucketId, kHeaderSize, kString1Size, mem1.id, mem1.offset);
7145 expected.set_token2.Init(GetNextToken());
7146 expected.set_bucket_data2.Init(
7147 kBucketId, kHeaderSize + kString1Size, kString2Size, mem2.id,
7149 expected.set_token3.Init(GetNextToken());
7150 expected.cmd_bucket.Init(%(bucket_args)s);
7151 expected.clear_bucket_size.Init(kBucketId, 0);
7152 const char* kStrings[] = { kString1, kString2 };
7153 gl_->%(name)s(%(gl_args)s);
7154 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
7159 for arg
in func
.GetOriginalArgs():
7160 if arg
== self
.__GetDataArg
(func
):
7161 gl_args
.append('kStrings')
7162 bucket_args
.append('kBucketId')
7163 elif arg
== self
.__GetLengthArg
(func
):
7164 gl_args
.append('NULL')
7165 elif arg
.name
== 'count':
7168 gl_args
.append(arg
.GetValidClientSideArg(func
))
7169 bucket_args
.append(arg
.GetValidClientSideArg(func
))
7172 'gl_args': ", ".join(gl_args
),
7173 'bucket_args': ", ".join(bucket_args
),
7176 if self
.__GetLengthArg
(func
) == None:
7179 TEST_F(GLES2ImplementationTest, %(name)sWithLength) {
7180 const uint32 kBucketId = GLES2Implementation::kResultBucketId;
7181 const char* kString = "foobar******";
7182 const size_t kStringSize = 6; // We only need "foobar".
7183 const size_t kHeaderSize = sizeof(GLint) * 2;
7184 const size_t kSourceSize = kHeaderSize + kStringSize + 1;
7185 const size_t kPaddedHeaderSize =
7186 transfer_buffer_->RoundToAlignment(kHeaderSize);
7187 const size_t kPaddedStringSize =
7188 transfer_buffer_->RoundToAlignment(kStringSize + 1);
7190 cmd::SetBucketSize set_bucket_size;
7191 cmd::SetBucketData set_bucket_header;
7192 cmd::SetToken set_token1;
7193 cmd::SetBucketData set_bucket_data;
7194 cmd::SetToken set_token2;
7195 cmds::ShaderSourceBucket shader_source_bucket;
7196 cmd::SetBucketSize clear_bucket_size;
7199 ExpectedMemoryInfo mem0 = GetExpectedMemory(kPaddedHeaderSize);
7200 ExpectedMemoryInfo mem1 = GetExpectedMemory(kPaddedStringSize);
7203 expected.set_bucket_size.Init(kBucketId, kSourceSize);
7204 expected.set_bucket_header.Init(
7205 kBucketId, 0, kHeaderSize, mem0.id, mem0.offset);
7206 expected.set_token1.Init(GetNextToken());
7207 expected.set_bucket_data.Init(
7208 kBucketId, kHeaderSize, kStringSize + 1, mem1.id, mem1.offset);
7209 expected.set_token2.Init(GetNextToken());
7210 expected.shader_source_bucket.Init(%(bucket_args)s);
7211 expected.clear_bucket_size.Init(kBucketId, 0);
7212 const char* kStrings[] = { kString };
7213 const GLint kLength[] = { kStringSize };
7214 gl_->%(name)s(%(gl_args)s);
7215 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
7219 for arg
in func
.GetOriginalArgs():
7220 if arg
== self
.__GetDataArg
(func
):
7221 gl_args
.append('kStrings')
7222 elif arg
== self
.__GetLengthArg
(func
):
7223 gl_args
.append('kLength')
7224 elif arg
.name
== 'count':
7227 gl_args
.append(arg
.GetValidClientSideArg(func
))
7230 'gl_args': ", ".join(gl_args
),
7231 'bucket_args': ", ".join(bucket_args
),
7234 def WriteBucketServiceUnitTest(self
, func
, file, *extras
):
7235 """Overrriden from TypeHandler."""
7237 cmd_args_with_invalid_id
= []
7239 for index
, arg
in enumerate(func
.GetOriginalArgs()):
7240 if arg
== self
.__GetLengthArg
(func
):
7242 elif arg
.name
== 'count':
7244 elif arg
== self
.__GetDataArg
(func
):
7245 cmd_args
.append('kBucketId')
7246 cmd_args_with_invalid_id
.append('kBucketId')
7248 elif index
== 0: # Resource ID arg
7249 cmd_args
.append(arg
.GetValidArg(func
))
7250 cmd_args_with_invalid_id
.append('kInvalidClientId')
7251 gl_args
.append(arg
.GetValidGLArg(func
))
7253 cmd_args
.append(arg
.GetValidArg(func
))
7254 cmd_args_with_invalid_id
.append(arg
.GetValidArg(func
))
7255 gl_args
.append(arg
.GetValidGLArg(func
))
7258 TEST_P(%(test_name)s, %(name)sValidArgs) {
7259 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
7260 const uint32 kBucketId = 123;
7261 const char kSource0[] = "hello";
7262 const char* kSource[] = { kSource0 };
7263 const char kValidStrEnd = 0;
7264 SetBucketAsCStrings(kBucketId, 1, kSource, 1, kValidStrEnd);
7266 cmd.Init(%(cmd_args)s);
7267 decoder_->set_unsafe_es3_apis_enabled(true);
7268 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));"""
7271 decoder_->set_unsafe_es3_apis_enabled(false);
7272 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));
7277 self
.WriteValidUnitTest(func
, file, test
, {
7278 'cmd_args': ", ".join(cmd_args
),
7279 'gl_args': ", ".join(gl_args
),
7283 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
7284 const uint32 kBucketId = 123;
7285 const char kSource0[] = "hello";
7286 const char* kSource[] = { kSource0 };
7287 const char kValidStrEnd = 0;
7288 decoder_->set_unsafe_es3_apis_enabled(true);
7291 cmd.Init(%(cmd_args)s);
7292 EXPECT_NE(error::kNoError, ExecuteCmd(cmd));
7293 // Test invalid client.
7294 SetBucketAsCStrings(kBucketId, 1, kSource, 1, kValidStrEnd);
7295 cmd.Init(%(cmd_args_with_invalid_id)s);
7296 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
7297 EXPECT_EQ(GL_INVALID_VALUE, GetGLError());
7300 self
.WriteValidUnitTest(func
, file, test
, {
7301 'cmd_args': ", ".join(cmd_args
),
7302 'cmd_args_with_invalid_id': ", ".join(cmd_args_with_invalid_id
),
7306 TEST_P(%(test_name)s, %(name)sInvalidHeader) {
7307 const uint32 kBucketId = 123;
7308 const char kSource0[] = "hello";
7309 const char* kSource[] = { kSource0 };
7310 const char kValidStrEnd = 0;
7311 const GLsizei kCount = static_cast<GLsizei>(arraysize(kSource));
7312 const GLsizei kTests[] = {
7315 std::numeric_limits<GLsizei>::max(),
7318 decoder_->set_unsafe_es3_apis_enabled(true);
7319 for (size_t ii = 0; ii < arraysize(kTests); ++ii) {
7320 SetBucketAsCStrings(kBucketId, 1, kSource, kTests[ii], kValidStrEnd);
7322 cmd.Init(%(cmd_args)s);
7323 EXPECT_EQ(error::kInvalidArguments, ExecuteCmd(cmd));
7327 self
.WriteValidUnitTest(func
, file, test
, {
7328 'cmd_args': ", ".join(cmd_args
),
7332 TEST_P(%(test_name)s, %(name)sInvalidStringEnding) {
7333 const uint32 kBucketId = 123;
7334 const char kSource0[] = "hello";
7335 const char* kSource[] = { kSource0 };
7336 const char kInvalidStrEnd = '*';
7337 SetBucketAsCStrings(kBucketId, 1, kSource, 1, kInvalidStrEnd);
7339 cmd.Init(%(cmd_args)s);
7340 decoder_->set_unsafe_es3_apis_enabled(true);
7341 EXPECT_EQ(error::kInvalidArguments, ExecuteCmd(cmd));
7344 self
.WriteValidUnitTest(func
, file, test
, {
7345 'cmd_args': ", ".join(cmd_args
),
7349 class PUTXnHandler(ArrayArgTypeHandler
):
7350 """Handler for glUniform?f functions."""
7352 ArrayArgTypeHandler
.__init
__(self
)
7354 def WriteHandlerImplementation(self
, func
, file):
7355 """Overrriden from TypeHandler."""
7356 code
= """ %(type)s temp[%(count)s] = { %(values)s};"""
7359 gl%(name)sv(%(location)s, 1, &temp[0]);
7363 Do%(name)sv(%(location)s, 1, &temp[0]);
7366 args
= func
.GetOriginalArgs()
7367 count
= int(self
.GetArrayCount(func
))
7368 num_args
= len(args
)
7369 for ii
in range(count
):
7370 values
+= "%s, " % args
[len(args
) - count
+ ii
].name
7374 'count': self
.GetArrayCount(func
),
7375 'type': self
.GetArrayType(func
),
7376 'location': args
[0].name
,
7377 'args': func
.MakeOriginalArgString(""),
7381 def WriteServiceUnitTest(self
, func
, file, *extras
):
7382 """Overrriden from TypeHandler."""
7384 TEST_P(%(test_name)s, %(name)sValidArgs) {
7385 EXPECT_CALL(*gl_, %(name)sv(%(local_args)s));
7386 SpecializedSetup<cmds::%(name)s, 0>(true);
7388 cmd.Init(%(args)s);"""
7391 decoder_->set_unsafe_es3_apis_enabled(true);"""
7393 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
7394 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
7397 decoder_->set_unsafe_es3_apis_enabled(false);
7398 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));"""
7402 args
= func
.GetOriginalArgs()
7403 local_args
= "%s, 1, _" % args
[0].GetValidGLArg(func
)
7404 self
.WriteValidUnitTest(func
, file, valid_test
, {
7406 'count': self
.GetArrayCount(func
),
7407 'local_args': local_args
,
7411 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
7412 EXPECT_CALL(*gl_, %(name)sv(_, _, _).Times(0);
7413 SpecializedSetup<cmds::%(name)s, 0>(false);
7416 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
7419 self
.WriteInvalidUnitTest(func
, file, invalid_test
, {
7420 'name': func
.GetInfo('name'),
7421 'count': self
.GetArrayCount(func
),
7425 class GLcharHandler(CustomHandler
):
7426 """Handler for functions that pass a single string ."""
7429 CustomHandler
.__init
__(self
)
7431 def WriteImmediateCmdComputeSize(self
, func
, file):
7432 """Overrriden from TypeHandler."""
7433 file.Write(" static uint32_t ComputeSize(uint32_t data_size) {\n")
7434 file.Write(" return static_cast<uint32_t>(\n")
7435 file.Write(" sizeof(ValueType) + data_size); // NOLINT\n")
7438 def WriteImmediateCmdSetHeader(self
, func
, file):
7439 """Overrriden from TypeHandler."""
7441 void SetHeader(uint32_t data_size) {
7442 header.SetCmdBySize<ValueType>(data_size);
7447 def WriteImmediateCmdInit(self
, func
, file):
7448 """Overrriden from TypeHandler."""
7449 last_arg
= func
.GetLastOriginalArg()
7450 args
= func
.GetCmdArgs()
7453 set_code
.append(" %s = _%s;" % (arg
.name
, arg
.name
))
7455 void Init(%(typed_args)s, uint32_t _data_size) {
7456 SetHeader(_data_size);
7458 memcpy(ImmediateDataAddress(this), _%(last_arg)s, _data_size);
7463 "typed_args": func
.MakeTypedArgString("_"),
7464 "set_code": "\n".join(set_code
),
7465 "last_arg": last_arg
.name
7468 def WriteImmediateCmdSet(self
, func
, file):
7469 """Overrriden from TypeHandler."""
7470 last_arg
= func
.GetLastOriginalArg()
7471 file.Write(" void* Set(void* cmd%s, uint32_t _data_size) {\n" %
7472 func
.MakeTypedCmdArgString("_", True))
7473 file.Write(" static_cast<ValueType*>(cmd)->Init(%s, _data_size);\n" %
7474 func
.MakeCmdArgString("_"))
7475 file.Write(" return NextImmediateCmdAddress<ValueType>("
7476 "cmd, _data_size);\n")
7480 def WriteImmediateCmdHelper(self
, func
, file):
7481 """Overrriden from TypeHandler."""
7482 code
= """ void %(name)s(%(typed_args)s) {
7483 const uint32_t data_size = strlen(name);
7484 gles2::cmds::%(name)s* c =
7485 GetImmediateCmdSpace<gles2::cmds::%(name)s>(data_size);
7487 c->Init(%(args)s, data_size);
7494 "typed_args": func
.MakeTypedOriginalArgString(""),
7495 "args": func
.MakeOriginalArgString(""),
7499 def WriteImmediateFormatTest(self
, func
, file):
7500 """Overrriden from TypeHandler."""
7503 all_but_last_arg
= func
.GetCmdArgs()[:-1]
7504 for value
, arg
in enumerate(all_but_last_arg
):
7505 init_code
.append(" static_cast<%s>(%d)," % (arg
.type, value
+ 11))
7506 for value
, arg
in enumerate(all_but_last_arg
):
7507 check_code
.append(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);" %
7508 (arg
.type, value
+ 11, arg
.name
))
7510 TEST_F(GLES2FormatTest, %(func_name)s) {
7511 cmds::%(func_name)s& cmd = *GetBufferAs<cmds::%(func_name)s>();
7512 static const char* const test_str = \"test string\";
7513 void* next_cmd = cmd.Set(
7518 EXPECT_EQ(static_cast<uint32_t>(cmds::%(func_name)s::kCmdId),
7519 cmd.header.command);
7520 EXPECT_EQ(sizeof(cmd) +
7521 RoundSizeToMultipleOfEntries(strlen(test_str)),
7522 cmd.header.size * 4u);
7523 EXPECT_EQ(static_cast<char*>(next_cmd),
7524 reinterpret_cast<char*>(&cmd) + sizeof(cmd) +
7525 RoundSizeToMultipleOfEntries(strlen(test_str)));
7527 EXPECT_EQ(static_cast<uint32_t>(strlen(test_str)), cmd.data_size);
7528 EXPECT_EQ(0, memcmp(test_str, ImmediateDataAddress(&cmd), strlen(test_str)));
7531 sizeof(cmd) + RoundSizeToMultipleOfEntries(strlen(test_str)),
7532 sizeof(cmd) + strlen(test_str));
7537 'func_name': func
.name
,
7538 'init_code': "\n".join(init_code
),
7539 'check_code': "\n".join(check_code
),
7543 class GLcharNHandler(CustomHandler
):
7544 """Handler for functions that pass a single string with an optional len."""
7547 CustomHandler
.__init
__(self
)
7549 def InitFunction(self
, func
):
7550 """Overrriden from TypeHandler."""
7552 func
.AddCmdArg(Argument('bucket_id', 'GLuint'))
7554 def NeedsDataTransferFunction(self
, func
):
7555 """Overriden from TypeHandler."""
7558 def AddBucketFunction(self
, generator
, func
):
7559 """Overrriden from TypeHandler."""
7562 def WriteServiceImplementation(self
, func
, file):
7563 """Overrriden from TypeHandler."""
7564 self
.WriteServiceHandlerFunctionHeader(func
, file)
7566 GLuint bucket_id = static_cast<GLuint>(c.%(bucket_id)s);
7567 Bucket* bucket = GetBucket(bucket_id);
7568 if (!bucket || bucket->size() == 0) {
7569 return error::kInvalidArguments;
7572 if (!bucket->GetAsString(&str)) {
7573 return error::kInvalidArguments;
7575 %(gl_func_name)s(0, str.c_str());
7576 return error::kNoError;
7581 'gl_func_name': func
.GetGLFunctionName(),
7582 'bucket_id': func
.cmd_args
[0].name
,
7586 class IsHandler(TypeHandler
):
7587 """Handler for glIs____ type and glGetError functions."""
7590 TypeHandler
.__init
__(self
)
7592 def InitFunction(self
, func
):
7593 """Overrriden from TypeHandler."""
7594 func
.AddCmdArg(Argument("result_shm_id", 'uint32_t'))
7595 func
.AddCmdArg(Argument("result_shm_offset", 'uint32_t'))
7596 if func
.GetInfo('result') == None:
7597 func
.AddInfo('result', ['uint32_t'])
7599 def WriteServiceUnitTest(self
, func
, file, *extras
):
7600 """Overrriden from TypeHandler."""
7602 TEST_P(%(test_name)s, %(name)sValidArgs) {
7603 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
7604 SpecializedSetup<cmds::%(name)s, 0>(true);
7606 cmd.Init(%(args)s%(comma)sshared_memory_id_, shared_memory_offset_);"""
7609 decoder_->set_unsafe_es3_apis_enabled(true);"""
7611 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
7612 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
7615 decoder_->set_unsafe_es3_apis_enabled(false);
7616 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));"""
7621 if len(func
.GetOriginalArgs()):
7623 self
.WriteValidUnitTest(func
, file, valid_test
, {
7628 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
7629 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
7630 SpecializedSetup<cmds::%(name)s, 0>(false);
7632 cmd.Init(%(args)s%(comma)sshared_memory_id_, shared_memory_offset_);
7633 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
7636 self
.WriteInvalidUnitTest(func
, file, invalid_test
, {
7641 TEST_P(%(test_name)s, %(name)sInvalidArgsBadSharedMemoryId) {
7642 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
7643 SpecializedSetup<cmds::%(name)s, 0>(false);"""
7646 decoder_->set_unsafe_es3_apis_enabled(true);"""
7649 cmd.Init(%(args)s%(comma)skInvalidSharedMemoryId, shared_memory_offset_);
7650 EXPECT_EQ(error::kOutOfBounds, ExecuteCmd(cmd));
7651 cmd.Init(%(args)s%(comma)sshared_memory_id_, kInvalidSharedMemoryOffset);
7652 EXPECT_EQ(error::kOutOfBounds, ExecuteCmd(cmd));"""
7655 decoder_->set_unsafe_es3_apis_enabled(true);"""
7659 self
.WriteValidUnitTest(func
, file, invalid_test
, {
7663 def WriteServiceImplementation(self
, func
, file):
7664 """Overrriden from TypeHandler."""
7665 self
.WriteServiceHandlerFunctionHeader(func
, file)
7666 args
= func
.GetOriginalArgs()
7668 arg
.WriteGetCode(file)
7670 code
= """ typedef cmds::%(func_name)s::Result Result;
7671 Result* result_dst = GetSharedMemoryAs<Result*>(
7672 c.result_shm_id, c.result_shm_offset, sizeof(*result_dst));
7674 return error::kOutOfBounds;
7677 file.Write(code
% {'func_name': func
.name
})
7678 func
.WriteHandlerValidation(file)
7680 assert func
.GetInfo('id_mapping')
7681 assert len(func
.GetInfo('id_mapping')) == 1
7682 assert len(args
) == 1
7683 id_type
= func
.GetInfo('id_mapping')[0]
7684 file.Write(" %s service_%s = 0;\n" % (args
[0].type, id_type
.lower()))
7685 file.Write(" *result_dst = group_->Get%sServiceId(%s, &service_%s);\n" %
7686 (id_type
, id_type
.lower(), id_type
.lower()))
7688 file.Write(" *result_dst = %s(%s);\n" %
7689 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
7690 file.Write(" return error::kNoError;\n")
7694 def WriteGLES2Implementation(self
, func
, file):
7695 """Overrriden from TypeHandler."""
7696 impl_func
= func
.GetInfo('impl_func')
7697 if impl_func
== None or impl_func
== True:
7698 error_value
= func
.GetInfo("error_value") or "GL_FALSE"
7699 file.Write("%s GLES2Implementation::%s(%s) {\n" %
7700 (func
.return_type
, func
.original_name
,
7701 func
.MakeTypedOriginalArgString("")))
7702 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
7703 self
.WriteTraceEvent(func
, file)
7704 func
.WriteDestinationInitalizationValidation(file)
7705 self
.WriteClientGLCallLog(func
, file)
7706 file.Write(" typedef cmds::%s::Result Result;\n" % func
.name
)
7707 file.Write(" Result* result = GetResultAs<Result*>();\n")
7708 file.Write(" if (!result) {\n")
7709 file.Write(" return %s;\n" % error_value
)
7711 file.Write(" *result = 0;\n")
7712 assert len(func
.GetOriginalArgs()) == 1
7713 id_arg
= func
.GetOriginalArgs()[0]
7714 if id_arg
.type == 'GLsync':
7715 arg_string
= "ToGLuint(%s)" % func
.MakeOriginalArgString("")
7717 arg_string
= func
.MakeOriginalArgString("")
7719 " helper_->%s(%s, GetResultShmId(), GetResultShmOffset());\n" %
7720 (func
.name
, arg_string
))
7721 file.Write(" WaitForCmd();\n")
7722 file.Write(" %s result_value = *result" % func
.return_type
)
7723 if func
.return_type
== "GLboolean":
7725 file.Write(';\n GPU_CLIENT_LOG("returned " << result_value);\n')
7726 file.Write(" CheckGLError();\n")
7727 file.Write(" return result_value;\n")
7731 def WriteGLES2ImplementationUnitTest(self
, func
, file):
7732 """Overrriden from TypeHandler."""
7733 client_test
= func
.GetInfo('client_test')
7734 if client_test
== None or client_test
== True:
7736 TEST_F(GLES2ImplementationTest, %(name)s) {
7742 ExpectedMemoryInfo result1 =
7743 GetExpectedResultMemory(sizeof(cmds::%(name)s::Result));
7744 expected.cmd.Init(%(cmd_id_value)s, result1.id, result1.offset);
7746 EXPECT_CALL(*command_buffer(), OnFlush())
7747 .WillOnce(SetMemory(result1.ptr, uint32_t(GL_TRUE)))
7748 .RetiresOnSaturation();
7750 GLboolean result = gl_->%(name)s(%(gl_id_value)s);
7751 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
7752 EXPECT_TRUE(result);
7755 args
= func
.GetOriginalArgs()
7756 assert len(args
) == 1
7759 'cmd_id_value': args
[0].GetValidClientSideCmdArg(func
),
7760 'gl_id_value': args
[0].GetValidClientSideArg(func
) })
7763 class STRnHandler(TypeHandler
):
7764 """Handler for GetProgramInfoLog, GetShaderInfoLog, GetShaderSource, and
7765 GetTranslatedShaderSourceANGLE."""
7768 TypeHandler
.__init
__(self
)
7770 def InitFunction(self
, func
):
7771 """Overrriden from TypeHandler."""
7772 # remove all but the first cmd args.
7773 cmd_args
= func
.GetCmdArgs()
7775 func
.AddCmdArg(cmd_args
[0])
7776 # add on a bucket id.
7777 func
.AddCmdArg(Argument('bucket_id', 'uint32_t'))
7779 def WriteGLES2Implementation(self
, func
, file):
7780 """Overrriden from TypeHandler."""
7781 code_1
= """%(return_type)s GLES2Implementation::%(func_name)s(%(args)s) {
7782 GPU_CLIENT_SINGLE_THREAD_CHECK();
7784 code_2
= """ GPU_CLIENT_LOG("[" << GetLogPrefix()
7785 << "] gl%(func_name)s" << "("
7788 << static_cast<void*>(%(arg2)s) << ", "
7789 << static_cast<void*>(%(arg3)s) << ")");
7790 helper_->SetBucketSize(kResultBucketId, 0);
7791 helper_->%(func_name)s(%(id_name)s, kResultBucketId);
7793 GLsizei max_size = 0;
7794 if (GetBucketAsString(kResultBucketId, &str)) {
7797 std::min(static_cast<size_t>(%(bufsize_name)s) - 1, str.size());
7798 memcpy(%(dest_name)s, str.c_str(), max_size);
7799 %(dest_name)s[max_size] = '\\0';
7800 GPU_CLIENT_LOG("------\\n" << %(dest_name)s << "\\n------");
7803 if (%(length_name)s != NULL) {
7804 *%(length_name)s = max_size;
7809 args
= func
.GetOriginalArgs()
7811 'return_type': func
.return_type
,
7812 'func_name': func
.original_name
,
7813 'args': func
.MakeTypedOriginalArgString(""),
7814 'id_name': args
[0].name
,
7815 'bufsize_name': args
[1].name
,
7816 'length_name': args
[2].name
,
7817 'dest_name': args
[3].name
,
7818 'arg0': args
[0].name
,
7819 'arg1': args
[1].name
,
7820 'arg2': args
[2].name
,
7821 'arg3': args
[3].name
,
7823 file.Write(code_1
% str_args
)
7824 func
.WriteDestinationInitalizationValidation(file)
7825 file.Write(code_2
% str_args
)
7827 def WriteServiceUnitTest(self
, func
, file, *extras
):
7828 """Overrriden from TypeHandler."""
7830 TEST_P(%(test_name)s, %(name)sValidArgs) {
7831 const char* kInfo = "hello";
7832 const uint32_t kBucketId = 123;
7833 SpecializedSetup<cmds::%(name)s, 0>(true);
7835 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s))
7836 .WillOnce(DoAll(SetArgumentPointee<2>(strlen(kInfo)),
7837 SetArrayArgument<3>(kInfo, kInfo + strlen(kInfo) + 1)));
7840 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
7841 CommonDecoder::Bucket* bucket = decoder_->GetBucket(kBucketId);
7842 ASSERT_TRUE(bucket != NULL);
7843 EXPECT_EQ(strlen(kInfo) + 1, bucket->size());
7844 EXPECT_EQ(0, memcmp(bucket->GetData(0, bucket->size()), kInfo,
7846 EXPECT_EQ(GL_NO_ERROR, GetGLError());
7849 args
= func
.GetOriginalArgs()
7850 id_name
= args
[0].GetValidGLArg(func
)
7851 get_len_func
= func
.GetInfo('get_len_func')
7852 get_len_enum
= func
.GetInfo('get_len_enum')
7855 'get_len_func': get_len_func
,
7856 'get_len_enum': get_len_enum
,
7857 'gl_args': '%s, strlen(kInfo) + 1, _, _' %
7858 args
[0].GetValidGLArg(func
),
7859 'args': '%s, kBucketId' % args
[0].GetValidArg(func
),
7860 'expect_len_code': '',
7862 if get_len_func
and get_len_func
[0:2] == 'gl':
7863 sub
['expect_len_code'] = (
7864 " EXPECT_CALL(*gl_, %s(%s, %s, _))\n"
7865 " .WillOnce(SetArgumentPointee<2>(strlen(kInfo) + 1));") % (
7866 get_len_func
[2:], id_name
, get_len_enum
)
7867 self
.WriteValidUnitTest(func
, file, valid_test
, sub
, *extras
)
7870 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
7871 const uint32_t kBucketId = 123;
7872 EXPECT_CALL(*gl_, %(gl_func_name)s(_, _, _, _))
7875 cmd.Init(kInvalidClientId, kBucketId);
7876 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
7877 EXPECT_EQ(GL_INVALID_VALUE, GetGLError());
7880 self
.WriteValidUnitTest(func
, file, invalid_test
, *extras
)
7882 def WriteServiceImplementation(self
, func
, file):
7883 """Overrriden from TypeHandler."""
7886 class NamedType(object):
7887 """A class that represents a type of an argument in a client function.
7889 A type of an argument that is to be passed through in the command buffer
7890 command. Currently used only for the arguments that are specificly named in
7891 the 'cmd_buffer_functions.txt' file, mostly enums.
7894 def __init__(self
, info
):
7895 assert not 'is_complete' in info
or info
['is_complete'] == True
7897 self
.valid
= info
['valid']
7898 if 'invalid' in info
:
7899 self
.invalid
= info
['invalid']
7902 if 'valid_es3' in info
:
7903 self
.valid_es3
= info
['valid_es3']
7906 if 'deprecated_es3' in info
:
7907 self
.deprecated_es3
= info
['deprecated_es3']
7909 self
.deprecated_es3
= []
7912 return self
.info
['type']
7914 def GetInvalidValues(self
):
7917 def GetValidValues(self
):
7920 def GetValidValuesES3(self
):
7921 return self
.valid_es3
7923 def GetDeprecatedValuesES3(self
):
7924 return self
.deprecated_es3
7926 def IsConstant(self
):
7927 if not 'is_complete' in self
.info
:
7930 return len(self
.GetValidValues()) == 1
7932 def GetConstantValue(self
):
7933 return self
.GetValidValues()[0]
7935 class Argument(object):
7936 """A class that represents a function argument."""
7939 'GLenum': 'uint32_t',
7941 'GLintptr': 'int32_t',
7942 'GLsizei': 'int32_t',
7943 'GLsizeiptr': 'int32_t',
7945 'GLclampf': 'float',
7947 need_validation_
= ['GLsizei*', 'GLboolean*', 'GLenum*', 'GLint*']
7949 def __init__(self
, name
, type):
7951 self
.optional
= type.endswith("Optional*")
7953 type = type[:-9] + "*"
7956 if type in self
.cmd_type_map_
:
7957 self
.cmd_type
= self
.cmd_type_map_
[type]
7959 self
.cmd_type
= 'uint32_t'
7961 def IsPointer(self
):
7962 """Returns true if argument is a pointer."""
7965 def IsPointer2D(self
):
7966 """Returns true if argument is a 2D pointer."""
7969 def IsConstant(self
):
7970 """Returns true if the argument has only one valid value."""
7973 def AddCmdArgs(self
, args
):
7974 """Adds command arguments for this argument to the given list."""
7975 if not self
.IsConstant():
7976 return args
.append(self
)
7978 def AddInitArgs(self
, args
):
7979 """Adds init arguments for this argument to the given list."""
7980 if not self
.IsConstant():
7981 return args
.append(self
)
7983 def GetValidArg(self
, func
):
7984 """Gets a valid value for this argument."""
7985 valid_arg
= func
.GetValidArg(self
)
7986 if valid_arg
!= None:
7989 index
= func
.GetOriginalArgs().index(self
)
7990 return str(index
+ 1)
7992 def GetValidClientSideArg(self
, func
):
7993 """Gets a valid value for this argument."""
7994 valid_arg
= func
.GetValidArg(self
)
7995 if valid_arg
!= None:
7998 if self
.IsPointer():
8000 index
= func
.GetOriginalArgs().index(self
)
8001 if self
.type == 'GLsync':
8002 return ("reinterpret_cast<GLsync>(%d)" % (index
+ 1))
8003 return str(index
+ 1)
8005 def GetValidClientSideCmdArg(self
, func
):
8006 """Gets a valid value for this argument."""
8007 valid_arg
= func
.GetValidArg(self
)
8008 if valid_arg
!= None:
8011 index
= func
.GetOriginalArgs().index(self
)
8012 return str(index
+ 1)
8015 index
= func
.GetCmdArgs().index(self
)
8016 return str(index
+ 1)
8018 def GetValidGLArg(self
, func
):
8019 """Gets a valid GL value for this argument."""
8020 value
= self
.GetValidArg(func
)
8021 if self
.type == 'GLsync':
8022 return ("reinterpret_cast<GLsync>(%s)" % value
)
8025 def GetValidNonCachedClientSideArg(self
, func
):
8026 """Returns a valid value for this argument in a GL call.
8027 Using the value will produce a command buffer service invocation.
8028 Returns None if there is no such value."""
8030 if self
.type == 'GLsync':
8031 return ("reinterpret_cast<GLsync>(%s)" % value
)
8034 def GetValidNonCachedClientSideCmdArg(self
, func
):
8035 """Returns a valid value for this argument in a command buffer command.
8036 Calling the GL function with the value returned by
8037 GetValidNonCachedClientSideArg will result in a command buffer command
8038 that contains the value returned by this function. """
8041 def GetNumInvalidValues(self
, func
):
8042 """returns the number of invalid values to be tested."""
8045 def GetInvalidArg(self
, index
):
8046 """returns an invalid value and expected parse result by index."""
8047 return ("---ERROR0---", "---ERROR2---", None)
8049 def GetLogArg(self
):
8050 """Get argument appropriate for LOG macro."""
8051 if self
.type == 'GLboolean':
8052 return 'GLES2Util::GetStringBool(%s)' % self
.name
8053 if self
.type == 'GLenum':
8054 return 'GLES2Util::GetStringEnum(%s)' % self
.name
8057 def WriteGetCode(self
, file):
8058 """Writes the code to get an argument from a command structure."""
8059 if self
.type == 'GLsync':
8063 file.Write(" %s %s = static_cast<%s>(c.%s);\n" %
8064 (my_type
, self
.name
, my_type
, self
.name
))
8066 def WriteValidationCode(self
, file, func
):
8067 """Writes the validation code for an argument."""
8070 def WriteClientSideValidationCode(self
, file, func
):
8071 """Writes the validation code for an argument."""
8074 def WriteDestinationInitalizationValidation(self
, file, func
):
8075 """Writes the client side destintion initialization validation."""
8078 def WriteDestinationInitalizationValidatationIfNeeded(self
, file, func
):
8079 """Writes the client side destintion initialization validation if needed."""
8080 parts
= self
.type.split(" ")
8083 if parts
[0] in self
.need_validation_
:
8085 " GPU_CLIENT_VALIDATE_DESTINATION_%sINITALIZATION(%s, %s);\n" %
8086 ("OPTIONAL_" if self
.optional
else "", self
.type[:-1], self
.name
))
8089 def WriteGetAddress(self
, file):
8090 """Writes the code to get the address this argument refers to."""
8093 def GetImmediateVersion(self
):
8094 """Gets the immediate version of this argument."""
8097 def GetBucketVersion(self
):
8098 """Gets the bucket version of this argument."""
8102 class BoolArgument(Argument
):
8103 """class for GLboolean"""
8105 def __init__(self
, name
, type):
8106 Argument
.__init
__(self
, name
, 'GLboolean')
8108 def GetValidArg(self
, func
):
8109 """Gets a valid value for this argument."""
8112 def GetValidClientSideArg(self
, func
):
8113 """Gets a valid value for this argument."""
8116 def GetValidClientSideCmdArg(self
, func
):
8117 """Gets a valid value for this argument."""
8120 def GetValidGLArg(self
, func
):
8121 """Gets a valid GL value for this argument."""
8125 class UniformLocationArgument(Argument
):
8126 """class for uniform locations."""
8128 def __init__(self
, name
):
8129 Argument
.__init
__(self
, name
, "GLint")
8131 def WriteGetCode(self
, file):
8132 """Writes the code to get an argument from a command structure."""
8133 code
= """ %s %s = static_cast<%s>(c.%s);
8135 file.Write(code
% (self
.type, self
.name
, self
.type, self
.name
))
8137 class DataSizeArgument(Argument
):
8138 """class for data_size which Bucket commands do not need."""
8140 def __init__(self
, name
):
8141 Argument
.__init
__(self
, name
, "uint32_t")
8143 def GetBucketVersion(self
):
8147 class SizeArgument(Argument
):
8148 """class for GLsizei and GLsizeiptr."""
8150 def __init__(self
, name
, type):
8151 Argument
.__init
__(self
, name
, type)
8153 def GetNumInvalidValues(self
, func
):
8154 """overridden from Argument."""
8155 if func
.IsImmediate():
8159 def GetInvalidArg(self
, index
):
8160 """overridden from Argument."""
8161 return ("-1", "kNoError", "GL_INVALID_VALUE")
8163 def WriteValidationCode(self
, file, func
):
8164 """overridden from Argument."""
8167 code
= """ if (%(var_name)s < 0) {
8168 LOCAL_SET_GL_ERROR(GL_INVALID_VALUE, "gl%(func_name)s", "%(var_name)s < 0");
8169 return error::kNoError;
8173 "var_name": self
.name
,
8174 "func_name": func
.original_name
,
8177 def WriteClientSideValidationCode(self
, file, func
):
8178 """overridden from Argument."""
8179 code
= """ if (%(var_name)s < 0) {
8180 SetGLError(GL_INVALID_VALUE, "gl%(func_name)s", "%(var_name)s < 0");
8185 "var_name": self
.name
,
8186 "func_name": func
.original_name
,
8190 class SizeNotNegativeArgument(SizeArgument
):
8191 """class for GLsizeiNotNegative. It's NEVER allowed to be negative"""
8193 def __init__(self
, name
, type, gl_type
):
8194 SizeArgument
.__init
__(self
, name
, gl_type
)
8196 def GetInvalidArg(self
, index
):
8197 """overridden from SizeArgument."""
8198 return ("-1", "kOutOfBounds", "GL_NO_ERROR")
8200 def WriteValidationCode(self
, file, func
):
8201 """overridden from SizeArgument."""
8205 class EnumBaseArgument(Argument
):
8206 """Base class for EnumArgument, IntArgument, BitfieldArgument, and
8207 ValidatedBoolArgument."""
8209 def __init__(self
, name
, gl_type
, type, gl_error
):
8210 Argument
.__init
__(self
, name
, gl_type
)
8212 self
.local_type
= type
8213 self
.gl_error
= gl_error
8214 name
= type[len(gl_type
):]
8215 self
.type_name
= name
8216 self
.named_type
= NamedType(_NAMED_TYPE_INFO
[name
])
8218 def IsConstant(self
):
8219 return self
.named_type
.IsConstant()
8221 def GetConstantValue(self
):
8222 return self
.named_type
.GetConstantValue()
8224 def WriteValidationCode(self
, file, func
):
8227 if self
.named_type
.IsConstant():
8229 file.Write(" if (!validators_->%s.IsValid(%s)) {\n" %
8230 (ToUnderscore(self
.type_name
), self
.name
))
8231 if self
.gl_error
== "GL_INVALID_ENUM":
8233 " LOCAL_SET_GL_ERROR_INVALID_ENUM(\"gl%s\", %s, \"%s\");\n" %
8234 (func
.original_name
, self
.name
, self
.name
))
8237 " LOCAL_SET_GL_ERROR(%s, \"gl%s\", \"%s %s\");\n" %
8238 (self
.gl_error
, func
.original_name
, self
.name
, self
.gl_error
))
8239 file.Write(" return error::kNoError;\n")
8242 def WriteClientSideValidationCode(self
, file, func
):
8243 if not self
.named_type
.IsConstant():
8245 file.Write(" if (%s != %s) {" % (self
.name
,
8246 self
.GetConstantValue()))
8248 " SetGLError(%s, \"gl%s\", \"%s %s\");\n" %
8249 (self
.gl_error
, func
.original_name
, self
.name
, self
.gl_error
))
8250 if func
.return_type
== "void":
8251 file.Write(" return;\n")
8253 file.Write(" return %s;\n" % func
.GetErrorReturnString())
8256 def GetValidArg(self
, func
):
8257 valid_arg
= func
.GetValidArg(self
)
8258 if valid_arg
!= None:
8260 valid
= self
.named_type
.GetValidValues()
8262 num_valid
= len(valid
)
8265 index
= func
.GetOriginalArgs().index(self
)
8266 return str(index
+ 1)
8268 def GetValidClientSideArg(self
, func
):
8269 """Gets a valid value for this argument."""
8270 return self
.GetValidArg(func
)
8272 def GetValidClientSideCmdArg(self
, func
):
8273 """Gets a valid value for this argument."""
8274 valid_arg
= func
.GetValidArg(self
)
8275 if valid_arg
!= None:
8278 valid
= self
.named_type
.GetValidValues()
8280 num_valid
= len(valid
)
8284 index
= func
.GetOriginalArgs().index(self
)
8285 return str(index
+ 1)
8288 index
= func
.GetCmdArgs().index(self
)
8289 return str(index
+ 1)
8291 def GetValidGLArg(self
, func
):
8292 """Gets a valid value for this argument."""
8293 return self
.GetValidArg(func
)
8295 def GetNumInvalidValues(self
, func
):
8296 """returns the number of invalid values to be tested."""
8297 return len(self
.named_type
.GetInvalidValues())
8299 def GetInvalidArg(self
, index
):
8300 """returns an invalid value by index."""
8301 invalid
= self
.named_type
.GetInvalidValues()
8303 num_invalid
= len(invalid
)
8304 if index
>= num_invalid
:
8305 index
= num_invalid
- 1
8306 return (invalid
[index
], "kNoError", self
.gl_error
)
8307 return ("---ERROR1---", "kNoError", self
.gl_error
)
8310 class EnumArgument(EnumBaseArgument
):
8311 """A class that represents a GLenum argument"""
8313 def __init__(self
, name
, type):
8314 EnumBaseArgument
.__init
__(self
, name
, "GLenum", type, "GL_INVALID_ENUM")
8316 def GetLogArg(self
):
8317 """Overridden from Argument."""
8318 return ("GLES2Util::GetString%s(%s)" %
8319 (self
.type_name
, self
.name
))
8322 class IntArgument(EnumBaseArgument
):
8323 """A class for a GLint argument that can only accept specific values.
8325 For example glTexImage2D takes a GLint for its internalformat
8326 argument instead of a GLenum.
8329 def __init__(self
, name
, type):
8330 EnumBaseArgument
.__init
__(self
, name
, "GLint", type, "GL_INVALID_VALUE")
8333 class ValidatedBoolArgument(EnumBaseArgument
):
8334 """A class for a GLboolean argument that can only accept specific values.
8336 For example glUniformMatrix takes a GLboolean for it's transpose but it
8340 def __init__(self
, name
, type):
8341 EnumBaseArgument
.__init
__(self
, name
, "GLboolean", type, "GL_INVALID_VALUE")
8343 def GetLogArg(self
):
8344 """Overridden from Argument."""
8345 return 'GLES2Util::GetStringBool(%s)' % self
.name
8348 class BitFieldArgument(EnumBaseArgument
):
8349 """A class for a GLbitfield argument that can only accept specific values.
8351 For example glFenceSync takes a GLbitfield for its flags argument bit it
8355 def __init__(self
, name
, type):
8356 EnumBaseArgument
.__init
__(self
, name
, "GLbitfield", type,
8360 class ImmediatePointerArgument(Argument
):
8361 """A class that represents an immediate argument to a function.
8363 An immediate argument is one where the data follows the command.
8366 def __init__(self
, name
, type):
8367 Argument
.__init
__(self
, name
, type)
8369 def IsPointer(self
):
8372 def GetPointedType(self
):
8373 match
= re
.match('(const\s+)?(?P<element_type>[\w]+)\s*\*', self
.type)
8375 return match
.groupdict()['element_type']
8377 def AddCmdArgs(self
, args
):
8378 """Overridden from Argument."""
8381 def WriteGetCode(self
, file):
8382 """Overridden from Argument."""
8384 " %s %s = GetImmediateDataAs<%s>(\n" %
8385 (self
.type, self
.name
, self
.type))
8386 file.Write(" c, data_size, immediate_data_size);\n")
8388 def WriteValidationCode(self
, file, func
):
8389 """Overridden from Argument."""
8392 file.Write(" if (%s == NULL) {\n" % self
.name
)
8393 file.Write(" return error::kOutOfBounds;\n")
8396 def GetImmediateVersion(self
):
8397 """Overridden from Argument."""
8400 def WriteDestinationInitalizationValidation(self
, file, func
):
8401 """Overridden from Argument."""
8402 self
.WriteDestinationInitalizationValidatationIfNeeded(file, func
)
8404 def GetLogArg(self
):
8405 """Overridden from Argument."""
8406 return "static_cast<const void*>(%s)" % self
.name
8409 class PointerArgument(Argument
):
8410 """A class that represents a pointer argument to a function."""
8412 def __init__(self
, name
, type):
8413 Argument
.__init
__(self
, name
, type)
8415 def IsPointer(self
):
8416 """Overridden from Argument."""
8419 def IsPointer2D(self
):
8420 """Overridden from Argument."""
8421 return self
.type.count('*') == 2
8423 def GetPointedType(self
):
8424 match
= re
.match('(const\s+)?(?P<element_type>[\w]+)\s*\*', self
.type)
8426 return match
.groupdict()['element_type']
8428 def GetValidArg(self
, func
):
8429 """Overridden from Argument."""
8430 return "shared_memory_id_, shared_memory_offset_"
8432 def GetValidGLArg(self
, func
):
8433 """Overridden from Argument."""
8434 return "reinterpret_cast<%s>(shared_memory_address_)" % self
.type
8436 def GetNumInvalidValues(self
, func
):
8437 """Overridden from Argument."""
8440 def GetInvalidArg(self
, index
):
8441 """Overridden from Argument."""
8443 return ("kInvalidSharedMemoryId, 0", "kOutOfBounds", None)
8445 return ("shared_memory_id_, kInvalidSharedMemoryOffset",
8446 "kOutOfBounds", None)
8448 def GetLogArg(self
):
8449 """Overridden from Argument."""
8450 return "static_cast<const void*>(%s)" % self
.name
8452 def AddCmdArgs(self
, args
):
8453 """Overridden from Argument."""
8454 args
.append(Argument("%s_shm_id" % self
.name
, 'uint32_t'))
8455 args
.append(Argument("%s_shm_offset" % self
.name
, 'uint32_t'))
8457 def WriteGetCode(self
, file):
8458 """Overridden from Argument."""
8460 " %s %s = GetSharedMemoryAs<%s>(\n" %
8461 (self
.type, self
.name
, self
.type))
8463 " c.%s_shm_id, c.%s_shm_offset, data_size);\n" %
8464 (self
.name
, self
.name
))
8466 def WriteGetAddress(self
, file):
8467 """Overridden from Argument."""
8469 " %s %s = GetSharedMemoryAs<%s>(\n" %
8470 (self
.type, self
.name
, self
.type))
8472 " %s_shm_id, %s_shm_offset, %s_size);\n" %
8473 (self
.name
, self
.name
, self
.name
))
8475 def WriteValidationCode(self
, file, func
):
8476 """Overridden from Argument."""
8479 file.Write(" if (%s == NULL) {\n" % self
.name
)
8480 file.Write(" return error::kOutOfBounds;\n")
8483 def GetImmediateVersion(self
):
8484 """Overridden from Argument."""
8485 return ImmediatePointerArgument(self
.name
, self
.type)
8487 def GetBucketVersion(self
):
8488 """Overridden from Argument."""
8489 if self
.type.find('char') >= 0:
8490 if self
.IsPointer2D():
8491 return InputStringArrayBucketArgument(self
.name
, self
.type)
8492 return InputStringBucketArgument(self
.name
, self
.type)
8493 return BucketPointerArgument(self
.name
, self
.type)
8495 def WriteDestinationInitalizationValidation(self
, file, func
):
8496 """Overridden from Argument."""
8497 self
.WriteDestinationInitalizationValidatationIfNeeded(file, func
)
8500 class BucketPointerArgument(PointerArgument
):
8501 """A class that represents an bucket argument to a function."""
8503 def __init__(self
, name
, type):
8504 Argument
.__init
__(self
, name
, type)
8506 def AddCmdArgs(self
, args
):
8507 """Overridden from Argument."""
8510 def WriteGetCode(self
, file):
8511 """Overridden from Argument."""
8513 " %s %s = bucket->GetData(0, data_size);\n" %
8514 (self
.type, self
.name
))
8516 def WriteValidationCode(self
, file, func
):
8517 """Overridden from Argument."""
8520 def GetImmediateVersion(self
):
8521 """Overridden from Argument."""
8524 def WriteDestinationInitalizationValidation(self
, file, func
):
8525 """Overridden from Argument."""
8526 self
.WriteDestinationInitalizationValidatationIfNeeded(file, func
)
8528 def GetLogArg(self
):
8529 """Overridden from Argument."""
8530 return "static_cast<const void*>(%s)" % self
.name
8533 class InputStringBucketArgument(Argument
):
8534 """A string input argument where the string is passed in a bucket."""
8536 def __init__(self
, name
, type):
8537 Argument
.__init
__(self
, name
+ "_bucket_id", "uint32_t")
8539 def IsPointer(self
):
8540 """Overridden from Argument."""
8543 def IsPointer2D(self
):
8544 """Overridden from Argument."""
8548 class InputStringArrayBucketArgument(Argument
):
8549 """A string array input argument where the strings are passed in a bucket."""
8551 def __init__(self
, name
, type):
8552 Argument
.__init
__(self
, name
+ "_bucket_id", "uint32_t")
8553 self
._original
_name
= name
8555 def WriteGetCode(self
, file):
8556 """Overridden from Argument."""
8558 Bucket* bucket = GetBucket(c.%(name)s);
8560 return error::kInvalidArguments;
8563 std::vector<char*> strs;
8564 std::vector<GLint> len;
8565 if (!bucket->GetAsStrings(&count, &strs, &len)) {
8566 return error::kInvalidArguments;
8568 const char** %(original_name)s =
8569 strs.size() > 0 ? const_cast<const char**>(&strs[0]) : NULL;
8570 const GLint* length =
8571 len.size() > 0 ? const_cast<const GLint*>(&len[0]) : NULL;
8576 'original_name': self
._original
_name
,
8579 def GetValidArg(self
, func
):
8580 return "kNameBucketId"
8582 def GetValidGLArg(self
, func
):
8585 def IsPointer(self
):
8586 """Overridden from Argument."""
8589 def IsPointer2D(self
):
8590 """Overridden from Argument."""
8594 class ResourceIdArgument(Argument
):
8595 """A class that represents a resource id argument to a function."""
8597 def __init__(self
, name
, type):
8598 match
= re
.match("(GLid\w+)", type)
8599 self
.resource_type
= match
.group(1)[4:]
8600 if self
.resource_type
== "Sync":
8601 type = type.replace(match
.group(1), "GLsync")
8603 type = type.replace(match
.group(1), "GLuint")
8604 Argument
.__init
__(self
, name
, type)
8606 def WriteGetCode(self
, file):
8607 """Overridden from Argument."""
8608 if self
.type == "GLsync":
8612 file.Write(" %s %s = c.%s;\n" % (my_type
, self
.name
, self
.name
))
8614 def GetValidArg(self
, func
):
8615 return "client_%s_id_" % self
.resource_type
.lower()
8617 def GetValidGLArg(self
, func
):
8618 if self
.resource_type
== "Sync":
8619 return "reinterpret_cast<GLsync>(kService%sId)" % self
.resource_type
8620 return "kService%sId" % self
.resource_type
8623 class ResourceIdBindArgument(Argument
):
8624 """Represents a resource id argument to a bind function."""
8626 def __init__(self
, name
, type):
8627 match
= re
.match("(GLidBind\w+)", type)
8628 self
.resource_type
= match
.group(1)[8:]
8629 type = type.replace(match
.group(1), "GLuint")
8630 Argument
.__init
__(self
, name
, type)
8632 def WriteGetCode(self
, file):
8633 """Overridden from Argument."""
8634 code
= """ %(type)s %(name)s = c.%(name)s;
8636 file.Write(code
% {'type': self
.type, 'name': self
.name
})
8638 def GetValidArg(self
, func
):
8639 return "client_%s_id_" % self
.resource_type
.lower()
8641 def GetValidGLArg(self
, func
):
8642 return "kService%sId" % self
.resource_type
8645 class ResourceIdZeroArgument(Argument
):
8646 """Represents a resource id argument to a function that can be zero."""
8648 def __init__(self
, name
, type):
8649 match
= re
.match("(GLidZero\w+)", type)
8650 self
.resource_type
= match
.group(1)[8:]
8651 type = type.replace(match
.group(1), "GLuint")
8652 Argument
.__init
__(self
, name
, type)
8654 def WriteGetCode(self
, file):
8655 """Overridden from Argument."""
8656 file.Write(" %s %s = c.%s;\n" % (self
.type, self
.name
, self
.name
))
8658 def GetValidArg(self
, func
):
8659 return "client_%s_id_" % self
.resource_type
.lower()
8661 def GetValidGLArg(self
, func
):
8662 return "kService%sId" % self
.resource_type
8664 def GetNumInvalidValues(self
, func
):
8665 """returns the number of invalid values to be tested."""
8668 def GetInvalidArg(self
, index
):
8669 """returns an invalid value by index."""
8670 return ("kInvalidClientId", "kNoError", "GL_INVALID_VALUE")
8673 class Function(object):
8674 """A class that represents a function."""
8678 'Bind': BindHandler(),
8679 'Create': CreateHandler(),
8680 'Custom': CustomHandler(),
8681 'Data': DataHandler(),
8682 'Delete': DeleteHandler(),
8683 'DELn': DELnHandler(),
8684 'GENn': GENnHandler(),
8685 'GETn': GETnHandler(),
8686 'GLchar': GLcharHandler(),
8687 'GLcharN': GLcharNHandler(),
8688 'HandWritten': HandWrittenHandler(),
8690 'Manual': ManualHandler(),
8691 'PUT': PUTHandler(),
8692 'PUTn': PUTnHandler(),
8693 'PUTSTR': PUTSTRHandler(),
8694 'PUTXn': PUTXnHandler(),
8695 'StateSet': StateSetHandler(),
8696 'StateSetRGBAlpha': StateSetRGBAlphaHandler(),
8697 'StateSetFrontBack': StateSetFrontBackHandler(),
8698 'StateSetFrontBackSeparate': StateSetFrontBackSeparateHandler(),
8699 'StateSetNamedParameter': StateSetNamedParameter(),
8700 'STRn': STRnHandler(),
8701 'Todo': TodoHandler(),
8704 def __init__(self
, name
, info
):
8706 self
.original_name
= info
['original_name']
8708 self
.original_args
= self
.ParseArgs(info
['original_args'])
8710 if 'cmd_args' in info
:
8711 self
.args_for_cmds
= self
.ParseArgs(info
['cmd_args'])
8713 self
.args_for_cmds
= self
.original_args
[:]
8715 self
.return_type
= info
['return_type']
8716 if self
.return_type
!= 'void':
8717 self
.return_arg
= CreateArg(info
['return_type'] + " result")
8719 self
.return_arg
= None
8721 self
.num_pointer_args
= sum(
8722 [1 for arg
in self
.args_for_cmds
if arg
.IsPointer()])
8723 if self
.num_pointer_args
> 0:
8724 for arg
in reversed(self
.original_args
):
8726 self
.last_original_pointer_arg
= arg
8729 self
.last_original_pointer_arg
= None
8731 self
.type_handler
= self
.type_handlers
[info
['type']]
8732 self
.can_auto_generate
= (self
.num_pointer_args
== 0 and
8733 info
['return_type'] == "void")
8736 def ParseArgs(self
, arg_string
):
8737 """Parses a function arg string."""
8739 parts
= arg_string
.split(',')
8740 for arg_string
in parts
:
8741 arg
= CreateArg(arg_string
)
8746 def IsType(self
, type_name
):
8747 """Returns true if function is a certain type."""
8748 return self
.info
['type'] == type_name
8750 def InitFunction(self
):
8751 """Creates command args and calls the init function for the type handler.
8753 Creates argument lists for command buffer commands, eg. self.cmd_args and
8755 Calls the type function initialization.
8756 Override to create different kind of command buffer command argument lists.
8759 for arg
in self
.args_for_cmds
:
8760 arg
.AddCmdArgs(self
.cmd_args
)
8763 for arg
in self
.args_for_cmds
:
8764 arg
.AddInitArgs(self
.init_args
)
8767 self
.init_args
.append(self
.return_arg
)
8769 self
.type_handler
.InitFunction(self
)
8771 def IsImmediate(self
):
8772 """Returns whether the function is immediate data function or not."""
8776 """Returns whether the function has service side validation or not."""
8777 return self
.GetInfo('unsafe', False)
8779 def GetInfo(self
, name
, default
= None):
8780 """Returns a value from the function info for this function."""
8781 if name
in self
.info
:
8782 return self
.info
[name
]
8785 def GetValidArg(self
, arg
):
8786 """Gets a valid argument value for the parameter arg from the function info
8789 index
= self
.GetOriginalArgs().index(arg
)
8793 valid_args
= self
.GetInfo('valid_args')
8794 if valid_args
and str(index
) in valid_args
:
8795 return valid_args
[str(index
)]
8798 def AddInfo(self
, name
, value
):
8800 self
.info
[name
] = value
8802 def IsExtension(self
):
8803 return self
.GetInfo('extension') or self
.GetInfo('extension_flag')
8805 def IsCoreGLFunction(self
):
8806 return (not self
.IsExtension() and
8807 not self
.GetInfo('pepper_interface') and
8808 not self
.IsUnsafe())
8810 def InPepperInterface(self
, interface
):
8811 ext
= self
.GetInfo('pepper_interface')
8812 if not interface
.GetName():
8813 return self
.IsCoreGLFunction()
8814 return ext
== interface
.GetName()
8816 def InAnyPepperExtension(self
):
8817 return self
.IsCoreGLFunction() or self
.GetInfo('pepper_interface')
8819 def GetErrorReturnString(self
):
8820 if self
.GetInfo("error_return"):
8821 return self
.GetInfo("error_return")
8822 elif self
.return_type
== "GLboolean":
8824 elif "*" in self
.return_type
:
8828 def GetGLFunctionName(self
):
8829 """Gets the function to call to execute GL for this command."""
8830 if self
.GetInfo('decoder_func'):
8831 return self
.GetInfo('decoder_func')
8832 return "gl%s" % self
.original_name
8834 def GetGLTestFunctionName(self
):
8835 gl_func_name
= self
.GetInfo('gl_test_func')
8836 if gl_func_name
== None:
8837 gl_func_name
= self
.GetGLFunctionName()
8838 if gl_func_name
.startswith("gl"):
8839 gl_func_name
= gl_func_name
[2:]
8841 gl_func_name
= self
.original_name
8844 def GetDataTransferMethods(self
):
8845 return self
.GetInfo('data_transfer_methods',
8846 ['immediate' if self
.num_pointer_args
== 1 else 'shm'])
8848 def AddCmdArg(self
, arg
):
8849 """Adds a cmd argument to this function."""
8850 self
.cmd_args
.append(arg
)
8852 def GetCmdArgs(self
):
8853 """Gets the command args for this function."""
8854 return self
.cmd_args
8856 def ClearCmdArgs(self
):
8857 """Clears the command args for this function."""
8860 def GetCmdConstants(self
):
8861 """Gets the constants for this function."""
8862 return [arg
for arg
in self
.args_for_cmds
if arg
.IsConstant()]
8864 def GetInitArgs(self
):
8865 """Gets the init args for this function."""
8866 return self
.init_args
8868 def GetOriginalArgs(self
):
8869 """Gets the original arguments to this function."""
8870 return self
.original_args
8872 def GetLastOriginalArg(self
):
8873 """Gets the last original argument to this function."""
8874 return self
.original_args
[len(self
.original_args
) - 1]
8876 def GetLastOriginalPointerArg(self
):
8877 return self
.last_original_pointer_arg
8879 def GetResourceIdArg(self
):
8880 for arg
in self
.original_args
:
8881 if hasattr(arg
, 'resource_type'):
8885 def _MaybePrependComma(self
, arg_string
, add_comma
):
8886 """Adds a comma if arg_string is not empty and add_comma is true."""
8888 if add_comma
and len(arg_string
):
8890 return "%s%s" % (comma
, arg_string
)
8892 def MakeTypedOriginalArgString(self
, prefix
, add_comma
= False):
8893 """Gets a list of arguments as they are in GL."""
8894 args
= self
.GetOriginalArgs()
8895 arg_string
= ", ".join(
8896 ["%s %s%s" % (arg
.type, prefix
, arg
.name
) for arg
in args
])
8897 return self
._MaybePrependComma
(arg_string
, add_comma
)
8899 def MakeOriginalArgString(self
, prefix
, add_comma
= False, separator
= ", "):
8900 """Gets the list of arguments as they are in GL."""
8901 args
= self
.GetOriginalArgs()
8902 arg_string
= separator
.join(
8903 ["%s%s" % (prefix
, arg
.name
) for arg
in args
])
8904 return self
._MaybePrependComma
(arg_string
, add_comma
)
8906 def MakeTypedHelperArgString(self
, prefix
, add_comma
= False):
8907 """Gets a list of typed GL arguments after removing unneeded arguments."""
8908 args
= self
.GetOriginalArgs()
8909 arg_string
= ", ".join(
8914 ) for arg
in args
if not arg
.IsConstant()])
8915 return self
._MaybePrependComma
(arg_string
, add_comma
)
8917 def MakeHelperArgString(self
, prefix
, add_comma
= False, separator
= ", "):
8918 """Gets a list of GL arguments after removing unneeded arguments."""
8919 args
= self
.GetOriginalArgs()
8920 arg_string
= separator
.join(
8921 ["%s%s" % (prefix
, arg
.name
)
8922 for arg
in args
if not arg
.IsConstant()])
8923 return self
._MaybePrependComma
(arg_string
, add_comma
)
8925 def MakeTypedPepperArgString(self
, prefix
):
8926 """Gets a list of arguments as they need to be for Pepper."""
8927 if self
.GetInfo("pepper_args"):
8928 return self
.GetInfo("pepper_args")
8930 return self
.MakeTypedOriginalArgString(prefix
, False)
8932 def MapCTypeToPepperIdlType(self
, ctype
, is_for_return_type
=False):
8933 """Converts a C type name to the corresponding Pepper IDL type."""
8935 'char*': '[out] str_t',
8936 'const GLchar* const*': '[out] cstr_t',
8937 'const char*': 'cstr_t',
8938 'const void*': 'mem_t',
8939 'void*': '[out] mem_t',
8940 'void**': '[out] mem_ptr_t',
8942 # We use "GLxxx_ptr_t" for "GLxxx*".
8943 matched
= re
.match(r
'(const )?(GL\w+)\*$', ctype
)
8945 idltype
= matched
.group(2) + '_ptr_t'
8946 if not matched
.group(1):
8947 idltype
= '[out] ' + idltype
8948 # If an in/out specifier is not specified yet, prepend [in].
8949 if idltype
[0] != '[':
8950 idltype
= '[in] ' + idltype
8951 # Strip the in/out specifier for a return type.
8952 if is_for_return_type
:
8953 idltype
= re
.sub(r
'\[\w+\] ', '', idltype
)
8956 def MakeTypedPepperIdlArgStrings(self
):
8957 """Gets a list of arguments as they need to be for Pepper IDL."""
8958 args
= self
.GetOriginalArgs()
8959 return ["%s %s" % (self
.MapCTypeToPepperIdlType(arg
.type), arg
.name
)
8962 def GetPepperName(self
):
8963 if self
.GetInfo("pepper_name"):
8964 return self
.GetInfo("pepper_name")
8967 def MakeTypedCmdArgString(self
, prefix
, add_comma
= False):
8968 """Gets a typed list of arguments as they need to be for command buffers."""
8969 args
= self
.GetCmdArgs()
8970 arg_string
= ", ".join(
8971 ["%s %s%s" % (arg
.type, prefix
, arg
.name
) for arg
in args
])
8972 return self
._MaybePrependComma
(arg_string
, add_comma
)
8974 def MakeCmdArgString(self
, prefix
, add_comma
= False):
8975 """Gets the list of arguments as they need to be for command buffers."""
8976 args
= self
.GetCmdArgs()
8977 arg_string
= ", ".join(
8978 ["%s%s" % (prefix
, arg
.name
) for arg
in args
])
8979 return self
._MaybePrependComma
(arg_string
, add_comma
)
8981 def MakeTypedInitString(self
, prefix
, add_comma
= False):
8982 """Gets a typed list of arguments as they need to be for cmd Init/Set."""
8983 args
= self
.GetInitArgs()
8984 arg_string
= ", ".join(
8985 ["%s %s%s" % (arg
.type, prefix
, arg
.name
) for arg
in args
])
8986 return self
._MaybePrependComma
(arg_string
, add_comma
)
8988 def MakeInitString(self
, prefix
, add_comma
= False):
8989 """Gets the list of arguments as they need to be for cmd Init/Set."""
8990 args
= self
.GetInitArgs()
8991 arg_string
= ", ".join(
8992 ["%s%s" % (prefix
, arg
.name
) for arg
in args
])
8993 return self
._MaybePrependComma
(arg_string
, add_comma
)
8995 def MakeLogArgString(self
):
8996 """Makes a string of the arguments for the LOG macros"""
8997 args
= self
.GetOriginalArgs()
8998 return ' << ", " << '.join([arg
.GetLogArg() for arg
in args
])
9000 def WriteCommandDescription(self
, file):
9001 """Writes a description of the command."""
9002 file.Write("//! Command that corresponds to gl%s.\n" % self
.original_name
)
9004 def WriteHandlerValidation(self
, file):
9005 """Writes validation code for the function."""
9006 for arg
in self
.GetOriginalArgs():
9007 arg
.WriteValidationCode(file, self
)
9008 self
.WriteValidationCode(file)
9010 def WriteHandlerImplementation(self
, file):
9011 """Writes the handler implementation for this command."""
9012 self
.type_handler
.WriteHandlerImplementation(self
, file)
9014 def WriteValidationCode(self
, file):
9015 """Writes the validation code for a command."""
9018 def WriteCmdFlag(self
, file):
9019 """Writes the cmd cmd_flags constant."""
9021 # By default trace only at the highest level 3.
9022 trace_level
= int(self
.GetInfo('trace_level', default
= 3))
9023 if trace_level
not in xrange(0, 4):
9024 raise KeyError("Unhandled trace_level: %d" % trace_level
)
9026 flags
.append('CMD_FLAG_SET_TRACE_LEVEL(%d)' % trace_level
)
9029 cmd_flags
= ' | '.join(flags
)
9033 file.Write(" static const uint8 cmd_flags = %s;\n" % cmd_flags
)
9036 def WriteCmdArgFlag(self
, file):
9037 """Writes the cmd kArgFlags constant."""
9038 file.Write(" static const cmd::ArgFlags kArgFlags = cmd::kFixed;\n")
9040 def WriteCmdComputeSize(self
, file):
9041 """Writes the ComputeSize function for the command."""
9042 file.Write(" static uint32_t ComputeSize() {\n")
9044 " return static_cast<uint32_t>(sizeof(ValueType)); // NOLINT\n")
9048 def WriteCmdSetHeader(self
, file):
9049 """Writes the cmd's SetHeader function."""
9050 file.Write(" void SetHeader() {\n")
9051 file.Write(" header.SetCmd<ValueType>();\n")
9055 def WriteCmdInit(self
, file):
9056 """Writes the cmd's Init function."""
9057 file.Write(" void Init(%s) {\n" % self
.MakeTypedCmdArgString("_"))
9058 file.Write(" SetHeader();\n")
9059 args
= self
.GetCmdArgs()
9061 file.Write(" %s = _%s;\n" % (arg
.name
, arg
.name
))
9065 def WriteCmdSet(self
, file):
9066 """Writes the cmd's Set function."""
9067 copy_args
= self
.MakeCmdArgString("_", False)
9068 file.Write(" void* Set(void* cmd%s) {\n" %
9069 self
.MakeTypedCmdArgString("_", True))
9070 file.Write(" static_cast<ValueType*>(cmd)->Init(%s);\n" % copy_args
)
9071 file.Write(" return NextCmdAddress<ValueType>(cmd);\n")
9075 def WriteStruct(self
, file):
9076 self
.type_handler
.WriteStruct(self
, file)
9078 def WriteDocs(self
, file):
9079 self
.type_handler
.WriteDocs(self
, file)
9081 def WriteCmdHelper(self
, file):
9082 """Writes the cmd's helper."""
9083 self
.type_handler
.WriteCmdHelper(self
, file)
9085 def WriteServiceImplementation(self
, file):
9086 """Writes the service implementation for a command."""
9087 self
.type_handler
.WriteServiceImplementation(self
, file)
9089 def WriteServiceUnitTest(self
, file, *extras
):
9090 """Writes the service implementation for a command."""
9091 self
.type_handler
.WriteServiceUnitTest(self
, file, *extras
)
9093 def WriteGLES2CLibImplementation(self
, file):
9094 """Writes the GLES2 C Lib Implemention."""
9095 self
.type_handler
.WriteGLES2CLibImplementation(self
, file)
9097 def WriteGLES2InterfaceHeader(self
, file):
9098 """Writes the GLES2 Interface declaration."""
9099 self
.type_handler
.WriteGLES2InterfaceHeader(self
, file)
9101 def WriteMojoGLES2ImplHeader(self
, file):
9102 """Writes the Mojo GLES2 implementation header declaration."""
9103 self
.type_handler
.WriteMojoGLES2ImplHeader(self
, file)
9105 def WriteMojoGLES2Impl(self
, file):
9106 """Writes the Mojo GLES2 implementation declaration."""
9107 self
.type_handler
.WriteMojoGLES2Impl(self
, file)
9109 def WriteGLES2InterfaceStub(self
, file):
9110 """Writes the GLES2 Interface Stub declaration."""
9111 self
.type_handler
.WriteGLES2InterfaceStub(self
, file)
9113 def WriteGLES2InterfaceStubImpl(self
, file):
9114 """Writes the GLES2 Interface Stub declaration."""
9115 self
.type_handler
.WriteGLES2InterfaceStubImpl(self
, file)
9117 def WriteGLES2ImplementationHeader(self
, file):
9118 """Writes the GLES2 Implemention declaration."""
9119 self
.type_handler
.WriteGLES2ImplementationHeader(self
, file)
9121 def WriteGLES2Implementation(self
, file):
9122 """Writes the GLES2 Implemention definition."""
9123 self
.type_handler
.WriteGLES2Implementation(self
, file)
9125 def WriteGLES2TraceImplementationHeader(self
, file):
9126 """Writes the GLES2 Trace Implemention declaration."""
9127 self
.type_handler
.WriteGLES2TraceImplementationHeader(self
, file)
9129 def WriteGLES2TraceImplementation(self
, file):
9130 """Writes the GLES2 Trace Implemention definition."""
9131 self
.type_handler
.WriteGLES2TraceImplementation(self
, file)
9133 def WriteGLES2Header(self
, file):
9134 """Writes the GLES2 Implemention unit test."""
9135 self
.type_handler
.WriteGLES2Header(self
, file)
9137 def WriteGLES2ImplementationUnitTest(self
, file):
9138 """Writes the GLES2 Implemention unit test."""
9139 self
.type_handler
.WriteGLES2ImplementationUnitTest(self
, file)
9141 def WriteDestinationInitalizationValidation(self
, file):
9142 """Writes the client side destintion initialization validation."""
9143 self
.type_handler
.WriteDestinationInitalizationValidation(self
, file)
9145 def WriteFormatTest(self
, file):
9146 """Writes the cmd's format test."""
9147 self
.type_handler
.WriteFormatTest(self
, file)
9150 class PepperInterface(object):
9151 """A class that represents a function."""
9153 def __init__(self
, info
):
9154 self
.name
= info
["name"]
9155 self
.dev
= info
["dev"]
9160 def GetInterfaceName(self
):
9164 upperint
= "_" + self
.name
.upper()
9167 return "PPB_OPENGLES2%s%s_INTERFACE" % (upperint
, dev
)
9169 def GetInterfaceString(self
):
9173 return "PPB_OpenGLES2%s%s" % (self
.name
, dev
)
9175 def GetStructName(self
):
9179 return "PPB_OpenGLES2%s%s" % (self
.name
, dev
)
9182 class ImmediateFunction(Function
):
9183 """A class that represnets an immediate function command."""
9185 def __init__(self
, func
):
9188 "%sImmediate" % func
.name
,
9191 def InitFunction(self
):
9192 # Override args in original_args and args_for_cmds with immediate versions
9195 new_original_args
= []
9196 for arg
in self
.original_args
:
9197 new_arg
= arg
.GetImmediateVersion()
9199 new_original_args
.append(new_arg
)
9200 self
.original_args
= new_original_args
9202 new_args_for_cmds
= []
9203 for arg
in self
.args_for_cmds
:
9204 new_arg
= arg
.GetImmediateVersion()
9206 new_args_for_cmds
.append(new_arg
)
9208 self
.args_for_cmds
= new_args_for_cmds
9210 Function
.InitFunction(self
)
9212 def IsImmediate(self
):
9215 def WriteCommandDescription(self
, file):
9216 """Overridden from Function"""
9217 file.Write("//! Immediate version of command that corresponds to gl%s.\n" %
9220 def WriteServiceImplementation(self
, file):
9221 """Overridden from Function"""
9222 self
.type_handler
.WriteImmediateServiceImplementation(self
, file)
9224 def WriteHandlerImplementation(self
, file):
9225 """Overridden from Function"""
9226 self
.type_handler
.WriteImmediateHandlerImplementation(self
, file)
9228 def WriteServiceUnitTest(self
, file, *extras
):
9229 """Writes the service implementation for a command."""
9230 self
.type_handler
.WriteImmediateServiceUnitTest(self
, file, *extras
)
9232 def WriteValidationCode(self
, file):
9233 """Overridden from Function"""
9234 self
.type_handler
.WriteImmediateValidationCode(self
, file)
9236 def WriteCmdArgFlag(self
, file):
9237 """Overridden from Function"""
9238 file.Write(" static const cmd::ArgFlags kArgFlags = cmd::kAtLeastN;\n")
9240 def WriteCmdComputeSize(self
, file):
9241 """Overridden from Function"""
9242 self
.type_handler
.WriteImmediateCmdComputeSize(self
, file)
9244 def WriteCmdSetHeader(self
, file):
9245 """Overridden from Function"""
9246 self
.type_handler
.WriteImmediateCmdSetHeader(self
, file)
9248 def WriteCmdInit(self
, file):
9249 """Overridden from Function"""
9250 self
.type_handler
.WriteImmediateCmdInit(self
, file)
9252 def WriteCmdSet(self
, file):
9253 """Overridden from Function"""
9254 self
.type_handler
.WriteImmediateCmdSet(self
, file)
9256 def WriteCmdHelper(self
, file):
9257 """Overridden from Function"""
9258 self
.type_handler
.WriteImmediateCmdHelper(self
, file)
9260 def WriteFormatTest(self
, file):
9261 """Overridden from Function"""
9262 self
.type_handler
.WriteImmediateFormatTest(self
, file)
9265 class BucketFunction(Function
):
9266 """A class that represnets a bucket version of a function command."""
9268 def __init__(self
, func
):
9271 "%sBucket" % func
.name
,
9274 def InitFunction(self
):
9275 # Override args in original_args and args_for_cmds with bucket versions
9278 new_original_args
= []
9279 for arg
in self
.original_args
:
9280 new_arg
= arg
.GetBucketVersion()
9282 new_original_args
.append(new_arg
)
9283 self
.original_args
= new_original_args
9285 new_args_for_cmds
= []
9286 for arg
in self
.args_for_cmds
:
9287 new_arg
= arg
.GetBucketVersion()
9289 new_args_for_cmds
.append(new_arg
)
9291 self
.args_for_cmds
= new_args_for_cmds
9293 Function
.InitFunction(self
)
9295 def WriteCommandDescription(self
, file):
9296 """Overridden from Function"""
9297 file.Write("//! Bucket version of command that corresponds to gl%s.\n" %
9300 def WriteServiceImplementation(self
, file):
9301 """Overridden from Function"""
9302 self
.type_handler
.WriteBucketServiceImplementation(self
, file)
9304 def WriteHandlerImplementation(self
, file):
9305 """Overridden from Function"""
9306 self
.type_handler
.WriteBucketHandlerImplementation(self
, file)
9308 def WriteServiceUnitTest(self
, file, *extras
):
9309 """Overridden from Function"""
9310 self
.type_handler
.WriteBucketServiceUnitTest(self
, file, *extras
)
9312 def MakeOriginalArgString(self
, prefix
, add_comma
= False, separator
= ", "):
9313 """Overridden from Function"""
9314 args
= self
.GetOriginalArgs()
9315 arg_string
= separator
.join(
9316 ["%s%s" % (prefix
, arg
.name
[0:-10] if arg
.name
.endswith("_bucket_id")
9317 else arg
.name
) for arg
in args
])
9318 return super(BucketFunction
, self
)._MaybePrependComma
(arg_string
, add_comma
)
9321 def CreateArg(arg_string
):
9322 """Creates an Argument."""
9323 arg_parts
= arg_string
.split()
9324 if len(arg_parts
) == 1 and arg_parts
[0] == 'void':
9326 # Is this a pointer argument?
9327 elif arg_string
.find('*') >= 0:
9328 return PointerArgument(
9330 " ".join(arg_parts
[0:-1]))
9331 # Is this a resource argument? Must come after pointer check.
9332 elif arg_parts
[0].startswith('GLidBind'):
9333 return ResourceIdBindArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
9334 elif arg_parts
[0].startswith('GLidZero'):
9335 return ResourceIdZeroArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
9336 elif arg_parts
[0].startswith('GLid'):
9337 return ResourceIdArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
9338 elif arg_parts
[0].startswith('GLenum') and len(arg_parts
[0]) > 6:
9339 return EnumArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
9340 elif arg_parts
[0].startswith('GLbitfield') and len(arg_parts
[0]) > 10:
9341 return BitFieldArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
9342 elif arg_parts
[0].startswith('GLboolean') and len(arg_parts
[0]) > 9:
9343 return ValidatedBoolArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
9344 elif arg_parts
[0].startswith('GLboolean'):
9345 return BoolArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
9346 elif arg_parts
[0].startswith('GLintUniformLocation'):
9347 return UniformLocationArgument(arg_parts
[-1])
9348 elif (arg_parts
[0].startswith('GLint') and len(arg_parts
[0]) > 5 and
9349 not arg_parts
[0].startswith('GLintptr')):
9350 return IntArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
9351 elif (arg_parts
[0].startswith('GLsizeiNotNegative') or
9352 arg_parts
[0].startswith('GLintptrNotNegative')):
9353 return SizeNotNegativeArgument(arg_parts
[-1],
9354 " ".join(arg_parts
[0:-1]),
9355 arg_parts
[0][0:-11])
9356 elif arg_parts
[0].startswith('GLsize'):
9357 return SizeArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
9359 return Argument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
9362 class GLGenerator(object):
9363 """A class to generate GL command buffers."""
9365 _function_re
= re
.compile(r
'GL_APICALL(.*?)GL_APIENTRY (.*?) \((.*?)\);')
9367 def __init__(self
, verbose
):
9368 self
.original_functions
= []
9370 self
.verbose
= verbose
9372 self
.pepper_interfaces
= []
9373 self
.interface_info
= {}
9374 self
.generated_cpp_filenames
= []
9376 for interface
in _PEPPER_INTERFACES
:
9377 interface
= PepperInterface(interface
)
9378 self
.pepper_interfaces
.append(interface
)
9379 self
.interface_info
[interface
.GetName()] = interface
9381 def AddFunction(self
, func
):
9382 """Adds a function."""
9383 self
.functions
.append(func
)
9385 def GetFunctionInfo(self
, name
):
9386 """Gets a type info for the given function name."""
9387 if name
in _FUNCTION_INFO
:
9388 func_info
= _FUNCTION_INFO
[name
].copy()
9392 if not 'type' in func_info
:
9393 func_info
['type'] = ''
9398 """Prints something if verbose is true."""
9402 def Error(self
, msg
):
9403 """Prints an error."""
9404 print "Error: %s" % msg
9407 def WriteLicense(self
, file):
9408 """Writes the license."""
9409 file.Write(_LICENSE
)
9411 def WriteNamespaceOpen(self
, file):
9412 """Writes the code for the namespace."""
9413 file.Write("namespace gpu {\n")
9414 file.Write("namespace gles2 {\n")
9417 def WriteNamespaceClose(self
, file):
9418 """Writes the code to close the namespace."""
9419 file.Write("} // namespace gles2\n")
9420 file.Write("} // namespace gpu\n")
9423 def ParseGLH(self
, filename
):
9424 """Parses the cmd_buffer_functions.txt file and extracts the functions"""
9425 f
= open(filename
, "r")
9426 functions
= f
.read()
9428 for line
in functions
.splitlines():
9429 match
= self
._function
_re
.match(line
)
9431 func_name
= match
.group(2)[2:]
9432 func_info
= self
.GetFunctionInfo(func_name
)
9433 if func_info
['type'] == 'Noop':
9436 parsed_func_info
= {
9437 'original_name': func_name
,
9438 'original_args': match
.group(3),
9439 'return_type': match
.group(1).strip(),
9442 for k
in parsed_func_info
.keys():
9443 if not k
in func_info
:
9444 func_info
[k
] = parsed_func_info
[k
]
9446 f
= Function(func_name
, func_info
)
9447 self
.original_functions
.append(f
)
9449 #for arg in f.GetOriginalArgs():
9450 # if not isinstance(arg, EnumArgument) and arg.type == 'GLenum':
9451 # self.Log("%s uses bare GLenum %s." % (func_name, arg.name))
9453 gen_cmd
= f
.GetInfo('gen_cmd')
9454 if gen_cmd
== True or gen_cmd
== None:
9455 if f
.type_handler
.NeedsDataTransferFunction(f
):
9456 methods
= f
.GetDataTransferMethods()
9457 if 'immediate' in methods
:
9458 self
.AddFunction(ImmediateFunction(f
))
9459 if 'bucket' in methods
:
9460 self
.AddFunction(BucketFunction(f
))
9461 if 'shm' in methods
:
9466 self
.Log("Auto Generated Functions : %d" %
9467 len([f
for f
in self
.functions
if f
.can_auto_generate
or
9468 (not f
.IsType('') and not f
.IsType('Custom') and
9469 not f
.IsType('Todo'))]))
9471 funcs
= [f
for f
in self
.functions
if not f
.can_auto_generate
and
9472 (f
.IsType('') or f
.IsType('Custom') or f
.IsType('Todo'))]
9473 self
.Log("Non Auto Generated Functions: %d" % len(funcs
))
9476 self
.Log(" %-10s %-20s gl%s" % (f
.info
['type'], f
.return_type
, f
.name
))
9478 def WriteCommandIds(self
, filename
):
9479 """Writes the command buffer format"""
9480 file = CHeaderWriter(filename
)
9481 file.Write("#define GLES2_COMMAND_LIST(OP) \\\n")
9483 for func
in self
.functions
:
9484 file.Write(" %-60s /* %d */ \\\n" %
9485 ("OP(%s)" % func
.name
, id))
9489 file.Write("enum CommandId {\n")
9490 file.Write(" kStartPoint = cmd::kLastCommonId, "
9491 "// All GLES2 commands start after this.\n")
9492 file.Write("#define GLES2_CMD_OP(name) k ## name,\n")
9493 file.Write(" GLES2_COMMAND_LIST(GLES2_CMD_OP)\n")
9494 file.Write("#undef GLES2_CMD_OP\n")
9495 file.Write(" kNumCommands\n")
9499 self
.generated_cpp_filenames
.append(file.filename
)
9501 def WriteFormat(self
, filename
):
9502 """Writes the command buffer format"""
9503 file = CHeaderWriter(filename
)
9504 # Forward declaration of a few enums used in constant argument
9505 # to avoid including GL header files.
9507 'GL_SYNC_GPU_COMMANDS_COMPLETE': '0x9117',
9508 'GL_SYNC_FLUSH_COMMANDS_BIT': '0x00000001',
9511 for enum
in enum_defines
:
9512 file.Write("#define %s %s\n" % (enum
, enum_defines
[enum
]))
9514 for func
in self
.functions
:
9516 #gen_cmd = func.GetInfo('gen_cmd')
9517 #if gen_cmd == True or gen_cmd == None:
9518 func
.WriteStruct(file)
9521 self
.generated_cpp_filenames
.append(file.filename
)
9523 def WriteDocs(self
, filename
):
9524 """Writes the command buffer doc version of the commands"""
9525 file = CWriter(filename
)
9526 for func
in self
.functions
:
9528 #gen_cmd = func.GetInfo('gen_cmd')
9529 #if gen_cmd == True or gen_cmd == None:
9530 func
.WriteDocs(file)
9533 self
.generated_cpp_filenames
.append(file.filename
)
9535 def WriteFormatTest(self
, filename
):
9536 """Writes the command buffer format test."""
9537 file = CHeaderWriter(
9539 "// This file contains unit tests for gles2 commmands\n"
9540 "// It is included by gles2_cmd_format_test.cc\n"
9543 for func
in self
.functions
:
9545 #gen_cmd = func.GetInfo('gen_cmd')
9546 #if gen_cmd == True or gen_cmd == None:
9547 func
.WriteFormatTest(file)
9550 self
.generated_cpp_filenames
.append(file.filename
)
9552 def WriteCmdHelperHeader(self
, filename
):
9553 """Writes the gles2 command helper."""
9554 file = CHeaderWriter(filename
)
9556 for func
in self
.functions
:
9558 #gen_cmd = func.GetInfo('gen_cmd')
9559 #if gen_cmd == True or gen_cmd == None:
9560 func
.WriteCmdHelper(file)
9563 self
.generated_cpp_filenames
.append(file.filename
)
9565 def WriteServiceContextStateHeader(self
, filename
):
9566 """Writes the service context state header."""
9567 file = CHeaderWriter(
9569 "// It is included by context_state.h\n")
9570 file.Write("struct EnableFlags {\n")
9571 file.Write(" EnableFlags();\n")
9572 for capability
in _CAPABILITY_FLAGS
:
9573 file.Write(" bool %s;\n" % capability
['name'])
9574 file.Write(" bool cached_%s;\n" % capability
['name'])
9575 file.Write("};\n\n")
9577 for state_name
in sorted(_STATES
.keys()):
9578 state
= _STATES
[state_name
]
9579 for item
in state
['states']:
9580 if isinstance(item
['default'], list):
9581 file.Write("%s %s[%d];\n" % (item
['type'], item
['name'],
9582 len(item
['default'])))
9584 file.Write("%s %s;\n" % (item
['type'], item
['name']))
9586 if item
.get('cached', False):
9587 if isinstance(item
['default'], list):
9588 file.Write("%s cached_%s[%d];\n" % (item
['type'], item
['name'],
9589 len(item
['default'])))
9591 file.Write("%s cached_%s;\n" % (item
['type'], item
['name']))
9596 inline void SetDeviceCapabilityState(GLenum cap, bool enable) {
9599 for capability
in _CAPABILITY_FLAGS
:
9602 """ % capability
['name'].upper())
9604 if (enable_flags.cached_%(name)s == enable &&
9605 !ignore_cached_state)
9607 enable_flags.cached_%(name)s = enable;
9624 self
.generated_cpp_filenames
.append(file.filename
)
9626 def WriteClientContextStateHeader(self
, filename
):
9627 """Writes the client context state header."""
9628 file = CHeaderWriter(
9630 "// It is included by client_context_state.h\n")
9631 file.Write("struct EnableFlags {\n")
9632 file.Write(" EnableFlags();\n")
9633 for capability
in _CAPABILITY_FLAGS
:
9634 file.Write(" bool %s;\n" % capability
['name'])
9635 file.Write("};\n\n")
9638 self
.generated_cpp_filenames
.append(file.filename
)
9640 def WriteContextStateGetters(self
, file, class_name
):
9641 """Writes the state getters."""
9642 for gl_type
in ["GLint", "GLfloat"]:
9644 bool %s::GetStateAs%s(
9645 GLenum pname, %s* params, GLsizei* num_written) const {
9647 """ % (class_name
, gl_type
, gl_type
))
9648 for state_name
in sorted(_STATES
.keys()):
9649 state
= _STATES
[state_name
]
9651 file.Write(" case %s:\n" % state
['enum'])
9652 file.Write(" *num_written = %d;\n" % len(state
['states']))
9653 file.Write(" if (params) {\n")
9654 for ndx
,item
in enumerate(state
['states']):
9655 file.Write(" params[%d] = static_cast<%s>(%s);\n" %
9656 (ndx
, gl_type
, item
['name']))
9658 file.Write(" return true;\n")
9660 for item
in state
['states']:
9661 file.Write(" case %s:\n" % item
['enum'])
9662 if isinstance(item
['default'], list):
9663 item_len
= len(item
['default'])
9664 file.Write(" *num_written = %d;\n" % item_len
)
9665 file.Write(" if (params) {\n")
9666 if item
['type'] == gl_type
:
9667 file.Write(" memcpy(params, %s, sizeof(%s) * %d);\n" %
9668 (item
['name'], item
['type'], item_len
))
9670 file.Write(" for (size_t i = 0; i < %s; ++i) {\n" %
9672 file.Write(" params[i] = %s;\n" %
9673 (GetGLGetTypeConversion(gl_type
, item
['type'],
9674 "%s[i]" % item
['name'])))
9677 file.Write(" *num_written = 1;\n")
9678 file.Write(" if (params) {\n")
9679 file.Write(" params[0] = %s;\n" %
9680 (GetGLGetTypeConversion(gl_type
, item
['type'],
9683 file.Write(" return true;\n")
9684 for capability
in _CAPABILITY_FLAGS
:
9685 file.Write(" case GL_%s:\n" % capability
['name'].upper())
9686 file.Write(" *num_written = 1;\n")
9687 file.Write(" if (params) {\n")
9689 " params[0] = static_cast<%s>(enable_flags.%s);\n" %
9690 (gl_type
, capability
['name']))
9692 file.Write(" return true;\n")
9693 file.Write(""" default:
9699 def WriteServiceContextStateImpl(self
, filename
):
9700 """Writes the context state service implementation."""
9701 file = CHeaderWriter(
9703 "// It is included by context_state.cc\n")
9705 for capability
in _CAPABILITY_FLAGS
:
9706 code
.append("%s(%s)" %
9707 (capability
['name'],
9708 ('false', 'true')['default' in capability
]))
9709 code
.append("cached_%s(%s)" %
9710 (capability
['name'],
9711 ('false', 'true')['default' in capability
]))
9712 file.Write("ContextState::EnableFlags::EnableFlags()\n : %s {\n}\n" %
9716 file.Write("void ContextState::Initialize() {\n")
9717 for state_name
in sorted(_STATES
.keys()):
9718 state
= _STATES
[state_name
]
9719 for item
in state
['states']:
9720 if isinstance(item
['default'], list):
9721 for ndx
, value
in enumerate(item
['default']):
9722 file.Write(" %s[%d] = %s;\n" % (item
['name'], ndx
, value
))
9724 file.Write(" %s = %s;\n" % (item
['name'], item
['default']))
9725 if item
.get('cached', False):
9726 if isinstance(item
['default'], list):
9727 for ndx
, value
in enumerate(item
['default']):
9728 file.Write(" cached_%s[%d] = %s;\n" % (item
['name'], ndx
, value
))
9730 file.Write(" cached_%s = %s;\n" % (item
['name'], item
['default']))
9734 void ContextState::InitCapabilities(const ContextState* prev_state) const {
9736 def WriteCapabilities(test_prev
, es3_caps
):
9737 for capability
in _CAPABILITY_FLAGS
:
9738 capability_name
= capability
['name']
9739 capability_es3
= 'es3' in capability
and capability
['es3'] == True
9740 if capability_es3
and not es3_caps
or not capability_es3
and es3_caps
:
9743 file.Write(""" if (prev_state->enable_flags.cached_%s !=
9744 enable_flags.cached_%s) {\n""" %
9745 (capability_name
, capability_name
))
9746 file.Write(" EnableDisable(GL_%s, enable_flags.cached_%s);\n" %
9747 (capability_name
.upper(), capability_name
))
9751 file.Write(" if (prev_state) {")
9752 WriteCapabilities(True, False)
9753 file.Write(" if (feature_info_->IsES3Capable()) {\n")
9754 WriteCapabilities(True, True)
9756 file.Write(" } else {")
9757 WriteCapabilities(False, False)
9758 file.Write(" if (feature_info_->IsES3Capable()) {\n")
9759 WriteCapabilities(False, True)
9765 void ContextState::InitState(const ContextState *prev_state) const {
9768 def WriteStates(test_prev
):
9769 # We need to sort the keys so the expectations match
9770 for state_name
in sorted(_STATES
.keys()):
9771 state
= _STATES
[state_name
]
9772 if state
['type'] == 'FrontBack':
9773 num_states
= len(state
['states'])
9774 for ndx
, group
in enumerate(Grouper(num_states
/ 2, state
['states'])):
9778 for place
, item
in enumerate(group
):
9779 item_name
= CachedStateName(item
)
9780 args
.append('%s' % item_name
)
9784 file.Write("(%s != prev_state->%s)" % (item_name
, item_name
))
9788 " gl%s(%s, %s);\n" %
9789 (state
['func'], ('GL_FRONT', 'GL_BACK')[ndx
], ", ".join(args
)))
9790 elif state
['type'] == 'NamedParameter':
9791 for item
in state
['states']:
9792 item_name
= CachedStateName(item
)
9794 if 'extension_flag' in item
:
9795 file.Write(" if (feature_info_->feature_flags().%s) {\n " %
9796 item
['extension_flag'])
9798 if isinstance(item
['default'], list):
9799 file.Write(" if (memcmp(prev_state->%s, %s, "
9800 "sizeof(%s) * %d)) {\n" %
9801 (item_name
, item_name
, item
['type'],
9802 len(item
['default'])))
9804 file.Write(" if (prev_state->%s != %s) {\n " %
9805 (item_name
, item_name
))
9806 if 'gl_version_flag' in item
:
9807 item_name
= item
['gl_version_flag']
9809 if item_name
[0] == '!':
9811 item_name
= item_name
[1:]
9812 file.Write(" if (%sfeature_info_->gl_version_info().%s) {\n" %
9813 (inverted
, item_name
))
9814 file.Write(" gl%s(%s, %s);\n" %
9817 if 'enum_set' in item
else item
['enum']),
9819 if 'gl_version_flag' in item
:
9822 if 'extension_flag' in item
:
9825 if 'extension_flag' in item
:
9828 if 'extension_flag' in state
:
9829 file.Write(" if (feature_info_->feature_flags().%s)\n " %
9830 state
['extension_flag'])
9834 for place
, item
in enumerate(state
['states']):
9835 item_name
= CachedStateName(item
)
9836 args
.append('%s' % item_name
)
9840 file.Write("(%s != prev_state->%s)" %
9841 (item_name
, item_name
))
9844 file.Write(" gl%s(%s);\n" % (state
['func'], ", ".join(args
)))
9846 file.Write(" if (prev_state) {")
9848 file.Write(" } else {")
9853 file.Write("""bool ContextState::GetEnabled(GLenum cap) const {
9856 for capability
in _CAPABILITY_FLAGS
:
9857 file.Write(" case GL_%s:\n" % capability
['name'].upper())
9858 file.Write(" return enable_flags.%s;\n" % capability
['name'])
9859 file.Write(""" default:
9866 self
.WriteContextStateGetters(file, "ContextState")
9868 self
.generated_cpp_filenames
.append(file.filename
)
9870 def WriteClientContextStateImpl(self
, filename
):
9871 """Writes the context state client side implementation."""
9872 file = CHeaderWriter(
9874 "// It is included by client_context_state.cc\n")
9876 for capability
in _CAPABILITY_FLAGS
:
9877 code
.append("%s(%s)" %
9878 (capability
['name'],
9879 ('false', 'true')['default' in capability
]))
9881 "ClientContextState::EnableFlags::EnableFlags()\n : %s {\n}\n" %
9886 bool ClientContextState::SetCapabilityState(
9887 GLenum cap, bool enabled, bool* changed) {
9891 for capability
in _CAPABILITY_FLAGS
:
9892 file.Write(" case GL_%s:\n" % capability
['name'].upper())
9893 file.Write(""" if (enable_flags.%(name)s != enabled) {
9895 enable_flags.%(name)s = enabled;
9899 file.Write(""" default:
9904 file.Write("""bool ClientContextState::GetEnabled(
9905 GLenum cap, bool* enabled) const {
9908 for capability
in _CAPABILITY_FLAGS
:
9909 file.Write(" case GL_%s:\n" % capability
['name'].upper())
9910 file.Write(" *enabled = enable_flags.%s;\n" % capability
['name'])
9911 file.Write(" return true;\n")
9912 file.Write(""" default:
9918 self
.generated_cpp_filenames
.append(file.filename
)
9920 def WriteServiceImplementation(self
, filename
):
9921 """Writes the service decorder implementation."""
9922 file = CHeaderWriter(
9924 "// It is included by gles2_cmd_decoder.cc\n")
9926 for func
in self
.functions
:
9928 #gen_cmd = func.GetInfo('gen_cmd')
9929 #if gen_cmd == True or gen_cmd == None:
9930 func
.WriteServiceImplementation(file)
9933 bool GLES2DecoderImpl::SetCapabilityState(GLenum cap, bool enabled) {
9936 for capability
in _CAPABILITY_FLAGS
:
9937 file.Write(" case GL_%s:\n" % capability
['name'].upper())
9938 if 'state_flag' in capability
:
9941 state_.enable_flags.%(name)s = enabled;
9942 if (state_.enable_flags.cached_%(name)s != enabled
9943 || state_.ignore_cached_state) {
9944 %(state_flag)s = true;
9950 state_.enable_flags.%(name)s = enabled;
9951 if (state_.enable_flags.cached_%(name)s != enabled
9952 || state_.ignore_cached_state) {
9953 state_.enable_flags.cached_%(name)s = enabled;
9958 file.Write(""" default:
9965 self
.generated_cpp_filenames
.append(file.filename
)
9967 def WriteServiceUnitTests(self
, filename
):
9968 """Writes the service decorder unit tests."""
9969 num_tests
= len(self
.functions
)
9970 FUNCTIONS_PER_FILE
= 98 # hard code this so it doesn't change.
9972 for test_num
in range(0, num_tests
, FUNCTIONS_PER_FILE
):
9974 name
= filename
% count
9975 file = CHeaderWriter(
9977 "// It is included by gles2_cmd_decoder_unittest_%d.cc\n" % count
)
9978 test_name
= 'GLES2DecoderTest%d' % count
9979 end
= test_num
+ FUNCTIONS_PER_FILE
9982 for idx
in range(test_num
, end
):
9983 func
= self
.functions
[idx
]
9985 # Do any filtering of the functions here, so that the functions
9986 # will not move between the numbered files if filtering properties
9988 if func
.GetInfo('extension_flag'):
9992 #gen_cmd = func.GetInfo('gen_cmd')
9993 #if gen_cmd == True or gen_cmd == None:
9994 if func
.GetInfo('unit_test') == False:
9995 file.Write("// TODO(gman): %s\n" % func
.name
)
9997 func
.WriteServiceUnitTest(file, {
9998 'test_name': test_name
10001 self
.generated_cpp_filenames
.append(file.filename
)
10002 file = CHeaderWriter(
10004 "// It is included by gles2_cmd_decoder_unittest_base.cc\n")
10006 """void GLES2DecoderTestBase::SetupInitCapabilitiesExpectations(
10007 bool es3_capable) {""")
10008 for capability
in _CAPABILITY_FLAGS
:
10009 capability_es3
= 'es3' in capability
and capability
['es3'] == True
10010 if not capability_es3
:
10011 file.Write(" ExpectEnableDisable(GL_%s, %s);\n" %
10012 (capability
['name'].upper(),
10013 ('false', 'true')['default' in capability
]))
10015 file.Write(" if (es3_capable) {")
10016 for capability
in _CAPABILITY_FLAGS
:
10017 capability_es3
= 'es3' in capability
and capability
['es3'] == True
10019 file.Write(" ExpectEnableDisable(GL_%s, %s);\n" %
10020 (capability
['name'].upper(),
10021 ('false', 'true')['default' in capability
]))
10025 void GLES2DecoderTestBase::SetupInitStateExpectations() {
10028 # We need to sort the keys so the expectations match
10029 for state_name
in sorted(_STATES
.keys()):
10030 state
= _STATES
[state_name
]
10031 if state
['type'] == 'FrontBack':
10032 num_states
= len(state
['states'])
10033 for ndx
, group
in enumerate(Grouper(num_states
/ 2, state
['states'])):
10036 if 'expected' in item
:
10037 args
.append(item
['expected'])
10039 args
.append(item
['default'])
10041 " EXPECT_CALL(*gl_, %s(%s, %s))\n" %
10042 (state
['func'], ('GL_FRONT', 'GL_BACK')[ndx
], ", ".join(args
)))
10043 file.Write(" .Times(1)\n")
10044 file.Write(" .RetiresOnSaturation();\n")
10045 elif state
['type'] == 'NamedParameter':
10046 for item
in state
['states']:
10047 if 'extension_flag' in item
:
10048 file.Write(" if (group_->feature_info()->feature_flags().%s) {\n" %
10049 item
['extension_flag'])
10051 expect_value
= item
['default']
10052 if isinstance(expect_value
, list):
10053 # TODO: Currently we do not check array values.
10057 " EXPECT_CALL(*gl_, %s(%s, %s))\n" %
10060 if 'enum_set' in item
else item
['enum']),
10062 file.Write(" .Times(1)\n")
10063 file.Write(" .RetiresOnSaturation();\n")
10064 if 'extension_flag' in item
:
10067 if 'extension_flag' in state
:
10068 file.Write(" if (group_->feature_info()->feature_flags().%s) {\n" %
10069 state
['extension_flag'])
10072 for item
in state
['states']:
10073 if 'expected' in item
:
10074 args
.append(item
['expected'])
10076 args
.append(item
['default'])
10077 # TODO: Currently we do not check array values.
10078 args
= ["_" if isinstance(arg
, list) else arg
for arg
in args
]
10079 file.Write(" EXPECT_CALL(*gl_, %s(%s))\n" %
10080 (state
['func'], ", ".join(args
)))
10081 file.Write(" .Times(1)\n")
10082 file.Write(" .RetiresOnSaturation();\n")
10083 if 'extension_flag' in state
:
10088 self
.generated_cpp_filenames
.append(file.filename
)
10090 def WriteServiceUnitTestsForExtensions(self
, filename
):
10091 """Writes the service decorder unit tests for functions with extension_flag.
10093 The functions are special in that they need a specific unit test
10094 baseclass to turn on the extension.
10096 functions
= [f
for f
in self
.functions
if f
.GetInfo('extension_flag')]
10097 file = CHeaderWriter(
10099 "// It is included by gles2_cmd_decoder_unittest_extensions.cc\n")
10100 for func
in functions
:
10102 if func
.GetInfo('unit_test') == False:
10103 file.Write("// TODO(gman): %s\n" % func
.name
)
10105 extension
= ToCamelCase(
10106 ToGLExtensionString(func
.GetInfo('extension_flag')))
10107 func
.WriteServiceUnitTest(file, {
10108 'test_name': 'GLES2DecoderTestWith%s' % extension
10112 self
.generated_cpp_filenames
.append(file.filename
)
10114 def WriteGLES2Header(self
, filename
):
10115 """Writes the GLES2 header."""
10116 file = CHeaderWriter(
10118 "// This file contains Chromium-specific GLES2 declarations.\n\n")
10120 for func
in self
.original_functions
:
10121 func
.WriteGLES2Header(file)
10125 self
.generated_cpp_filenames
.append(file.filename
)
10127 def WriteGLES2CLibImplementation(self
, filename
):
10128 """Writes the GLES2 c lib implementation."""
10129 file = CHeaderWriter(
10131 "// These functions emulate GLES2 over command buffers.\n")
10133 for func
in self
.original_functions
:
10134 func
.WriteGLES2CLibImplementation(file)
10139 extern const NameToFunc g_gles2_function_table[] = {
10141 for func
in self
.original_functions
:
10143 ' { "gl%s", reinterpret_cast<GLES2FunctionPointer>(gl%s), },\n' %
10144 (func
.name
, func
.name
))
10145 file.Write(""" { NULL, NULL, },
10148 } // namespace gles2
10151 self
.generated_cpp_filenames
.append(file.filename
)
10153 def WriteGLES2InterfaceHeader(self
, filename
):
10154 """Writes the GLES2 interface header."""
10155 file = CHeaderWriter(
10157 "// This file is included by gles2_interface.h to declare the\n"
10158 "// GL api functions.\n")
10159 for func
in self
.original_functions
:
10160 func
.WriteGLES2InterfaceHeader(file)
10162 self
.generated_cpp_filenames
.append(file.filename
)
10164 def WriteMojoGLES2ImplHeader(self
, filename
):
10165 """Writes the Mojo GLES2 implementation header."""
10166 file = CHeaderWriter(
10168 "// This file is included by gles2_interface.h to declare the\n"
10169 "// GL api functions.\n")
10172 #include "gpu/command_buffer/client/gles2_interface.h"
10173 #include "third_party/mojo/src/mojo/public/c/gles2/gles2.h"
10177 class MojoGLES2Impl : public gpu::gles2::GLES2Interface {
10179 explicit MojoGLES2Impl(MojoGLES2Context context) {
10180 context_ = context;
10182 ~MojoGLES2Impl() override {}
10185 for func
in self
.original_functions
:
10186 func
.WriteMojoGLES2ImplHeader(file)
10189 MojoGLES2Context context_;
10192 } // namespace mojo
10196 self
.generated_cpp_filenames
.append(file.filename
)
10198 def WriteMojoGLES2Impl(self
, filename
):
10199 """Writes the Mojo GLES2 implementation."""
10200 file = CWriter(filename
)
10201 file.Write(_LICENSE
)
10202 file.Write(_DO_NOT_EDIT_WARNING
)
10205 #include "mojo/gpu/mojo_gles2_impl_autogen.h"
10207 #include "base/logging.h"
10208 #include "third_party/mojo/src/mojo/public/c/gles2/chromium_miscellaneous.h"
10209 #include "third_party/mojo/src/mojo/public/c/gles2/chromium_sub_image.h"
10210 #include "third_party/mojo/src/mojo/public/c/gles2/chromium_sync_point.h"
10211 #include "third_party/mojo/src/mojo/public/c/gles2/chromium_texture_mailbox.h"
10212 #include "third_party/mojo/src/mojo/public/c/gles2/gles2.h"
10213 #include "third_party/mojo/src/mojo/public/c/gles2/occlusion_query_ext.h"
10219 for func
in self
.original_functions
:
10220 func
.WriteMojoGLES2Impl(file)
10223 } // namespace mojo
10227 self
.generated_cpp_filenames
.append(file.filename
)
10229 def WriteGLES2InterfaceStub(self
, filename
):
10230 """Writes the GLES2 interface stub header."""
10231 file = CHeaderWriter(
10233 "// This file is included by gles2_interface_stub.h.\n")
10234 for func
in self
.original_functions
:
10235 func
.WriteGLES2InterfaceStub(file)
10237 self
.generated_cpp_filenames
.append(file.filename
)
10239 def WriteGLES2InterfaceStubImpl(self
, filename
):
10240 """Writes the GLES2 interface header."""
10241 file = CHeaderWriter(
10243 "// This file is included by gles2_interface_stub.cc.\n")
10244 for func
in self
.original_functions
:
10245 func
.WriteGLES2InterfaceStubImpl(file)
10247 self
.generated_cpp_filenames
.append(file.filename
)
10249 def WriteGLES2ImplementationHeader(self
, filename
):
10250 """Writes the GLES2 Implementation header."""
10251 file = CHeaderWriter(
10253 "// This file is included by gles2_implementation.h to declare the\n"
10254 "// GL api functions.\n")
10255 for func
in self
.original_functions
:
10256 func
.WriteGLES2ImplementationHeader(file)
10258 self
.generated_cpp_filenames
.append(file.filename
)
10260 def WriteGLES2Implementation(self
, filename
):
10261 """Writes the GLES2 Implementation."""
10262 file = CHeaderWriter(
10264 "// This file is included by gles2_implementation.cc to define the\n"
10265 "// GL api functions.\n")
10266 for func
in self
.original_functions
:
10267 func
.WriteGLES2Implementation(file)
10269 self
.generated_cpp_filenames
.append(file.filename
)
10271 def WriteGLES2TraceImplementationHeader(self
, filename
):
10272 """Writes the GLES2 Trace Implementation header."""
10273 file = CHeaderWriter(
10275 "// This file is included by gles2_trace_implementation.h\n")
10276 for func
in self
.original_functions
:
10277 func
.WriteGLES2TraceImplementationHeader(file)
10279 self
.generated_cpp_filenames
.append(file.filename
)
10281 def WriteGLES2TraceImplementation(self
, filename
):
10282 """Writes the GLES2 Trace Implementation."""
10283 file = CHeaderWriter(
10285 "// This file is included by gles2_trace_implementation.cc\n")
10286 for func
in self
.original_functions
:
10287 func
.WriteGLES2TraceImplementation(file)
10289 self
.generated_cpp_filenames
.append(file.filename
)
10291 def WriteGLES2ImplementationUnitTests(self
, filename
):
10292 """Writes the GLES2 helper header."""
10293 file = CHeaderWriter(
10295 "// This file is included by gles2_implementation.h to declare the\n"
10296 "// GL api functions.\n")
10297 for func
in self
.original_functions
:
10298 func
.WriteGLES2ImplementationUnitTest(file)
10300 self
.generated_cpp_filenames
.append(file.filename
)
10302 def WriteServiceUtilsHeader(self
, filename
):
10303 """Writes the gles2 auto generated utility header."""
10304 file = CHeaderWriter(filename
)
10305 for name
in sorted(_NAMED_TYPE_INFO
.keys()):
10306 named_type
= NamedType(_NAMED_TYPE_INFO
[name
])
10307 if named_type
.IsConstant():
10309 file.Write("ValueValidator<%s> %s;\n" %
10310 (named_type
.GetType(), ToUnderscore(name
)))
10313 self
.generated_cpp_filenames
.append(file.filename
)
10315 def WriteServiceUtilsImplementation(self
, filename
):
10316 """Writes the gles2 auto generated utility implementation."""
10317 file = CHeaderWriter(filename
)
10318 names
= sorted(_NAMED_TYPE_INFO
.keys())
10320 named_type
= NamedType(_NAMED_TYPE_INFO
[name
])
10321 if named_type
.IsConstant():
10323 if named_type
.GetValidValues():
10324 file.Write("static const %s valid_%s_table[] = {\n" %
10325 (named_type
.GetType(), ToUnderscore(name
)))
10326 for value
in named_type
.GetValidValues():
10327 file.Write(" %s,\n" % value
)
10330 if named_type
.GetValidValuesES3():
10331 file.Write("static const %s valid_%s_table_es3[] = {\n" %
10332 (named_type
.GetType(), ToUnderscore(name
)))
10333 for value
in named_type
.GetValidValuesES3():
10334 file.Write(" %s,\n" % value
)
10337 if named_type
.GetDeprecatedValuesES3():
10338 file.Write("static const %s deprecated_%s_table_es3[] = {\n" %
10339 (named_type
.GetType(), ToUnderscore(name
)))
10340 for value
in named_type
.GetDeprecatedValuesES3():
10341 file.Write(" %s,\n" % value
)
10344 file.Write("Validators::Validators()")
10346 for count
, name
in enumerate(names
):
10347 named_type
= NamedType(_NAMED_TYPE_INFO
[name
])
10348 if named_type
.IsConstant():
10350 if named_type
.GetValidValues():
10351 code
= """%(pre)s%(name)s(
10352 valid_%(name)s_table, arraysize(valid_%(name)s_table))"""
10354 code
= "%(pre)s%(name)s()"
10355 file.Write(code
% {
10356 'name': ToUnderscore(name
),
10360 file.Write(" {\n");
10361 file.Write("}\n\n");
10363 file.Write("void Validators::UpdateValuesES3() {\n")
10365 named_type
= NamedType(_NAMED_TYPE_INFO
[name
])
10366 if named_type
.GetDeprecatedValuesES3():
10367 code
= """ %(name)s.RemoveValues(
10368 deprecated_%(name)s_table_es3, arraysize(deprecated_%(name)s_table_es3));
10370 file.Write(code
% {
10371 'name': ToUnderscore(name
),
10373 if named_type
.GetValidValuesES3():
10374 code
= """ %(name)s.AddValues(
10375 valid_%(name)s_table_es3, arraysize(valid_%(name)s_table_es3));
10377 file.Write(code
% {
10378 'name': ToUnderscore(name
),
10380 file.Write("}\n\n");
10382 self
.generated_cpp_filenames
.append(file.filename
)
10384 def WriteCommonUtilsHeader(self
, filename
):
10385 """Writes the gles2 common utility header."""
10386 file = CHeaderWriter(filename
)
10387 type_infos
= sorted(_NAMED_TYPE_INFO
.keys())
10388 for type_info
in type_infos
:
10389 if _NAMED_TYPE_INFO
[type_info
]['type'] == 'GLenum':
10390 file.Write("static std::string GetString%s(uint32_t value);\n" %
10394 self
.generated_cpp_filenames
.append(file.filename
)
10396 def WriteCommonUtilsImpl(self
, filename
):
10397 """Writes the gles2 common utility header."""
10398 enum_re
= re
.compile(r
'\#define\s+(GL_[a-zA-Z0-9_]+)\s+([0-9A-Fa-fx]+)')
10400 for fname
in ['third_party/khronos/GLES2/gl2.h',
10401 'third_party/khronos/GLES2/gl2ext.h',
10402 'third_party/khronos/GLES3/gl3.h',
10403 'gpu/GLES2/gl2chromium.h',
10404 'gpu/GLES2/gl2extchromium.h']:
10405 lines
= open(fname
).readlines()
10407 m
= enum_re
.match(line
)
10411 if len(value
) <= 10:
10412 if not value
in dict:
10414 # check our own _CHROMIUM macro conflicts with khronos GL headers.
10415 elif dict[value
] != name
and (name
.endswith('_CHROMIUM') or
10416 dict[value
].endswith('_CHROMIUM')):
10417 self
.Error("code collision: %s and %s have the same code %s" %
10418 (dict[value
], name
, value
))
10420 file = CHeaderWriter(filename
)
10421 file.Write("static const GLES2Util::EnumToString "
10422 "enum_to_string_table[] = {\n")
10424 file.Write(' { %s, "%s", },\n' % (value
, dict[value
]))
10427 const GLES2Util::EnumToString* const GLES2Util::enum_to_string_table_ =
10428 enum_to_string_table;
10429 const size_t GLES2Util::enum_to_string_table_len_ =
10430 sizeof(enum_to_string_table) / sizeof(enum_to_string_table[0]);
10434 enums
= sorted(_NAMED_TYPE_INFO
.keys())
10436 if _NAMED_TYPE_INFO
[enum
]['type'] == 'GLenum':
10437 file.Write("std::string GLES2Util::GetString%s(uint32_t value) {\n" %
10439 valid_list
= _NAMED_TYPE_INFO
[enum
]['valid']
10440 if 'valid_es3' in _NAMED_TYPE_INFO
[enum
]:
10441 valid_list
= valid_list
+ _NAMED_TYPE_INFO
[enum
]['valid_es3']
10442 assert len(valid_list
) == len(set(valid_list
))
10443 if len(valid_list
) > 0:
10444 file.Write(" static const EnumToString string_table[] = {\n")
10445 for value
in valid_list
:
10446 file.Write(' { %s, "%s" },\n' % (value
, value
))
10448 return GLES2Util::GetQualifiedEnumString(
10449 string_table, arraysize(string_table), value);
10454 file.Write(""" return GLES2Util::GetQualifiedEnumString(
10460 self
.generated_cpp_filenames
.append(file.filename
)
10462 def WritePepperGLES2Interface(self
, filename
, dev
):
10463 """Writes the Pepper OpenGLES interface definition."""
10464 file = CWriter(filename
)
10465 file.Write(_LICENSE
)
10466 file.Write(_DO_NOT_EDIT_WARNING
)
10468 file.Write("label Chrome {\n")
10469 file.Write(" M39 = 1.0\n")
10470 file.Write("};\n\n")
10473 # Declare GL types.
10474 file.Write("[version=1.0]\n")
10475 file.Write("describe {\n")
10476 for gltype
in ['GLbitfield', 'GLboolean', 'GLbyte', 'GLclampf',
10477 'GLclampx', 'GLenum', 'GLfixed', 'GLfloat', 'GLint',
10478 'GLintptr', 'GLshort', 'GLsizei', 'GLsizeiptr',
10479 'GLubyte', 'GLuint', 'GLushort']:
10480 file.Write(" %s;\n" % gltype
)
10481 file.Write(" %s_ptr_t;\n" % gltype
)
10482 file.Write("};\n\n")
10484 # C level typedefs.
10485 file.Write("#inline c\n")
10486 file.Write("#include \"ppapi/c/pp_resource.h\"\n")
10488 file.Write("#include \"ppapi/c/ppb_opengles2.h\"\n\n")
10490 file.Write("\n#ifndef __gl2_h_\n")
10491 for (k
, v
) in _GL_TYPES
.iteritems():
10492 file.Write("typedef %s %s;\n" % (v
, k
))
10493 file.Write("#ifdef _WIN64\n")
10494 for (k
, v
) in _GL_TYPES_64
.iteritems():
10495 file.Write("typedef %s %s;\n" % (v
, k
))
10496 file.Write("#else\n")
10497 for (k
, v
) in _GL_TYPES_32
.iteritems():
10498 file.Write("typedef %s %s;\n" % (v
, k
))
10499 file.Write("#endif // _WIN64\n")
10500 file.Write("#endif // __gl2_h_\n\n")
10501 file.Write("#endinl\n")
10503 for interface
in self
.pepper_interfaces
:
10504 if interface
.dev
!= dev
:
10506 # Historically, we provide OpenGLES2 interfaces with struct
10507 # namespace. Not to break code which uses the interface as
10508 # "struct OpenGLES2", we put it in struct namespace.
10509 file.Write('\n[macro="%s", force_struct_namespace]\n' %
10510 interface
.GetInterfaceName())
10511 file.Write("interface %s {\n" % interface
.GetStructName())
10512 for func
in self
.original_functions
:
10513 if not func
.InPepperInterface(interface
):
10516 ret_type
= func
.MapCTypeToPepperIdlType(func
.return_type
,
10517 is_for_return_type
=True)
10518 func_prefix
= " %s %s(" % (ret_type
, func
.GetPepperName())
10519 file.Write(func_prefix
)
10520 file.Write("[in] PP_Resource context")
10521 for arg
in func
.MakeTypedPepperIdlArgStrings():
10522 file.Write(",\n" + " " * len(func_prefix
) + arg
)
10524 file.Write("};\n\n")
10529 def WritePepperGLES2Implementation(self
, filename
):
10530 """Writes the Pepper OpenGLES interface implementation."""
10532 file = CWriter(filename
)
10533 file.Write(_LICENSE
)
10534 file.Write(_DO_NOT_EDIT_WARNING
)
10536 file.Write("#include \"ppapi/shared_impl/ppb_opengles2_shared.h\"\n\n")
10537 file.Write("#include \"base/logging.h\"\n")
10538 file.Write("#include \"gpu/command_buffer/client/gles2_implementation.h\"\n")
10539 file.Write("#include \"ppapi/shared_impl/ppb_graphics_3d_shared.h\"\n")
10540 file.Write("#include \"ppapi/thunk/enter.h\"\n\n")
10542 file.Write("namespace ppapi {\n\n")
10543 file.Write("namespace {\n\n")
10545 file.Write("typedef thunk::EnterResource<thunk::PPB_Graphics3D_API>"
10548 file.Write("gpu::gles2::GLES2Implementation* ToGles2Impl(Enter3D*"
10550 file.Write(" DCHECK(enter);\n")
10551 file.Write(" DCHECK(enter->succeeded());\n")
10552 file.Write(" return static_cast<PPB_Graphics3D_Shared*>(enter->object())->"
10553 "gles2_impl();\n");
10554 file.Write("}\n\n");
10556 for func
in self
.original_functions
:
10557 if not func
.InAnyPepperExtension():
10560 original_arg
= func
.MakeTypedPepperArgString("")
10561 context_arg
= "PP_Resource context_id"
10562 if len(original_arg
):
10563 arg
= context_arg
+ ", " + original_arg
10566 file.Write("%s %s(%s) {\n" %
10567 (func
.return_type
, func
.GetPepperName(), arg
))
10568 file.Write(" Enter3D enter(context_id, true);\n")
10569 file.Write(" if (enter.succeeded()) {\n")
10571 return_str
= "" if func
.return_type
== "void" else "return "
10572 file.Write(" %sToGles2Impl(&enter)->%s(%s);\n" %
10573 (return_str
, func
.original_name
,
10574 func
.MakeOriginalArgString("")))
10576 if func
.return_type
== "void":
10579 file.Write(" else {\n")
10580 file.Write(" return %s;\n" % func
.GetErrorReturnString())
10582 file.Write("}\n\n")
10584 file.Write("} // namespace\n")
10586 for interface
in self
.pepper_interfaces
:
10587 file.Write("const %s* PPB_OpenGLES2_Shared::Get%sInterface() {\n" %
10588 (interface
.GetStructName(), interface
.GetName()))
10589 file.Write(" static const struct %s "
10590 "ppb_opengles2 = {\n" % interface
.GetStructName())
10592 file.Write(",\n &".join(
10593 f
.GetPepperName() for f
in self
.original_functions
10594 if f
.InPepperInterface(interface
)))
10597 file.Write(" };\n")
10598 file.Write(" return &ppb_opengles2;\n")
10601 file.Write("} // namespace ppapi\n")
10603 self
.generated_cpp_filenames
.append(file.filename
)
10605 def WriteGLES2ToPPAPIBridge(self
, filename
):
10606 """Connects GLES2 helper library to PPB_OpenGLES2 interface"""
10608 file = CWriter(filename
)
10609 file.Write(_LICENSE
)
10610 file.Write(_DO_NOT_EDIT_WARNING
)
10612 file.Write("#ifndef GL_GLEXT_PROTOTYPES\n")
10613 file.Write("#define GL_GLEXT_PROTOTYPES\n")
10614 file.Write("#endif\n")
10615 file.Write("#include <GLES2/gl2.h>\n")
10616 file.Write("#include <GLES2/gl2ext.h>\n")
10617 file.Write("#include \"ppapi/lib/gl/gles2/gl2ext_ppapi.h\"\n\n")
10619 for func
in self
.original_functions
:
10620 if not func
.InAnyPepperExtension():
10623 interface
= self
.interface_info
[func
.GetInfo('pepper_interface') or '']
10625 file.Write("%s GL_APIENTRY gl%s(%s) {\n" %
10626 (func
.return_type
, func
.GetPepperName(),
10627 func
.MakeTypedPepperArgString("")))
10628 return_str
= "" if func
.return_type
== "void" else "return "
10629 interface_str
= "glGet%sInterfacePPAPI()" % interface
.GetName()
10630 original_arg
= func
.MakeOriginalArgString("")
10631 context_arg
= "glGetCurrentContextPPAPI()"
10632 if len(original_arg
):
10633 arg
= context_arg
+ ", " + original_arg
10636 if interface
.GetName():
10637 file.Write(" const struct %s* ext = %s;\n" %
10638 (interface
.GetStructName(), interface_str
))
10639 file.Write(" if (ext)\n")
10640 file.Write(" %sext->%s(%s);\n" %
10641 (return_str
, func
.GetPepperName(), arg
))
10643 file.Write(" %s0;\n" % return_str
)
10645 file.Write(" %s%s->%s(%s);\n" %
10646 (return_str
, interface_str
, func
.GetPepperName(), arg
))
10647 file.Write("}\n\n")
10649 self
.generated_cpp_filenames
.append(file.filename
)
10651 def WriteMojoGLCallVisitor(self
, filename
):
10652 """Provides the GL implementation for mojo"""
10653 file = CWriter(filename
)
10654 file.Write(_LICENSE
)
10655 file.Write(_DO_NOT_EDIT_WARNING
)
10657 for func
in self
.original_functions
:
10658 if not func
.IsCoreGLFunction():
10660 file.Write("VISIT_GL_CALL(%s, %s, (%s), (%s))\n" %
10661 (func
.name
, func
.return_type
,
10662 func
.MakeTypedOriginalArgString(""),
10663 func
.MakeOriginalArgString("")))
10666 self
.generated_cpp_filenames
.append(file.filename
)
10668 def WriteMojoGLCallVisitorForExtension(self
, filename
, extension
):
10669 """Provides the GL implementation for mojo for a particular extension"""
10670 file = CWriter(filename
)
10671 file.Write(_LICENSE
)
10672 file.Write(_DO_NOT_EDIT_WARNING
)
10674 for func
in self
.original_functions
:
10675 if func
.GetInfo("extension") != extension
:
10677 file.Write("VISIT_GL_CALL(%s, %s, (%s), (%s))\n" %
10678 (func
.name
, func
.return_type
,
10679 func
.MakeTypedOriginalArgString(""),
10680 func
.MakeOriginalArgString("")))
10683 self
.generated_cpp_filenames
.append(file.filename
)
10685 def Format(generated_files
):
10686 formatter
= "clang-format"
10687 if platform
.system() == "Windows":
10688 formatter
+= ".bat"
10689 for filename
in generated_files
:
10690 call([formatter
, "-i", "-style=chromium", filename
])
10693 """This is the main function."""
10694 parser
= OptionParser()
10697 help="base directory for resulting files, under chrome/src. default is "
10698 "empty. Use this if you want the result stored under gen.")
10700 "-v", "--verbose", action
="store_true",
10701 help="prints more output.")
10703 (options
, args
) = parser
.parse_args(args
=argv
)
10705 # Add in states and capabilites to GLState
10706 gl_state_valid
= _NAMED_TYPE_INFO
['GLState']['valid']
10707 for state_name
in sorted(_STATES
.keys()):
10708 state
= _STATES
[state_name
]
10709 if 'extension_flag' in state
:
10711 if 'enum' in state
:
10712 if not state
['enum'] in gl_state_valid
:
10713 gl_state_valid
.append(state
['enum'])
10715 for item
in state
['states']:
10716 if 'extension_flag' in item
:
10718 if not item
['enum'] in gl_state_valid
:
10719 gl_state_valid
.append(item
['enum'])
10720 for capability
in _CAPABILITY_FLAGS
:
10721 valid_value
= "GL_%s" % capability
['name'].upper()
10722 if not valid_value
in gl_state_valid
:
10723 gl_state_valid
.append(valid_value
)
10725 # This script lives under gpu/command_buffer, cd to base directory.
10726 os
.chdir(os
.path
.dirname(__file__
) + "/../..")
10727 base_dir
= os
.getcwd()
10728 gen
= GLGenerator(options
.verbose
)
10729 gen
.ParseGLH("gpu/command_buffer/cmd_buffer_functions.txt")
10731 # Support generating files under gen/
10732 if options
.output_dir
!= None:
10733 os
.chdir(options
.output_dir
)
10735 gen
.WritePepperGLES2Interface("ppapi/api/ppb_opengles2.idl", False)
10736 gen
.WritePepperGLES2Interface("ppapi/api/dev/ppb_opengles2ext_dev.idl", True)
10737 gen
.WriteGLES2ToPPAPIBridge("ppapi/lib/gl/gles2/gles2.c")
10738 gen
.WritePepperGLES2Implementation(
10739 "ppapi/shared_impl/ppb_opengles2_shared.cc")
10741 gen
.WriteCommandIds("gpu/command_buffer/common/gles2_cmd_ids_autogen.h")
10742 gen
.WriteFormat("gpu/command_buffer/common/gles2_cmd_format_autogen.h")
10743 gen
.WriteFormatTest(
10744 "gpu/command_buffer/common/gles2_cmd_format_test_autogen.h")
10745 gen
.WriteGLES2InterfaceHeader(
10746 "gpu/command_buffer/client/gles2_interface_autogen.h")
10747 gen
.WriteMojoGLES2ImplHeader(
10748 "mojo/gpu/mojo_gles2_impl_autogen.h")
10749 gen
.WriteMojoGLES2Impl(
10750 "mojo/gpu/mojo_gles2_impl_autogen.cc")
10751 gen
.WriteGLES2InterfaceStub(
10752 "gpu/command_buffer/client/gles2_interface_stub_autogen.h")
10753 gen
.WriteGLES2InterfaceStubImpl(
10754 "gpu/command_buffer/client/gles2_interface_stub_impl_autogen.h")
10755 gen
.WriteGLES2ImplementationHeader(
10756 "gpu/command_buffer/client/gles2_implementation_autogen.h")
10757 gen
.WriteGLES2Implementation(
10758 "gpu/command_buffer/client/gles2_implementation_impl_autogen.h")
10759 gen
.WriteGLES2ImplementationUnitTests(
10760 "gpu/command_buffer/client/gles2_implementation_unittest_autogen.h")
10761 gen
.WriteGLES2TraceImplementationHeader(
10762 "gpu/command_buffer/client/gles2_trace_implementation_autogen.h")
10763 gen
.WriteGLES2TraceImplementation(
10764 "gpu/command_buffer/client/gles2_trace_implementation_impl_autogen.h")
10765 gen
.WriteGLES2CLibImplementation(
10766 "gpu/command_buffer/client/gles2_c_lib_autogen.h")
10767 gen
.WriteCmdHelperHeader(
10768 "gpu/command_buffer/client/gles2_cmd_helper_autogen.h")
10769 gen
.WriteServiceImplementation(
10770 "gpu/command_buffer/service/gles2_cmd_decoder_autogen.h")
10771 gen
.WriteServiceContextStateHeader(
10772 "gpu/command_buffer/service/context_state_autogen.h")
10773 gen
.WriteServiceContextStateImpl(
10774 "gpu/command_buffer/service/context_state_impl_autogen.h")
10775 gen
.WriteClientContextStateHeader(
10776 "gpu/command_buffer/client/client_context_state_autogen.h")
10777 gen
.WriteClientContextStateImpl(
10778 "gpu/command_buffer/client/client_context_state_impl_autogen.h")
10779 gen
.WriteServiceUnitTests(
10780 "gpu/command_buffer/service/gles2_cmd_decoder_unittest_%d_autogen.h")
10781 gen
.WriteServiceUnitTestsForExtensions(
10782 "gpu/command_buffer/service/"
10783 "gles2_cmd_decoder_unittest_extensions_autogen.h")
10784 gen
.WriteServiceUtilsHeader(
10785 "gpu/command_buffer/service/gles2_cmd_validation_autogen.h")
10786 gen
.WriteServiceUtilsImplementation(
10787 "gpu/command_buffer/service/"
10788 "gles2_cmd_validation_implementation_autogen.h")
10789 gen
.WriteCommonUtilsHeader(
10790 "gpu/command_buffer/common/gles2_cmd_utils_autogen.h")
10791 gen
.WriteCommonUtilsImpl(
10792 "gpu/command_buffer/common/gles2_cmd_utils_implementation_autogen.h")
10793 gen
.WriteGLES2Header("gpu/GLES2/gl2chromium_autogen.h")
10794 mojo_gles2_prefix
= ("third_party/mojo/src/mojo/public/c/gles2/"
10795 "gles2_call_visitor")
10796 gen
.WriteMojoGLCallVisitor(mojo_gles2_prefix
+ "_autogen.h")
10797 gen
.WriteMojoGLCallVisitorForExtension(
10798 mojo_gles2_prefix
+ "_chromium_texture_mailbox_autogen.h",
10799 "CHROMIUM_texture_mailbox")
10800 gen
.WriteMojoGLCallVisitorForExtension(
10801 mojo_gles2_prefix
+ "_chromium_sync_point_autogen.h",
10802 "CHROMIUM_sync_point")
10803 gen
.WriteMojoGLCallVisitorForExtension(
10804 mojo_gles2_prefix
+ "_chromium_sub_image_autogen.h",
10805 "CHROMIUM_sub_image")
10806 gen
.WriteMojoGLCallVisitorForExtension(
10807 mojo_gles2_prefix
+ "_chromium_miscellaneous_autogen.h",
10808 "CHROMIUM_miscellaneous")
10809 gen
.WriteMojoGLCallVisitorForExtension(
10810 mojo_gles2_prefix
+ "_occlusion_query_ext_autogen.h",
10811 "occlusion_query_EXT")
10813 Format(gen
.generated_cpp_filenames
)
10816 print "%d errors" % gen
.errors
10821 if __name__
== '__main__':
10822 sys
.exit(main(sys
.argv
[1:]))