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',
543 'PathStencilFuncCHROMIUM': {
545 'func': 'PathStencilFuncNV',
546 'extension_flag': 'chromium_path_rendering',
549 'name': 'stencil_path_func',
551 'enum': 'GL_PATH_STENCIL_FUNC_CHROMIUM',
552 'default': 'GL_ALWAYS',
555 'name': 'stencil_path_ref',
557 'enum': 'GL_PATH_STENCIL_REF_CHROMIUM',
561 'name': 'stencil_path_mask',
563 'enum': 'GL_PATH_STENCIL_VALUE_MASK_CHROMIUM',
564 'default': '0xFFFFFFFFU',
570 # Named type info object represents a named type that is used in OpenGL call
571 # arguments. Each named type defines a set of valid OpenGL call arguments. The
572 # named types are used in 'cmd_buffer_functions.txt'.
573 # type: The actual GL type of the named type.
574 # valid: The list of values that are valid for both the client and the service.
575 # valid_es3: The list of values that are valid in OpenGL ES 3, but not ES 2.
576 # invalid: Examples of invalid values for the type. At least these values
577 # should be tested to be invalid.
578 # deprecated_es3: The list of values that are valid in OpenGL ES 2, but
579 # deprecated in ES 3.
580 # is_complete: The list of valid values of type are final and will not be
581 # modified during runtime.
590 'GL_LINEAR_MIPMAP_LINEAR',
593 'FrameBufferTarget': {
599 'GL_DRAW_FRAMEBUFFER' ,
600 'GL_READ_FRAMEBUFFER' ,
606 'InvalidateFrameBufferTarget': {
612 'GL_DRAW_FRAMEBUFFER' ,
613 'GL_READ_FRAMEBUFFER' ,
616 'RenderBufferTarget': {
629 'GL_ELEMENT_ARRAY_BUFFER',
632 'GL_COPY_READ_BUFFER',
633 'GL_COPY_WRITE_BUFFER',
634 'GL_PIXEL_PACK_BUFFER',
635 'GL_PIXEL_UNPACK_BUFFER',
636 'GL_TRANSFORM_FEEDBACK_BUFFER',
643 'IndexedBufferTarget': {
646 'GL_TRANSFORM_FEEDBACK_BUFFER',
658 'GL_MAP_INVALIDATE_RANGE_BIT',
659 'GL_MAP_INVALIDATE_BUFFER_BIT',
660 'GL_MAP_FLUSH_EXPLICIT_BIT',
661 'GL_MAP_UNSYNCHRONIZED_BIT',
664 'GL_SYNC_FLUSH_COMMANDS_BIT',
724 'CompressedTextureFormat': {
729 'GL_COMPRESSED_R11_EAC',
730 'GL_COMPRESSED_SIGNED_R11_EAC',
731 'GL_COMPRESSED_RG11_EAC',
732 'GL_COMPRESSED_SIGNED_RG11_EAC',
733 'GL_COMPRESSED_RGB8_ETC2',
734 'GL_COMPRESSED_SRGB8_ETC2',
735 'GL_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2',
736 'GL_COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2',
737 'GL_COMPRESSED_RGBA8_ETC2_EAC',
738 'GL_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC',
744 # NOTE: State an Capability entries added later.
746 'GL_ALIASED_LINE_WIDTH_RANGE',
747 'GL_ALIASED_POINT_SIZE_RANGE',
749 'GL_ARRAY_BUFFER_BINDING',
751 'GL_COMPRESSED_TEXTURE_FORMATS',
752 'GL_CURRENT_PROGRAM',
755 'GL_ELEMENT_ARRAY_BUFFER_BINDING',
756 'GL_FRAMEBUFFER_BINDING',
757 'GL_GENERATE_MIPMAP_HINT',
759 'GL_IMPLEMENTATION_COLOR_READ_FORMAT',
760 'GL_IMPLEMENTATION_COLOR_READ_TYPE',
761 'GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS',
762 'GL_MAX_CUBE_MAP_TEXTURE_SIZE',
763 'GL_MAX_FRAGMENT_UNIFORM_VECTORS',
764 'GL_MAX_RENDERBUFFER_SIZE',
765 'GL_MAX_TEXTURE_IMAGE_UNITS',
766 'GL_MAX_TEXTURE_SIZE',
767 'GL_MAX_VARYING_VECTORS',
768 'GL_MAX_VERTEX_ATTRIBS',
769 'GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS',
770 'GL_MAX_VERTEX_UNIFORM_VECTORS',
771 'GL_MAX_VIEWPORT_DIMS',
772 'GL_NUM_COMPRESSED_TEXTURE_FORMATS',
773 'GL_NUM_SHADER_BINARY_FORMATS',
776 'GL_RENDERBUFFER_BINDING',
778 'GL_SAMPLE_COVERAGE_INVERT',
779 'GL_SAMPLE_COVERAGE_VALUE',
782 'GL_SHADER_BINARY_FORMATS',
783 'GL_SHADER_COMPILER',
786 'GL_TEXTURE_BINDING_2D',
787 'GL_TEXTURE_BINDING_CUBE_MAP',
788 'GL_UNPACK_ALIGNMENT',
789 'GL_BIND_GENERATES_RESOURCE_CHROMIUM',
790 # we can add this because we emulate it if the driver does not support it.
791 'GL_VERTEX_ARRAY_BINDING_OES',
795 'GL_COPY_READ_BUFFER_BINDING',
796 'GL_COPY_WRITE_BUFFER_BINDING',
813 'GL_DRAW_FRAMEBUFFER_BINDING',
814 'GL_FRAGMENT_SHADER_DERIVATIVE_HINT',
816 'GL_MAX_3D_TEXTURE_SIZE',
817 'GL_MAX_ARRAY_TEXTURE_LAYERS',
818 'GL_MAX_COLOR_ATTACHMENTS',
819 'GL_MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS',
820 'GL_MAX_COMBINED_UNIFORM_BLOCKS',
821 'GL_MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS',
822 'GL_MAX_DRAW_BUFFERS',
823 'GL_MAX_ELEMENT_INDEX',
824 'GL_MAX_ELEMENTS_INDICES',
825 'GL_MAX_ELEMENTS_VERTICES',
826 'GL_MAX_FRAGMENT_INPUT_COMPONENTS',
827 'GL_MAX_FRAGMENT_UNIFORM_BLOCKS',
828 'GL_MAX_FRAGMENT_UNIFORM_COMPONENTS',
829 'GL_MAX_PROGRAM_TEXEL_OFFSET',
831 'GL_MAX_SERVER_WAIT_TIMEOUT',
832 'GL_MAX_TEXTURE_LOD_BIAS',
833 'GL_MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS',
834 'GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS',
835 'GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS',
836 'GL_MAX_UNIFORM_BLOCK_SIZE',
837 'GL_MAX_UNIFORM_BUFFER_BINDINGS',
838 'GL_MAX_VARYING_COMPONENTS',
839 'GL_MAX_VERTEX_OUTPUT_COMPONENTS',
840 'GL_MAX_VERTEX_UNIFORM_BLOCKS',
841 'GL_MAX_VERTEX_UNIFORM_COMPONENTS',
842 'GL_MIN_PROGRAM_TEXEL_OFFSET',
845 'GL_NUM_PROGRAM_BINARY_FORMATS',
846 'GL_PACK_ROW_LENGTH',
847 'GL_PACK_SKIP_PIXELS',
849 'GL_PIXEL_PACK_BUFFER_BINDING',
850 'GL_PIXEL_UNPACK_BUFFER_BINDING',
851 'GL_PROGRAM_BINARY_FORMATS',
853 'GL_READ_FRAMEBUFFER_BINDING',
854 'GL_SAMPLER_BINDING',
855 'GL_TEXTURE_BINDING_2D_ARRAY',
856 'GL_TEXTURE_BINDING_3D',
857 'GL_TRANSFORM_FEEDBACK_BINDING',
858 'GL_TRANSFORM_FEEDBACK_ACTIVE',
859 'GL_TRANSFORM_FEEDBACK_BUFFER_BINDING',
860 'GL_TRANSFORM_FEEDBACK_PAUSED',
861 'GL_TRANSFORM_FEEDBACK_BUFFER_SIZE',
862 'GL_TRANSFORM_FEEDBACK_BUFFER_START',
863 'GL_UNIFORM_BUFFER_BINDING',
864 'GL_UNIFORM_BUFFER_OFFSET_ALIGNMENT',
865 'GL_UNIFORM_BUFFER_SIZE',
866 'GL_UNIFORM_BUFFER_START',
867 'GL_UNPACK_IMAGE_HEIGHT',
868 'GL_UNPACK_ROW_LENGTH',
869 'GL_UNPACK_SKIP_IMAGES',
870 'GL_UNPACK_SKIP_PIXELS',
871 'GL_UNPACK_SKIP_ROWS',
872 # GL_VERTEX_ARRAY_BINDING is the same as GL_VERTEX_ARRAY_BINDING_OES
873 # 'GL_VERTEX_ARRAY_BINDING',
882 'GL_TRANSFORM_FEEDBACK_BUFFER_BINDING',
883 'GL_TRANSFORM_FEEDBACK_BUFFER_SIZE',
884 'GL_TRANSFORM_FEEDBACK_BUFFER_START',
885 'GL_UNIFORM_BUFFER_BINDING',
886 'GL_UNIFORM_BUFFER_SIZE',
887 'GL_UNIFORM_BUFFER_START',
893 'GetTexParamTarget': {
897 'GL_TEXTURE_CUBE_MAP',
900 'GL_TEXTURE_2D_ARRAY',
904 'GL_PROXY_TEXTURE_CUBE_MAP',
911 'GL_TEXTURE_CUBE_MAP_POSITIVE_X',
912 'GL_TEXTURE_CUBE_MAP_NEGATIVE_X',
913 'GL_TEXTURE_CUBE_MAP_POSITIVE_Y',
914 'GL_TEXTURE_CUBE_MAP_NEGATIVE_Y',
915 'GL_TEXTURE_CUBE_MAP_POSITIVE_Z',
916 'GL_TEXTURE_CUBE_MAP_NEGATIVE_Z',
919 'GL_PROXY_TEXTURE_CUBE_MAP',
926 'GL_TEXTURE_2D_ARRAY',
932 'TextureBindTarget': {
936 'GL_TEXTURE_CUBE_MAP',
940 'GL_TEXTURE_2D_ARRAY',
947 'TransformFeedbackBindTarget': {
950 'GL_TRANSFORM_FEEDBACK',
956 'TransformFeedbackPrimitiveMode': {
971 'GL_FRAGMENT_SHADER',
974 'GL_GEOMETRY_SHADER',
1010 'GL_FUNC_REVERSE_SUBTRACT',
1026 'GL_ONE_MINUS_SRC_COLOR',
1028 'GL_ONE_MINUS_DST_COLOR',
1030 'GL_ONE_MINUS_SRC_ALPHA',
1032 'GL_ONE_MINUS_DST_ALPHA',
1033 'GL_CONSTANT_COLOR',
1034 'GL_ONE_MINUS_CONSTANT_COLOR',
1035 'GL_CONSTANT_ALPHA',
1036 'GL_ONE_MINUS_CONSTANT_ALPHA',
1037 'GL_SRC_ALPHA_SATURATE',
1046 'GL_ONE_MINUS_SRC_COLOR',
1048 'GL_ONE_MINUS_DST_COLOR',
1050 'GL_ONE_MINUS_SRC_ALPHA',
1052 'GL_ONE_MINUS_DST_ALPHA',
1053 'GL_CONSTANT_COLOR',
1054 'GL_ONE_MINUS_CONSTANT_COLOR',
1055 'GL_CONSTANT_ALPHA',
1056 'GL_ONE_MINUS_CONSTANT_ALPHA',
1061 'valid': ["GL_%s" % cap
['name'].upper() for cap
in _CAPABILITY_FLAGS
1062 if 'es3' not in cap
or cap
['es3'] != True],
1063 'valid_es3': ["GL_%s" % cap
['name'].upper() for cap
in _CAPABILITY_FLAGS
1064 if 'es3' in cap
and cap
['es3'] == True],
1077 'GL_TRIANGLE_STRIP',
1090 'GL_UNSIGNED_SHORT',
1099 'GetMaxIndexType': {
1103 'GL_UNSIGNED_SHORT',
1113 'GL_COLOR_ATTACHMENT0',
1114 'GL_DEPTH_ATTACHMENT',
1115 'GL_STENCIL_ATTACHMENT',
1118 'GL_DEPTH_STENCIL_ATTACHMENT',
1121 'BackbufferAttachment': {
1129 'BufferParameter': {
1136 'GL_BUFFER_ACCESS_FLAGS',
1138 'GL_BUFFER_MAP_LENGTH',
1139 'GL_BUFFER_MAP_OFFSET',
1142 'GL_PIXEL_PACK_BUFFER',
1148 'GL_INTERLEAVED_ATTRIBS',
1149 'GL_SEPARATE_ATTRIBS',
1152 'GL_PIXEL_PACK_BUFFER',
1155 'FrameBufferParameter': {
1158 'GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE',
1159 'GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME',
1160 'GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL',
1161 'GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE',
1164 'GL_FRAMEBUFFER_ATTACHMENT_RED_SIZE',
1165 'GL_FRAMEBUFFER_ATTACHMENT_GREEN_SIZE',
1166 'GL_FRAMEBUFFER_ATTACHMENT_BLUE_SIZE',
1167 'GL_FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE',
1168 'GL_FRAMEBUFFER_ATTACHMENT_DEPTH_SIZE',
1169 'GL_FRAMEBUFFER_ATTACHMENT_STENCIL_SIZE',
1170 'GL_FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE',
1171 'GL_FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING',
1172 'GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER',
1178 'GL_PATH_PROJECTION_CHROMIUM',
1179 'GL_PATH_MODELVIEW_CHROMIUM',
1182 'ProgramParameter': {
1187 'GL_VALIDATE_STATUS',
1188 'GL_INFO_LOG_LENGTH',
1189 'GL_ATTACHED_SHADERS',
1190 'GL_ACTIVE_ATTRIBUTES',
1191 'GL_ACTIVE_ATTRIBUTE_MAX_LENGTH',
1192 'GL_ACTIVE_UNIFORMS',
1193 'GL_ACTIVE_UNIFORM_MAX_LENGTH',
1196 'GL_ACTIVE_UNIFORM_BLOCKS',
1197 'GL_ACTIVE_UNIFORM_BLOCK_MAX_NAME_LENGTH',
1198 'GL_TRANSFORM_FEEDBACK_BUFFER_MODE',
1199 'GL_TRANSFORM_FEEDBACK_VARYINGS',
1200 'GL_TRANSFORM_FEEDBACK_VARYING_MAX_LENGTH',
1203 'GL_PROGRAM_BINARY_RETRIEVABLE_HINT', # not supported in Chromium.
1206 'QueryObjectParameter': {
1209 'GL_QUERY_RESULT_EXT',
1210 'GL_QUERY_RESULT_AVAILABLE_EXT',
1216 'GL_CURRENT_QUERY_EXT',
1222 'GL_ANY_SAMPLES_PASSED_EXT',
1223 'GL_ANY_SAMPLES_PASSED_CONSERVATIVE_EXT',
1224 'GL_COMMANDS_ISSUED_CHROMIUM',
1225 'GL_LATENCY_QUERY_CHROMIUM',
1226 'GL_ASYNC_PIXEL_UNPACK_COMPLETED_CHROMIUM',
1227 'GL_ASYNC_PIXEL_PACK_COMPLETED_CHROMIUM',
1228 'GL_COMMANDS_COMPLETED_CHROMIUM',
1231 'RenderBufferParameter': {
1234 'GL_RENDERBUFFER_RED_SIZE',
1235 'GL_RENDERBUFFER_GREEN_SIZE',
1236 'GL_RENDERBUFFER_BLUE_SIZE',
1237 'GL_RENDERBUFFER_ALPHA_SIZE',
1238 'GL_RENDERBUFFER_DEPTH_SIZE',
1239 'GL_RENDERBUFFER_STENCIL_SIZE',
1240 'GL_RENDERBUFFER_WIDTH',
1241 'GL_RENDERBUFFER_HEIGHT',
1242 'GL_RENDERBUFFER_INTERNAL_FORMAT',
1245 'GL_RENDERBUFFER_SAMPLES',
1248 'InternalFormatParameter': {
1251 'GL_NUM_SAMPLE_COUNTS',
1255 'SamplerParameter': {
1258 'GL_TEXTURE_MAG_FILTER',
1259 'GL_TEXTURE_MIN_FILTER',
1260 'GL_TEXTURE_MIN_LOD',
1261 'GL_TEXTURE_MAX_LOD',
1262 'GL_TEXTURE_WRAP_S',
1263 'GL_TEXTURE_WRAP_T',
1264 'GL_TEXTURE_WRAP_R',
1265 'GL_TEXTURE_COMPARE_MODE',
1266 'GL_TEXTURE_COMPARE_FUNC',
1269 'GL_GENERATE_MIPMAP',
1272 'ShaderParameter': {
1277 'GL_COMPILE_STATUS',
1278 'GL_INFO_LOG_LENGTH',
1279 'GL_SHADER_SOURCE_LENGTH',
1280 'GL_TRANSLATED_SHADER_SOURCE_LENGTH_ANGLE',
1283 'ShaderPrecision': {
1300 'GL_SHADING_LANGUAGE_VERSION',
1304 'TextureParameter': {
1307 'GL_TEXTURE_MAG_FILTER',
1308 'GL_TEXTURE_MIN_FILTER',
1309 'GL_TEXTURE_POOL_CHROMIUM',
1310 'GL_TEXTURE_WRAP_S',
1311 'GL_TEXTURE_WRAP_T',
1314 'GL_TEXTURE_BASE_LEVEL',
1315 'GL_TEXTURE_COMPARE_FUNC',
1316 'GL_TEXTURE_COMPARE_MODE',
1317 'GL_TEXTURE_IMMUTABLE_FORMAT',
1318 'GL_TEXTURE_IMMUTABLE_LEVELS',
1319 'GL_TEXTURE_MAX_LEVEL',
1320 'GL_TEXTURE_MAX_LOD',
1321 'GL_TEXTURE_MIN_LOD',
1322 'GL_TEXTURE_WRAP_R',
1325 'GL_GENERATE_MIPMAP',
1331 'GL_TEXTURE_POOL_MANAGED_CHROMIUM',
1332 'GL_TEXTURE_POOL_UNMANAGED_CHROMIUM',
1335 'TextureWrapMode': {
1339 'GL_MIRRORED_REPEAT',
1343 'TextureMinFilterMode': {
1348 'GL_NEAREST_MIPMAP_NEAREST',
1349 'GL_LINEAR_MIPMAP_NEAREST',
1350 'GL_NEAREST_MIPMAP_LINEAR',
1351 'GL_LINEAR_MIPMAP_LINEAR',
1354 'TextureMagFilterMode': {
1361 'TextureCompareFunc': {
1374 'TextureCompareMode': {
1378 'GL_COMPARE_REF_TO_TEXTURE',
1385 'GL_FRAMEBUFFER_ATTACHMENT_ANGLE',
1388 'VertexAttribute': {
1391 # some enum that the decoder actually passes through to GL needs
1392 # to be the first listed here since it's used in unit tests.
1393 'GL_VERTEX_ATTRIB_ARRAY_NORMALIZED',
1394 'GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING',
1395 'GL_VERTEX_ATTRIB_ARRAY_ENABLED',
1396 'GL_VERTEX_ATTRIB_ARRAY_SIZE',
1397 'GL_VERTEX_ATTRIB_ARRAY_STRIDE',
1398 'GL_VERTEX_ATTRIB_ARRAY_TYPE',
1399 'GL_CURRENT_VERTEX_ATTRIB',
1402 'GL_VERTEX_ATTRIB_ARRAY_INTEGER',
1403 'GL_VERTEX_ATTRIB_ARRAY_DIVISOR',
1409 'GL_VERTEX_ATTRIB_ARRAY_POINTER',
1415 'GL_GENERATE_MIPMAP_HINT',
1418 'GL_FRAGMENT_SHADER_DERIVATIVE_HINT',
1421 'GL_PERSPECTIVE_CORRECTION_HINT',
1435 'GL_PACK_ALIGNMENT',
1436 'GL_UNPACK_ALIGNMENT',
1439 'GL_PACK_ROW_LENGTH',
1440 'GL_PACK_SKIP_PIXELS',
1441 'GL_PACK_SKIP_ROWS',
1442 'GL_UNPACK_ROW_LENGTH',
1443 'GL_UNPACK_IMAGE_HEIGHT',
1444 'GL_UNPACK_SKIP_PIXELS',
1445 'GL_UNPACK_SKIP_ROWS',
1446 'GL_UNPACK_SKIP_IMAGES',
1449 'GL_PACK_SWAP_BYTES',
1450 'GL_UNPACK_SWAP_BYTES',
1453 'PixelStoreAlignment': {
1466 'ReadPixelFormat': {
1485 'GL_UNSIGNED_SHORT_5_6_5',
1486 'GL_UNSIGNED_SHORT_4_4_4_4',
1487 'GL_UNSIGNED_SHORT_5_5_5_1',
1491 'GL_UNSIGNED_SHORT',
1497 'GL_UNSIGNED_INT_2_10_10_10_REV',
1498 'GL_UNSIGNED_INT_10F_11F_11F_REV',
1499 'GL_UNSIGNED_INT_5_9_9_9_REV',
1500 'GL_UNSIGNED_INT_24_8',
1501 'GL_FLOAT_32_UNSIGNED_INT_24_8_REV',
1504 'GL_UNSIGNED_BYTE_3_3_2',
1513 'GL_UNSIGNED_SHORT',
1520 'GL_CONVEX_HULL_CHROMIUM',
1521 'GL_BOUNDING_BOX_CHROMIUM',
1528 'GL_COUNT_UP_CHROMIUM',
1529 'GL_COUNT_DOWN_CHROMIUM',
1535 'GL_PATH_STROKE_WIDTH_CHROMIUM',
1536 'GL_PATH_END_CAPS_CHROMIUM',
1537 'GL_PATH_JOIN_STYLE_CHROMIUM',
1538 'GL_PATH_MITER_LIMIT_CHROMIUM',
1539 'GL_PATH_STROKE_BOUND_CHROMIUM',
1542 'PathParameterCapValues': {
1546 'GL_SQUARE_CHROMIUM',
1547 'GL_ROUND_CHROMIUM',
1550 'PathParameterJoinValues': {
1553 'GL_MITER_REVERT_CHROMIUM',
1554 'GL_BEVEL_CHROMIUM',
1555 'GL_ROUND_CHROMIUM',
1562 'GL_UNSIGNED_SHORT_5_6_5',
1563 'GL_UNSIGNED_SHORT_4_4_4_4',
1564 'GL_UNSIGNED_SHORT_5_5_5_1',
1575 'GL_UNSIGNED_SHORT_5_6_5',
1576 'GL_UNSIGNED_SHORT_4_4_4_4',
1577 'GL_UNSIGNED_SHORT_5_5_5_1',
1580 'RenderBufferFormat': {
1586 'GL_DEPTH_COMPONENT16',
1587 'GL_STENCIL_INDEX8',
1615 'GL_DEPTH_COMPONENT24',
1616 'GL_DEPTH_COMPONENT32F',
1617 'GL_DEPTH24_STENCIL8',
1618 'GL_DEPTH32F_STENCIL8',
1621 'ShaderBinaryFormat': {
1644 'GL_LUMINANCE_ALPHA',
1655 'GL_DEPTH_COMPONENT',
1663 'TextureInternalFormat': {
1668 'GL_LUMINANCE_ALPHA',
1697 'GL_R11F_G11F_B10F',
1722 # The DEPTH/STENCIL formats are not supported in CopyTexImage2D.
1723 # We will reject them dynamically in GPU command buffer.
1724 'GL_DEPTH_COMPONENT16',
1725 'GL_DEPTH_COMPONENT24',
1726 'GL_DEPTH_COMPONENT32F',
1727 'GL_DEPTH24_STENCIL8',
1728 'GL_DEPTH32F_STENCIL8',
1735 'TextureInternalFormatStorage': {
1742 'GL_LUMINANCE8_EXT',
1743 'GL_LUMINANCE8_ALPHA8_EXT',
1771 'GL_R11F_G11F_B10F',
1794 'GL_DEPTH_COMPONENT16',
1795 'GL_DEPTH_COMPONENT24',
1796 'GL_DEPTH_COMPONENT32F',
1797 'GL_DEPTH24_STENCIL8',
1798 'GL_DEPTH32F_STENCIL8',
1799 'GL_COMPRESSED_R11_EAC',
1800 'GL_COMPRESSED_SIGNED_R11_EAC',
1801 'GL_COMPRESSED_RG11_EAC',
1802 'GL_COMPRESSED_SIGNED_RG11_EAC',
1803 'GL_COMPRESSED_RGB8_ETC2',
1804 'GL_COMPRESSED_SRGB8_ETC2',
1805 'GL_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2',
1806 'GL_COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2',
1807 'GL_COMPRESSED_RGBA8_ETC2_EAC',
1808 'GL_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC',
1812 'GL_LUMINANCE8_EXT',
1813 'GL_LUMINANCE8_ALPHA8_EXT',
1815 'GL_LUMINANCE16F_EXT',
1816 'GL_LUMINANCE_ALPHA16F_EXT',
1818 'GL_LUMINANCE32F_EXT',
1819 'GL_LUMINANCE_ALPHA32F_EXT',
1822 'ImageInternalFormat': {
1826 'GL_RGB_YUV_420_CHROMIUM',
1834 'GL_SCANOUT_CHROMIUM'
1837 'ValueBufferTarget': {
1840 'GL_SUBSCRIBED_VALUES_BUFFER_CHROMIUM',
1843 'SubscriptionTarget': {
1846 'GL_MOUSE_POSITION_CHROMIUM',
1849 'UniformParameter': {
1854 'GL_UNIFORM_NAME_LENGTH',
1855 'GL_UNIFORM_BLOCK_INDEX',
1856 'GL_UNIFORM_OFFSET',
1857 'GL_UNIFORM_ARRAY_STRIDE',
1858 'GL_UNIFORM_MATRIX_STRIDE',
1859 'GL_UNIFORM_IS_ROW_MAJOR',
1862 'GL_UNIFORM_BLOCK_NAME_LENGTH',
1865 'UniformBlockParameter': {
1868 'GL_UNIFORM_BLOCK_BINDING',
1869 'GL_UNIFORM_BLOCK_DATA_SIZE',
1870 'GL_UNIFORM_BLOCK_NAME_LENGTH',
1871 'GL_UNIFORM_BLOCK_ACTIVE_UNIFORMS',
1872 'GL_UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES',
1873 'GL_UNIFORM_BLOCK_REFERENCED_BY_VERTEX_SHADER',
1874 'GL_UNIFORM_BLOCK_REFERENCED_BY_FRAGMENT_SHADER',
1880 'VertexAttribType': {
1886 'GL_UNSIGNED_SHORT',
1887 # 'GL_FIXED', // This is not available on Desktop GL.
1894 'GL_INT_2_10_10_10_REV',
1895 'GL_UNSIGNED_INT_2_10_10_10_REV',
1901 'VertexAttribIType': {
1907 'GL_UNSIGNED_SHORT',
1918 'is_complete': True,
1926 'VertexAttribSize': {
1941 'is_complete': True,
1950 'type': 'GLboolean',
1951 'is_complete': True,
1962 'GL_GUILTY_CONTEXT_RESET_ARB',
1963 'GL_INNOCENT_CONTEXT_RESET_ARB',
1964 'GL_UNKNOWN_CONTEXT_RESET_ARB',
1969 'is_complete': True,
1971 'GL_SYNC_GPU_COMMANDS_COMPLETE',
1978 'type': 'GLbitfield',
1979 'is_complete': True,
1988 'type': 'GLbitfield',
1990 'GL_SYNC_FLUSH_COMMANDS_BIT',
2000 'GL_SYNC_STATUS', # This needs to be the 1st; all others are cached.
2002 'GL_SYNC_CONDITION',
2011 # This table specifies the different pepper interfaces that are supported for
2012 # GL commands. 'dev' is true if it's a dev interface.
2013 _PEPPER_INTERFACES
= [
2014 {'name': '', 'dev': False},
2015 {'name': 'InstancedArrays', 'dev': False},
2016 {'name': 'FramebufferBlit', 'dev': False},
2017 {'name': 'FramebufferMultisample', 'dev': False},
2018 {'name': 'ChromiumEnableFeature', 'dev': False},
2019 {'name': 'ChromiumMapSub', 'dev': False},
2020 {'name': 'Query', 'dev': False},
2021 {'name': 'VertexArrayObject', 'dev': False},
2022 {'name': 'DrawBuffers', 'dev': True},
2025 # A function info object specifies the type and other special data for the
2026 # command that will be generated. A base function info object is generated by
2027 # parsing the "cmd_buffer_functions.txt", one for each function in the
2028 # file. These function info objects can be augmented and their values can be
2029 # overridden by adding an object to the table below.
2031 # Must match function names specified in "cmd_buffer_functions.txt".
2033 # cmd_comment: A comment added to the cmd format.
2034 # type: defines which handler will be used to generate code.
2035 # decoder_func: defines which function to call in the decoder to execute the
2036 # corresponding GL command. If not specified the GL command will
2037 # be called directly.
2038 # gl_test_func: GL function that is expected to be called when testing.
2039 # cmd_args: The arguments to use for the command. This overrides generating
2040 # them based on the GL function arguments.
2041 # gen_cmd: Whether or not this function geneates a command. Default = True.
2042 # data_transfer_methods: Array of methods that are used for transfering the
2043 # pointer data. Possible values: 'immediate', 'shm', 'bucket'.
2044 # The default is 'immediate' if the command has one pointer
2045 # argument, otherwise 'shm'. One command is generated for each
2046 # transfer method. Affects only commands which are not of type
2047 # 'HandWritten', 'GETn' or 'GLcharN'.
2048 # Note: the command arguments that affect this are the final args,
2049 # taking cmd_args override into consideration.
2050 # impl_func: Whether or not to generate the GLES2Implementation part of this
2052 # impl_decl: Whether or not to generate the GLES2Implementation declaration
2054 # needs_size: If True a data_size field is added to the command.
2055 # count: The number of units per element. For PUTn or PUT types.
2056 # use_count_func: If True the actual data count needs to be computed; the count
2057 # argument specifies the maximum count.
2058 # unit_test: If False no service side unit test will be generated.
2059 # client_test: If False no client side unit test will be generated.
2060 # expectation: If False the unit test will have no expected calls.
2061 # gen_func: Name of function that generates GL resource for corresponding
2063 # states: array of states that get set by this function corresponding to
2064 # the given arguments
2065 # state_flag: name of flag that is set to true when function is called.
2066 # no_gl: no GL function is called.
2067 # valid_args: A dictionary of argument indices to args to use in unit tests
2068 # when they can not be automatically determined.
2069 # pepper_interface: The pepper interface that is used for this extension
2070 # pepper_name: The name of the function as exposed to pepper.
2071 # pepper_args: A string representing the argument list (what would appear in
2072 # C/C++ between the parentheses for the function declaration)
2073 # that the Pepper API expects for this function. Use this only if
2074 # the stable Pepper API differs from the GLES2 argument list.
2075 # invalid_test: False if no invalid test needed.
2076 # shadowed: True = the value is shadowed so no glGetXXX call will be made.
2077 # first_element_only: For PUT types, True if only the first element of an
2078 # array is used and we end up calling the single value
2079 # corresponding function. eg. TexParameteriv -> TexParameteri
2080 # extension: Function is an extension to GL and should not be exposed to
2081 # pepper unless pepper_interface is defined.
2082 # extension_flag: Function is an extension and should be enabled only when
2083 # the corresponding feature info flag is enabled. Implies
2084 # 'extension': True.
2085 # not_shared: For GENn types, True if objects can't be shared between contexts
2086 # unsafe: True = no validation is implemented on the service side and the
2087 # command is only available with --enable-unsafe-es3-apis.
2088 # id_mapping: A list of resource type names whose client side IDs need to be
2089 # mapped to service side IDs. This is only used for unsafe APIs.
2093 'decoder_func': 'DoActiveTexture',
2096 'client_test': False,
2098 'AttachShader': {'decoder_func': 'DoAttachShader'},
2099 'BindAttribLocation': {
2101 'data_transfer_methods': ['bucket'],
2106 'decoder_func': 'DoBindBuffer',
2107 'gen_func': 'GenBuffersARB',
2111 'id_mapping': [ 'Buffer' ],
2112 'gen_func': 'GenBuffersARB',
2115 'BindBufferRange': {
2117 'id_mapping': [ 'Buffer' ],
2118 'gen_func': 'GenBuffersARB',
2125 'BindFramebuffer': {
2127 'decoder_func': 'DoBindFramebuffer',
2128 'gl_test_func': 'glBindFramebufferEXT',
2129 'gen_func': 'GenFramebuffersEXT',
2132 'BindRenderbuffer': {
2134 'decoder_func': 'DoBindRenderbuffer',
2135 'gl_test_func': 'glBindRenderbufferEXT',
2136 'gen_func': 'GenRenderbuffersEXT',
2140 'id_mapping': [ 'Sampler' ],
2145 'decoder_func': 'DoBindTexture',
2146 'gen_func': 'GenTextures',
2147 # TODO(gman): remove this once client side caching works.
2148 'client_test': False,
2151 'BindTransformFeedback': {
2153 'id_mapping': [ 'TransformFeedback' ],
2156 'BlitFramebufferCHROMIUM': {
2157 'decoder_func': 'DoBlitFramebufferCHROMIUM',
2159 'extension_flag': 'chromium_framebuffer_multisample',
2160 'pepper_interface': 'FramebufferBlit',
2161 'pepper_name': 'BlitFramebufferEXT',
2162 'defer_reads': True,
2163 'defer_draws': True,
2168 'data_transfer_methods': ['shm'],
2169 'client_test': False,
2174 'client_test': False,
2175 'decoder_func': 'DoBufferSubData',
2176 'data_transfer_methods': ['shm'],
2179 'CheckFramebufferStatus': {
2181 'decoder_func': 'DoCheckFramebufferStatus',
2182 'gl_test_func': 'glCheckFramebufferStatusEXT',
2183 'error_value': 'GL_FRAMEBUFFER_UNSUPPORTED',
2184 'result': ['GLenum'],
2187 'decoder_func': 'DoClear',
2188 'defer_draws': True,
2193 'use_count_func': True,
2206 'use_count_func': True,
2217 'state': 'ClearColor',
2221 'state': 'ClearDepthf',
2222 'decoder_func': 'glClearDepth',
2223 'gl_test_func': 'glClearDepth',
2230 'data_transfer_methods': ['shm'],
2231 'cmd_args': 'GLuint sync, GLbitfieldSyncFlushFlags flags, '
2232 'GLuint timeout_0, GLuint timeout_1, GLenum* result',
2234 'result': ['GLenum'],
2239 'state': 'ColorMask',
2241 'expectation': False,
2243 'ConsumeTextureCHROMIUM': {
2244 'decoder_func': 'DoConsumeTextureCHROMIUM',
2247 'count': 64, # GL_MAILBOX_SIZE_CHROMIUM
2249 'client_test': False,
2250 'extension': "CHROMIUM_texture_mailbox",
2254 'CopyBufferSubData': {
2257 'CreateAndConsumeTextureCHROMIUM': {
2258 'decoder_func': 'DoCreateAndConsumeTextureCHROMIUM',
2260 'type': 'HandWritten',
2261 'data_transfer_methods': ['immediate'],
2263 'client_test': False,
2264 'extension': "CHROMIUM_texture_mailbox",
2268 'GenValuebuffersCHROMIUM': {
2270 'gl_test_func': 'glGenValuebuffersCHROMIUM',
2271 'resource_type': 'Valuebuffer',
2272 'resource_types': 'Valuebuffers',
2277 'DeleteValuebuffersCHROMIUM': {
2279 'gl_test_func': 'glDeleteValuebuffersCHROMIUM',
2280 'resource_type': 'Valuebuffer',
2281 'resource_types': 'Valuebuffers',
2286 'IsValuebufferCHROMIUM': {
2288 'decoder_func': 'DoIsValuebufferCHROMIUM',
2289 'expectation': False,
2293 'BindValuebufferCHROMIUM': {
2295 'decoder_func': 'DoBindValueBufferCHROMIUM',
2296 'gen_func': 'GenValueBuffersCHROMIUM',
2301 'SubscribeValueCHROMIUM': {
2302 'decoder_func': 'DoSubscribeValueCHROMIUM',
2307 'PopulateSubscribedValuesCHROMIUM': {
2308 'decoder_func': 'DoPopulateSubscribedValuesCHROMIUM',
2313 'UniformValuebufferCHROMIUM': {
2314 'decoder_func': 'DoUniformValueBufferCHROMIUM',
2321 'state': 'ClearStencil',
2323 'EnableFeatureCHROMIUM': {
2325 'data_transfer_methods': ['shm'],
2326 'decoder_func': 'DoEnableFeatureCHROMIUM',
2327 'expectation': False,
2328 'cmd_args': 'GLuint bucket_id, GLint* result',
2329 'result': ['GLint'],
2332 'pepper_interface': 'ChromiumEnableFeature',
2334 'CompileShader': {'decoder_func': 'DoCompileShader', 'unit_test': False},
2335 'CompressedTexImage2D': {
2337 'data_transfer_methods': ['bucket', 'shm'],
2340 'CompressedTexSubImage2D': {
2342 'data_transfer_methods': ['bucket', 'shm'],
2343 'decoder_func': 'DoCompressedTexSubImage2D',
2347 'decoder_func': 'DoCopyTexImage2D',
2349 'defer_reads': True,
2352 'CopyTexSubImage2D': {
2353 'decoder_func': 'DoCopyTexSubImage2D',
2354 'defer_reads': True,
2357 'CompressedTexImage3D': {
2359 'data_transfer_methods': ['bucket', 'shm'],
2363 'CompressedTexSubImage3D': {
2365 'data_transfer_methods': ['bucket', 'shm'],
2366 'decoder_func': 'DoCompressedTexSubImage3D',
2370 'CopyTexSubImage3D': {
2371 'defer_reads': True,
2375 'CreateImageCHROMIUM': {
2378 'ClientBuffer buffer, GLsizei width, GLsizei height, '
2379 'GLenum internalformat',
2380 'result': ['GLuint'],
2381 'client_test': False,
2383 'expectation': False,
2384 'extension': "CHROMIUM_image",
2388 'DestroyImageCHROMIUM': {
2390 'client_test': False,
2392 'extension': "CHROMIUM_image",
2396 'CreateGpuMemoryBufferImageCHROMIUM': {
2399 'GLsizei width, GLsizei height, GLenum internalformat, GLenum usage',
2400 'result': ['GLuint'],
2401 'client_test': False,
2403 'expectation': False,
2404 'extension': "CHROMIUM_image",
2410 'client_test': False,
2414 'client_test': False,
2418 'state': 'BlendColor',
2421 'type': 'StateSetRGBAlpha',
2422 'state': 'BlendEquation',
2424 '0': 'GL_FUNC_SUBTRACT'
2427 'BlendEquationSeparate': {
2429 'state': 'BlendEquation',
2431 '0': 'GL_FUNC_SUBTRACT'
2435 'type': 'StateSetRGBAlpha',
2436 'state': 'BlendFunc',
2438 'BlendFuncSeparate': {
2440 'state': 'BlendFunc',
2442 'BlendBarrierKHR': {
2443 'gl_test_func': 'glBlendBarrierKHR',
2445 'extension_flag': 'blend_equation_advanced',
2446 'client_test': False,
2448 'SampleCoverage': {'decoder_func': 'DoSampleCoverage'},
2450 'type': 'StateSetFrontBack',
2451 'state': 'StencilFunc',
2453 'StencilFuncSeparate': {
2454 'type': 'StateSetFrontBackSeparate',
2455 'state': 'StencilFunc',
2458 'type': 'StateSetFrontBack',
2459 'state': 'StencilOp',
2464 'StencilOpSeparate': {
2465 'type': 'StateSetFrontBackSeparate',
2466 'state': 'StencilOp',
2472 'type': 'StateSetNamedParameter',
2475 'CullFace': {'type': 'StateSet', 'state': 'CullFace'},
2476 'FrontFace': {'type': 'StateSet', 'state': 'FrontFace'},
2477 'DepthFunc': {'type': 'StateSet', 'state': 'DepthFunc'},
2480 'state': 'LineWidth',
2487 'state': 'PolygonOffset',
2491 'gl_test_func': 'glDeleteBuffersARB',
2492 'resource_type': 'Buffer',
2493 'resource_types': 'Buffers',
2495 'DeleteFramebuffers': {
2497 'gl_test_func': 'glDeleteFramebuffersEXT',
2498 'resource_type': 'Framebuffer',
2499 'resource_types': 'Framebuffers',
2502 'DeleteProgram': { 'type': 'Delete' },
2503 'DeleteRenderbuffers': {
2505 'gl_test_func': 'glDeleteRenderbuffersEXT',
2506 'resource_type': 'Renderbuffer',
2507 'resource_types': 'Renderbuffers',
2512 'resource_type': 'Sampler',
2513 'resource_types': 'Samplers',
2516 'DeleteShader': { 'type': 'Delete' },
2519 'cmd_args': 'GLuint sync',
2520 'resource_type': 'Sync',
2525 'resource_type': 'Texture',
2526 'resource_types': 'Textures',
2528 'DeleteTransformFeedbacks': {
2530 'resource_type': 'TransformFeedback',
2531 'resource_types': 'TransformFeedbacks',
2535 'decoder_func': 'DoDepthRangef',
2536 'gl_test_func': 'glDepthRange',
2540 'state': 'DepthMask',
2542 'expectation': False,
2544 'DetachShader': {'decoder_func': 'DoDetachShader'},
2546 'decoder_func': 'DoDisable',
2548 'client_test': False,
2550 'DisableVertexAttribArray': {
2551 'decoder_func': 'DoDisableVertexAttribArray',
2556 'cmd_args': 'GLenumDrawMode mode, GLint first, GLsizei count',
2557 'defer_draws': True,
2562 'cmd_args': 'GLenumDrawMode mode, GLsizei count, '
2563 'GLenumIndexType type, GLuint index_offset',
2564 'client_test': False,
2565 'defer_draws': True,
2568 'DrawRangeElements': {
2574 'decoder_func': 'DoEnable',
2576 'client_test': False,
2578 'EnableVertexAttribArray': {
2579 'decoder_func': 'DoEnableVertexAttribArray',
2584 'client_test': False,
2590 'client_test': False,
2591 'decoder_func': 'DoFinish',
2592 'defer_reads': True,
2597 'decoder_func': 'DoFlush',
2600 'FramebufferRenderbuffer': {
2601 'decoder_func': 'DoFramebufferRenderbuffer',
2602 'gl_test_func': 'glFramebufferRenderbufferEXT',
2605 'FramebufferTexture2D': {
2606 'decoder_func': 'DoFramebufferTexture2D',
2607 'gl_test_func': 'glFramebufferTexture2DEXT',
2610 'FramebufferTexture2DMultisampleEXT': {
2611 'decoder_func': 'DoFramebufferTexture2DMultisample',
2612 'gl_test_func': 'glFramebufferTexture2DMultisampleEXT',
2613 'expectation': False,
2615 'extension_flag': 'multisampled_render_to_texture',
2618 'FramebufferTextureLayer': {
2619 'decoder_func': 'DoFramebufferTextureLayer',
2624 'decoder_func': 'DoGenerateMipmap',
2625 'gl_test_func': 'glGenerateMipmapEXT',
2630 'gl_test_func': 'glGenBuffersARB',
2631 'resource_type': 'Buffer',
2632 'resource_types': 'Buffers',
2634 'GenMailboxCHROMIUM': {
2635 'type': 'HandWritten',
2637 'extension': "CHROMIUM_texture_mailbox",
2640 'GenFramebuffers': {
2642 'gl_test_func': 'glGenFramebuffersEXT',
2643 'resource_type': 'Framebuffer',
2644 'resource_types': 'Framebuffers',
2646 'GenRenderbuffers': {
2647 'type': 'GENn', 'gl_test_func': 'glGenRenderbuffersEXT',
2648 'resource_type': 'Renderbuffer',
2649 'resource_types': 'Renderbuffers',
2653 'gl_test_func': 'glGenSamplers',
2654 'resource_type': 'Sampler',
2655 'resource_types': 'Samplers',
2660 'gl_test_func': 'glGenTextures',
2661 'resource_type': 'Texture',
2662 'resource_types': 'Textures',
2664 'GenTransformFeedbacks': {
2666 'gl_test_func': 'glGenTransformFeedbacks',
2667 'resource_type': 'TransformFeedback',
2668 'resource_types': 'TransformFeedbacks',
2671 'GetActiveAttrib': {
2673 'data_transfer_methods': ['shm'],
2675 'GLidProgram program, GLuint index, uint32_t name_bucket_id, '
2683 'GetActiveUniform': {
2685 'data_transfer_methods': ['shm'],
2687 'GLidProgram program, GLuint index, uint32_t name_bucket_id, '
2695 'GetActiveUniformBlockiv': {
2697 'data_transfer_methods': ['shm'],
2698 'result': ['SizedResult<GLint>'],
2701 'GetActiveUniformBlockName': {
2703 'data_transfer_methods': ['shm'],
2705 'GLidProgram program, GLuint index, uint32_t name_bucket_id, '
2707 'result': ['int32_t'],
2710 'GetActiveUniformsiv': {
2712 'data_transfer_methods': ['shm'],
2714 'GLidProgram program, uint32_t indices_bucket_id, GLenum pname, '
2716 'result': ['SizedResult<GLint>'],
2719 'GetAttachedShaders': {
2721 'data_transfer_methods': ['shm'],
2722 'cmd_args': 'GLidProgram program, void* result, uint32_t result_size',
2723 'result': ['SizedResult<GLuint>'],
2725 'GetAttribLocation': {
2727 'data_transfer_methods': ['shm'],
2729 'GLidProgram program, uint32_t name_bucket_id, GLint* location',
2730 'result': ['GLint'],
2733 'GetFragDataLocation': {
2735 'data_transfer_methods': ['shm'],
2737 'GLidProgram program, uint32_t name_bucket_id, GLint* location',
2738 'result': ['GLint'],
2744 'result': ['SizedResult<GLboolean>'],
2745 'decoder_func': 'DoGetBooleanv',
2746 'gl_test_func': 'glGetBooleanv',
2748 'GetBufferParameteriv': {
2750 'result': ['SizedResult<GLint>'],
2751 'decoder_func': 'DoGetBufferParameteriv',
2752 'expectation': False,
2757 'decoder_func': 'GetErrorState()->GetGLError',
2759 'result': ['GLenum'],
2760 'client_test': False,
2764 'result': ['SizedResult<GLfloat>'],
2765 'decoder_func': 'DoGetFloatv',
2766 'gl_test_func': 'glGetFloatv',
2768 'GetFramebufferAttachmentParameteriv': {
2770 'decoder_func': 'DoGetFramebufferAttachmentParameteriv',
2771 'gl_test_func': 'glGetFramebufferAttachmentParameterivEXT',
2772 'result': ['SizedResult<GLint>'],
2774 'GetGraphicsResetStatusKHR': {
2776 'client_test': False,
2782 'result': ['SizedResult<GLint64>'],
2783 'client_test': False,
2784 'decoder_func': 'DoGetInteger64v',
2789 'result': ['SizedResult<GLint>'],
2790 'decoder_func': 'DoGetIntegerv',
2791 'client_test': False,
2793 'GetInteger64i_v': {
2795 'result': ['SizedResult<GLint64>'],
2796 'client_test': False,
2801 'result': ['SizedResult<GLint>'],
2802 'client_test': False,
2805 'GetInternalformativ': {
2807 'data_transfer_methods': ['shm'],
2808 'result': ['SizedResult<GLint>'],
2810 'GLenumRenderBufferTarget target, GLenumRenderBufferFormat format, '
2811 'GLenumInternalFormatParameter pname, GLint* params',
2814 'GetMaxValueInBufferCHROMIUM': {
2816 'decoder_func': 'DoGetMaxValueInBufferCHROMIUM',
2817 'result': ['GLuint'],
2819 'client_test': False,
2826 'decoder_func': 'DoGetProgramiv',
2827 'result': ['SizedResult<GLint>'],
2828 'expectation': False,
2830 'GetProgramInfoCHROMIUM': {
2832 'expectation': False,
2836 'client_test': False,
2837 'cmd_args': 'GLidProgram program, uint32_t bucket_id',
2839 'uint32_t link_status',
2840 'uint32_t num_attribs',
2841 'uint32_t num_uniforms',
2844 'GetProgramInfoLog': {
2846 'expectation': False,
2848 'GetRenderbufferParameteriv': {
2850 'decoder_func': 'DoGetRenderbufferParameteriv',
2851 'gl_test_func': 'glGetRenderbufferParameterivEXT',
2852 'result': ['SizedResult<GLint>'],
2854 'GetSamplerParameterfv': {
2856 'result': ['SizedResult<GLfloat>'],
2857 'id_mapping': [ 'Sampler' ],
2860 'GetSamplerParameteriv': {
2862 'result': ['SizedResult<GLint>'],
2863 'id_mapping': [ 'Sampler' ],
2868 'decoder_func': 'DoGetShaderiv',
2869 'result': ['SizedResult<GLint>'],
2871 'GetShaderInfoLog': {
2873 'get_len_func': 'glGetShaderiv',
2874 'get_len_enum': 'GL_INFO_LOG_LENGTH',
2877 'GetShaderPrecisionFormat': {
2879 'data_transfer_methods': ['shm'],
2881 'GLenumShaderType shadertype, GLenumShaderPrecision precisiontype, '
2885 'int32_t min_range',
2886 'int32_t max_range',
2887 'int32_t precision',
2890 'GetShaderSource': {
2892 'get_len_func': 'DoGetShaderiv',
2893 'get_len_enum': 'GL_SHADER_SOURCE_LENGTH',
2895 'client_test': False,
2899 'client_test': False,
2900 'cmd_args': 'GLenumStringType name, uint32_t bucket_id',
2904 'cmd_args': 'GLuint sync, GLenumSyncParameter pname, void* values',
2905 'result': ['SizedResult<GLint>'],
2906 'id_mapping': ['Sync'],
2909 'GetTexParameterfv': {
2911 'decoder_func': 'DoGetTexParameterfv',
2912 'result': ['SizedResult<GLfloat>']
2914 'GetTexParameteriv': {
2916 'decoder_func': 'DoGetTexParameteriv',
2917 'result': ['SizedResult<GLint>']
2919 'GetTranslatedShaderSourceANGLE': {
2921 'get_len_func': 'DoGetShaderiv',
2922 'get_len_enum': 'GL_TRANSLATED_SHADER_SOURCE_LENGTH_ANGLE',
2926 'GetUniformBlockIndex': {
2928 'data_transfer_methods': ['shm'],
2930 'GLidProgram program, uint32_t name_bucket_id, GLuint* index',
2931 'result': ['GLuint'],
2932 'error_return': 'GL_INVALID_INDEX',
2935 'GetUniformBlocksCHROMIUM': {
2937 'expectation': False,
2941 'client_test': False,
2942 'cmd_args': 'GLidProgram program, uint32_t bucket_id',
2943 'result': ['uint32_t'],
2946 'GetUniformsES3CHROMIUM': {
2948 'expectation': False,
2952 'client_test': False,
2953 'cmd_args': 'GLidProgram program, uint32_t bucket_id',
2954 'result': ['uint32_t'],
2957 'GetTransformFeedbackVarying': {
2959 'data_transfer_methods': ['shm'],
2961 'GLidProgram program, GLuint index, uint32_t name_bucket_id, '
2970 'GetTransformFeedbackVaryingsCHROMIUM': {
2972 'expectation': False,
2976 'client_test': False,
2977 'cmd_args': 'GLidProgram program, uint32_t bucket_id',
2978 'result': ['uint32_t'],
2983 'data_transfer_methods': ['shm'],
2984 'result': ['SizedResult<GLfloat>'],
2988 'data_transfer_methods': ['shm'],
2989 'result': ['SizedResult<GLint>'],
2993 'data_transfer_methods': ['shm'],
2994 'result': ['SizedResult<GLuint>'],
2997 'GetUniformIndices': {
2999 'data_transfer_methods': ['shm'],
3000 'result': ['SizedResult<GLuint>'],
3001 'cmd_args': 'GLidProgram program, uint32_t names_bucket_id, '
3005 'GetUniformLocation': {
3007 'data_transfer_methods': ['shm'],
3009 'GLidProgram program, uint32_t name_bucket_id, GLint* location',
3010 'result': ['GLint'],
3011 'error_return': -1, # http://www.opengl.org/sdk/docs/man/xhtml/glGetUniformLocation.xml
3013 'GetVertexAttribfv': {
3015 'result': ['SizedResult<GLfloat>'],
3017 'decoder_func': 'DoGetVertexAttribfv',
3018 'expectation': False,
3019 'client_test': False,
3021 'GetVertexAttribiv': {
3023 'result': ['SizedResult<GLint>'],
3025 'decoder_func': 'DoGetVertexAttribiv',
3026 'expectation': False,
3027 'client_test': False,
3029 'GetVertexAttribIiv': {
3031 'result': ['SizedResult<GLint>'],
3033 'decoder_func': 'DoGetVertexAttribIiv',
3034 'expectation': False,
3035 'client_test': False,
3038 'GetVertexAttribIuiv': {
3040 'result': ['SizedResult<GLuint>'],
3042 'decoder_func': 'DoGetVertexAttribIuiv',
3043 'expectation': False,
3044 'client_test': False,
3047 'GetVertexAttribPointerv': {
3049 'data_transfer_methods': ['shm'],
3050 'result': ['SizedResult<GLuint>'],
3051 'client_test': False,
3053 'InvalidateFramebuffer': {
3056 'client_test': False,
3060 'InvalidateSubFramebuffer': {
3063 'client_test': False,
3069 'decoder_func': 'DoIsBuffer',
3070 'expectation': False,
3074 'decoder_func': 'DoIsEnabled',
3075 'client_test': False,
3077 'expectation': False,
3081 'decoder_func': 'DoIsFramebuffer',
3082 'expectation': False,
3086 'decoder_func': 'DoIsProgram',
3087 'expectation': False,
3091 'decoder_func': 'DoIsRenderbuffer',
3092 'expectation': False,
3096 'decoder_func': 'DoIsShader',
3097 'expectation': False,
3101 'id_mapping': [ 'Sampler' ],
3102 'expectation': False,
3107 'id_mapping': [ 'Sync' ],
3108 'cmd_args': 'GLuint sync',
3109 'expectation': False,
3114 'decoder_func': 'DoIsTexture',
3115 'expectation': False,
3117 'IsTransformFeedback': {
3119 'id_mapping': [ 'TransformFeedback' ],
3120 'expectation': False,
3124 'decoder_func': 'DoLinkProgram',
3128 'MapBufferCHROMIUM': {
3130 'extension': "CHROMIUM_pixel_transfer_buffer_object",
3132 'client_test': False,
3135 'MapBufferSubDataCHROMIUM': {
3139 'client_test': False,
3140 'pepper_interface': 'ChromiumMapSub',
3143 'MapTexSubImage2DCHROMIUM': {
3145 'extension': "CHROMIUM_sub_image",
3147 'client_test': False,
3148 'pepper_interface': 'ChromiumMapSub',
3153 'data_transfer_methods': ['shm'],
3154 'cmd_args': 'GLenumBufferTarget target, GLintptrNotNegative offset, '
3155 'GLsizeiptr size, GLbitfieldMapBufferAccess access, '
3156 'uint32_t data_shm_id, uint32_t data_shm_offset, '
3157 'uint32_t result_shm_id, uint32_t result_shm_offset',
3159 'result': ['uint32_t'],
3162 'PauseTransformFeedback': {
3165 'PixelStorei': {'type': 'Manual'},
3166 'PostSubBufferCHROMIUM': {
3170 'client_test': False,
3174 'ProduceTextureCHROMIUM': {
3175 'decoder_func': 'DoProduceTextureCHROMIUM',
3178 'count': 64, # GL_MAILBOX_SIZE_CHROMIUM
3180 'client_test': False,
3181 'extension': "CHROMIUM_texture_mailbox",
3185 'ProduceTextureDirectCHROMIUM': {
3186 'decoder_func': 'DoProduceTextureDirectCHROMIUM',
3189 'count': 64, # GL_MAILBOX_SIZE_CHROMIUM
3191 'client_test': False,
3192 'extension': "CHROMIUM_texture_mailbox",
3196 'RenderbufferStorage': {
3197 'decoder_func': 'DoRenderbufferStorage',
3198 'gl_test_func': 'glRenderbufferStorageEXT',
3199 'expectation': False,
3202 'RenderbufferStorageMultisampleCHROMIUM': {
3204 '// GL_CHROMIUM_framebuffer_multisample\n',
3205 'decoder_func': 'DoRenderbufferStorageMultisampleCHROMIUM',
3206 'gl_test_func': 'glRenderbufferStorageMultisampleCHROMIUM',
3207 'expectation': False,
3209 'extension_flag': 'chromium_framebuffer_multisample',
3210 'pepper_interface': 'FramebufferMultisample',
3211 'pepper_name': 'RenderbufferStorageMultisampleEXT',
3214 'RenderbufferStorageMultisampleEXT': {
3216 '// GL_EXT_multisampled_render_to_texture\n',
3217 'decoder_func': 'DoRenderbufferStorageMultisampleEXT',
3218 'gl_test_func': 'glRenderbufferStorageMultisampleEXT',
3219 'expectation': False,
3221 'extension_flag': 'multisampled_render_to_texture',
3230 '// ReadPixels has the result separated from the pixel buffer so that\n'
3231 '// it is easier to specify the result going to some specific place\n'
3232 '// that exactly fits the rectangle of pixels.\n',
3234 'data_transfer_methods': ['shm'],
3236 'client_test': False,
3238 'GLint x, GLint y, GLsizei width, GLsizei height, '
3239 'GLenumReadPixelFormat format, GLenumReadPixelType type, '
3240 'uint32_t pixels_shm_id, uint32_t pixels_shm_offset, '
3241 'uint32_t result_shm_id, uint32_t result_shm_offset, '
3243 'result': ['uint32_t'],
3244 'defer_reads': True,
3247 'ReleaseShaderCompiler': {
3248 'decoder_func': 'DoReleaseShaderCompiler',
3251 'ResumeTransformFeedback': {
3254 'SamplerParameterf': {
3258 'id_mapping': [ 'Sampler' ],
3261 'SamplerParameterfv': {
3263 'data_value': 'GL_NEAREST',
3265 'gl_test_func': 'glSamplerParameterf',
3266 'decoder_func': 'DoSamplerParameterfv',
3267 'first_element_only': True,
3268 'id_mapping': [ 'Sampler' ],
3271 'SamplerParameteri': {
3275 'id_mapping': [ 'Sampler' ],
3278 'SamplerParameteriv': {
3280 'data_value': 'GL_NEAREST',
3282 'gl_test_func': 'glSamplerParameteri',
3283 'decoder_func': 'DoSamplerParameteriv',
3284 'first_element_only': True,
3289 'client_test': False,
3293 'decoder_func': 'DoShaderSource',
3294 'expectation': False,
3295 'data_transfer_methods': ['bucket'],
3297 'GLuint shader, const char** str',
3299 'GLuint shader, GLsizei count, const char** str, const GLint* length',
3302 'type': 'StateSetFrontBack',
3303 'state': 'StencilMask',
3305 'expectation': False,
3307 'StencilMaskSeparate': {
3308 'type': 'StateSetFrontBackSeparate',
3309 'state': 'StencilMask',
3311 'expectation': False,
3315 'decoder_func': 'DoSwapBuffers',
3317 'client_test': False,
3323 'decoder_func': 'DoSwapInterval',
3325 'client_test': False,
3331 'data_transfer_methods': ['shm'],
3332 'client_test': False,
3337 'data_transfer_methods': ['shm'],
3338 'client_test': False,
3343 'decoder_func': 'DoTexParameterf',
3349 'decoder_func': 'DoTexParameteri',
3356 'data_value': 'GL_NEAREST',
3358 'decoder_func': 'DoTexParameterfv',
3359 'gl_test_func': 'glTexParameterf',
3360 'first_element_only': True,
3364 'data_value': 'GL_NEAREST',
3366 'decoder_func': 'DoTexParameteriv',
3367 'gl_test_func': 'glTexParameteri',
3368 'first_element_only': True,
3376 'data_transfer_methods': ['shm'],
3377 'client_test': False,
3379 'cmd_args': 'GLenumTextureTarget target, GLint level, '
3380 'GLint xoffset, GLint yoffset, '
3381 'GLsizei width, GLsizei height, '
3382 'GLenumTextureFormat format, GLenumPixelType type, '
3383 'const void* pixels, GLboolean internal'
3387 'data_transfer_methods': ['shm'],
3388 'client_test': False,
3390 'cmd_args': 'GLenumTextureTarget target, GLint level, '
3391 'GLint xoffset, GLint yoffset, GLint zoffset, '
3392 'GLsizei width, GLsizei height, GLsizei depth, '
3393 'GLenumTextureFormat format, GLenumPixelType type, '
3394 'const void* pixels, GLboolean internal',
3397 'TransformFeedbackVaryings': {
3399 'data_transfer_methods': ['bucket'],
3400 'decoder_func': 'DoTransformFeedbackVaryings',
3402 'GLuint program, const char** varyings, GLenum buffermode',
3405 'Uniform1f': {'type': 'PUTXn', 'count': 1},
3409 'decoder_func': 'DoUniform1fv',
3411 'Uniform1i': {'decoder_func': 'DoUniform1i', 'unit_test': False},
3415 'decoder_func': 'DoUniform1iv',
3428 'Uniform2i': {'type': 'PUTXn', 'count': 2},
3429 'Uniform2f': {'type': 'PUTXn', 'count': 2},
3433 'decoder_func': 'DoUniform2fv',
3438 'decoder_func': 'DoUniform2iv',
3450 'Uniform3i': {'type': 'PUTXn', 'count': 3},
3451 'Uniform3f': {'type': 'PUTXn', 'count': 3},
3455 'decoder_func': 'DoUniform3fv',
3460 'decoder_func': 'DoUniform3iv',
3472 'Uniform4i': {'type': 'PUTXn', 'count': 4},
3473 'Uniform4f': {'type': 'PUTXn', 'count': 4},
3477 'decoder_func': 'DoUniform4fv',
3482 'decoder_func': 'DoUniform4iv',
3494 'UniformMatrix2fv': {
3497 'decoder_func': 'DoUniformMatrix2fv',
3499 'UniformMatrix2x3fv': {
3504 'UniformMatrix2x4fv': {
3509 'UniformMatrix3fv': {
3512 'decoder_func': 'DoUniformMatrix3fv',
3514 'UniformMatrix3x2fv': {
3519 'UniformMatrix3x4fv': {
3524 'UniformMatrix4fv': {
3527 'decoder_func': 'DoUniformMatrix4fv',
3529 'UniformMatrix4x2fv': {
3534 'UniformMatrix4x3fv': {
3539 'UniformBlockBinding': {
3544 'UnmapBufferCHROMIUM': {
3546 'extension': "CHROMIUM_pixel_transfer_buffer_object",
3548 'client_test': False,
3551 'UnmapBufferSubDataCHROMIUM': {
3555 'client_test': False,
3556 'pepper_interface': 'ChromiumMapSub',
3564 'UnmapTexSubImage2DCHROMIUM': {
3566 'extension': "CHROMIUM_sub_image",
3568 'client_test': False,
3569 'pepper_interface': 'ChromiumMapSub',
3574 'decoder_func': 'DoUseProgram',
3576 'ValidateProgram': {'decoder_func': 'DoValidateProgram'},
3577 'VertexAttrib1f': {'decoder_func': 'DoVertexAttrib1f'},
3578 'VertexAttrib1fv': {
3581 'decoder_func': 'DoVertexAttrib1fv',
3583 'VertexAttrib2f': {'decoder_func': 'DoVertexAttrib2f'},
3584 'VertexAttrib2fv': {
3587 'decoder_func': 'DoVertexAttrib2fv',
3589 'VertexAttrib3f': {'decoder_func': 'DoVertexAttrib3f'},
3590 'VertexAttrib3fv': {
3593 'decoder_func': 'DoVertexAttrib3fv',
3595 'VertexAttrib4f': {'decoder_func': 'DoVertexAttrib4f'},
3596 'VertexAttrib4fv': {
3599 'decoder_func': 'DoVertexAttrib4fv',
3601 'VertexAttribI4i': {
3603 'decoder_func': 'DoVertexAttribI4i',
3605 'VertexAttribI4iv': {
3609 'decoder_func': 'DoVertexAttribI4iv',
3611 'VertexAttribI4ui': {
3613 'decoder_func': 'DoVertexAttribI4ui',
3615 'VertexAttribI4uiv': {
3619 'decoder_func': 'DoVertexAttribI4uiv',
3621 'VertexAttribIPointer': {
3623 'cmd_args': 'GLuint indx, GLintVertexAttribSize size, '
3624 'GLenumVertexAttribIType type, GLsizei stride, '
3626 'client_test': False,
3629 'VertexAttribPointer': {
3631 'cmd_args': 'GLuint indx, GLintVertexAttribSize size, '
3632 'GLenumVertexAttribType type, GLboolean normalized, '
3633 'GLsizei stride, GLuint offset',
3634 'client_test': False,
3638 'cmd_args': 'GLuint sync, GLbitfieldSyncFlushFlags flags, '
3639 'GLuint timeout_0, GLuint timeout_1',
3641 'client_test': False,
3650 'decoder_func': 'DoViewport',
3660 'GetRequestableExtensionsCHROMIUM': {
3663 'cmd_args': 'uint32_t bucket_id',
3667 'RequestExtensionCHROMIUM': {
3670 'client_test': False,
3671 'cmd_args': 'uint32_t bucket_id',
3675 'RateLimitOffscreenContextCHROMIUM': {
3679 'client_test': False,
3681 'CreateStreamTextureCHROMIUM': {
3682 'type': 'HandWritten',
3689 'TexImageIOSurface2DCHROMIUM': {
3690 'decoder_func': 'DoTexImageIOSurface2DCHROMIUM',
3696 'CopyTextureCHROMIUM': {
3697 'decoder_func': 'DoCopyTextureCHROMIUM',
3699 'extension': "CHROMIUM_copy_texture",
3703 'CopySubTextureCHROMIUM': {
3704 'decoder_func': 'DoCopySubTextureCHROMIUM',
3706 'extension': "CHROMIUM_copy_texture",
3710 'CompressedCopyTextureCHROMIUM': {
3711 'decoder_func': 'DoCompressedCopyTextureCHROMIUM',
3716 'TexStorage2DEXT': {
3719 'decoder_func': 'DoTexStorage2DEXT',
3722 'DrawArraysInstancedANGLE': {
3724 'cmd_args': 'GLenumDrawMode mode, GLint first, GLsizei count, '
3725 'GLsizei primcount',
3728 'pepper_interface': 'InstancedArrays',
3729 'defer_draws': True,
3734 'decoder_func': 'DoDrawBuffersEXT',
3736 'client_test': False,
3738 # could use 'extension_flag': 'ext_draw_buffers' but currently expected to
3741 'pepper_interface': 'DrawBuffers',
3744 'DrawElementsInstancedANGLE': {
3746 'cmd_args': 'GLenumDrawMode mode, GLsizei count, '
3747 'GLenumIndexType type, GLuint index_offset, GLsizei primcount',
3750 'client_test': False,
3751 'pepper_interface': 'InstancedArrays',
3752 'defer_draws': True,
3755 'VertexAttribDivisorANGLE': {
3757 'cmd_args': 'GLuint index, GLuint divisor',
3760 'pepper_interface': 'InstancedArrays',
3764 'gl_test_func': 'glGenQueriesARB',
3765 'resource_type': 'Query',
3766 'resource_types': 'Queries',
3768 'pepper_interface': 'Query',
3769 'not_shared': 'True',
3770 'extension': "occlusion_query_EXT",
3772 'DeleteQueriesEXT': {
3774 'gl_test_func': 'glDeleteQueriesARB',
3775 'resource_type': 'Query',
3776 'resource_types': 'Queries',
3778 'pepper_interface': 'Query',
3779 'extension': "occlusion_query_EXT",
3783 'client_test': False,
3784 'pepper_interface': 'Query',
3785 'extension': "occlusion_query_EXT",
3789 'cmd_args': 'GLenumQueryTarget target, GLidQuery id, void* sync_data',
3790 'data_transfer_methods': ['shm'],
3791 'gl_test_func': 'glBeginQuery',
3792 'pepper_interface': 'Query',
3793 'extension': "occlusion_query_EXT",
3795 'BeginTransformFeedback': {
3800 'cmd_args': 'GLenumQueryTarget target, GLuint submit_count',
3801 'gl_test_func': 'glEndnQuery',
3802 'client_test': False,
3803 'pepper_interface': 'Query',
3804 'extension': "occlusion_query_EXT",
3806 'EndTransformFeedback': {
3809 'FlushDriverCachesCHROMIUM': {
3810 'decoder_func': 'DoFlushDriverCachesCHROMIUM',
3818 'client_test': False,
3819 'gl_test_func': 'glGetQueryiv',
3820 'pepper_interface': 'Query',
3821 'extension': "occlusion_query_EXT",
3823 'QueryCounterEXT' : {
3825 'cmd_args': 'GLidQuery id, GLenumQueryTarget target, '
3826 'void* sync_data, GLuint submit_count',
3827 'data_transfer_methods': ['shm'],
3828 'gl_test_func': 'glQueryCounter',
3829 'extension': "disjoint_timer_query_EXT",
3831 'GetQueryObjectuivEXT': {
3833 'client_test': False,
3834 'gl_test_func': 'glGetQueryObjectuiv',
3835 'pepper_interface': 'Query',
3836 'extension': "occlusion_query_EXT",
3838 'GetQueryObjectui64vEXT': {
3840 'client_test': False,
3841 'gl_test_func': 'glGetQueryObjectui64v',
3842 'extension': "disjoint_timer_query_EXT",
3844 'BindUniformLocationCHROMIUM': {
3847 'data_transfer_methods': ['bucket'],
3849 'gl_test_func': 'DoBindUniformLocationCHROMIUM',
3851 'InsertEventMarkerEXT': {
3853 'decoder_func': 'DoInsertEventMarkerEXT',
3854 'expectation': False,
3857 'PushGroupMarkerEXT': {
3859 'decoder_func': 'DoPushGroupMarkerEXT',
3860 'expectation': False,
3863 'PopGroupMarkerEXT': {
3864 'decoder_func': 'DoPopGroupMarkerEXT',
3865 'expectation': False,
3870 'GenVertexArraysOES': {
3873 'gl_test_func': 'glGenVertexArraysOES',
3874 'resource_type': 'VertexArray',
3875 'resource_types': 'VertexArrays',
3877 'pepper_interface': 'VertexArrayObject',
3879 'BindVertexArrayOES': {
3882 'gl_test_func': 'glBindVertexArrayOES',
3883 'decoder_func': 'DoBindVertexArrayOES',
3884 'gen_func': 'GenVertexArraysOES',
3886 'client_test': False,
3887 'pepper_interface': 'VertexArrayObject',
3889 'DeleteVertexArraysOES': {
3892 'gl_test_func': 'glDeleteVertexArraysOES',
3893 'resource_type': 'VertexArray',
3894 'resource_types': 'VertexArrays',
3896 'pepper_interface': 'VertexArrayObject',
3898 'IsVertexArrayOES': {
3901 'gl_test_func': 'glIsVertexArrayOES',
3902 'decoder_func': 'DoIsVertexArrayOES',
3903 'expectation': False,
3905 'pepper_interface': 'VertexArrayObject',
3907 'BindTexImage2DCHROMIUM': {
3908 'decoder_func': 'DoBindTexImage2DCHROMIUM',
3910 'extension': "CHROMIUM_image",
3913 'ReleaseTexImage2DCHROMIUM': {
3914 'decoder_func': 'DoReleaseTexImage2DCHROMIUM',
3916 'extension': "CHROMIUM_image",
3919 'ShallowFinishCHROMIUM': {
3924 'client_test': False,
3926 'ShallowFlushCHROMIUM': {
3929 'extension': "CHROMIUM_miscellaneous",
3931 'client_test': False,
3933 'OrderingBarrierCHROMIUM': {
3938 'client_test': False,
3940 'TraceBeginCHROMIUM': {
3943 'client_test': False,
3944 'cmd_args': 'GLuint category_bucket_id, GLuint name_bucket_id',
3948 'TraceEndCHROMIUM': {
3950 'client_test': False,
3951 'decoder_func': 'DoTraceEndCHROMIUM',
3956 'AsyncTexImage2DCHROMIUM': {
3958 'data_transfer_methods': ['shm'],
3959 'client_test': False,
3960 'cmd_args': 'GLenumTextureTarget target, GLint level, '
3961 'GLintTextureInternalFormat internalformat, '
3962 'GLsizei width, GLsizei height, '
3963 'GLintTextureBorder border, '
3964 'GLenumTextureFormat format, GLenumPixelType type, '
3965 'const void* pixels, '
3966 'uint32_t async_upload_token, '
3972 'AsyncTexSubImage2DCHROMIUM': {
3974 'data_transfer_methods': ['shm'],
3975 'client_test': False,
3976 'cmd_args': 'GLenumTextureTarget target, GLint level, '
3977 'GLint xoffset, GLint yoffset, '
3978 'GLsizei width, GLsizei height, '
3979 'GLenumTextureFormat format, GLenumPixelType type, '
3980 'const void* data, '
3981 'uint32_t async_upload_token, '
3987 'WaitAsyncTexImage2DCHROMIUM': {
3989 'client_test': False,
3994 'WaitAllAsyncTexImage2DCHROMIUM': {
3996 'client_test': False,
4001 'DiscardFramebufferEXT': {
4004 'decoder_func': 'DoDiscardFramebufferEXT',
4006 'client_test': False,
4007 'extension_flag': 'ext_discard_framebuffer',
4010 'LoseContextCHROMIUM': {
4011 'decoder_func': 'DoLoseContextCHROMIUM',
4017 'InsertSyncPointCHROMIUM': {
4018 'type': 'HandWritten',
4020 'extension': "CHROMIUM_sync_point",
4024 'WaitSyncPointCHROMIUM': {
4027 'extension': "CHROMIUM_sync_point",
4031 'DiscardBackbufferCHROMIUM': {
4038 'ScheduleOverlayPlaneCHROMIUM': {
4042 'client_test': False,
4046 'MatrixLoadfCHROMIUM': {
4049 'data_type': 'GLfloat',
4050 'decoder_func': 'DoMatrixLoadfCHROMIUM',
4051 'gl_test_func': 'glMatrixLoadfEXT',
4054 'extension_flag': 'chromium_path_rendering',
4056 'MatrixLoadIdentityCHROMIUM': {
4057 'decoder_func': 'DoMatrixLoadIdentityCHROMIUM',
4058 'gl_test_func': 'glMatrixLoadIdentityEXT',
4061 'extension_flag': 'chromium_path_rendering',
4063 'GenPathsCHROMIUM': {
4065 'cmd_args': 'GLuint first_client_id, GLsizei range',
4068 'extension_flag': 'chromium_path_rendering',
4070 'DeletePathsCHROMIUM': {
4072 'cmd_args': 'GLuint first_client_id, GLsizei range',
4077 'extension_flag': 'chromium_path_rendering',
4081 'decoder_func': 'DoIsPathCHROMIUM',
4082 'gl_test_func': 'glIsPathNV',
4085 'extension_flag': 'chromium_path_rendering',
4087 'PathCommandsCHROMIUM': {
4092 'extension_flag': 'chromium_path_rendering',
4094 'PathParameterfCHROMIUM': {
4098 'extension_flag': 'chromium_path_rendering',
4100 'PathParameteriCHROMIUM': {
4104 'extension_flag': 'chromium_path_rendering',
4106 'PathStencilFuncCHROMIUM': {
4108 'state': 'PathStencilFuncCHROMIUM',
4109 'decoder_func': 'glPathStencilFuncNV',
4112 'extension_flag': 'chromium_path_rendering',
4114 'StencilFillPathCHROMIUM': {
4118 'extension_flag': 'chromium_path_rendering',
4120 'StencilStrokePathCHROMIUM': {
4124 'extension_flag': 'chromium_path_rendering',
4126 'CoverFillPathCHROMIUM': {
4130 'extension_flag': 'chromium_path_rendering',
4132 'CoverStrokePathCHROMIUM': {
4136 'extension_flag': 'chromium_path_rendering',
4138 'StencilThenCoverFillPathCHROMIUM': {
4142 'extension_flag': 'chromium_path_rendering',
4144 'StencilThenCoverStrokePathCHROMIUM': {
4148 'extension_flag': 'chromium_path_rendering',
4154 def Grouper(n
, iterable
, fillvalue
=None):
4155 """Collect data into fixed-length chunks or blocks"""
4156 args
= [iter(iterable
)] * n
4157 return itertools
.izip_longest(fillvalue
=fillvalue
, *args
)
4160 def SplitWords(input_string
):
4161 """Split by '_' if found, otherwise split at uppercase/numeric chars.
4163 Will split "some_TEXT" into ["some", "TEXT"], "CamelCase" into ["Camel",
4164 "Case"], and "Vector3" into ["Vector", "3"].
4166 if input_string
.find('_') > -1:
4167 # 'some_TEXT_' -> 'some TEXT'
4168 return input_string
.replace('_', ' ').strip().split()
4170 if re
.search('[A-Z]', input_string
) and re
.search('[a-z]', input_string
):
4172 # look for capitalization to cut input_strings
4173 # 'SomeText' -> 'Some Text'
4174 input_string
= re
.sub('([A-Z])', r
' \1', input_string
).strip()
4175 # 'Vector3' -> 'Vector 3'
4176 input_string
= re
.sub('([^0-9])([0-9])', r
'\1 \2', input_string
)
4177 return input_string
.split()
4179 def ToUnderscore(input_string
):
4180 """converts CamelCase to camel_case."""
4181 words
= SplitWords(input_string
)
4182 return '_'.join([word
.lower() for word
in words
])
4184 def CachedStateName(item
):
4185 if item
.get('cached', False):
4186 return 'cached_' + item
['name']
4189 def ToGLExtensionString(extension_flag
):
4190 """Returns GL-type extension string of a extension flag."""
4191 if extension_flag
== "oes_compressed_etc1_rgb8_texture":
4192 return "OES_compressed_ETC1_RGB8_texture" # Fixup inconsitency with rgb8,
4194 uppercase_words
= [ 'img', 'ext', 'arb', 'chromium', 'oes', 'amd', 'bgra8888',
4195 'egl', 'atc', 'etc1', 'angle']
4196 parts
= extension_flag
.split('_')
4198 [part
.upper() if part
in uppercase_words
else part
for part
in parts
])
4200 def ToCamelCase(input_string
):
4201 """converts ABC_underscore_case to ABCUnderscoreCase."""
4202 return ''.join(w
[0].upper() + w
[1:] for w
in input_string
.split('_'))
4204 def GetGLGetTypeConversion(result_type
, value_type
, value
):
4205 """Makes a gl compatible type conversion string for accessing state variables.
4207 Useful when accessing state variables through glGetXXX calls.
4208 glGet documetation (for example, the manual pages):
4209 [...] If glGetIntegerv is called, [...] most floating-point values are
4210 rounded to the nearest integer value. [...]
4213 result_type: the gl type to be obtained
4214 value_type: the GL type of the state variable
4215 value: the name of the state variable
4218 String that converts the state variable to desired GL type according to GL
4222 if result_type
== 'GLint':
4223 if value_type
== 'GLfloat':
4224 return 'static_cast<GLint>(round(%s))' % value
4225 return 'static_cast<%s>(%s)' % (result_type
, value
)
4227 class CWriter(object):
4228 """Writes to a file formatting it for Google's style guidelines."""
4230 def __init__(self
, filename
):
4231 self
.filename
= filename
4234 def Write(self
, string
):
4235 """Writes a string to a file spliting if it's > 80 characters."""
4236 lines
= string
.splitlines()
4237 num_lines
= len(lines
)
4238 for ii
in range(0, num_lines
):
4239 self
.content
.append(lines
[ii
])
4240 if ii
< (num_lines
- 1) or string
[-1] == '\n':
4241 self
.content
.append('\n')
4244 """Close the file."""
4245 content
= "".join(self
.content
)
4247 if os
.path
.exists(self
.filename
):
4248 old_file
= open(self
.filename
, "rb");
4249 old_content
= old_file
.read()
4251 if content
== old_content
:
4254 file = open(self
.filename
, "wb")
4259 class CHeaderWriter(CWriter
):
4260 """Writes a C Header file."""
4262 _non_alnum_re
= re
.compile(r
'[^a-zA-Z0-9]')
4264 def __init__(self
, filename
, file_comment
= None):
4265 CWriter
.__init
__(self
, filename
)
4267 base
= os
.path
.abspath(filename
)
4268 while os
.path
.basename(base
) != 'src':
4269 new_base
= os
.path
.dirname(base
)
4270 assert new_base
!= base
# Prevent infinite loop.
4273 hpath
= os
.path
.relpath(filename
, base
)
4274 self
.guard
= self
._non
_alnum
_re
.sub('_', hpath
).upper() + '_'
4276 self
.Write(_LICENSE
)
4277 self
.Write(_DO_NOT_EDIT_WARNING
)
4278 if not file_comment
== None:
4279 self
.Write(file_comment
)
4280 self
.Write("#ifndef %s\n" % self
.guard
)
4281 self
.Write("#define %s\n\n" % self
.guard
)
4284 self
.Write("#endif // %s\n\n" % self
.guard
)
4287 class TypeHandler(object):
4288 """This class emits code for a particular type of function."""
4290 _remove_expected_call_re
= re
.compile(r
' EXPECT_CALL.*?;\n', re
.S
)
4295 def InitFunction(self
, func
):
4296 """Add or adjust anything type specific for this function."""
4297 if func
.GetInfo('needs_size') and not func
.name
.endswith('Bucket'):
4298 func
.AddCmdArg(DataSizeArgument('data_size'))
4300 def NeedsDataTransferFunction(self
, func
):
4301 """Overriden from TypeHandler."""
4302 return func
.num_pointer_args
>= 1
4304 def WriteStruct(self
, func
, file):
4305 """Writes a structure that matches the arguments to a function."""
4306 comment
= func
.GetInfo('cmd_comment')
4307 if not comment
== None:
4309 file.Write("struct %s {\n" % func
.name
)
4310 file.Write(" typedef %s ValueType;\n" % func
.name
)
4311 file.Write(" static const CommandId kCmdId = k%s;\n" % func
.name
)
4312 func
.WriteCmdArgFlag(file)
4313 func
.WriteCmdFlag(file)
4315 result
= func
.GetInfo('result')
4316 if not result
== None:
4317 if len(result
) == 1:
4318 file.Write(" typedef %s Result;\n\n" % result
[0])
4320 file.Write(" struct Result {\n")
4322 file.Write(" %s;\n" % line
)
4323 file.Write(" };\n\n")
4325 func
.WriteCmdComputeSize(file)
4326 func
.WriteCmdSetHeader(file)
4327 func
.WriteCmdInit(file)
4328 func
.WriteCmdSet(file)
4330 file.Write(" gpu::CommandHeader header;\n")
4331 args
= func
.GetCmdArgs()
4333 file.Write(" %s %s;\n" % (arg
.cmd_type
, arg
.name
))
4335 consts
= func
.GetCmdConstants()
4336 for const
in consts
:
4337 file.Write(" static const %s %s = %s;\n" %
4338 (const
.cmd_type
, const
.name
, const
.GetConstantValue()))
4343 size
= len(args
) * _SIZE_OF_UINT32
+ _SIZE_OF_COMMAND_HEADER
4344 file.Write("static_assert(sizeof(%s) == %d,\n" % (func
.name
, size
))
4345 file.Write(" \"size of %s should be %d\");\n" %
4347 file.Write("static_assert(offsetof(%s, header) == 0,\n" % func
.name
)
4348 file.Write(" \"offset of %s header should be 0\");\n" %
4350 offset
= _SIZE_OF_COMMAND_HEADER
4352 file.Write("static_assert(offsetof(%s, %s) == %d,\n" %
4353 (func
.name
, arg
.name
, offset
))
4354 file.Write(" \"offset of %s %s should be %d\");\n" %
4355 (func
.name
, arg
.name
, offset
))
4356 offset
+= _SIZE_OF_UINT32
4357 if not result
== None and len(result
) > 1:
4360 parts
= line
.split()
4363 static_assert(offsetof(%(cmd_name)s::Result, %(field_name)s) == %(offset)d,
4364 "offset of %(cmd_name)s Result %(field_name)s should be "
4367 file.Write((check
.strip() + "\n") % {
4368 'cmd_name': func
.name
,
4372 offset
+= _SIZE_OF_UINT32
4375 def WriteHandlerImplementation(self
, func
, file):
4376 """Writes the handler implementation for this command."""
4377 if func
.IsUnsafe() and func
.GetInfo('id_mapping'):
4378 code_no_gen
= """ if (!group_->Get%(type)sServiceId(
4379 %(var)s, &%(service_var)s)) {
4380 LOCAL_SET_GL_ERROR(GL_INVALID_OPERATION, "%(func)s", "invalid %(var)s id");
4381 return error::kNoError;
4384 code_gen
= """ if (!group_->Get%(type)sServiceId(
4385 %(var)s, &%(service_var)s)) {
4386 if (!group_->bind_generates_resource()) {
4388 GL_INVALID_OPERATION, "%(func)s", "invalid %(var)s id");
4389 return error::kNoError;
4391 GLuint client_id = %(var)s;
4392 gl%(gen_func)s(1, &%(service_var)s);
4393 Create%(type)s(client_id, %(service_var)s);
4396 gen_func
= func
.GetInfo('gen_func')
4397 for id_type
in func
.GetInfo('id_mapping'):
4398 service_var
= id_type
.lower()
4399 if id_type
== 'Sync':
4400 service_var
= "service_%s" % service_var
4401 file.Write(" GLsync %s = 0;\n" % service_var
)
4402 if gen_func
and id_type
in gen_func
:
4403 file.Write(code_gen
% { 'type': id_type
,
4404 'var': id_type
.lower(),
4405 'service_var': service_var
,
4406 'func': func
.GetGLFunctionName(),
4407 'gen_func': gen_func
})
4409 file.Write(code_no_gen
% { 'type': id_type
,
4410 'var': id_type
.lower(),
4411 'service_var': service_var
,
4412 'func': func
.GetGLFunctionName() })
4414 for arg
in func
.GetOriginalArgs():
4415 if arg
.type == "GLsync":
4416 args
.append("service_%s" % arg
.name
)
4417 elif arg
.name
.endswith("size") and arg
.type == "GLsizei":
4418 args
.append("num_%s" % func
.GetLastOriginalArg().name
)
4419 elif arg
.name
== "length":
4420 args
.append("nullptr")
4422 args
.append(arg
.name
)
4423 file.Write(" %s(%s);\n" %
4424 (func
.GetGLFunctionName(), ", ".join(args
)))
4426 def WriteCmdSizeTest(self
, func
, file):
4427 """Writes the size test for a command."""
4428 file.Write(" EXPECT_EQ(sizeof(cmd), cmd.header.size * 4u);\n")
4430 def WriteFormatTest(self
, func
, file):
4431 """Writes a format test for a command."""
4432 file.Write("TEST_F(GLES2FormatTest, %s) {\n" % func
.name
)
4433 file.Write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
4434 (func
.name
, func
.name
))
4435 file.Write(" void* next_cmd = cmd.Set(\n")
4437 args
= func
.GetCmdArgs()
4438 for value
, arg
in enumerate(args
):
4439 file.Write(",\n static_cast<%s>(%d)" % (arg
.type, value
+ 11))
4441 file.Write(" EXPECT_EQ(static_cast<uint32_t>(cmds::%s::kCmdId),\n" %
4443 file.Write(" cmd.header.command);\n")
4444 func
.type_handler
.WriteCmdSizeTest(func
, file)
4445 for value
, arg
in enumerate(args
):
4446 file.Write(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);\n" %
4447 (arg
.type, value
+ 11, arg
.name
))
4448 file.Write(" CheckBytesWrittenMatchesExpectedSize(\n")
4449 file.Write(" next_cmd, sizeof(cmd));\n")
4453 def WriteImmediateFormatTest(self
, func
, file):
4454 """Writes a format test for an immediate version of a command."""
4457 def WriteBucketFormatTest(self
, func
, file):
4458 """Writes a format test for a bucket version of a command."""
4461 def WriteGetDataSizeCode(self
, func
, file):
4462 """Writes the code to set data_size used in validation"""
4465 def WriteImmediateCmdSizeTest(self
, func
, file):
4466 """Writes a size test for an immediate version of a command."""
4467 file.Write(" // TODO(gman): Compute correct size.\n")
4468 file.Write(" EXPECT_EQ(sizeof(cmd), cmd.header.size * 4u);\n")
4470 def __WriteIdMapping(self
, func
, file):
4471 """Writes client side / service side ID mapping."""
4472 if not func
.IsUnsafe() or not func
.GetInfo('id_mapping'):
4474 for id_type
in func
.GetInfo('id_mapping'):
4475 file.Write(" group_->Get%sServiceId(%s, &%s);\n" %
4476 (id_type
, id_type
.lower(), id_type
.lower()))
4478 def WriteImmediateHandlerImplementation (self
, func
, file):
4479 """Writes the handler impl for the immediate version of a command."""
4480 self
.__WriteIdMapping
(func
, file)
4481 file.Write(" %s(%s);\n" %
4482 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
4484 def WriteBucketHandlerImplementation (self
, func
, file):
4485 """Writes the handler impl for the bucket version of a command."""
4486 self
.__WriteIdMapping
(func
, file)
4487 file.Write(" %s(%s);\n" %
4488 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
4490 def WriteServiceHandlerFunctionHeader(self
, func
, file):
4491 """Writes function header for service implementation handlers."""
4492 file.Write("""error::Error GLES2DecoderImpl::Handle%(name)s(
4493 uint32_t immediate_data_size, const void* cmd_data) {
4494 """ % {'name': func
.name
})
4496 file.Write("""if (!unsafe_es3_apis_enabled())
4497 return error::kUnknownCommand;
4499 file.Write("""const gles2::cmds::%(name)s& c =
4500 *static_cast<const gles2::cmds::%(name)s*>(cmd_data);
4502 """ % {'name': func
.name
})
4504 def WriteServiceImplementation(self
, func
, file):
4505 """Writes the service implementation for a command."""
4506 self
.WriteServiceHandlerFunctionHeader(func
, file)
4507 self
.WriteHandlerExtensionCheck(func
, file)
4508 self
.WriteHandlerDeferReadWrite(func
, file);
4509 if len(func
.GetOriginalArgs()) > 0:
4510 last_arg
= func
.GetLastOriginalArg()
4511 all_but_last_arg
= func
.GetOriginalArgs()[:-1]
4512 for arg
in all_but_last_arg
:
4513 arg
.WriteGetCode(file)
4514 self
.WriteGetDataSizeCode(func
, file)
4515 last_arg
.WriteGetCode(file)
4516 func
.WriteHandlerValidation(file)
4517 func
.WriteHandlerImplementation(file)
4518 file.Write(" return error::kNoError;\n")
4522 def WriteImmediateServiceImplementation(self
, func
, file):
4523 """Writes the service implementation for an immediate version of command."""
4524 self
.WriteServiceHandlerFunctionHeader(func
, file)
4525 self
.WriteHandlerExtensionCheck(func
, file)
4526 self
.WriteHandlerDeferReadWrite(func
, file);
4527 for arg
in func
.GetOriginalArgs():
4529 self
.WriteGetDataSizeCode(func
, file)
4530 arg
.WriteGetCode(file)
4531 func
.WriteHandlerValidation(file)
4532 func
.WriteHandlerImplementation(file)
4533 file.Write(" return error::kNoError;\n")
4537 def WriteBucketServiceImplementation(self
, func
, file):
4538 """Writes the service implementation for a bucket version of command."""
4539 self
.WriteServiceHandlerFunctionHeader(func
, file)
4540 self
.WriteHandlerExtensionCheck(func
, file)
4541 self
.WriteHandlerDeferReadWrite(func
, file);
4542 for arg
in func
.GetCmdArgs():
4543 arg
.WriteGetCode(file)
4544 func
.WriteHandlerValidation(file)
4545 func
.WriteHandlerImplementation(file)
4546 file.Write(" return error::kNoError;\n")
4550 def WriteHandlerExtensionCheck(self
, func
, file):
4551 if func
.GetInfo('extension_flag'):
4552 file.Write(" if (!features().%s) {\n" % func
.GetInfo('extension_flag'))
4553 file.Write(" LOCAL_SET_GL_ERROR(GL_INVALID_OPERATION, \"gl%s\","
4554 " \"function not available\");\n" % func
.original_name
)
4555 file.Write(" return error::kNoError;")
4556 file.Write(" }\n\n")
4558 def WriteHandlerDeferReadWrite(self
, func
, file):
4559 """Writes the code to handle deferring reads or writes."""
4560 defer_draws
= func
.GetInfo('defer_draws')
4561 defer_reads
= func
.GetInfo('defer_reads')
4562 if defer_draws
or defer_reads
:
4563 file.Write(" error::Error error;\n")
4565 file.Write(" error = WillAccessBoundFramebufferForDraw();\n")
4566 file.Write(" if (error != error::kNoError)\n")
4567 file.Write(" return error;\n")
4569 file.Write(" error = WillAccessBoundFramebufferForRead();\n")
4570 file.Write(" if (error != error::kNoError)\n")
4571 file.Write(" return error;\n")
4573 def WriteValidUnitTest(self
, func
, file, test
, *extras
):
4574 """Writes a valid unit test for the service implementation."""
4575 if func
.GetInfo('expectation') == False:
4576 test
= self
._remove
_expected
_call
_re
.sub('', test
)
4579 arg
.GetValidArg(func
) \
4580 for arg
in func
.GetOriginalArgs() if not arg
.IsConstant()
4583 arg
.GetValidGLArg(func
) \
4584 for arg
in func
.GetOriginalArgs()
4586 gl_func_name
= func
.GetGLTestFunctionName()
4589 'gl_func_name': gl_func_name
,
4590 'args': ", ".join(arg_strings
),
4591 'gl_args': ", ".join(gl_arg_strings
),
4593 for extra
in extras
:
4596 while (old_test
!= test
):
4599 file.Write(test
% vars)
4601 def WriteInvalidUnitTest(self
, func
, file, test
, *extras
):
4602 """Writes an invalid unit test for the service implementation."""
4605 for invalid_arg_index
, invalid_arg
in enumerate(func
.GetOriginalArgs()):
4606 # Service implementation does not test constants, as they are not part of
4607 # the call in the service side.
4608 if invalid_arg
.IsConstant():
4611 num_invalid_values
= invalid_arg
.GetNumInvalidValues(func
)
4612 for value_index
in range(0, num_invalid_values
):
4614 parse_result
= "kNoError"
4616 for arg
in func
.GetOriginalArgs():
4617 if arg
.IsConstant():
4619 if invalid_arg
is arg
:
4620 (arg_string
, parse_result
, gl_error
) = arg
.GetInvalidArg(
4623 arg_string
= arg
.GetValidArg(func
)
4624 arg_strings
.append(arg_string
)
4626 for arg
in func
.GetOriginalArgs():
4627 gl_arg_strings
.append("_")
4628 gl_func_name
= func
.GetGLTestFunctionName()
4630 if not gl_error
== None:
4631 gl_error_test
= '\n EXPECT_EQ(%s, GetGLError());' % gl_error
4635 'arg_index': invalid_arg_index
,
4636 'value_index': value_index
,
4637 'gl_func_name': gl_func_name
,
4638 'args': ", ".join(arg_strings
),
4639 'all_but_last_args': ", ".join(arg_strings
[:-1]),
4640 'gl_args': ", ".join(gl_arg_strings
),
4641 'parse_result': parse_result
,
4642 'gl_error_test': gl_error_test
,
4644 for extra
in extras
:
4646 file.Write(test
% vars)
4648 def WriteServiceUnitTest(self
, func
, file, *extras
):
4649 """Writes the service unit test for a command."""
4651 if func
.name
== 'Enable':
4653 TEST_P(%(test_name)s, %(name)sValidArgs) {
4654 SetupExpectationsForEnableDisable(%(gl_args)s, true);
4655 SpecializedSetup<cmds::%(name)s, 0>(true);
4657 cmd.Init(%(args)s);"""
4658 elif func
.name
== 'Disable':
4660 TEST_P(%(test_name)s, %(name)sValidArgs) {
4661 SetupExpectationsForEnableDisable(%(gl_args)s, false);
4662 SpecializedSetup<cmds::%(name)s, 0>(true);
4664 cmd.Init(%(args)s);"""
4667 TEST_P(%(test_name)s, %(name)sValidArgs) {
4668 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
4669 SpecializedSetup<cmds::%(name)s, 0>(true);
4671 cmd.Init(%(args)s);"""
4674 decoder_->set_unsafe_es3_apis_enabled(true);
4675 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4676 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4677 decoder_->set_unsafe_es3_apis_enabled(false);
4678 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));
4683 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4684 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4687 self
.WriteValidUnitTest(func
, file, valid_test
, *extras
)
4689 if not func
.IsUnsafe():
4691 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
4692 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
4693 SpecializedSetup<cmds::%(name)s, 0>(false);
4696 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
4699 self
.WriteInvalidUnitTest(func
, file, invalid_test
, *extras
)
4701 def WriteImmediateServiceUnitTest(self
, func
, file, *extras
):
4702 """Writes the service unit test for an immediate command."""
4703 file.Write("// TODO(gman): %s\n" % func
.name
)
4705 def WriteImmediateValidationCode(self
, func
, file):
4706 """Writes the validation code for an immediate version of a command."""
4709 def WriteBucketServiceUnitTest(self
, func
, file, *extras
):
4710 """Writes the service unit test for a bucket command."""
4711 file.Write("// TODO(gman): %s\n" % func
.name
)
4713 def WriteBucketValidationCode(self
, func
, file):
4714 """Writes the validation code for a bucket version of a command."""
4715 file.Write("// TODO(gman): %s\n" % func
.name
)
4717 def WriteGLES2ImplementationDeclaration(self
, func
, file):
4718 """Writes the GLES2 Implemention declaration."""
4719 impl_decl
= func
.GetInfo('impl_decl')
4720 if impl_decl
== None or impl_decl
== True:
4721 file.Write("%s %s(%s) override;\n" %
4722 (func
.return_type
, func
.original_name
,
4723 func
.MakeTypedOriginalArgString("")))
4726 def WriteGLES2CLibImplementation(self
, func
, file):
4727 file.Write("%s GLES2%s(%s) {\n" %
4728 (func
.return_type
, func
.name
,
4729 func
.MakeTypedOriginalArgString("")))
4730 result_string
= "return "
4731 if func
.return_type
== "void":
4733 file.Write(" %sgles2::GetGLContext()->%s(%s);\n" %
4734 (result_string
, func
.original_name
,
4735 func
.MakeOriginalArgString("")))
4738 def WriteGLES2Header(self
, func
, file):
4739 """Writes a re-write macro for GLES"""
4740 file.Write("#define gl%s GLES2_GET_FUN(%s)\n" %(func
.name
, func
.name
))
4742 def WriteClientGLCallLog(self
, func
, file):
4743 """Writes a logging macro for the client side code."""
4745 if len(func
.GetOriginalArgs()):
4748 ' GPU_CLIENT_LOG("[" << GetLogPrefix() << "] gl%s("%s%s << ")");\n' %
4749 (func
.original_name
, comma
, func
.MakeLogArgString()))
4751 def WriteClientGLReturnLog(self
, func
, file):
4752 """Writes the return value logging code."""
4753 if func
.return_type
!= "void":
4754 file.Write(' GPU_CLIENT_LOG("return:" << result)\n')
4756 def WriteGLES2ImplementationHeader(self
, func
, file):
4757 """Writes the GLES2 Implemention."""
4758 self
.WriteGLES2ImplementationDeclaration(func
, file)
4760 def WriteGLES2TraceImplementationHeader(self
, func
, file):
4761 """Writes the GLES2 Trace Implemention header."""
4762 file.Write("%s %s(%s) override;\n" %
4763 (func
.return_type
, func
.original_name
,
4764 func
.MakeTypedOriginalArgString("")))
4766 def WriteGLES2TraceImplementation(self
, func
, file):
4767 """Writes the GLES2 Trace Implemention."""
4768 file.Write("%s GLES2TraceImplementation::%s(%s) {\n" %
4769 (func
.return_type
, func
.original_name
,
4770 func
.MakeTypedOriginalArgString("")))
4771 result_string
= "return "
4772 if func
.return_type
== "void":
4774 file.Write(' TRACE_EVENT_BINARY_EFFICIENT0("gpu", "GLES2Trace::%s");\n' %
4776 file.Write(" %sgl_->%s(%s);\n" %
4777 (result_string
, func
.name
, func
.MakeOriginalArgString("")))
4781 def WriteGLES2Implementation(self
, func
, file):
4782 """Writes the GLES2 Implemention."""
4783 impl_func
= func
.GetInfo('impl_func')
4784 impl_decl
= func
.GetInfo('impl_decl')
4785 gen_cmd
= func
.GetInfo('gen_cmd')
4786 if (func
.can_auto_generate
and
4787 (impl_func
== None or impl_func
== True) and
4788 (impl_decl
== None or impl_decl
== True) and
4789 (gen_cmd
== None or gen_cmd
== True)):
4790 file.Write("%s GLES2Implementation::%s(%s) {\n" %
4791 (func
.return_type
, func
.original_name
,
4792 func
.MakeTypedOriginalArgString("")))
4793 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
4794 self
.WriteClientGLCallLog(func
, file)
4795 func
.WriteDestinationInitalizationValidation(file)
4796 for arg
in func
.GetOriginalArgs():
4797 arg
.WriteClientSideValidationCode(file, func
)
4798 file.Write(" helper_->%s(%s);\n" %
4799 (func
.name
, func
.MakeHelperArgString("")))
4800 file.Write(" CheckGLError();\n")
4801 self
.WriteClientGLReturnLog(func
, file)
4805 def WriteGLES2InterfaceHeader(self
, func
, file):
4806 """Writes the GLES2 Interface."""
4807 file.Write("virtual %s %s(%s) = 0;\n" %
4808 (func
.return_type
, func
.original_name
,
4809 func
.MakeTypedOriginalArgString("")))
4811 def WriteMojoGLES2ImplHeader(self
, func
, file):
4812 """Writes the Mojo GLES2 implementation header."""
4813 file.Write("%s %s(%s) override;\n" %
4814 (func
.return_type
, func
.original_name
,
4815 func
.MakeTypedOriginalArgString("")))
4817 def WriteMojoGLES2Impl(self
, func
, file):
4818 """Writes the Mojo GLES2 implementation."""
4819 file.Write("%s MojoGLES2Impl::%s(%s) {\n" %
4820 (func
.return_type
, func
.original_name
,
4821 func
.MakeTypedOriginalArgString("")))
4822 extensions
= ["CHROMIUM_sync_point", "CHROMIUM_texture_mailbox",
4823 "CHROMIUM_sub_image", "CHROMIUM_miscellaneous",
4824 "occlusion_query_EXT", "CHROMIUM_image",
4825 "CHROMIUM_copy_texture",
4826 "CHROMIUM_pixel_transfer_buffer_object"]
4827 if func
.IsCoreGLFunction() or func
.GetInfo("extension") in extensions
:
4828 file.Write("MojoGLES2MakeCurrent(context_);");
4829 func_return
= "gl" + func
.original_name
+ "(" + \
4830 func
.MakeOriginalArgString("") + ");"
4831 if func
.return_type
== "void":
4832 file.Write(func_return
);
4834 file.Write("return " + func_return
);
4836 file.Write("NOTREACHED() << \"Unimplemented %s.\";\n" %
4837 func
.original_name
);
4838 if func
.return_type
!= "void":
4839 file.Write("return 0;")
4842 def WriteGLES2InterfaceStub(self
, func
, file):
4843 """Writes the GLES2 Interface stub declaration."""
4844 file.Write("%s %s(%s) override;\n" %
4845 (func
.return_type
, func
.original_name
,
4846 func
.MakeTypedOriginalArgString("")))
4848 def WriteGLES2InterfaceStubImpl(self
, func
, file):
4849 """Writes the GLES2 Interface stub declaration."""
4850 args
= func
.GetOriginalArgs()
4851 arg_string
= ", ".join(
4852 ["%s /* %s */" % (arg
.type, arg
.name
) for arg
in args
])
4853 file.Write("%s GLES2InterfaceStub::%s(%s) {\n" %
4854 (func
.return_type
, func
.original_name
, arg_string
))
4855 if func
.return_type
!= "void":
4856 file.Write(" return 0;\n")
4859 def WriteGLES2ImplementationUnitTest(self
, func
, file):
4860 """Writes the GLES2 Implemention unit test."""
4861 client_test
= func
.GetInfo('client_test')
4862 if (func
.can_auto_generate
and
4863 (client_test
== None or client_test
== True)):
4865 TEST_F(GLES2ImplementationTest, %(name)s) {
4870 expected.cmd.Init(%(cmd_args)s);
4872 gl_->%(name)s(%(args)s);
4873 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
4877 arg
.GetValidClientSideCmdArg(func
) for arg
in func
.GetCmdArgs()
4881 arg
.GetValidClientSideArg(func
) for arg
in func
.GetOriginalArgs()
4886 'args': ", ".join(gl_arg_strings
),
4887 'cmd_args': ", ".join(cmd_arg_strings
),
4890 # Test constants for invalid values, as they are not tested by the
4892 constants
= [arg
for arg
in func
.GetOriginalArgs() if arg
.IsConstant()]
4895 TEST_F(GLES2ImplementationTest, %(name)sInvalidConstantArg%(invalid_index)d) {
4896 gl_->%(name)s(%(args)s);
4897 EXPECT_TRUE(NoCommandsWritten());
4898 EXPECT_EQ(%(gl_error)s, CheckError());
4901 for invalid_arg
in constants
:
4903 invalid
= invalid_arg
.GetInvalidArg(func
)
4904 for arg
in func
.GetOriginalArgs():
4905 if arg
is invalid_arg
:
4906 gl_arg_strings
.append(invalid
[0])
4908 gl_arg_strings
.append(arg
.GetValidClientSideArg(func
))
4912 'invalid_index': func
.GetOriginalArgs().index(invalid_arg
),
4913 'args': ", ".join(gl_arg_strings
),
4914 'gl_error': invalid
[2],
4917 if client_test
!= False:
4918 file.Write("// TODO(zmo): Implement unit test for %s\n" % func
.name
)
4920 def WriteDestinationInitalizationValidation(self
, func
, file):
4921 """Writes the client side destintion initialization validation."""
4922 for arg
in func
.GetOriginalArgs():
4923 arg
.WriteDestinationInitalizationValidation(file, func
)
4925 def WriteTraceEvent(self
, func
, file):
4926 file.Write(' TRACE_EVENT0("gpu", "GLES2Implementation::%s");\n' %
4929 def WriteImmediateCmdComputeSize(self
, func
, file):
4930 """Writes the size computation code for the immediate version of a cmd."""
4931 file.Write(" static uint32_t ComputeSize(uint32_t size_in_bytes) {\n")
4932 file.Write(" return static_cast<uint32_t>(\n")
4933 file.Write(" sizeof(ValueType) + // NOLINT\n")
4934 file.Write(" RoundSizeToMultipleOfEntries(size_in_bytes));\n")
4938 def WriteImmediateCmdSetHeader(self
, func
, file):
4939 """Writes the SetHeader function for the immediate version of a cmd."""
4940 file.Write(" void SetHeader(uint32_t size_in_bytes) {\n")
4941 file.Write(" header.SetCmdByTotalSize<ValueType>(size_in_bytes);\n")
4945 def WriteImmediateCmdInit(self
, func
, file):
4946 """Writes the Init function for the immediate version of a command."""
4947 raise NotImplementedError(func
.name
)
4949 def WriteImmediateCmdSet(self
, func
, file):
4950 """Writes the Set function for the immediate version of a command."""
4951 raise NotImplementedError(func
.name
)
4953 def WriteCmdHelper(self
, func
, file):
4954 """Writes the cmd helper definition for a cmd."""
4955 code
= """ void %(name)s(%(typed_args)s) {
4956 gles2::cmds::%(name)s* c = GetCmdSpace<gles2::cmds::%(name)s>();
4965 "typed_args": func
.MakeTypedCmdArgString(""),
4966 "args": func
.MakeCmdArgString(""),
4969 def WriteImmediateCmdHelper(self
, func
, file):
4970 """Writes the cmd helper definition for the immediate version of a cmd."""
4971 code
= """ void %(name)s(%(typed_args)s) {
4972 const uint32_t s = 0; // TODO(gman): compute correct size
4973 gles2::cmds::%(name)s* c =
4974 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(s);
4983 "typed_args": func
.MakeTypedCmdArgString(""),
4984 "args": func
.MakeCmdArgString(""),
4988 class StateSetHandler(TypeHandler
):
4989 """Handler for commands that simply set state."""
4992 TypeHandler
.__init
__(self
)
4994 def WriteHandlerImplementation(self
, func
, file):
4995 """Overrriden from TypeHandler."""
4996 state_name
= func
.GetInfo('state')
4997 state
= _STATES
[state_name
]
4998 states
= state
['states']
4999 args
= func
.GetOriginalArgs()
5000 for ndx
,item
in enumerate(states
):
5002 if 'range_checks' in item
:
5003 for range_check
in item
['range_checks']:
5004 code
.append("%s %s" % (args
[ndx
].name
, range_check
['check']))
5005 if 'nan_check' in item
:
5006 # Drivers might generate an INVALID_VALUE error when a value is set
5007 # to NaN. This is allowed behavior under GLES 3.0 section 2.1.1 or
5008 # OpenGL 4.5 section 2.3.4.1 - providing NaN allows undefined results.
5009 # Make this behavior consistent within Chromium, and avoid leaking GL
5010 # errors by generating the error in the command buffer instead of
5011 # letting the GL driver generate it.
5012 code
.append("std::isnan(%s)" % args
[ndx
].name
)
5014 file.Write(" if (%s) {\n" % " ||\n ".join(code
))
5016 ' LOCAL_SET_GL_ERROR(GL_INVALID_VALUE,'
5017 ' "%s", "%s out of range");\n' %
5018 (func
.name
, args
[ndx
].name
))
5019 file.Write(" return error::kNoError;\n")
5022 for ndx
,item
in enumerate(states
):
5023 code
.append("state_.%s != %s" % (item
['name'], args
[ndx
].name
))
5024 file.Write(" if (%s) {\n" % " ||\n ".join(code
))
5025 for ndx
,item
in enumerate(states
):
5026 file.Write(" state_.%s = %s;\n" % (item
['name'], args
[ndx
].name
))
5027 if 'state_flag' in state
:
5028 file.Write(" %s = true;\n" % state
['state_flag'])
5029 if not func
.GetInfo("no_gl"):
5030 for ndx
,item
in enumerate(states
):
5031 if item
.get('cached', False):
5032 file.Write(" state_.%s = %s;\n" %
5033 (CachedStateName(item
), args
[ndx
].name
))
5034 file.Write(" %s(%s);\n" %
5035 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
5038 def WriteServiceUnitTest(self
, func
, file, *extras
):
5039 """Overrriden from TypeHandler."""
5040 TypeHandler
.WriteServiceUnitTest(self
, func
, file, *extras
)
5041 state_name
= func
.GetInfo('state')
5042 state
= _STATES
[state_name
]
5043 states
= state
['states']
5044 for ndx
,item
in enumerate(states
):
5045 if 'range_checks' in item
:
5046 for check_ndx
, range_check
in enumerate(item
['range_checks']):
5048 TEST_P(%(test_name)s, %(name)sInvalidValue%(ndx)d_%(check_ndx)d) {
5049 SpecializedSetup<cmds::%(name)s, 0>(false);
5052 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5053 EXPECT_EQ(GL_INVALID_VALUE, GetGLError());
5058 arg
.GetValidArg(func
) \
5059 for arg
in func
.GetOriginalArgs() if not arg
.IsConstant()
5062 arg_strings
[ndx
] = range_check
['test_value']
5066 'check_ndx': check_ndx
,
5067 'args': ", ".join(arg_strings
),
5069 for extra
in extras
:
5071 file.Write(valid_test
% vars)
5072 if 'nan_check' in item
:
5074 TEST_P(%(test_name)s, %(name)sNaNValue%(ndx)d) {
5075 SpecializedSetup<cmds::%(name)s, 0>(false);
5078 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5079 EXPECT_EQ(GL_INVALID_VALUE, GetGLError());
5084 arg
.GetValidArg(func
) \
5085 for arg
in func
.GetOriginalArgs() if not arg
.IsConstant()
5088 arg_strings
[ndx
] = 'nanf("")'
5092 'args': ", ".join(arg_strings
),
5094 for extra
in extras
:
5096 file.Write(valid_test
% vars)
5099 class StateSetRGBAlphaHandler(TypeHandler
):
5100 """Handler for commands that simply set state that have rgb/alpha."""
5103 TypeHandler
.__init
__(self
)
5105 def WriteHandlerImplementation(self
, func
, file):
5106 """Overrriden from TypeHandler."""
5107 state_name
= func
.GetInfo('state')
5108 state
= _STATES
[state_name
]
5109 states
= state
['states']
5110 args
= func
.GetOriginalArgs()
5111 num_args
= len(args
)
5113 for ndx
,item
in enumerate(states
):
5114 code
.append("state_.%s != %s" % (item
['name'], args
[ndx
% num_args
].name
))
5115 file.Write(" if (%s) {\n" % " ||\n ".join(code
))
5116 for ndx
, item
in enumerate(states
):
5117 file.Write(" state_.%s = %s;\n" %
5118 (item
['name'], args
[ndx
% num_args
].name
))
5119 if 'state_flag' in state
:
5120 file.Write(" %s = true;\n" % state
['state_flag'])
5121 if not func
.GetInfo("no_gl"):
5122 file.Write(" %s(%s);\n" %
5123 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
5127 class StateSetFrontBackSeparateHandler(TypeHandler
):
5128 """Handler for commands that simply set state that have front/back."""
5131 TypeHandler
.__init
__(self
)
5133 def WriteHandlerImplementation(self
, func
, file):
5134 """Overrriden from TypeHandler."""
5135 state_name
= func
.GetInfo('state')
5136 state
= _STATES
[state_name
]
5137 states
= state
['states']
5138 args
= func
.GetOriginalArgs()
5140 num_args
= len(args
)
5141 file.Write(" bool changed = false;\n")
5142 for group_ndx
, group
in enumerate(Grouper(num_args
- 1, states
)):
5143 file.Write(" if (%s == %s || %s == GL_FRONT_AND_BACK) {\n" %
5144 (face
, ('GL_FRONT', 'GL_BACK')[group_ndx
], face
))
5146 for ndx
, item
in enumerate(group
):
5147 code
.append("state_.%s != %s" % (item
['name'], args
[ndx
+ 1].name
))
5148 file.Write(" changed |= %s;\n" % " ||\n ".join(code
))
5150 file.Write(" if (changed) {\n")
5151 for group_ndx
, group
in enumerate(Grouper(num_args
- 1, states
)):
5152 file.Write(" if (%s == %s || %s == GL_FRONT_AND_BACK) {\n" %
5153 (face
, ('GL_FRONT', 'GL_BACK')[group_ndx
], face
))
5154 for ndx
, item
in enumerate(group
):
5155 file.Write(" state_.%s = %s;\n" %
5156 (item
['name'], args
[ndx
+ 1].name
))
5158 if 'state_flag' in state
:
5159 file.Write(" %s = true;\n" % state
['state_flag'])
5160 if not func
.GetInfo("no_gl"):
5161 file.Write(" %s(%s);\n" %
5162 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
5166 class StateSetFrontBackHandler(TypeHandler
):
5167 """Handler for commands that simply set state that set both front/back."""
5170 TypeHandler
.__init
__(self
)
5172 def WriteHandlerImplementation(self
, func
, file):
5173 """Overrriden from TypeHandler."""
5174 state_name
= func
.GetInfo('state')
5175 state
= _STATES
[state_name
]
5176 states
= state
['states']
5177 args
= func
.GetOriginalArgs()
5178 num_args
= len(args
)
5180 for group_ndx
, group
in enumerate(Grouper(num_args
, states
)):
5181 for ndx
, item
in enumerate(group
):
5182 code
.append("state_.%s != %s" % (item
['name'], args
[ndx
].name
))
5183 file.Write(" if (%s) {\n" % " ||\n ".join(code
))
5184 for group_ndx
, group
in enumerate(Grouper(num_args
, states
)):
5185 for ndx
, item
in enumerate(group
):
5186 file.Write(" state_.%s = %s;\n" % (item
['name'], args
[ndx
].name
))
5187 if 'state_flag' in state
:
5188 file.Write(" %s = true;\n" % state
['state_flag'])
5189 if not func
.GetInfo("no_gl"):
5190 file.Write(" %s(%s);\n" %
5191 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
5195 class StateSetNamedParameter(TypeHandler
):
5196 """Handler for commands that set a state chosen with an enum parameter."""
5199 TypeHandler
.__init
__(self
)
5201 def WriteHandlerImplementation(self
, func
, file):
5202 """Overridden from TypeHandler."""
5203 state_name
= func
.GetInfo('state')
5204 state
= _STATES
[state_name
]
5205 states
= state
['states']
5206 args
= func
.GetOriginalArgs()
5207 num_args
= len(args
)
5208 assert num_args
== 2
5209 file.Write(" switch (%s) {\n" % args
[0].name
)
5210 for state
in states
:
5211 file.Write(" case %s:\n" % state
['enum'])
5212 file.Write(" if (state_.%s != %s) {\n" %
5213 (state
['name'], args
[1].name
))
5214 file.Write(" state_.%s = %s;\n" % (state
['name'], args
[1].name
))
5215 if not func
.GetInfo("no_gl"):
5216 file.Write(" %s(%s);\n" %
5217 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
5219 file.Write(" break;\n")
5220 file.Write(" default:\n")
5221 file.Write(" NOTREACHED();\n")
5225 class CustomHandler(TypeHandler
):
5226 """Handler for commands that are auto-generated but require minor tweaks."""
5229 TypeHandler
.__init
__(self
)
5231 def WriteServiceImplementation(self
, func
, file):
5232 """Overrriden from TypeHandler."""
5235 def WriteImmediateServiceImplementation(self
, func
, file):
5236 """Overrriden from TypeHandler."""
5239 def WriteBucketServiceImplementation(self
, func
, file):
5240 """Overrriden from TypeHandler."""
5243 def WriteServiceUnitTest(self
, func
, file, *extras
):
5244 """Overrriden from TypeHandler."""
5245 file.Write("// TODO(gman): %s\n\n" % func
.name
)
5247 def WriteImmediateServiceUnitTest(self
, func
, file, *extras
):
5248 """Overrriden from TypeHandler."""
5249 file.Write("// TODO(gman): %s\n\n" % func
.name
)
5251 def WriteImmediateCmdGetTotalSize(self
, func
, file):
5252 """Overrriden from TypeHandler."""
5254 " uint32_t total_size = 0; // TODO(gman): get correct size.\n")
5256 def WriteImmediateCmdInit(self
, func
, file):
5257 """Overrriden from TypeHandler."""
5258 file.Write(" void Init(%s) {\n" % func
.MakeTypedCmdArgString("_"))
5259 self
.WriteImmediateCmdGetTotalSize(func
, file)
5260 file.Write(" SetHeader(total_size);\n")
5261 args
= func
.GetCmdArgs()
5263 file.Write(" %s = _%s;\n" % (arg
.name
, arg
.name
))
5267 def WriteImmediateCmdSet(self
, func
, file):
5268 """Overrriden from TypeHandler."""
5269 copy_args
= func
.MakeCmdArgString("_", False)
5270 file.Write(" void* Set(void* cmd%s) {\n" %
5271 func
.MakeTypedCmdArgString("_", True))
5272 self
.WriteImmediateCmdGetTotalSize(func
, file)
5273 file.Write(" static_cast<ValueType*>(cmd)->Init(%s);\n" % copy_args
)
5274 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
5275 "cmd, total_size);\n")
5280 class TodoHandler(CustomHandler
):
5281 """Handle for commands that are not yet implemented."""
5283 def NeedsDataTransferFunction(self
, func
):
5284 """Overriden from TypeHandler."""
5287 def WriteImmediateFormatTest(self
, func
, file):
5288 """Overrriden from TypeHandler."""
5291 def WriteGLES2ImplementationUnitTest(self
, func
, file):
5292 """Overrriden from TypeHandler."""
5295 def WriteGLES2Implementation(self
, func
, file):
5296 """Overrriden from TypeHandler."""
5297 file.Write("%s GLES2Implementation::%s(%s) {\n" %
5298 (func
.return_type
, func
.original_name
,
5299 func
.MakeTypedOriginalArgString("")))
5300 file.Write(" // TODO: for now this is a no-op\n")
5303 "GL_INVALID_OPERATION, \"gl%s\", \"not implemented\");\n" %
5305 if func
.return_type
!= "void":
5306 file.Write(" return 0;\n")
5310 def WriteServiceImplementation(self
, func
, file):
5311 """Overrriden from TypeHandler."""
5312 self
.WriteServiceHandlerFunctionHeader(func
, file)
5313 file.Write(" // TODO: for now this is a no-op\n")
5315 " LOCAL_SET_GL_ERROR("
5316 "GL_INVALID_OPERATION, \"gl%s\", \"not implemented\");\n" %
5318 file.Write(" return error::kNoError;\n")
5323 class HandWrittenHandler(CustomHandler
):
5324 """Handler for comands where everything must be written by hand."""
5326 def InitFunction(self
, func
):
5327 """Add or adjust anything type specific for this function."""
5328 CustomHandler
.InitFunction(self
, func
)
5329 func
.can_auto_generate
= False
5331 def NeedsDataTransferFunction(self
, func
):
5332 """Overriden from TypeHandler."""
5333 # If specified explicitly, force the data transfer method.
5334 if func
.GetInfo('data_transfer_methods'):
5338 def WriteStruct(self
, func
, file):
5339 """Overrriden from TypeHandler."""
5342 def WriteDocs(self
, func
, file):
5343 """Overrriden from TypeHandler."""
5346 def WriteServiceUnitTest(self
, func
, file, *extras
):
5347 """Overrriden from TypeHandler."""
5348 file.Write("// TODO(gman): %s\n\n" % func
.name
)
5350 def WriteImmediateServiceUnitTest(self
, func
, file, *extras
):
5351 """Overrriden from TypeHandler."""
5352 file.Write("// TODO(gman): %s\n\n" % func
.name
)
5354 def WriteBucketServiceUnitTest(self
, func
, file, *extras
):
5355 """Overrriden from TypeHandler."""
5356 file.Write("// TODO(gman): %s\n\n" % func
.name
)
5358 def WriteServiceImplementation(self
, func
, file):
5359 """Overrriden from TypeHandler."""
5362 def WriteImmediateServiceImplementation(self
, func
, file):
5363 """Overrriden from TypeHandler."""
5366 def WriteBucketServiceImplementation(self
, func
, file):
5367 """Overrriden from TypeHandler."""
5370 def WriteImmediateCmdHelper(self
, func
, file):
5371 """Overrriden from TypeHandler."""
5374 def WriteCmdHelper(self
, func
, file):
5375 """Overrriden from TypeHandler."""
5378 def WriteFormatTest(self
, func
, file):
5379 """Overrriden from TypeHandler."""
5380 file.Write("// TODO(gman): Write test for %s\n" % func
.name
)
5382 def WriteImmediateFormatTest(self
, func
, file):
5383 """Overrriden from TypeHandler."""
5384 file.Write("// TODO(gman): Write test for %s\n" % func
.name
)
5386 def WriteBucketFormatTest(self
, func
, file):
5387 """Overrriden from TypeHandler."""
5388 file.Write("// TODO(gman): Write test for %s\n" % func
.name
)
5392 class ManualHandler(CustomHandler
):
5393 """Handler for commands who's handlers must be written by hand."""
5396 CustomHandler
.__init
__(self
)
5398 def InitFunction(self
, func
):
5399 """Overrriden from TypeHandler."""
5400 if (func
.name
== 'CompressedTexImage2DBucket' or
5401 func
.name
== 'CompressedTexImage3DBucket'):
5402 func
.cmd_args
= func
.cmd_args
[:-1]
5403 func
.AddCmdArg(Argument('bucket_id', 'GLuint'))
5405 CustomHandler
.InitFunction(self
, func
)
5407 def WriteServiceImplementation(self
, func
, file):
5408 """Overrriden from TypeHandler."""
5411 def WriteBucketServiceImplementation(self
, func
, file):
5412 """Overrriden from TypeHandler."""
5415 def WriteServiceUnitTest(self
, func
, file, *extras
):
5416 """Overrriden from TypeHandler."""
5417 file.Write("// TODO(gman): %s\n\n" % func
.name
)
5419 def WriteImmediateServiceUnitTest(self
, func
, file, *extras
):
5420 """Overrriden from TypeHandler."""
5421 file.Write("// TODO(gman): %s\n\n" % func
.name
)
5423 def WriteImmediateServiceImplementation(self
, func
, file):
5424 """Overrriden from TypeHandler."""
5427 def WriteImmediateFormatTest(self
, func
, file):
5428 """Overrriden from TypeHandler."""
5429 file.Write("// TODO(gman): Implement test for %s\n" % func
.name
)
5431 def WriteGLES2Implementation(self
, func
, file):
5432 """Overrriden from TypeHandler."""
5433 if func
.GetInfo('impl_func'):
5434 super(ManualHandler
, self
).WriteGLES2Implementation(func
, file)
5436 def WriteGLES2ImplementationHeader(self
, func
, file):
5437 """Overrriden from TypeHandler."""
5438 file.Write("%s %s(%s) override;\n" %
5439 (func
.return_type
, func
.original_name
,
5440 func
.MakeTypedOriginalArgString("")))
5443 def WriteImmediateCmdGetTotalSize(self
, func
, file):
5444 """Overrriden from TypeHandler."""
5445 # TODO(gman): Move this data to _FUNCTION_INFO?
5446 CustomHandler
.WriteImmediateCmdGetTotalSize(self
, func
, file)
5449 class DataHandler(TypeHandler
):
5450 """Handler for glBufferData, glBufferSubData, glTexImage*D, glTexSubImage*D,
5451 glCompressedTexImage*D, glCompressedTexImageSub*D."""
5453 TypeHandler
.__init
__(self
)
5455 def InitFunction(self
, func
):
5456 """Overrriden from TypeHandler."""
5457 if (func
.name
== 'CompressedTexSubImage2DBucket' or
5458 func
.name
== 'CompressedTexSubImage3DBucket'):
5459 func
.cmd_args
= func
.cmd_args
[:-1]
5460 func
.AddCmdArg(Argument('bucket_id', 'GLuint'))
5462 def WriteGetDataSizeCode(self
, func
, file):
5463 """Overrriden from TypeHandler."""
5464 # TODO(gman): Move this data to _FUNCTION_INFO?
5466 if name
.endswith("Immediate"):
5468 if name
== 'BufferData' or name
== 'BufferSubData':
5469 file.Write(" uint32_t data_size = size;\n")
5470 elif (name
== 'CompressedTexImage2D' or
5471 name
== 'CompressedTexSubImage2D' or
5472 name
== 'CompressedTexImage3D' or
5473 name
== 'CompressedTexSubImage3D'):
5474 file.Write(" uint32_t data_size = imageSize;\n")
5475 elif (name
== 'CompressedTexSubImage2DBucket' or
5476 name
== 'CompressedTexSubImage3DBucket'):
5477 file.Write(" Bucket* bucket = GetBucket(c.bucket_id);\n")
5478 file.Write(" uint32_t data_size = bucket->size();\n")
5479 file.Write(" GLsizei imageSize = data_size;\n")
5480 elif name
== 'TexImage2D' or name
== 'TexSubImage2D':
5481 code
= """ uint32_t data_size;
5482 if (!GLES2Util::ComputeImageDataSize(
5483 width, height, format, type, unpack_alignment_, &data_size)) {
5484 return error::kOutOfBounds;
5490 "// uint32_t data_size = 0; // TODO(gman): get correct size!\n")
5492 def WriteImmediateCmdGetTotalSize(self
, func
, file):
5493 """Overrriden from TypeHandler."""
5496 def WriteImmediateCmdSizeTest(self
, func
, file):
5497 """Overrriden from TypeHandler."""
5498 file.Write(" EXPECT_EQ(sizeof(cmd), total_size);\n")
5500 def WriteImmediateCmdInit(self
, func
, file):
5501 """Overrriden from TypeHandler."""
5502 file.Write(" void Init(%s) {\n" % func
.MakeTypedCmdArgString("_"))
5503 self
.WriteImmediateCmdGetTotalSize(func
, file)
5504 file.Write(" SetHeader(total_size);\n")
5505 args
= func
.GetCmdArgs()
5507 file.Write(" %s = _%s;\n" % (arg
.name
, arg
.name
))
5511 def WriteImmediateCmdSet(self
, func
, file):
5512 """Overrriden from TypeHandler."""
5513 copy_args
= func
.MakeCmdArgString("_", False)
5514 file.Write(" void* Set(void* cmd%s) {\n" %
5515 func
.MakeTypedCmdArgString("_", True))
5516 self
.WriteImmediateCmdGetTotalSize(func
, file)
5517 file.Write(" static_cast<ValueType*>(cmd)->Init(%s);\n" % copy_args
)
5518 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
5519 "cmd, total_size);\n")
5523 def WriteImmediateFormatTest(self
, func
, file):
5524 """Overrriden from TypeHandler."""
5525 # TODO(gman): Remove this exception.
5526 file.Write("// TODO(gman): Implement test for %s\n" % func
.name
)
5529 def WriteServiceUnitTest(self
, func
, file, *extras
):
5530 """Overrriden from TypeHandler."""
5531 file.Write("// TODO(gman): %s\n\n" % func
.name
)
5533 def WriteImmediateServiceUnitTest(self
, func
, file, *extras
):
5534 """Overrriden from TypeHandler."""
5535 file.Write("// TODO(gman): %s\n\n" % func
.name
)
5537 def WriteBucketServiceImplementation(self
, func
, file):
5538 """Overrriden from TypeHandler."""
5539 if ((not func
.name
== 'CompressedTexSubImage2DBucket') and
5540 (not func
.name
== 'CompressedTexSubImage3DBucket')):
5541 TypeHandler
.WriteBucketServiceImplemenation(self
, func
, file)
5544 class BindHandler(TypeHandler
):
5545 """Handler for glBind___ type functions."""
5548 TypeHandler
.__init
__(self
)
5550 def WriteServiceUnitTest(self
, func
, file, *extras
):
5551 """Overrriden from TypeHandler."""
5553 if len(func
.GetOriginalArgs()) == 1:
5555 TEST_P(%(test_name)s, %(name)sValidArgs) {
5556 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
5557 SpecializedSetup<cmds::%(name)s, 0>(true);
5559 cmd.Init(%(args)s);"""
5562 decoder_->set_unsafe_es3_apis_enabled(true);
5563 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5564 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5565 decoder_->set_unsafe_es3_apis_enabled(false);
5566 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));
5571 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5572 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5575 if func
.GetInfo("gen_func"):
5577 TEST_P(%(test_name)s, %(name)sValidArgsNewId) {
5578 EXPECT_CALL(*gl_, %(gl_func_name)s(kNewServiceId));
5579 EXPECT_CALL(*gl_, %(gl_gen_func_name)s(1, _))
5580 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
5581 SpecializedSetup<cmds::%(name)s, 0>(true);
5583 cmd.Init(kNewClientId);
5584 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5585 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5586 EXPECT_TRUE(Get%(resource_type)s(kNewClientId) != NULL);
5589 self
.WriteValidUnitTest(func
, file, valid_test
, {
5590 'resource_type': func
.GetOriginalArgs()[0].resource_type
,
5591 'gl_gen_func_name': func
.GetInfo("gen_func"),
5595 TEST_P(%(test_name)s, %(name)sValidArgs) {
5596 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
5597 SpecializedSetup<cmds::%(name)s, 0>(true);
5599 cmd.Init(%(args)s);"""
5602 decoder_->set_unsafe_es3_apis_enabled(true);
5603 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5604 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5605 decoder_->set_unsafe_es3_apis_enabled(false);
5606 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));
5611 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5612 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5615 if func
.GetInfo("gen_func"):
5617 TEST_P(%(test_name)s, %(name)sValidArgsNewId) {
5619 %(gl_func_name)s(%(gl_args_with_new_id)s));
5620 EXPECT_CALL(*gl_, %(gl_gen_func_name)s(1, _))
5621 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
5622 SpecializedSetup<cmds::%(name)s, 0>(true);
5624 cmd.Init(%(args_with_new_id)s);"""
5627 decoder_->set_unsafe_es3_apis_enabled(true);
5628 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5629 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5630 EXPECT_TRUE(Get%(resource_type)s(kNewClientId) != NULL);
5631 decoder_->set_unsafe_es3_apis_enabled(false);
5632 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));
5637 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5638 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5639 EXPECT_TRUE(Get%(resource_type)s(kNewClientId) != NULL);
5643 gl_args_with_new_id
= []
5644 args_with_new_id
= []
5645 for arg
in func
.GetOriginalArgs():
5646 if hasattr(arg
, 'resource_type'):
5647 gl_args_with_new_id
.append('kNewServiceId')
5648 args_with_new_id
.append('kNewClientId')
5650 gl_args_with_new_id
.append(arg
.GetValidGLArg(func
))
5651 args_with_new_id
.append(arg
.GetValidArg(func
))
5652 self
.WriteValidUnitTest(func
, file, valid_test
, {
5653 'args_with_new_id': ", ".join(args_with_new_id
),
5654 'gl_args_with_new_id': ", ".join(gl_args_with_new_id
),
5655 'resource_type': func
.GetResourceIdArg().resource_type
,
5656 'gl_gen_func_name': func
.GetInfo("gen_func"),
5660 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
5661 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
5662 SpecializedSetup<cmds::%(name)s, 0>(false);
5665 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
5668 self
.WriteInvalidUnitTest(func
, file, invalid_test
, *extras
)
5670 def WriteGLES2Implementation(self
, func
, file):
5671 """Writes the GLES2 Implemention."""
5673 impl_func
= func
.GetInfo('impl_func')
5674 impl_decl
= func
.GetInfo('impl_decl')
5676 if (func
.can_auto_generate
and
5677 (impl_func
== None or impl_func
== True) and
5678 (impl_decl
== None or impl_decl
== True)):
5680 file.Write("%s GLES2Implementation::%s(%s) {\n" %
5681 (func
.return_type
, func
.original_name
,
5682 func
.MakeTypedOriginalArgString("")))
5683 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
5684 func
.WriteDestinationInitalizationValidation(file)
5685 self
.WriteClientGLCallLog(func
, file)
5686 for arg
in func
.GetOriginalArgs():
5687 arg
.WriteClientSideValidationCode(file, func
)
5689 code
= """ if (Is%(type)sReservedId(%(id)s)) {
5690 SetGLError(GL_INVALID_OPERATION, "%(name)s\", \"%(id)s reserved id");
5693 %(name)sHelper(%(arg_string)s);
5698 name_arg
= func
.GetResourceIdArg()
5701 'arg_string': func
.MakeOriginalArgString(""),
5702 'id': name_arg
.name
,
5703 'type': name_arg
.resource_type
,
5704 'lc_type': name_arg
.resource_type
.lower(),
5707 def WriteGLES2ImplementationUnitTest(self
, func
, file):
5708 """Overrriden from TypeHandler."""
5709 client_test
= func
.GetInfo('client_test')
5710 if client_test
== False:
5713 TEST_F(GLES2ImplementationTest, %(name)s) {
5718 expected.cmd.Init(%(cmd_args)s);
5720 gl_->%(name)s(%(args)s);
5721 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));"""
5722 if not func
.IsUnsafe():
5725 gl_->%(name)s(%(args)s);
5726 EXPECT_TRUE(NoCommandsWritten());"""
5731 arg
.GetValidClientSideCmdArg(func
) for arg
in func
.GetCmdArgs()
5734 arg
.GetValidClientSideArg(func
) for arg
in func
.GetOriginalArgs()
5739 'args': ", ".join(gl_arg_strings
),
5740 'cmd_args': ", ".join(cmd_arg_strings
),
5744 class GENnHandler(TypeHandler
):
5745 """Handler for glGen___ type functions."""
5748 TypeHandler
.__init
__(self
)
5750 def InitFunction(self
, func
):
5751 """Overrriden from TypeHandler."""
5754 def WriteGetDataSizeCode(self
, func
, file):
5755 """Overrriden from TypeHandler."""
5756 code
= """ uint32_t data_size;
5757 if (!SafeMultiplyUint32(n, sizeof(GLuint), &data_size)) {
5758 return error::kOutOfBounds;
5763 def WriteHandlerImplementation (self
, func
, file):
5764 """Overrriden from TypeHandler."""
5765 file.Write(" if (!%sHelper(n, %s)) {\n"
5766 " return error::kInvalidArguments;\n"
5768 (func
.name
, func
.GetLastOriginalArg().name
))
5770 def WriteImmediateHandlerImplementation(self
, func
, file):
5771 """Overrriden from TypeHandler."""
5773 file.Write(""" for (GLsizei ii = 0; ii < n; ++ii) {
5774 if (group_->Get%(resource_name)sServiceId(%(last_arg_name)s[ii], NULL)) {
5775 return error::kInvalidArguments;
5778 scoped_ptr<GLuint[]> service_ids(new GLuint[n]);
5779 gl%(func_name)s(n, service_ids.get());
5780 for (GLsizei ii = 0; ii < n; ++ii) {
5781 group_->Add%(resource_name)sId(%(last_arg_name)s[ii], service_ids[ii]);
5783 """ % { 'func_name': func
.original_name
,
5784 'last_arg_name': func
.GetLastOriginalArg().name
,
5785 'resource_name': func
.GetInfo('resource_type') })
5787 file.Write(" if (!%sHelper(n, %s)) {\n"
5788 " return error::kInvalidArguments;\n"
5790 (func
.original_name
, func
.GetLastOriginalArg().name
))
5792 def WriteGLES2Implementation(self
, func
, file):
5793 """Overrriden from TypeHandler."""
5794 log_code
= (""" GPU_CLIENT_LOG_CODE_BLOCK({
5795 for (GLsizei i = 0; i < n; ++i) {
5796 GPU_CLIENT_LOG(" " << i << ": " << %s[i]);
5798 });""" % func
.GetOriginalArgs()[1].name
)
5800 'log_code': log_code
,
5801 'return_type': func
.return_type
,
5802 'name': func
.original_name
,
5803 'typed_args': func
.MakeTypedOriginalArgString(""),
5804 'args': func
.MakeOriginalArgString(""),
5805 'resource_types': func
.GetInfo('resource_types'),
5806 'count_name': func
.GetOriginalArgs()[0].name
,
5809 "%(return_type)s GLES2Implementation::%(name)s(%(typed_args)s) {\n" %
5811 func
.WriteDestinationInitalizationValidation(file)
5812 self
.WriteClientGLCallLog(func
, file)
5813 for arg
in func
.GetOriginalArgs():
5814 arg
.WriteClientSideValidationCode(file, func
)
5815 not_shared
= func
.GetInfo('not_shared')
5819 """ IdAllocator* id_allocator = GetIdAllocator(id_namespaces::k%s);
5820 for (GLsizei ii = 0; ii < n; ++ii)
5821 %s[ii] = id_allocator->AllocateID();""" %
5822 (func
.GetInfo('resource_types'), func
.GetOriginalArgs()[1].name
))
5824 alloc_code
= (""" GetIdHandler(id_namespaces::k%(resource_types)s)->
5825 MakeIds(this, 0, %(args)s);""" % args
)
5826 args
['alloc_code'] = alloc_code
5828 code
= """ GPU_CLIENT_SINGLE_THREAD_CHECK();
5830 %(name)sHelper(%(args)s);
5831 helper_->%(name)sImmediate(%(args)s);
5832 if (share_group_->bind_generates_resource())
5833 helper_->CommandBufferHelper::Flush();
5839 file.Write(code
% args
)
5841 def WriteGLES2ImplementationUnitTest(self
, func
, file):
5842 """Overrriden from TypeHandler."""
5844 TEST_F(GLES2ImplementationTest, %(name)s) {
5845 GLuint ids[2] = { 0, };
5847 cmds::%(name)sImmediate gen;
5851 expected.gen.Init(arraysize(ids), &ids[0]);
5852 expected.data[0] = k%(types)sStartId;
5853 expected.data[1] = k%(types)sStartId + 1;
5854 gl_->%(name)s(arraysize(ids), &ids[0]);
5855 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
5856 EXPECT_EQ(k%(types)sStartId, ids[0]);
5857 EXPECT_EQ(k%(types)sStartId + 1, ids[1]);
5862 'types': func
.GetInfo('resource_types'),
5865 def WriteServiceUnitTest(self
, func
, file, *extras
):
5866 """Overrriden from TypeHandler."""
5868 TEST_P(%(test_name)s, %(name)sValidArgs) {
5869 EXPECT_CALL(*gl_, %(gl_func_name)s(1, _))
5870 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
5871 GetSharedMemoryAs<GLuint*>()[0] = kNewClientId;
5872 SpecializedSetup<cmds::%(name)s, 0>(true);
5875 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5876 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
5880 EXPECT_TRUE(Get%(resource_name)sServiceId(kNewClientId, &service_id));
5881 EXPECT_EQ(kNewServiceId, service_id)
5886 EXPECT_TRUE(Get%(resource_name)s(kNewClientId, &service_id) != NULL);
5889 self
.WriteValidUnitTest(func
, file, valid_test
, {
5890 'resource_name': func
.GetInfo('resource_type'),
5893 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
5894 EXPECT_CALL(*gl_, %(gl_func_name)s(_, _)).Times(0);
5895 GetSharedMemoryAs<GLuint*>()[0] = client_%(resource_name)s_id_;
5896 SpecializedSetup<cmds::%(name)s, 0>(false);
5899 EXPECT_EQ(error::kInvalidArguments, ExecuteCmd(cmd));
5902 self
.WriteValidUnitTest(func
, file, invalid_test
, {
5903 'resource_name': func
.GetInfo('resource_type').lower(),
5906 def WriteImmediateServiceUnitTest(self
, func
, file, *extras
):
5907 """Overrriden from TypeHandler."""
5909 TEST_P(%(test_name)s, %(name)sValidArgs) {
5910 EXPECT_CALL(*gl_, %(gl_func_name)s(1, _))
5911 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
5912 cmds::%(name)s* cmd = GetImmediateAs<cmds::%(name)s>();
5913 GLuint temp = kNewClientId;
5914 SpecializedSetup<cmds::%(name)s, 0>(true);"""
5917 decoder_->set_unsafe_es3_apis_enabled(true);"""
5919 cmd->Init(1, &temp);
5920 EXPECT_EQ(error::kNoError,
5921 ExecuteImmediateCmd(*cmd, sizeof(temp)));
5922 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
5926 EXPECT_TRUE(Get%(resource_name)sServiceId(kNewClientId, &service_id));
5927 EXPECT_EQ(kNewServiceId, service_id);
5928 decoder_->set_unsafe_es3_apis_enabled(false);
5929 EXPECT_EQ(error::kUnknownCommand,
5930 ExecuteImmediateCmd(*cmd, sizeof(temp)));
5935 EXPECT_TRUE(Get%(resource_name)s(kNewClientId) != NULL);
5938 self
.WriteValidUnitTest(func
, file, valid_test
, {
5939 'resource_name': func
.GetInfo('resource_type'),
5942 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
5943 EXPECT_CALL(*gl_, %(gl_func_name)s(_, _)).Times(0);
5944 cmds::%(name)s* cmd = GetImmediateAs<cmds::%(name)s>();
5945 SpecializedSetup<cmds::%(name)s, 0>(false);
5946 cmd->Init(1, &client_%(resource_name)s_id_);"""
5949 decoder_->set_unsafe_es3_apis_enabled(true);
5950 EXPECT_EQ(error::kInvalidArguments,
5951 ExecuteImmediateCmd(*cmd, sizeof(&client_%(resource_name)s_id_)));
5952 decoder_->set_unsafe_es3_apis_enabled(false);
5957 EXPECT_EQ(error::kInvalidArguments,
5958 ExecuteImmediateCmd(*cmd, sizeof(&client_%(resource_name)s_id_)));
5961 self
.WriteValidUnitTest(func
, file, invalid_test
, {
5962 'resource_name': func
.GetInfo('resource_type').lower(),
5965 def WriteImmediateCmdComputeSize(self
, func
, file):
5966 """Overrriden from TypeHandler."""
5967 file.Write(" static uint32_t ComputeDataSize(GLsizei n) {\n")
5969 " return static_cast<uint32_t>(sizeof(GLuint) * n); // NOLINT\n")
5972 file.Write(" static uint32_t ComputeSize(GLsizei n) {\n")
5973 file.Write(" return static_cast<uint32_t>(\n")
5974 file.Write(" sizeof(ValueType) + ComputeDataSize(n)); // NOLINT\n")
5978 def WriteImmediateCmdSetHeader(self
, func
, file):
5979 """Overrriden from TypeHandler."""
5980 file.Write(" void SetHeader(GLsizei n) {\n")
5981 file.Write(" header.SetCmdByTotalSize<ValueType>(ComputeSize(n));\n")
5985 def WriteImmediateCmdInit(self
, func
, file):
5986 """Overrriden from TypeHandler."""
5987 last_arg
= func
.GetLastOriginalArg()
5988 file.Write(" void Init(%s, %s _%s) {\n" %
5989 (func
.MakeTypedCmdArgString("_"),
5990 last_arg
.type, last_arg
.name
))
5991 file.Write(" SetHeader(_n);\n")
5992 args
= func
.GetCmdArgs()
5994 file.Write(" %s = _%s;\n" % (arg
.name
, arg
.name
))
5995 file.Write(" memcpy(ImmediateDataAddress(this),\n")
5996 file.Write(" _%s, ComputeDataSize(_n));\n" % last_arg
.name
)
6000 def WriteImmediateCmdSet(self
, func
, file):
6001 """Overrriden from TypeHandler."""
6002 last_arg
= func
.GetLastOriginalArg()
6003 copy_args
= func
.MakeCmdArgString("_", False)
6004 file.Write(" void* Set(void* cmd%s, %s _%s) {\n" %
6005 (func
.MakeTypedCmdArgString("_", True),
6006 last_arg
.type, last_arg
.name
))
6007 file.Write(" static_cast<ValueType*>(cmd)->Init(%s, _%s);\n" %
6008 (copy_args
, last_arg
.name
))
6009 file.Write(" const uint32_t size = ComputeSize(_n);\n")
6010 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
6015 def WriteImmediateCmdHelper(self
, func
, file):
6016 """Overrriden from TypeHandler."""
6017 code
= """ void %(name)s(%(typed_args)s) {
6018 const uint32_t size = gles2::cmds::%(name)s::ComputeSize(n);
6019 gles2::cmds::%(name)s* c =
6020 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
6029 "typed_args": func
.MakeTypedOriginalArgString(""),
6030 "args": func
.MakeOriginalArgString(""),
6033 def WriteImmediateFormatTest(self
, func
, file):
6034 """Overrriden from TypeHandler."""
6035 file.Write("TEST_F(GLES2FormatTest, %s) {\n" % func
.name
)
6036 file.Write(" static GLuint ids[] = { 12, 23, 34, };\n")
6037 file.Write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
6038 (func
.name
, func
.name
))
6039 file.Write(" void* next_cmd = cmd.Set(\n")
6040 file.Write(" &cmd, static_cast<GLsizei>(arraysize(ids)), ids);\n")
6041 file.Write(" EXPECT_EQ(static_cast<uint32_t>(cmds::%s::kCmdId),\n" %
6043 file.Write(" cmd.header.command);\n")
6044 file.Write(" EXPECT_EQ(sizeof(cmd) +\n")
6045 file.Write(" RoundSizeToMultipleOfEntries(cmd.n * 4u),\n")
6046 file.Write(" cmd.header.size * 4u);\n")
6047 file.Write(" EXPECT_EQ(static_cast<GLsizei>(arraysize(ids)), cmd.n);\n");
6048 file.Write(" CheckBytesWrittenMatchesExpectedSize(\n")
6049 file.Write(" next_cmd, sizeof(cmd) +\n")
6050 file.Write(" RoundSizeToMultipleOfEntries(arraysize(ids) * 4u));\n")
6051 file.Write(" // TODO(gman): Check that ids were inserted;\n")
6056 class CreateHandler(TypeHandler
):
6057 """Handler for glCreate___ type functions."""
6060 TypeHandler
.__init
__(self
)
6062 def InitFunction(self
, func
):
6063 """Overrriden from TypeHandler."""
6064 func
.AddCmdArg(Argument("client_id", 'uint32_t'))
6066 def __GetResourceType(self
, func
):
6067 if func
.return_type
== "GLsync":
6070 return func
.name
[6:] # Create*
6072 def WriteServiceUnitTest(self
, func
, file, *extras
):
6073 """Overrriden from TypeHandler."""
6075 TEST_P(%(test_name)s, %(name)sValidArgs) {
6076 %(id_type_cast)sEXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s))
6077 .WillOnce(Return(%(const_service_id)s));
6078 SpecializedSetup<cmds::%(name)s, 0>(true);
6080 cmd.Init(%(args)s%(comma)skNewClientId);"""
6083 decoder_->set_unsafe_es3_apis_enabled(true);"""
6085 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
6086 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
6089 %(return_type)s service_id = 0;
6090 EXPECT_TRUE(Get%(resource_type)sServiceId(kNewClientId, &service_id));
6091 EXPECT_EQ(%(const_service_id)s, service_id);
6092 decoder_->set_unsafe_es3_apis_enabled(false);
6093 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));
6098 EXPECT_TRUE(Get%(resource_type)s(kNewClientId));
6103 for arg
in func
.GetOriginalArgs():
6104 if not arg
.IsConstant():
6108 if func
.return_type
== 'GLsync':
6109 id_type_cast
= ("const GLsync kNewServiceIdGLuint = reinterpret_cast"
6110 "<GLsync>(kNewServiceId);\n ")
6111 const_service_id
= "kNewServiceIdGLuint"
6114 const_service_id
= "kNewServiceId"
6115 self
.WriteValidUnitTest(func
, file, valid_test
, {
6117 'resource_type': self
.__GetResourceType
(func
),
6118 'return_type': func
.return_type
,
6119 'id_type_cast': id_type_cast
,
6120 'const_service_id': const_service_id
,
6123 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
6124 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
6125 SpecializedSetup<cmds::%(name)s, 0>(false);
6127 cmd.Init(%(args)s%(comma)skNewClientId);
6128 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));%(gl_error_test)s
6131 self
.WriteInvalidUnitTest(func
, file, invalid_test
, {
6135 def WriteHandlerImplementation (self
, func
, file):
6136 """Overrriden from TypeHandler."""
6138 code
= """ uint32_t client_id = c.client_id;
6139 %(return_type)s service_id = 0;
6140 if (group_->Get%(resource_name)sServiceId(client_id, &service_id)) {
6141 return error::kInvalidArguments;
6143 service_id = %(gl_func_name)s(%(gl_args)s);
6145 group_->Add%(resource_name)sId(client_id, service_id);
6149 code
= """ uint32_t client_id = c.client_id;
6150 if (Get%(resource_name)s(client_id)) {
6151 return error::kInvalidArguments;
6153 %(return_type)s service_id = %(gl_func_name)s(%(gl_args)s);
6155 Create%(resource_name)s(client_id, service_id%(gl_args_with_comma)s);
6159 'resource_name': self
.__GetResourceType
(func
),
6160 'return_type': func
.return_type
,
6161 'gl_func_name': func
.GetGLFunctionName(),
6162 'gl_args': func
.MakeOriginalArgString(""),
6163 'gl_args_with_comma': func
.MakeOriginalArgString("", True) })
6165 def WriteGLES2Implementation(self
, func
, file):
6166 """Overrriden from TypeHandler."""
6167 file.Write("%s GLES2Implementation::%s(%s) {\n" %
6168 (func
.return_type
, func
.original_name
,
6169 func
.MakeTypedOriginalArgString("")))
6170 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
6171 func
.WriteDestinationInitalizationValidation(file)
6172 self
.WriteClientGLCallLog(func
, file)
6173 for arg
in func
.GetOriginalArgs():
6174 arg
.WriteClientSideValidationCode(file, func
)
6175 file.Write(" GLuint client_id;\n")
6176 if func
.return_type
== "GLsync":
6178 " GetIdHandler(id_namespaces::kSyncs)->\n")
6181 " GetIdHandler(id_namespaces::kProgramsAndShaders)->\n")
6182 file.Write(" MakeIds(this, 0, 1, &client_id);\n")
6183 file.Write(" helper_->%s(%s);\n" %
6184 (func
.name
, func
.MakeCmdArgString("")))
6185 file.Write(' GPU_CLIENT_LOG("returned " << client_id);\n')
6186 file.Write(" CheckGLError();\n")
6187 if func
.return_type
== "GLsync":
6188 file.Write(" return reinterpret_cast<GLsync>(client_id);\n")
6190 file.Write(" return client_id;\n")
6195 class DeleteHandler(TypeHandler
):
6196 """Handler for glDelete___ single resource type functions."""
6199 TypeHandler
.__init
__(self
)
6201 def WriteServiceImplementation(self
, func
, file):
6202 """Overrriden from TypeHandler."""
6204 TypeHandler
.WriteServiceImplementation(self
, func
, file)
6205 # HandleDeleteShader and HandleDeleteProgram are manually written.
6208 def WriteGLES2Implementation(self
, func
, file):
6209 """Overrriden from TypeHandler."""
6210 file.Write("%s GLES2Implementation::%s(%s) {\n" %
6211 (func
.return_type
, func
.original_name
,
6212 func
.MakeTypedOriginalArgString("")))
6213 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
6214 func
.WriteDestinationInitalizationValidation(file)
6215 self
.WriteClientGLCallLog(func
, file)
6216 for arg
in func
.GetOriginalArgs():
6217 arg
.WriteClientSideValidationCode(file, func
)
6219 " GPU_CLIENT_DCHECK(%s != 0);\n" % func
.GetOriginalArgs()[-1].name
)
6220 file.Write(" %sHelper(%s);\n" %
6221 (func
.original_name
, func
.GetOriginalArgs()[-1].name
))
6222 file.Write(" CheckGLError();\n")
6226 def WriteHandlerImplementation (self
, func
, file):
6227 """Overrriden from TypeHandler."""
6228 assert len(func
.GetOriginalArgs()) == 1
6229 arg
= func
.GetOriginalArgs()[0]
6231 file.Write(""" %(arg_type)s service_id = 0;
6232 if (group_->Get%(resource_type)sServiceId(%(arg_name)s, &service_id)) {
6233 glDelete%(resource_type)s(service_id);
6234 group_->Remove%(resource_type)sId(%(arg_name)s);
6237 GL_INVALID_VALUE, "gl%(func_name)s", "unknown %(arg_name)s");
6239 """ % { 'resource_type': func
.GetInfo('resource_type'),
6240 'arg_name': arg
.name
,
6241 'arg_type': arg
.type,
6242 'func_name': func
.original_name
})
6244 file.Write(" %sHelper(%s);\n" % (func
.original_name
, arg
.name
))
6246 class DELnHandler(TypeHandler
):
6247 """Handler for glDelete___ type functions."""
6250 TypeHandler
.__init
__(self
)
6252 def WriteGetDataSizeCode(self
, func
, file):
6253 """Overrriden from TypeHandler."""
6254 code
= """ uint32_t data_size;
6255 if (!SafeMultiplyUint32(n, sizeof(GLuint), &data_size)) {
6256 return error::kOutOfBounds;
6261 def WriteGLES2ImplementationUnitTest(self
, func
, file):
6262 """Overrriden from TypeHandler."""
6264 TEST_F(GLES2ImplementationTest, %(name)s) {
6265 GLuint ids[2] = { k%(types)sStartId, k%(types)sStartId + 1 };
6267 cmds::%(name)sImmediate del;
6271 expected.del.Init(arraysize(ids), &ids[0]);
6272 expected.data[0] = k%(types)sStartId;
6273 expected.data[1] = k%(types)sStartId + 1;
6274 gl_->%(name)s(arraysize(ids), &ids[0]);
6275 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
6280 'types': func
.GetInfo('resource_types'),
6283 def WriteServiceUnitTest(self
, func
, file, *extras
):
6284 """Overrriden from TypeHandler."""
6286 TEST_P(%(test_name)s, %(name)sValidArgs) {
6289 %(gl_func_name)s(1, Pointee(kService%(upper_resource_name)sId)))
6291 GetSharedMemoryAs<GLuint*>()[0] = client_%(resource_name)s_id_;
6292 SpecializedSetup<cmds::%(name)s, 0>(true);
6295 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
6296 EXPECT_EQ(GL_NO_ERROR, GetGLError());
6298 Get%(upper_resource_name)s(client_%(resource_name)s_id_) == NULL);
6301 self
.WriteValidUnitTest(func
, file, valid_test
, {
6302 'resource_name': func
.GetInfo('resource_type').lower(),
6303 'upper_resource_name': func
.GetInfo('resource_type'),
6306 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
6307 GetSharedMemoryAs<GLuint*>()[0] = kInvalidClientId;
6308 SpecializedSetup<cmds::%(name)s, 0>(false);
6311 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
6314 self
.WriteValidUnitTest(func
, file, invalid_test
, *extras
)
6316 def WriteImmediateServiceUnitTest(self
, func
, file, *extras
):
6317 """Overrriden from TypeHandler."""
6319 TEST_P(%(test_name)s, %(name)sValidArgs) {
6322 %(gl_func_name)s(1, Pointee(kService%(upper_resource_name)sId)))
6324 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
6325 SpecializedSetup<cmds::%(name)s, 0>(true);
6326 cmd.Init(1, &client_%(resource_name)s_id_);"""
6329 decoder_->set_unsafe_es3_apis_enabled(true);"""
6331 EXPECT_EQ(error::kNoError,
6332 ExecuteImmediateCmd(cmd, sizeof(client_%(resource_name)s_id_)));
6333 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
6336 EXPECT_FALSE(Get%(upper_resource_name)sServiceId(
6337 client_%(resource_name)s_id_, NULL));
6338 decoder_->set_unsafe_es3_apis_enabled(false);
6339 EXPECT_EQ(error::kUnknownCommand,
6340 ExecuteImmediateCmd(cmd, sizeof(client_%(resource_name)s_id_)));
6346 Get%(upper_resource_name)s(client_%(resource_name)s_id_) == NULL);
6349 self
.WriteValidUnitTest(func
, file, valid_test
, {
6350 'resource_name': func
.GetInfo('resource_type').lower(),
6351 'upper_resource_name': func
.GetInfo('resource_type'),
6354 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
6355 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
6356 SpecializedSetup<cmds::%(name)s, 0>(false);
6357 GLuint temp = kInvalidClientId;
6358 cmd.Init(1, &temp);"""
6361 decoder_->set_unsafe_es3_apis_enabled(true);
6362 EXPECT_EQ(error::kNoError,
6363 ExecuteImmediateCmd(cmd, sizeof(temp)));
6364 decoder_->set_unsafe_es3_apis_enabled(false);
6365 EXPECT_EQ(error::kUnknownCommand,
6366 ExecuteImmediateCmd(cmd, sizeof(temp)));
6371 EXPECT_EQ(error::kNoError,
6372 ExecuteImmediateCmd(cmd, sizeof(temp)));
6375 self
.WriteValidUnitTest(func
, file, invalid_test
, *extras
)
6377 def WriteHandlerImplementation (self
, func
, file):
6378 """Overrriden from TypeHandler."""
6379 file.Write(" %sHelper(n, %s);\n" %
6380 (func
.name
, func
.GetLastOriginalArg().name
))
6382 def WriteImmediateHandlerImplementation (self
, func
, file):
6383 """Overrriden from TypeHandler."""
6385 file.Write(""" for (GLsizei ii = 0; ii < n; ++ii) {
6386 GLuint service_id = 0;
6387 if (group_->Get%(resource_type)sServiceId(
6388 %(last_arg_name)s[ii], &service_id)) {
6389 glDelete%(resource_type)ss(1, &service_id);
6390 group_->Remove%(resource_type)sId(%(last_arg_name)s[ii]);
6393 """ % { 'resource_type': func
.GetInfo('resource_type'),
6394 'last_arg_name': func
.GetLastOriginalArg().name
})
6396 file.Write(" %sHelper(n, %s);\n" %
6397 (func
.original_name
, func
.GetLastOriginalArg().name
))
6399 def WriteGLES2Implementation(self
, func
, file):
6400 """Overrriden from TypeHandler."""
6401 impl_decl
= func
.GetInfo('impl_decl')
6402 if impl_decl
== None or impl_decl
== True:
6404 'return_type': func
.return_type
,
6405 'name': func
.original_name
,
6406 'typed_args': func
.MakeTypedOriginalArgString(""),
6407 'args': func
.MakeOriginalArgString(""),
6408 'resource_type': func
.GetInfo('resource_type').lower(),
6409 'count_name': func
.GetOriginalArgs()[0].name
,
6412 "%(return_type)s GLES2Implementation::%(name)s(%(typed_args)s) {\n" %
6414 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
6415 func
.WriteDestinationInitalizationValidation(file)
6416 self
.WriteClientGLCallLog(func
, file)
6417 file.Write(""" GPU_CLIENT_LOG_CODE_BLOCK({
6418 for (GLsizei i = 0; i < n; ++i) {
6419 GPU_CLIENT_LOG(" " << i << ": " << %s[i]);
6422 """ % func
.GetOriginalArgs()[1].name
)
6423 file.Write(""" GPU_CLIENT_DCHECK_CODE_BLOCK({
6424 for (GLsizei i = 0; i < n; ++i) {
6428 """ % func
.GetOriginalArgs()[1].name
)
6429 for arg
in func
.GetOriginalArgs():
6430 arg
.WriteClientSideValidationCode(file, func
)
6431 code
= """ %(name)sHelper(%(args)s);
6436 file.Write(code
% args
)
6438 def WriteImmediateCmdComputeSize(self
, func
, file):
6439 """Overrriden from TypeHandler."""
6440 file.Write(" static uint32_t ComputeDataSize(GLsizei n) {\n")
6442 " return static_cast<uint32_t>(sizeof(GLuint) * n); // NOLINT\n")
6445 file.Write(" static uint32_t ComputeSize(GLsizei n) {\n")
6446 file.Write(" return static_cast<uint32_t>(\n")
6447 file.Write(" sizeof(ValueType) + ComputeDataSize(n)); // NOLINT\n")
6451 def WriteImmediateCmdSetHeader(self
, func
, file):
6452 """Overrriden from TypeHandler."""
6453 file.Write(" void SetHeader(GLsizei n) {\n")
6454 file.Write(" header.SetCmdByTotalSize<ValueType>(ComputeSize(n));\n")
6458 def WriteImmediateCmdInit(self
, func
, file):
6459 """Overrriden from TypeHandler."""
6460 last_arg
= func
.GetLastOriginalArg()
6461 file.Write(" void Init(%s, %s _%s) {\n" %
6462 (func
.MakeTypedCmdArgString("_"),
6463 last_arg
.type, last_arg
.name
))
6464 file.Write(" SetHeader(_n);\n")
6465 args
= func
.GetCmdArgs()
6467 file.Write(" %s = _%s;\n" % (arg
.name
, arg
.name
))
6468 file.Write(" memcpy(ImmediateDataAddress(this),\n")
6469 file.Write(" _%s, ComputeDataSize(_n));\n" % last_arg
.name
)
6473 def WriteImmediateCmdSet(self
, func
, file):
6474 """Overrriden from TypeHandler."""
6475 last_arg
= func
.GetLastOriginalArg()
6476 copy_args
= func
.MakeCmdArgString("_", False)
6477 file.Write(" void* Set(void* cmd%s, %s _%s) {\n" %
6478 (func
.MakeTypedCmdArgString("_", True),
6479 last_arg
.type, last_arg
.name
))
6480 file.Write(" static_cast<ValueType*>(cmd)->Init(%s, _%s);\n" %
6481 (copy_args
, last_arg
.name
))
6482 file.Write(" const uint32_t size = ComputeSize(_n);\n")
6483 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
6488 def WriteImmediateCmdHelper(self
, func
, file):
6489 """Overrriden from TypeHandler."""
6490 code
= """ void %(name)s(%(typed_args)s) {
6491 const uint32_t size = gles2::cmds::%(name)s::ComputeSize(n);
6492 gles2::cmds::%(name)s* c =
6493 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
6502 "typed_args": func
.MakeTypedOriginalArgString(""),
6503 "args": func
.MakeOriginalArgString(""),
6506 def WriteImmediateFormatTest(self
, func
, file):
6507 """Overrriden from TypeHandler."""
6508 file.Write("TEST_F(GLES2FormatTest, %s) {\n" % func
.name
)
6509 file.Write(" static GLuint ids[] = { 12, 23, 34, };\n")
6510 file.Write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
6511 (func
.name
, func
.name
))
6512 file.Write(" void* next_cmd = cmd.Set(\n")
6513 file.Write(" &cmd, static_cast<GLsizei>(arraysize(ids)), ids);\n")
6514 file.Write(" EXPECT_EQ(static_cast<uint32_t>(cmds::%s::kCmdId),\n" %
6516 file.Write(" cmd.header.command);\n")
6517 file.Write(" EXPECT_EQ(sizeof(cmd) +\n")
6518 file.Write(" RoundSizeToMultipleOfEntries(cmd.n * 4u),\n")
6519 file.Write(" cmd.header.size * 4u);\n")
6520 file.Write(" EXPECT_EQ(static_cast<GLsizei>(arraysize(ids)), cmd.n);\n");
6521 file.Write(" CheckBytesWrittenMatchesExpectedSize(\n")
6522 file.Write(" next_cmd, sizeof(cmd) +\n")
6523 file.Write(" RoundSizeToMultipleOfEntries(arraysize(ids) * 4u));\n")
6524 file.Write(" // TODO(gman): Check that ids were inserted;\n")
6529 class GETnHandler(TypeHandler
):
6530 """Handler for GETn for glGetBooleanv, glGetFloatv, ... type functions."""
6533 TypeHandler
.__init
__(self
)
6535 def NeedsDataTransferFunction(self
, func
):
6536 """Overriden from TypeHandler."""
6539 def WriteServiceImplementation(self
, func
, file):
6540 """Overrriden from TypeHandler."""
6541 self
.WriteServiceHandlerFunctionHeader(func
, file)
6542 last_arg
= func
.GetLastOriginalArg()
6543 # All except shm_id and shm_offset.
6544 all_but_last_args
= func
.GetCmdArgs()[:-2]
6545 for arg
in all_but_last_args
:
6546 arg
.WriteGetCode(file)
6548 code
= """ typedef cmds::%(func_name)s::Result Result;
6549 GLsizei num_values = 0;
6550 GetNumValuesReturnedForGLGet(pname, &num_values);
6551 Result* result = GetSharedMemoryAs<Result*>(
6552 c.%(last_arg_name)s_shm_id, c.%(last_arg_name)s_shm_offset,
6553 Result::ComputeSize(num_values));
6554 %(last_arg_type)s %(last_arg_name)s = result ? result->GetData() : NULL;
6557 'last_arg_type': last_arg
.type,
6558 'last_arg_name': last_arg
.name
,
6559 'func_name': func
.name
,
6561 func
.WriteHandlerValidation(file)
6562 code
= """ // Check that the client initialized the result.
6563 if (result->size != 0) {
6564 return error::kInvalidArguments;
6567 shadowed
= func
.GetInfo('shadowed')
6569 file.Write(' LOCAL_COPY_REAL_GL_ERRORS_TO_WRAPPER("%s");\n' % func
.name
)
6571 func
.WriteHandlerImplementation(file)
6573 code
= """ result->SetNumResults(num_values);
6574 return error::kNoError;
6578 code
= """ GLenum error = LOCAL_PEEK_GL_ERROR("%(func_name)s");
6579 if (error == GL_NO_ERROR) {
6580 result->SetNumResults(num_values);
6582 return error::kNoError;
6586 file.Write(code
% {'func_name': func
.name
})
6588 def WriteGLES2Implementation(self
, func
, file):
6589 """Overrriden from TypeHandler."""
6590 impl_decl
= func
.GetInfo('impl_decl')
6591 if impl_decl
== None or impl_decl
== True:
6592 file.Write("%s GLES2Implementation::%s(%s) {\n" %
6593 (func
.return_type
, func
.original_name
,
6594 func
.MakeTypedOriginalArgString("")))
6595 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
6596 func
.WriteDestinationInitalizationValidation(file)
6597 self
.WriteClientGLCallLog(func
, file)
6598 for arg
in func
.GetOriginalArgs():
6599 arg
.WriteClientSideValidationCode(file, func
)
6600 all_but_last_args
= func
.GetOriginalArgs()[:-1]
6602 has_length_arg
= False
6603 for arg
in all_but_last_args
:
6604 if arg
.type == 'GLsync':
6605 args
.append('ToGLuint(%s)' % arg
.name
)
6606 elif arg
.name
.endswith('size') and arg
.type == 'GLsizei':
6608 elif arg
.name
== 'length':
6609 has_length_arg
= True
6612 args
.append(arg
.name
)
6613 arg_string
= ", ".join(args
)
6617 for arg
in func
.GetOriginalArgs() if not arg
.IsConstant()]))
6618 self
.WriteTraceEvent(func
, file)
6619 code
= """ if (%(func_name)sHelper(%(all_arg_string)s)) {
6622 typedef cmds::%(func_name)s::Result Result;
6623 Result* result = GetResultAs<Result*>();
6627 result->SetNumResults(0);
6628 helper_->%(func_name)s(%(arg_string)s,
6629 GetResultShmId(), GetResultShmOffset());
6631 result->CopyResult(%(last_arg_name)s);
6632 GPU_CLIENT_LOG_CODE_BLOCK({
6633 for (int32_t i = 0; i < result->GetNumResults(); ++i) {
6634 GPU_CLIENT_LOG(" " << i << ": " << result->GetData()[i]);
6640 *length = result->GetNumResults();
6647 'func_name': func
.name
,
6648 'arg_string': arg_string
,
6649 'all_arg_string': all_arg_string
,
6650 'last_arg_name': func
.GetLastOriginalArg().name
,
6653 def WriteGLES2ImplementationUnitTest(self
, func
, file):
6654 """Writes the GLES2 Implemention unit test."""
6656 TEST_F(GLES2ImplementationTest, %(name)s) {
6660 typedef cmds::%(name)s::Result::Type ResultType;
6661 ResultType result = 0;
6663 ExpectedMemoryInfo result1 = GetExpectedResultMemory(
6664 sizeof(uint32_t) + sizeof(ResultType));
6665 expected.cmd.Init(%(cmd_args)s, result1.id, result1.offset);
6666 EXPECT_CALL(*command_buffer(), OnFlush())
6667 .WillOnce(SetMemory(result1.ptr, SizedResultHelper<ResultType>(1)))
6668 .RetiresOnSaturation();
6669 gl_->%(name)s(%(args)s, &result);
6670 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
6671 EXPECT_EQ(static_cast<ResultType>(1), result);
6674 first_cmd_arg
= func
.GetCmdArgs()[0].GetValidNonCachedClientSideCmdArg(func
)
6675 if not first_cmd_arg
:
6678 first_gl_arg
= func
.GetOriginalArgs()[0].GetValidNonCachedClientSideArg(
6681 cmd_arg_strings
= [first_cmd_arg
]
6682 for arg
in func
.GetCmdArgs()[1:-2]:
6683 cmd_arg_strings
.append(arg
.GetValidClientSideCmdArg(func
))
6684 gl_arg_strings
= [first_gl_arg
]
6685 for arg
in func
.GetOriginalArgs()[1:-1]:
6686 gl_arg_strings
.append(arg
.GetValidClientSideArg(func
))
6690 'args': ", ".join(gl_arg_strings
),
6691 'cmd_args': ", ".join(cmd_arg_strings
),
6694 def WriteServiceUnitTest(self
, func
, file, *extras
):
6695 """Overrriden from TypeHandler."""
6697 TEST_P(%(test_name)s, %(name)sValidArgs) {
6698 EXPECT_CALL(*gl_, GetError())
6699 .WillOnce(Return(GL_NO_ERROR))
6700 .WillOnce(Return(GL_NO_ERROR))
6701 .RetiresOnSaturation();
6702 SpecializedSetup<cmds::%(name)s, 0>(true);
6703 typedef cmds::%(name)s::Result Result;
6704 Result* result = static_cast<Result*>(shared_memory_address_);
6705 EXPECT_CALL(*gl_, %(gl_func_name)s(%(local_gl_args)s));
6708 cmd.Init(%(cmd_args)s);"""
6711 decoder_->set_unsafe_es3_apis_enabled(true);"""
6713 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
6714 EXPECT_EQ(decoder_->GetGLES2Util()->GLGetNumValuesReturned(
6716 result->GetNumResults());
6717 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
6720 decoder_->set_unsafe_es3_apis_enabled(false);
6721 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));"""
6726 cmd_arg_strings
= []
6728 for arg
in func
.GetOriginalArgs()[:-1]:
6729 if arg
.name
== 'length':
6730 gl_arg_value
= 'nullptr'
6731 elif arg
.name
.endswith('size'):
6732 gl_arg_value
= ("decoder_->GetGLES2Util()->GLGetNumValuesReturned(%s)" %
6734 elif arg
.type == 'GLsync':
6735 gl_arg_value
= 'reinterpret_cast<GLsync>(kServiceSyncId)'
6737 gl_arg_value
= arg
.GetValidGLArg(func
)
6738 gl_arg_strings
.append(gl_arg_value
)
6739 if arg
.name
== 'pname':
6740 valid_pname
= gl_arg_value
6741 if arg
.name
.endswith('size') or arg
.name
== 'length':
6743 if arg
.type == 'GLsync':
6744 arg_value
= 'client_sync_id_'
6746 arg_value
= arg
.GetValidArg(func
)
6747 cmd_arg_strings
.append(arg_value
)
6748 if func
.GetInfo('gl_test_func') == 'glGetIntegerv':
6749 gl_arg_strings
.append("_")
6751 gl_arg_strings
.append("result->GetData()")
6752 cmd_arg_strings
.append("shared_memory_id_")
6753 cmd_arg_strings
.append("shared_memory_offset_")
6755 self
.WriteValidUnitTest(func
, file, valid_test
, {
6756 'local_gl_args': ", ".join(gl_arg_strings
),
6757 'cmd_args': ", ".join(cmd_arg_strings
),
6758 'valid_pname': valid_pname
,
6761 if not func
.IsUnsafe():
6763 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
6764 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
6765 SpecializedSetup<cmds::%(name)s, 0>(false);
6766 cmds::%(name)s::Result* result =
6767 static_cast<cmds::%(name)s::Result*>(shared_memory_address_);
6771 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));
6772 EXPECT_EQ(0u, result->size);%(gl_error_test)s
6775 self
.WriteInvalidUnitTest(func
, file, invalid_test
, *extras
)
6777 class ArrayArgTypeHandler(TypeHandler
):
6778 """Base class for type handlers that handle args that are arrays"""
6781 TypeHandler
.__init
__(self
)
6783 def GetArrayType(self
, func
):
6784 """Returns the type of the element in the element array being PUT to."""
6785 for arg
in func
.GetOriginalArgs():
6787 element_type
= arg
.GetPointedType()
6790 # Special case: array type handler is used for a function that is forwarded
6791 # to the actual array type implementation
6792 element_type
= func
.GetOriginalArgs()[-1].type
6793 assert all(arg
.type == element_type \
6794 for arg
in func
.GetOriginalArgs()[-self
.GetArrayCount(func
):])
6797 def GetArrayCount(self
, func
):
6798 """Returns the count of the elements in the array being PUT to."""
6799 return func
.GetInfo('count')
6801 class PUTHandler(ArrayArgTypeHandler
):
6802 """Handler for glTexParameter_v, glVertexAttrib_v functions."""
6805 ArrayArgTypeHandler
.__init
__(self
)
6807 def WriteServiceUnitTest(self
, func
, file, *extras
):
6808 """Writes the service unit test for a command."""
6809 expected_call
= "EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));"
6810 if func
.GetInfo("first_element_only"):
6812 arg
.GetValidGLArg(func
) for arg
in func
.GetOriginalArgs()
6814 gl_arg_strings
[-1] = "*" + gl_arg_strings
[-1]
6815 expected_call
= ("EXPECT_CALL(*gl_, %%(gl_func_name)s(%s));" %
6816 ", ".join(gl_arg_strings
))
6818 TEST_P(%(test_name)s, %(name)sValidArgs) {
6819 SpecializedSetup<cmds::%(name)s, 0>(true);
6822 GetSharedMemoryAs<%(data_type)s*>()[0] = %(data_value)s;
6824 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
6825 EXPECT_EQ(GL_NO_ERROR, GetGLError());
6829 'data_type': self
.GetArrayType(func
),
6830 'data_value': func
.GetInfo('data_value') or '0',
6831 'expected_call': expected_call
,
6833 self
.WriteValidUnitTest(func
, file, valid_test
, extra
, *extras
)
6836 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
6837 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
6838 SpecializedSetup<cmds::%(name)s, 0>(false);
6841 GetSharedMemoryAs<%(data_type)s*>()[0] = %(data_value)s;
6842 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
6845 self
.WriteInvalidUnitTest(func
, file, invalid_test
, extra
, *extras
)
6847 def WriteImmediateServiceUnitTest(self
, func
, file, *extras
):
6848 """Writes the service unit test for a command."""
6850 TEST_P(%(test_name)s, %(name)sValidArgs) {
6851 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
6852 SpecializedSetup<cmds::%(name)s, 0>(true);
6853 %(data_type)s temp[%(data_count)s] = { %(data_value)s, };
6854 cmd.Init(%(gl_args)s, &temp[0]);
6857 %(gl_func_name)s(%(gl_args)s, %(data_ref)sreinterpret_cast<
6858 %(data_type)s*>(ImmediateDataAddress(&cmd))));"""
6861 decoder_->set_unsafe_es3_apis_enabled(true);"""
6863 EXPECT_EQ(error::kNoError,
6864 ExecuteImmediateCmd(cmd, sizeof(temp)));
6865 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
6868 decoder_->set_unsafe_es3_apis_enabled(false);
6869 EXPECT_EQ(error::kUnknownCommand,
6870 ExecuteImmediateCmd(cmd, sizeof(temp)));"""
6875 arg
.GetValidGLArg(func
) for arg
in func
.GetOriginalArgs()[0:-1]
6877 gl_any_strings
= ["_"] * len(gl_arg_strings
)
6880 'data_ref': ("*" if func
.GetInfo('first_element_only') else ""),
6881 'data_type': self
.GetArrayType(func
),
6882 'data_count': self
.GetArrayCount(func
),
6883 'data_value': func
.GetInfo('data_value') or '0',
6884 'gl_args': ", ".join(gl_arg_strings
),
6885 'gl_any_args': ", ".join(gl_any_strings
),
6887 self
.WriteValidUnitTest(func
, file, valid_test
, extra
, *extras
)
6890 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
6891 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();"""
6894 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_any_args)s, _)).Times(1);
6898 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_any_args)s, _)).Times(0);
6901 SpecializedSetup<cmds::%(name)s, 0>(false);
6902 %(data_type)s temp[%(data_count)s] = { %(data_value)s, };
6903 cmd.Init(%(all_but_last_args)s, &temp[0]);"""
6906 decoder_->set_unsafe_es3_apis_enabled(true);
6907 EXPECT_EQ(error::%(parse_result)s,
6908 ExecuteImmediateCmd(cmd, sizeof(temp)));
6909 decoder_->set_unsafe_es3_apis_enabled(false);
6914 EXPECT_EQ(error::%(parse_result)s,
6915 ExecuteImmediateCmd(cmd, sizeof(temp)));
6919 self
.WriteInvalidUnitTest(func
, file, invalid_test
, extra
, *extras
)
6921 def WriteGetDataSizeCode(self
, func
, file):
6922 """Overrriden from TypeHandler."""
6923 code
= """ uint32_t data_size;
6924 if (!ComputeDataSize(1, sizeof(%s), %d, &data_size)) {
6925 return error::kOutOfBounds;
6928 file.Write(code
% (self
.GetArrayType(func
), self
.GetArrayCount(func
)))
6929 if func
.IsImmediate():
6930 file.Write(" if (data_size > immediate_data_size) {\n")
6931 file.Write(" return error::kOutOfBounds;\n")
6934 def __NeedsToCalcDataCount(self
, func
):
6935 use_count_func
= func
.GetInfo('use_count_func')
6936 return use_count_func
!= None and use_count_func
!= False
6938 def WriteGLES2Implementation(self
, func
, file):
6939 """Overrriden from TypeHandler."""
6940 impl_func
= func
.GetInfo('impl_func')
6941 if (impl_func
!= None and impl_func
!= True):
6943 file.Write("%s GLES2Implementation::%s(%s) {\n" %
6944 (func
.return_type
, func
.original_name
,
6945 func
.MakeTypedOriginalArgString("")))
6946 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
6947 func
.WriteDestinationInitalizationValidation(file)
6948 self
.WriteClientGLCallLog(func
, file)
6950 if self
.__NeedsToCalcDataCount
(func
):
6951 file.Write(" size_t count = GLES2Util::Calc%sDataCount(%s);\n" %
6952 (func
.name
, func
.GetOriginalArgs()[0].name
))
6953 file.Write(" DCHECK_LE(count, %du);\n" % self
.GetArrayCount(func
))
6955 file.Write(" size_t count = %d;" % self
.GetArrayCount(func
))
6956 file.Write(" for (size_t ii = 0; ii < count; ++ii)\n")
6957 file.Write(' GPU_CLIENT_LOG("value[" << ii << "]: " << %s[ii]);\n' %
6958 func
.GetLastOriginalArg().name
)
6959 for arg
in func
.GetOriginalArgs():
6960 arg
.WriteClientSideValidationCode(file, func
)
6961 file.Write(" helper_->%sImmediate(%s);\n" %
6962 (func
.name
, func
.MakeOriginalArgString("")))
6963 file.Write(" CheckGLError();\n")
6967 def WriteGLES2ImplementationUnitTest(self
, func
, file):
6968 """Writes the GLES2 Implemention unit test."""
6969 client_test
= func
.GetInfo('client_test')
6970 if (client_test
!= None and client_test
!= True):
6973 TEST_F(GLES2ImplementationTest, %(name)s) {
6974 %(type)s data[%(count)d] = {0};
6976 cmds::%(name)sImmediate cmd;
6977 %(type)s data[%(count)d];
6980 for (int jj = 0; jj < %(count)d; ++jj) {
6981 data[jj] = static_cast<%(type)s>(jj);
6984 expected.cmd.Init(%(cmd_args)s, &data[0]);
6985 gl_->%(name)s(%(args)s, &data[0]);
6986 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
6990 arg
.GetValidClientSideCmdArg(func
) for arg
in func
.GetCmdArgs()[0:-2]
6993 arg
.GetValidClientSideArg(func
) for arg
in func
.GetOriginalArgs()[0:-1]
6998 'type': self
.GetArrayType(func
),
6999 'count': self
.GetArrayCount(func
),
7000 'args': ", ".join(gl_arg_strings
),
7001 'cmd_args': ", ".join(cmd_arg_strings
),
7004 def WriteImmediateCmdComputeSize(self
, func
, file):
7005 """Overrriden from TypeHandler."""
7006 file.Write(" static uint32_t ComputeDataSize() {\n")
7007 file.Write(" return static_cast<uint32_t>(\n")
7008 file.Write(" sizeof(%s) * %d);\n" %
7009 (self
.GetArrayType(func
), self
.GetArrayCount(func
)))
7012 if self
.__NeedsToCalcDataCount
(func
):
7013 file.Write(" static uint32_t ComputeEffectiveDataSize(%s %s) {\n" %
7014 (func
.GetOriginalArgs()[0].type,
7015 func
.GetOriginalArgs()[0].name
))
7016 file.Write(" return static_cast<uint32_t>(\n")
7017 file.Write(" sizeof(%s) * GLES2Util::Calc%sDataCount(%s));\n" %
7018 (self
.GetArrayType(func
), func
.original_name
,
7019 func
.GetOriginalArgs()[0].name
))
7022 file.Write(" static uint32_t ComputeSize() {\n")
7023 file.Write(" return static_cast<uint32_t>(\n")
7025 " sizeof(ValueType) + ComputeDataSize());\n")
7029 def WriteImmediateCmdSetHeader(self
, func
, file):
7030 """Overrriden from TypeHandler."""
7031 file.Write(" void SetHeader() {\n")
7033 " header.SetCmdByTotalSize<ValueType>(ComputeSize());\n")
7037 def WriteImmediateCmdInit(self
, func
, file):
7038 """Overrriden from TypeHandler."""
7039 last_arg
= func
.GetLastOriginalArg()
7040 file.Write(" void Init(%s, %s _%s) {\n" %
7041 (func
.MakeTypedCmdArgString("_"),
7042 last_arg
.type, last_arg
.name
))
7043 file.Write(" SetHeader();\n")
7044 args
= func
.GetCmdArgs()
7046 file.Write(" %s = _%s;\n" % (arg
.name
, arg
.name
))
7047 file.Write(" memcpy(ImmediateDataAddress(this),\n")
7048 if self
.__NeedsToCalcDataCount
(func
):
7049 file.Write(" _%s, ComputeEffectiveDataSize(%s));" %
7050 (last_arg
.name
, func
.GetOriginalArgs()[0].name
))
7052 DCHECK_GE(ComputeDataSize(), ComputeEffectiveDataSize(%(arg)s));
7053 char* pointer = reinterpret_cast<char*>(ImmediateDataAddress(this)) +
7054 ComputeEffectiveDataSize(%(arg)s);
7055 memset(pointer, 0, ComputeDataSize() - ComputeEffectiveDataSize(%(arg)s));
7056 """ % { 'arg': func
.GetOriginalArgs()[0].name
, })
7058 file.Write(" _%s, ComputeDataSize());\n" % last_arg
.name
)
7062 def WriteImmediateCmdSet(self
, func
, file):
7063 """Overrriden from TypeHandler."""
7064 last_arg
= func
.GetLastOriginalArg()
7065 copy_args
= func
.MakeCmdArgString("_", False)
7066 file.Write(" void* Set(void* cmd%s, %s _%s) {\n" %
7067 (func
.MakeTypedCmdArgString("_", True),
7068 last_arg
.type, last_arg
.name
))
7069 file.Write(" static_cast<ValueType*>(cmd)->Init(%s, _%s);\n" %
7070 (copy_args
, last_arg
.name
))
7071 file.Write(" const uint32_t size = ComputeSize();\n")
7072 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
7077 def WriteImmediateCmdHelper(self
, func
, file):
7078 """Overrriden from TypeHandler."""
7079 code
= """ void %(name)s(%(typed_args)s) {
7080 const uint32_t size = gles2::cmds::%(name)s::ComputeSize();
7081 gles2::cmds::%(name)s* c =
7082 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
7091 "typed_args": func
.MakeTypedOriginalArgString(""),
7092 "args": func
.MakeOriginalArgString(""),
7095 def WriteImmediateFormatTest(self
, func
, file):
7096 """Overrriden from TypeHandler."""
7097 file.Write("TEST_F(GLES2FormatTest, %s) {\n" % func
.name
)
7098 file.Write(" const int kSomeBaseValueToTestWith = 51;\n")
7099 file.Write(" static %s data[] = {\n" % self
.GetArrayType(func
))
7100 for v
in range(0, self
.GetArrayCount(func
)):
7101 file.Write(" static_cast<%s>(kSomeBaseValueToTestWith + %d),\n" %
7102 (self
.GetArrayType(func
), v
))
7104 file.Write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
7105 (func
.name
, func
.name
))
7106 file.Write(" void* next_cmd = cmd.Set(\n")
7108 args
= func
.GetCmdArgs()
7109 for value
, arg
in enumerate(args
):
7110 file.Write(",\n static_cast<%s>(%d)" % (arg
.type, value
+ 11))
7111 file.Write(",\n data);\n")
7112 args
= func
.GetCmdArgs()
7113 file.Write(" EXPECT_EQ(static_cast<uint32_t>(cmds::%s::kCmdId),\n"
7115 file.Write(" cmd.header.command);\n")
7116 file.Write(" EXPECT_EQ(sizeof(cmd) +\n")
7117 file.Write(" RoundSizeToMultipleOfEntries(sizeof(data)),\n")
7118 file.Write(" cmd.header.size * 4u);\n")
7119 for value
, arg
in enumerate(args
):
7120 file.Write(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);\n" %
7121 (arg
.type, value
+ 11, arg
.name
))
7122 file.Write(" CheckBytesWrittenMatchesExpectedSize(\n")
7123 file.Write(" next_cmd, sizeof(cmd) +\n")
7124 file.Write(" RoundSizeToMultipleOfEntries(sizeof(data)));\n")
7125 file.Write(" // TODO(gman): Check that data was inserted;\n")
7130 class PUTnHandler(ArrayArgTypeHandler
):
7131 """Handler for PUTn 'glUniform__v' type functions."""
7134 ArrayArgTypeHandler
.__init
__(self
)
7136 def WriteServiceUnitTest(self
, func
, file, *extras
):
7137 """Overridden from TypeHandler."""
7138 ArrayArgTypeHandler
.WriteServiceUnitTest(self
, func
, file, *extras
)
7141 TEST_P(%(test_name)s, %(name)sValidArgsCountTooLarge) {
7142 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
7143 SpecializedSetup<cmds::%(name)s, 0>(true);
7146 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
7147 EXPECT_EQ(GL_NO_ERROR, GetGLError());
7152 for count
, arg
in enumerate(func
.GetOriginalArgs()):
7153 # hardcoded to match unit tests.
7155 # the location of the second element of the 2nd uniform.
7156 # defined in GLES2DecoderBase::SetupShaderForUniform
7157 gl_arg_strings
.append("3")
7158 arg_strings
.append("ProgramManager::MakeFakeLocation(1, 1)")
7160 # the number of elements that gl will be called with.
7161 gl_arg_strings
.append("3")
7162 # the number of elements requested in the command.
7163 arg_strings
.append("5")
7165 gl_arg_strings
.append(arg
.GetValidGLArg(func
))
7166 if not arg
.IsConstant():
7167 arg_strings
.append(arg
.GetValidArg(func
))
7169 'gl_args': ", ".join(gl_arg_strings
),
7170 'args': ", ".join(arg_strings
),
7172 self
.WriteValidUnitTest(func
, file, valid_test
, extra
, *extras
)
7174 def WriteImmediateServiceUnitTest(self
, func
, file, *extras
):
7175 """Overridden from TypeHandler."""
7177 TEST_P(%(test_name)s, %(name)sValidArgs) {
7178 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
7181 %(gl_func_name)s(%(gl_args)s,
7182 reinterpret_cast<%(data_type)s*>(ImmediateDataAddress(&cmd))));
7183 SpecializedSetup<cmds::%(name)s, 0>(true);
7184 %(data_type)s temp[%(data_count)s * 2] = { 0, };
7185 cmd.Init(%(args)s, &temp[0]);"""
7188 decoder_->set_unsafe_es3_apis_enabled(true);"""
7190 EXPECT_EQ(error::kNoError,
7191 ExecuteImmediateCmd(cmd, sizeof(temp)));
7192 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
7195 decoder_->set_unsafe_es3_apis_enabled(false);
7196 EXPECT_EQ(error::kUnknownCommand,
7197 ExecuteImmediateCmd(cmd, sizeof(temp)));"""
7204 for arg
in func
.GetOriginalArgs()[0:-1]:
7205 gl_arg_strings
.append(arg
.GetValidGLArg(func
))
7206 gl_any_strings
.append("_")
7207 if not arg
.IsConstant():
7208 arg_strings
.append(arg
.GetValidArg(func
))
7210 'data_type': self
.GetArrayType(func
),
7211 'data_count': self
.GetArrayCount(func
),
7212 'args': ", ".join(arg_strings
),
7213 'gl_args': ", ".join(gl_arg_strings
),
7214 'gl_any_args': ", ".join(gl_any_strings
),
7216 self
.WriteValidUnitTest(func
, file, valid_test
, extra
, *extras
)
7219 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
7220 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
7221 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_any_args)s, _)).Times(0);
7222 SpecializedSetup<cmds::%(name)s, 0>(false);
7223 %(data_type)s temp[%(data_count)s * 2] = { 0, };
7224 cmd.Init(%(all_but_last_args)s, &temp[0]);
7225 EXPECT_EQ(error::%(parse_result)s,
7226 ExecuteImmediateCmd(cmd, sizeof(temp)));%(gl_error_test)s
7229 self
.WriteInvalidUnitTest(func
, file, invalid_test
, extra
, *extras
)
7231 def WriteGetDataSizeCode(self
, func
, file):
7232 """Overrriden from TypeHandler."""
7233 code
= """ uint32_t data_size;
7234 if (!ComputeDataSize(count, sizeof(%s), %d, &data_size)) {
7235 return error::kOutOfBounds;
7238 file.Write(code
% (self
.GetArrayType(func
), self
.GetArrayCount(func
)))
7239 if func
.IsImmediate():
7240 file.Write(" if (data_size > immediate_data_size) {\n")
7241 file.Write(" return error::kOutOfBounds;\n")
7244 def WriteGLES2Implementation(self
, func
, file):
7245 """Overrriden from TypeHandler."""
7246 file.Write("%s GLES2Implementation::%s(%s) {\n" %
7247 (func
.return_type
, func
.original_name
,
7248 func
.MakeTypedOriginalArgString("")))
7249 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
7250 func
.WriteDestinationInitalizationValidation(file)
7251 self
.WriteClientGLCallLog(func
, file)
7252 last_pointer_name
= func
.GetLastOriginalPointerArg().name
7253 file.Write(""" GPU_CLIENT_LOG_CODE_BLOCK({
7254 for (GLsizei i = 0; i < count; ++i) {
7256 values_str
= ' << ", " << '.join(
7257 ["%s[%d + i * %d]" % (
7258 last_pointer_name
, ndx
, self
.GetArrayCount(func
)) for ndx
in range(
7259 0, self
.GetArrayCount(func
))])
7260 file.Write(' GPU_CLIENT_LOG(" " << i << ": " << %s);\n' % values_str
)
7261 file.Write(" }\n });\n")
7262 for arg
in func
.GetOriginalArgs():
7263 arg
.WriteClientSideValidationCode(file, func
)
7264 file.Write(" helper_->%sImmediate(%s);\n" %
7265 (func
.name
, func
.MakeInitString("")))
7266 file.Write(" CheckGLError();\n")
7270 def WriteGLES2ImplementationUnitTest(self
, func
, file):
7271 """Writes the GLES2 Implemention unit test."""
7273 TEST_F(GLES2ImplementationTest, %(name)s) {
7274 %(type)s data[%(count_param)d][%(count)d] = {{0}};
7276 cmds::%(name)sImmediate cmd;
7277 %(type)s data[%(count_param)d][%(count)d];
7281 for (int ii = 0; ii < %(count_param)d; ++ii) {
7282 for (int jj = 0; jj < %(count)d; ++jj) {
7283 data[ii][jj] = static_cast<%(type)s>(ii * %(count)d + jj);
7286 expected.cmd.Init(%(cmd_args)s);
7287 gl_->%(name)s(%(args)s);
7288 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
7291 cmd_arg_strings
= []
7292 for arg
in func
.GetCmdArgs():
7293 if arg
.name
.endswith("_shm_id"):
7294 cmd_arg_strings
.append("&data[0][0]")
7295 elif arg
.name
.endswith("_shm_offset"):
7298 cmd_arg_strings
.append(arg
.GetValidClientSideCmdArg(func
))
7301 for arg
in func
.GetOriginalArgs():
7303 valid_value
= "&data[0][0]"
7305 valid_value
= arg
.GetValidClientSideArg(func
)
7306 gl_arg_strings
.append(valid_value
)
7307 if arg
.name
== "count":
7308 count_param
= int(valid_value
)
7311 'type': self
.GetArrayType(func
),
7312 'count': self
.GetArrayCount(func
),
7313 'args': ", ".join(gl_arg_strings
),
7314 'cmd_args': ", ".join(cmd_arg_strings
),
7315 'count_param': count_param
,
7318 # Test constants for invalid values, as they are not tested by the
7321 arg
for arg
in func
.GetOriginalArgs()[0:-1] if arg
.IsConstant()
7327 TEST_F(GLES2ImplementationTest, %(name)sInvalidConstantArg%(invalid_index)d) {
7328 %(type)s data[%(count_param)d][%(count)d] = {{0}};
7329 for (int ii = 0; ii < %(count_param)d; ++ii) {
7330 for (int jj = 0; jj < %(count)d; ++jj) {
7331 data[ii][jj] = static_cast<%(type)s>(ii * %(count)d + jj);
7334 gl_->%(name)s(%(args)s);
7335 EXPECT_TRUE(NoCommandsWritten());
7336 EXPECT_EQ(%(gl_error)s, CheckError());
7339 for invalid_arg
in constants
:
7341 invalid
= invalid_arg
.GetInvalidArg(func
)
7342 for arg
in func
.GetOriginalArgs():
7343 if arg
is invalid_arg
:
7344 gl_arg_strings
.append(invalid
[0])
7345 elif arg
.IsPointer():
7346 gl_arg_strings
.append("&data[0][0]")
7348 valid_value
= arg
.GetValidClientSideArg(func
)
7349 gl_arg_strings
.append(valid_value
)
7350 if arg
.name
== "count":
7351 count_param
= int(valid_value
)
7355 'invalid_index': func
.GetOriginalArgs().index(invalid_arg
),
7356 'type': self
.GetArrayType(func
),
7357 'count': self
.GetArrayCount(func
),
7358 'args': ", ".join(gl_arg_strings
),
7359 'gl_error': invalid
[2],
7360 'count_param': count_param
,
7364 def WriteImmediateCmdComputeSize(self
, func
, file):
7365 """Overrriden from TypeHandler."""
7366 file.Write(" static uint32_t ComputeDataSize(GLsizei count) {\n")
7367 file.Write(" return static_cast<uint32_t>(\n")
7368 file.Write(" sizeof(%s) * %d * count); // NOLINT\n" %
7369 (self
.GetArrayType(func
), self
.GetArrayCount(func
)))
7372 file.Write(" static uint32_t ComputeSize(GLsizei count) {\n")
7373 file.Write(" return static_cast<uint32_t>(\n")
7375 " sizeof(ValueType) + ComputeDataSize(count)); // NOLINT\n")
7379 def WriteImmediateCmdSetHeader(self
, func
, file):
7380 """Overrriden from TypeHandler."""
7381 file.Write(" void SetHeader(GLsizei count) {\n")
7383 " header.SetCmdByTotalSize<ValueType>(ComputeSize(count));\n")
7387 def WriteImmediateCmdInit(self
, func
, file):
7388 """Overrriden from TypeHandler."""
7389 file.Write(" void Init(%s) {\n" %
7390 func
.MakeTypedInitString("_"))
7391 file.Write(" SetHeader(_count);\n")
7392 args
= func
.GetCmdArgs()
7394 file.Write(" %s = _%s;\n" % (arg
.name
, arg
.name
))
7395 file.Write(" memcpy(ImmediateDataAddress(this),\n")
7396 pointer_arg
= func
.GetLastOriginalPointerArg()
7397 file.Write(" _%s, ComputeDataSize(_count));\n" % pointer_arg
.name
)
7401 def WriteImmediateCmdSet(self
, func
, file):
7402 """Overrriden from TypeHandler."""
7403 file.Write(" void* Set(void* cmd%s) {\n" %
7404 func
.MakeTypedInitString("_", True))
7405 file.Write(" static_cast<ValueType*>(cmd)->Init(%s);\n" %
7406 func
.MakeInitString("_"))
7407 file.Write(" const uint32_t size = ComputeSize(_count);\n")
7408 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
7413 def WriteImmediateCmdHelper(self
, func
, file):
7414 """Overrriden from TypeHandler."""
7415 code
= """ void %(name)s(%(typed_args)s) {
7416 const uint32_t size = gles2::cmds::%(name)s::ComputeSize(count);
7417 gles2::cmds::%(name)s* c =
7418 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
7427 "typed_args": func
.MakeTypedInitString(""),
7428 "args": func
.MakeInitString("")
7431 def WriteImmediateFormatTest(self
, func
, file):
7432 """Overrriden from TypeHandler."""
7433 args
= func
.GetOriginalArgs()
7436 if arg
.name
== "count":
7437 count_param
= int(arg
.GetValidClientSideCmdArg(func
))
7438 file.Write("TEST_F(GLES2FormatTest, %s) {\n" % func
.name
)
7439 file.Write(" const int kSomeBaseValueToTestWith = 51;\n")
7440 file.Write(" static %s data[] = {\n" % self
.GetArrayType(func
))
7441 for v
in range(0, self
.GetArrayCount(func
) * count_param
):
7442 file.Write(" static_cast<%s>(kSomeBaseValueToTestWith + %d),\n" %
7443 (self
.GetArrayType(func
), v
))
7445 file.Write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
7446 (func
.name
, func
.name
))
7447 file.Write(" const GLsizei kNumElements = %d;\n" % count_param
)
7448 file.Write(" const size_t kExpectedCmdSize =\n")
7449 file.Write(" sizeof(cmd) + kNumElements * sizeof(%s) * %d;\n" %
7450 (self
.GetArrayType(func
), self
.GetArrayCount(func
)))
7451 file.Write(" void* next_cmd = cmd.Set(\n")
7453 for value
, arg
in enumerate(args
):
7455 file.Write(",\n data")
7456 elif arg
.IsConstant():
7459 file.Write(",\n static_cast<%s>(%d)" % (arg
.type, value
+ 1))
7461 file.Write(" EXPECT_EQ(static_cast<uint32_t>(cmds::%s::kCmdId),\n" %
7463 file.Write(" cmd.header.command);\n")
7464 file.Write(" EXPECT_EQ(kExpectedCmdSize, cmd.header.size * 4u);\n")
7465 for value
, arg
in enumerate(args
):
7466 if arg
.IsPointer() or arg
.IsConstant():
7468 file.Write(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);\n" %
7469 (arg
.type, value
+ 1, arg
.name
))
7470 file.Write(" CheckBytesWrittenMatchesExpectedSize(\n")
7471 file.Write(" next_cmd, sizeof(cmd) +\n")
7472 file.Write(" RoundSizeToMultipleOfEntries(sizeof(data)));\n")
7473 file.Write(" // TODO(gman): Check that data was inserted;\n")
7477 class PUTSTRHandler(ArrayArgTypeHandler
):
7478 """Handler for functions that pass a string array."""
7481 ArrayArgTypeHandler
.__init
__(self
)
7483 def __GetDataArg(self
, func
):
7484 """Return the argument that points to the 2D char arrays"""
7485 for arg
in func
.GetOriginalArgs():
7486 if arg
.IsPointer2D():
7490 def __GetLengthArg(self
, func
):
7491 """Return the argument that holds length for each char array"""
7492 for arg
in func
.GetOriginalArgs():
7493 if arg
.IsPointer() and not arg
.IsPointer2D():
7497 def WriteGLES2Implementation(self
, func
, file):
7498 """Overrriden from TypeHandler."""
7499 file.Write("%s GLES2Implementation::%s(%s) {\n" %
7500 (func
.return_type
, func
.original_name
,
7501 func
.MakeTypedOriginalArgString("")))
7502 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
7503 func
.WriteDestinationInitalizationValidation(file)
7504 self
.WriteClientGLCallLog(func
, file)
7505 data_arg
= self
.__GetDataArg
(func
)
7506 length_arg
= self
.__GetLengthArg
(func
)
7507 log_code_block
= """ GPU_CLIENT_LOG_CODE_BLOCK({
7508 for (GLsizei ii = 0; ii < count; ++ii) {
7509 if (%(data)s[ii]) {"""
7510 if length_arg
== None:
7511 log_code_block
+= """
7512 GPU_CLIENT_LOG(" " << ii << ": ---\\n" << %(data)s[ii] << "\\n---");"""
7514 log_code_block
+= """
7515 if (%(length)s && %(length)s[ii] >= 0) {
7516 const std::string my_str(%(data)s[ii], %(length)s[ii]);
7517 GPU_CLIENT_LOG(" " << ii << ": ---\\n" << my_str << "\\n---");
7519 GPU_CLIENT_LOG(" " << ii << ": ---\\n" << %(data)s[ii] << "\\n---");
7521 log_code_block
+= """
7523 GPU_CLIENT_LOG(" " << ii << ": NULL");
7528 file.Write(log_code_block
% {
7529 'data': data_arg
.name
,
7530 'length': length_arg
.name
if not length_arg
== None else ''
7532 for arg
in func
.GetOriginalArgs():
7533 arg
.WriteClientSideValidationCode(file, func
)
7536 for arg
in func
.GetOriginalArgs():
7537 if arg
.name
== 'count' or arg
== self
.__GetLengthArg
(func
):
7539 if arg
== self
.__GetDataArg
(func
):
7540 bucket_args
.append('kResultBucketId')
7542 bucket_args
.append(arg
.name
)
7544 if (!PackStringsToBucket(count, %(data)s, %(length)s, "gl%(func_name)s")) {
7547 helper_->%(func_name)sBucket(%(bucket_args)s);
7548 helper_->SetBucketSize(kResultBucketId, 0);
7553 file.Write(code_block
% {
7554 'data': data_arg
.name
,
7555 'length': length_arg
.name
if not length_arg
== None else 'NULL',
7556 'func_name': func
.name
,
7557 'bucket_args': ', '.join(bucket_args
),
7560 def WriteGLES2ImplementationUnitTest(self
, func
, file):
7561 """Overrriden from TypeHandler."""
7563 TEST_F(GLES2ImplementationTest, %(name)s) {
7564 const uint32 kBucketId = GLES2Implementation::kResultBucketId;
7565 const char* kString1 = "happy";
7566 const char* kString2 = "ending";
7567 const size_t kString1Size = ::strlen(kString1) + 1;
7568 const size_t kString2Size = ::strlen(kString2) + 1;
7569 const size_t kHeaderSize = sizeof(GLint) * 3;
7570 const size_t kSourceSize = kHeaderSize + kString1Size + kString2Size;
7571 const size_t kPaddedHeaderSize =
7572 transfer_buffer_->RoundToAlignment(kHeaderSize);
7573 const size_t kPaddedString1Size =
7574 transfer_buffer_->RoundToAlignment(kString1Size);
7575 const size_t kPaddedString2Size =
7576 transfer_buffer_->RoundToAlignment(kString2Size);
7578 cmd::SetBucketSize set_bucket_size;
7579 cmd::SetBucketData set_bucket_header;
7580 cmd::SetToken set_token1;
7581 cmd::SetBucketData set_bucket_data1;
7582 cmd::SetToken set_token2;
7583 cmd::SetBucketData set_bucket_data2;
7584 cmd::SetToken set_token3;
7585 cmds::%(name)sBucket cmd_bucket;
7586 cmd::SetBucketSize clear_bucket_size;
7589 ExpectedMemoryInfo mem0 = GetExpectedMemory(kPaddedHeaderSize);
7590 ExpectedMemoryInfo mem1 = GetExpectedMemory(kPaddedString1Size);
7591 ExpectedMemoryInfo mem2 = GetExpectedMemory(kPaddedString2Size);
7594 expected.set_bucket_size.Init(kBucketId, kSourceSize);
7595 expected.set_bucket_header.Init(
7596 kBucketId, 0, kHeaderSize, mem0.id, mem0.offset);
7597 expected.set_token1.Init(GetNextToken());
7598 expected.set_bucket_data1.Init(
7599 kBucketId, kHeaderSize, kString1Size, mem1.id, mem1.offset);
7600 expected.set_token2.Init(GetNextToken());
7601 expected.set_bucket_data2.Init(
7602 kBucketId, kHeaderSize + kString1Size, kString2Size, mem2.id,
7604 expected.set_token3.Init(GetNextToken());
7605 expected.cmd_bucket.Init(%(bucket_args)s);
7606 expected.clear_bucket_size.Init(kBucketId, 0);
7607 const char* kStrings[] = { kString1, kString2 };
7608 gl_->%(name)s(%(gl_args)s);
7609 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
7614 for arg
in func
.GetOriginalArgs():
7615 if arg
== self
.__GetDataArg
(func
):
7616 gl_args
.append('kStrings')
7617 bucket_args
.append('kBucketId')
7618 elif arg
== self
.__GetLengthArg
(func
):
7619 gl_args
.append('NULL')
7620 elif arg
.name
== 'count':
7623 gl_args
.append(arg
.GetValidClientSideArg(func
))
7624 bucket_args
.append(arg
.GetValidClientSideArg(func
))
7627 'gl_args': ", ".join(gl_args
),
7628 'bucket_args': ", ".join(bucket_args
),
7631 if self
.__GetLengthArg
(func
) == None:
7634 TEST_F(GLES2ImplementationTest, %(name)sWithLength) {
7635 const uint32 kBucketId = GLES2Implementation::kResultBucketId;
7636 const char* kString = "foobar******";
7637 const size_t kStringSize = 6; // We only need "foobar".
7638 const size_t kHeaderSize = sizeof(GLint) * 2;
7639 const size_t kSourceSize = kHeaderSize + kStringSize + 1;
7640 const size_t kPaddedHeaderSize =
7641 transfer_buffer_->RoundToAlignment(kHeaderSize);
7642 const size_t kPaddedStringSize =
7643 transfer_buffer_->RoundToAlignment(kStringSize + 1);
7645 cmd::SetBucketSize set_bucket_size;
7646 cmd::SetBucketData set_bucket_header;
7647 cmd::SetToken set_token1;
7648 cmd::SetBucketData set_bucket_data;
7649 cmd::SetToken set_token2;
7650 cmds::ShaderSourceBucket shader_source_bucket;
7651 cmd::SetBucketSize clear_bucket_size;
7654 ExpectedMemoryInfo mem0 = GetExpectedMemory(kPaddedHeaderSize);
7655 ExpectedMemoryInfo mem1 = GetExpectedMemory(kPaddedStringSize);
7658 expected.set_bucket_size.Init(kBucketId, kSourceSize);
7659 expected.set_bucket_header.Init(
7660 kBucketId, 0, kHeaderSize, mem0.id, mem0.offset);
7661 expected.set_token1.Init(GetNextToken());
7662 expected.set_bucket_data.Init(
7663 kBucketId, kHeaderSize, kStringSize + 1, mem1.id, mem1.offset);
7664 expected.set_token2.Init(GetNextToken());
7665 expected.shader_source_bucket.Init(%(bucket_args)s);
7666 expected.clear_bucket_size.Init(kBucketId, 0);
7667 const char* kStrings[] = { kString };
7668 const GLint kLength[] = { kStringSize };
7669 gl_->%(name)s(%(gl_args)s);
7670 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
7674 for arg
in func
.GetOriginalArgs():
7675 if arg
== self
.__GetDataArg
(func
):
7676 gl_args
.append('kStrings')
7677 elif arg
== self
.__GetLengthArg
(func
):
7678 gl_args
.append('kLength')
7679 elif arg
.name
== 'count':
7682 gl_args
.append(arg
.GetValidClientSideArg(func
))
7685 'gl_args': ", ".join(gl_args
),
7686 'bucket_args': ", ".join(bucket_args
),
7689 def WriteBucketServiceUnitTest(self
, func
, file, *extras
):
7690 """Overrriden from TypeHandler."""
7692 cmd_args_with_invalid_id
= []
7694 for index
, arg
in enumerate(func
.GetOriginalArgs()):
7695 if arg
== self
.__GetLengthArg
(func
):
7697 elif arg
.name
== 'count':
7699 elif arg
== self
.__GetDataArg
(func
):
7700 cmd_args
.append('kBucketId')
7701 cmd_args_with_invalid_id
.append('kBucketId')
7703 elif index
== 0: # Resource ID arg
7704 cmd_args
.append(arg
.GetValidArg(func
))
7705 cmd_args_with_invalid_id
.append('kInvalidClientId')
7706 gl_args
.append(arg
.GetValidGLArg(func
))
7708 cmd_args
.append(arg
.GetValidArg(func
))
7709 cmd_args_with_invalid_id
.append(arg
.GetValidArg(func
))
7710 gl_args
.append(arg
.GetValidGLArg(func
))
7713 TEST_P(%(test_name)s, %(name)sValidArgs) {
7714 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
7715 const uint32 kBucketId = 123;
7716 const char kSource0[] = "hello";
7717 const char* kSource[] = { kSource0 };
7718 const char kValidStrEnd = 0;
7719 SetBucketAsCStrings(kBucketId, 1, kSource, 1, kValidStrEnd);
7721 cmd.Init(%(cmd_args)s);
7722 decoder_->set_unsafe_es3_apis_enabled(true);
7723 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));"""
7726 decoder_->set_unsafe_es3_apis_enabled(false);
7727 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));
7732 self
.WriteValidUnitTest(func
, file, test
, {
7733 'cmd_args': ", ".join(cmd_args
),
7734 'gl_args': ", ".join(gl_args
),
7738 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
7739 const uint32 kBucketId = 123;
7740 const char kSource0[] = "hello";
7741 const char* kSource[] = { kSource0 };
7742 const char kValidStrEnd = 0;
7743 decoder_->set_unsafe_es3_apis_enabled(true);
7746 cmd.Init(%(cmd_args)s);
7747 EXPECT_NE(error::kNoError, ExecuteCmd(cmd));
7748 // Test invalid client.
7749 SetBucketAsCStrings(kBucketId, 1, kSource, 1, kValidStrEnd);
7750 cmd.Init(%(cmd_args_with_invalid_id)s);
7751 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
7752 EXPECT_EQ(GL_INVALID_VALUE, GetGLError());
7755 self
.WriteValidUnitTest(func
, file, test
, {
7756 'cmd_args': ", ".join(cmd_args
),
7757 'cmd_args_with_invalid_id': ", ".join(cmd_args_with_invalid_id
),
7761 TEST_P(%(test_name)s, %(name)sInvalidHeader) {
7762 const uint32 kBucketId = 123;
7763 const char kSource0[] = "hello";
7764 const char* kSource[] = { kSource0 };
7765 const char kValidStrEnd = 0;
7766 const GLsizei kCount = static_cast<GLsizei>(arraysize(kSource));
7767 const GLsizei kTests[] = {
7770 std::numeric_limits<GLsizei>::max(),
7773 decoder_->set_unsafe_es3_apis_enabled(true);
7774 for (size_t ii = 0; ii < arraysize(kTests); ++ii) {
7775 SetBucketAsCStrings(kBucketId, 1, kSource, kTests[ii], kValidStrEnd);
7777 cmd.Init(%(cmd_args)s);
7778 EXPECT_EQ(error::kInvalidArguments, ExecuteCmd(cmd));
7782 self
.WriteValidUnitTest(func
, file, test
, {
7783 'cmd_args': ", ".join(cmd_args
),
7787 TEST_P(%(test_name)s, %(name)sInvalidStringEnding) {
7788 const uint32 kBucketId = 123;
7789 const char kSource0[] = "hello";
7790 const char* kSource[] = { kSource0 };
7791 const char kInvalidStrEnd = '*';
7792 SetBucketAsCStrings(kBucketId, 1, kSource, 1, kInvalidStrEnd);
7794 cmd.Init(%(cmd_args)s);
7795 decoder_->set_unsafe_es3_apis_enabled(true);
7796 EXPECT_EQ(error::kInvalidArguments, ExecuteCmd(cmd));
7799 self
.WriteValidUnitTest(func
, file, test
, {
7800 'cmd_args': ", ".join(cmd_args
),
7804 class PUTXnHandler(ArrayArgTypeHandler
):
7805 """Handler for glUniform?f functions."""
7807 ArrayArgTypeHandler
.__init
__(self
)
7809 def WriteHandlerImplementation(self
, func
, file):
7810 """Overrriden from TypeHandler."""
7811 code
= """ %(type)s temp[%(count)s] = { %(values)s};"""
7814 gl%(name)sv(%(location)s, 1, &temp[0]);
7818 Do%(name)sv(%(location)s, 1, &temp[0]);
7821 args
= func
.GetOriginalArgs()
7822 count
= int(self
.GetArrayCount(func
))
7823 num_args
= len(args
)
7824 for ii
in range(count
):
7825 values
+= "%s, " % args
[len(args
) - count
+ ii
].name
7829 'count': self
.GetArrayCount(func
),
7830 'type': self
.GetArrayType(func
),
7831 'location': args
[0].name
,
7832 'args': func
.MakeOriginalArgString(""),
7836 def WriteServiceUnitTest(self
, func
, file, *extras
):
7837 """Overrriden from TypeHandler."""
7839 TEST_P(%(test_name)s, %(name)sValidArgs) {
7840 EXPECT_CALL(*gl_, %(name)sv(%(local_args)s));
7841 SpecializedSetup<cmds::%(name)s, 0>(true);
7843 cmd.Init(%(args)s);"""
7846 decoder_->set_unsafe_es3_apis_enabled(true);"""
7848 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
7849 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
7852 decoder_->set_unsafe_es3_apis_enabled(false);
7853 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));"""
7857 args
= func
.GetOriginalArgs()
7858 local_args
= "%s, 1, _" % args
[0].GetValidGLArg(func
)
7859 self
.WriteValidUnitTest(func
, file, valid_test
, {
7861 'count': self
.GetArrayCount(func
),
7862 'local_args': local_args
,
7866 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
7867 EXPECT_CALL(*gl_, %(name)sv(_, _, _).Times(0);
7868 SpecializedSetup<cmds::%(name)s, 0>(false);
7871 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
7874 self
.WriteInvalidUnitTest(func
, file, invalid_test
, {
7875 'name': func
.GetInfo('name'),
7876 'count': self
.GetArrayCount(func
),
7880 class GLcharHandler(CustomHandler
):
7881 """Handler for functions that pass a single string ."""
7884 CustomHandler
.__init
__(self
)
7886 def WriteImmediateCmdComputeSize(self
, func
, file):
7887 """Overrriden from TypeHandler."""
7888 file.Write(" static uint32_t ComputeSize(uint32_t data_size) {\n")
7889 file.Write(" return static_cast<uint32_t>(\n")
7890 file.Write(" sizeof(ValueType) + data_size); // NOLINT\n")
7893 def WriteImmediateCmdSetHeader(self
, func
, file):
7894 """Overrriden from TypeHandler."""
7896 void SetHeader(uint32_t data_size) {
7897 header.SetCmdBySize<ValueType>(data_size);
7902 def WriteImmediateCmdInit(self
, func
, file):
7903 """Overrriden from TypeHandler."""
7904 last_arg
= func
.GetLastOriginalArg()
7905 args
= func
.GetCmdArgs()
7908 set_code
.append(" %s = _%s;" % (arg
.name
, arg
.name
))
7910 void Init(%(typed_args)s, uint32_t _data_size) {
7911 SetHeader(_data_size);
7913 memcpy(ImmediateDataAddress(this), _%(last_arg)s, _data_size);
7918 "typed_args": func
.MakeTypedArgString("_"),
7919 "set_code": "\n".join(set_code
),
7920 "last_arg": last_arg
.name
7923 def WriteImmediateCmdSet(self
, func
, file):
7924 """Overrriden from TypeHandler."""
7925 last_arg
= func
.GetLastOriginalArg()
7926 file.Write(" void* Set(void* cmd%s, uint32_t _data_size) {\n" %
7927 func
.MakeTypedCmdArgString("_", True))
7928 file.Write(" static_cast<ValueType*>(cmd)->Init(%s, _data_size);\n" %
7929 func
.MakeCmdArgString("_"))
7930 file.Write(" return NextImmediateCmdAddress<ValueType>("
7931 "cmd, _data_size);\n")
7935 def WriteImmediateCmdHelper(self
, func
, file):
7936 """Overrriden from TypeHandler."""
7937 code
= """ void %(name)s(%(typed_args)s) {
7938 const uint32_t data_size = strlen(name);
7939 gles2::cmds::%(name)s* c =
7940 GetImmediateCmdSpace<gles2::cmds::%(name)s>(data_size);
7942 c->Init(%(args)s, data_size);
7949 "typed_args": func
.MakeTypedOriginalArgString(""),
7950 "args": func
.MakeOriginalArgString(""),
7954 def WriteImmediateFormatTest(self
, func
, file):
7955 """Overrriden from TypeHandler."""
7958 all_but_last_arg
= func
.GetCmdArgs()[:-1]
7959 for value
, arg
in enumerate(all_but_last_arg
):
7960 init_code
.append(" static_cast<%s>(%d)," % (arg
.type, value
+ 11))
7961 for value
, arg
in enumerate(all_but_last_arg
):
7962 check_code
.append(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);" %
7963 (arg
.type, value
+ 11, arg
.name
))
7965 TEST_F(GLES2FormatTest, %(func_name)s) {
7966 cmds::%(func_name)s& cmd = *GetBufferAs<cmds::%(func_name)s>();
7967 static const char* const test_str = \"test string\";
7968 void* next_cmd = cmd.Set(
7973 EXPECT_EQ(static_cast<uint32_t>(cmds::%(func_name)s::kCmdId),
7974 cmd.header.command);
7975 EXPECT_EQ(sizeof(cmd) +
7976 RoundSizeToMultipleOfEntries(strlen(test_str)),
7977 cmd.header.size * 4u);
7978 EXPECT_EQ(static_cast<char*>(next_cmd),
7979 reinterpret_cast<char*>(&cmd) + sizeof(cmd) +
7980 RoundSizeToMultipleOfEntries(strlen(test_str)));
7982 EXPECT_EQ(static_cast<uint32_t>(strlen(test_str)), cmd.data_size);
7983 EXPECT_EQ(0, memcmp(test_str, ImmediateDataAddress(&cmd), strlen(test_str)));
7986 sizeof(cmd) + RoundSizeToMultipleOfEntries(strlen(test_str)),
7987 sizeof(cmd) + strlen(test_str));
7992 'func_name': func
.name
,
7993 'init_code': "\n".join(init_code
),
7994 'check_code': "\n".join(check_code
),
7998 class GLcharNHandler(CustomHandler
):
7999 """Handler for functions that pass a single string with an optional len."""
8002 CustomHandler
.__init
__(self
)
8004 def InitFunction(self
, func
):
8005 """Overrriden from TypeHandler."""
8007 func
.AddCmdArg(Argument('bucket_id', 'GLuint'))
8009 def NeedsDataTransferFunction(self
, func
):
8010 """Overriden from TypeHandler."""
8013 def AddBucketFunction(self
, generator
, func
):
8014 """Overrriden from TypeHandler."""
8017 def WriteServiceImplementation(self
, func
, file):
8018 """Overrriden from TypeHandler."""
8019 self
.WriteServiceHandlerFunctionHeader(func
, file)
8021 GLuint bucket_id = static_cast<GLuint>(c.%(bucket_id)s);
8022 Bucket* bucket = GetBucket(bucket_id);
8023 if (!bucket || bucket->size() == 0) {
8024 return error::kInvalidArguments;
8027 if (!bucket->GetAsString(&str)) {
8028 return error::kInvalidArguments;
8030 %(gl_func_name)s(0, str.c_str());
8031 return error::kNoError;
8036 'gl_func_name': func
.GetGLFunctionName(),
8037 'bucket_id': func
.cmd_args
[0].name
,
8041 class IsHandler(TypeHandler
):
8042 """Handler for glIs____ type and glGetError functions."""
8045 TypeHandler
.__init
__(self
)
8047 def InitFunction(self
, func
):
8048 """Overrriden from TypeHandler."""
8049 func
.AddCmdArg(Argument("result_shm_id", 'uint32_t'))
8050 func
.AddCmdArg(Argument("result_shm_offset", 'uint32_t'))
8051 if func
.GetInfo('result') == None:
8052 func
.AddInfo('result', ['uint32_t'])
8054 def WriteServiceUnitTest(self
, func
, file, *extras
):
8055 """Overrriden from TypeHandler."""
8057 TEST_P(%(test_name)s, %(name)sValidArgs) {
8058 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
8059 SpecializedSetup<cmds::%(name)s, 0>(true);
8061 cmd.Init(%(args)s%(comma)sshared_memory_id_, shared_memory_offset_);"""
8064 decoder_->set_unsafe_es3_apis_enabled(true);"""
8066 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
8067 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
8070 decoder_->set_unsafe_es3_apis_enabled(false);
8071 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));"""
8076 if len(func
.GetOriginalArgs()):
8078 self
.WriteValidUnitTest(func
, file, valid_test
, {
8083 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
8084 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
8085 SpecializedSetup<cmds::%(name)s, 0>(false);
8087 cmd.Init(%(args)s%(comma)sshared_memory_id_, shared_memory_offset_);
8088 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
8091 self
.WriteInvalidUnitTest(func
, file, invalid_test
, {
8096 TEST_P(%(test_name)s, %(name)sInvalidArgsBadSharedMemoryId) {
8097 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
8098 SpecializedSetup<cmds::%(name)s, 0>(false);"""
8101 decoder_->set_unsafe_es3_apis_enabled(true);"""
8104 cmd.Init(%(args)s%(comma)skInvalidSharedMemoryId, shared_memory_offset_);
8105 EXPECT_EQ(error::kOutOfBounds, ExecuteCmd(cmd));
8106 cmd.Init(%(args)s%(comma)sshared_memory_id_, kInvalidSharedMemoryOffset);
8107 EXPECT_EQ(error::kOutOfBounds, ExecuteCmd(cmd));"""
8110 decoder_->set_unsafe_es3_apis_enabled(true);"""
8114 self
.WriteValidUnitTest(func
, file, invalid_test
, {
8118 def WriteServiceImplementation(self
, func
, file):
8119 """Overrriden from TypeHandler."""
8120 self
.WriteServiceHandlerFunctionHeader(func
, file)
8121 self
.WriteHandlerExtensionCheck(func
, file)
8122 args
= func
.GetOriginalArgs()
8124 arg
.WriteGetCode(file)
8126 code
= """ typedef cmds::%(func_name)s::Result Result;
8127 Result* result_dst = GetSharedMemoryAs<Result*>(
8128 c.result_shm_id, c.result_shm_offset, sizeof(*result_dst));
8130 return error::kOutOfBounds;
8133 file.Write(code
% {'func_name': func
.name
})
8134 func
.WriteHandlerValidation(file)
8136 assert func
.GetInfo('id_mapping')
8137 assert len(func
.GetInfo('id_mapping')) == 1
8138 assert len(args
) == 1
8139 id_type
= func
.GetInfo('id_mapping')[0]
8140 file.Write(" %s service_%s = 0;\n" % (args
[0].type, id_type
.lower()))
8141 file.Write(" *result_dst = group_->Get%sServiceId(%s, &service_%s);\n" %
8142 (id_type
, id_type
.lower(), id_type
.lower()))
8144 file.Write(" *result_dst = %s(%s);\n" %
8145 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
8146 file.Write(" return error::kNoError;\n")
8150 def WriteGLES2Implementation(self
, func
, file):
8151 """Overrriden from TypeHandler."""
8152 impl_func
= func
.GetInfo('impl_func')
8153 if impl_func
== None or impl_func
== True:
8154 error_value
= func
.GetInfo("error_value") or "GL_FALSE"
8155 file.Write("%s GLES2Implementation::%s(%s) {\n" %
8156 (func
.return_type
, func
.original_name
,
8157 func
.MakeTypedOriginalArgString("")))
8158 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
8159 self
.WriteTraceEvent(func
, file)
8160 func
.WriteDestinationInitalizationValidation(file)
8161 self
.WriteClientGLCallLog(func
, file)
8162 file.Write(" typedef cmds::%s::Result Result;\n" % func
.name
)
8163 file.Write(" Result* result = GetResultAs<Result*>();\n")
8164 file.Write(" if (!result) {\n")
8165 file.Write(" return %s;\n" % error_value
)
8167 file.Write(" *result = 0;\n")
8168 assert len(func
.GetOriginalArgs()) == 1
8169 id_arg
= func
.GetOriginalArgs()[0]
8170 if id_arg
.type == 'GLsync':
8171 arg_string
= "ToGLuint(%s)" % func
.MakeOriginalArgString("")
8173 arg_string
= func
.MakeOriginalArgString("")
8175 " helper_->%s(%s, GetResultShmId(), GetResultShmOffset());\n" %
8176 (func
.name
, arg_string
))
8177 file.Write(" WaitForCmd();\n")
8178 file.Write(" %s result_value = *result" % func
.return_type
)
8179 if func
.return_type
== "GLboolean":
8181 file.Write(';\n GPU_CLIENT_LOG("returned " << result_value);\n')
8182 file.Write(" CheckGLError();\n")
8183 file.Write(" return result_value;\n")
8187 def WriteGLES2ImplementationUnitTest(self
, func
, file):
8188 """Overrriden from TypeHandler."""
8189 client_test
= func
.GetInfo('client_test')
8190 if client_test
== None or client_test
== True:
8192 TEST_F(GLES2ImplementationTest, %(name)s) {
8198 ExpectedMemoryInfo result1 =
8199 GetExpectedResultMemory(sizeof(cmds::%(name)s::Result));
8200 expected.cmd.Init(%(cmd_id_value)s, result1.id, result1.offset);
8202 EXPECT_CALL(*command_buffer(), OnFlush())
8203 .WillOnce(SetMemory(result1.ptr, uint32_t(GL_TRUE)))
8204 .RetiresOnSaturation();
8206 GLboolean result = gl_->%(name)s(%(gl_id_value)s);
8207 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
8208 EXPECT_TRUE(result);
8211 args
= func
.GetOriginalArgs()
8212 assert len(args
) == 1
8215 'cmd_id_value': args
[0].GetValidClientSideCmdArg(func
),
8216 'gl_id_value': args
[0].GetValidClientSideArg(func
) })
8219 class STRnHandler(TypeHandler
):
8220 """Handler for GetProgramInfoLog, GetShaderInfoLog, GetShaderSource, and
8221 GetTranslatedShaderSourceANGLE."""
8224 TypeHandler
.__init
__(self
)
8226 def InitFunction(self
, func
):
8227 """Overrriden from TypeHandler."""
8228 # remove all but the first cmd args.
8229 cmd_args
= func
.GetCmdArgs()
8231 func
.AddCmdArg(cmd_args
[0])
8232 # add on a bucket id.
8233 func
.AddCmdArg(Argument('bucket_id', 'uint32_t'))
8235 def WriteGLES2Implementation(self
, func
, file):
8236 """Overrriden from TypeHandler."""
8237 code_1
= """%(return_type)s GLES2Implementation::%(func_name)s(%(args)s) {
8238 GPU_CLIENT_SINGLE_THREAD_CHECK();
8240 code_2
= """ GPU_CLIENT_LOG("[" << GetLogPrefix()
8241 << "] gl%(func_name)s" << "("
8244 << static_cast<void*>(%(arg2)s) << ", "
8245 << static_cast<void*>(%(arg3)s) << ")");
8246 helper_->SetBucketSize(kResultBucketId, 0);
8247 helper_->%(func_name)s(%(id_name)s, kResultBucketId);
8249 GLsizei max_size = 0;
8250 if (GetBucketAsString(kResultBucketId, &str)) {
8253 std::min(static_cast<size_t>(%(bufsize_name)s) - 1, str.size());
8254 memcpy(%(dest_name)s, str.c_str(), max_size);
8255 %(dest_name)s[max_size] = '\\0';
8256 GPU_CLIENT_LOG("------\\n" << %(dest_name)s << "\\n------");
8259 if (%(length_name)s != NULL) {
8260 *%(length_name)s = max_size;
8265 args
= func
.GetOriginalArgs()
8267 'return_type': func
.return_type
,
8268 'func_name': func
.original_name
,
8269 'args': func
.MakeTypedOriginalArgString(""),
8270 'id_name': args
[0].name
,
8271 'bufsize_name': args
[1].name
,
8272 'length_name': args
[2].name
,
8273 'dest_name': args
[3].name
,
8274 'arg0': args
[0].name
,
8275 'arg1': args
[1].name
,
8276 'arg2': args
[2].name
,
8277 'arg3': args
[3].name
,
8279 file.Write(code_1
% str_args
)
8280 func
.WriteDestinationInitalizationValidation(file)
8281 file.Write(code_2
% str_args
)
8283 def WriteServiceUnitTest(self
, func
, file, *extras
):
8284 """Overrriden from TypeHandler."""
8286 TEST_P(%(test_name)s, %(name)sValidArgs) {
8287 const char* kInfo = "hello";
8288 const uint32_t kBucketId = 123;
8289 SpecializedSetup<cmds::%(name)s, 0>(true);
8291 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s))
8292 .WillOnce(DoAll(SetArgumentPointee<2>(strlen(kInfo)),
8293 SetArrayArgument<3>(kInfo, kInfo + strlen(kInfo) + 1)));
8296 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
8297 CommonDecoder::Bucket* bucket = decoder_->GetBucket(kBucketId);
8298 ASSERT_TRUE(bucket != NULL);
8299 EXPECT_EQ(strlen(kInfo) + 1, bucket->size());
8300 EXPECT_EQ(0, memcmp(bucket->GetData(0, bucket->size()), kInfo,
8302 EXPECT_EQ(GL_NO_ERROR, GetGLError());
8305 args
= func
.GetOriginalArgs()
8306 id_name
= args
[0].GetValidGLArg(func
)
8307 get_len_func
= func
.GetInfo('get_len_func')
8308 get_len_enum
= func
.GetInfo('get_len_enum')
8311 'get_len_func': get_len_func
,
8312 'get_len_enum': get_len_enum
,
8313 'gl_args': '%s, strlen(kInfo) + 1, _, _' %
8314 args
[0].GetValidGLArg(func
),
8315 'args': '%s, kBucketId' % args
[0].GetValidArg(func
),
8316 'expect_len_code': '',
8318 if get_len_func
and get_len_func
[0:2] == 'gl':
8319 sub
['expect_len_code'] = (
8320 " EXPECT_CALL(*gl_, %s(%s, %s, _))\n"
8321 " .WillOnce(SetArgumentPointee<2>(strlen(kInfo) + 1));") % (
8322 get_len_func
[2:], id_name
, get_len_enum
)
8323 self
.WriteValidUnitTest(func
, file, valid_test
, sub
, *extras
)
8326 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
8327 const uint32_t kBucketId = 123;
8328 EXPECT_CALL(*gl_, %(gl_func_name)s(_, _, _, _))
8331 cmd.Init(kInvalidClientId, kBucketId);
8332 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
8333 EXPECT_EQ(GL_INVALID_VALUE, GetGLError());
8336 self
.WriteValidUnitTest(func
, file, invalid_test
, *extras
)
8338 def WriteServiceImplementation(self
, func
, file):
8339 """Overrriden from TypeHandler."""
8342 class NamedType(object):
8343 """A class that represents a type of an argument in a client function.
8345 A type of an argument that is to be passed through in the command buffer
8346 command. Currently used only for the arguments that are specificly named in
8347 the 'cmd_buffer_functions.txt' file, mostly enums.
8350 def __init__(self
, info
):
8351 assert not 'is_complete' in info
or info
['is_complete'] == True
8353 self
.valid
= info
['valid']
8354 if 'invalid' in info
:
8355 self
.invalid
= info
['invalid']
8358 if 'valid_es3' in info
:
8359 self
.valid_es3
= info
['valid_es3']
8362 if 'deprecated_es3' in info
:
8363 self
.deprecated_es3
= info
['deprecated_es3']
8365 self
.deprecated_es3
= []
8368 return self
.info
['type']
8370 def GetInvalidValues(self
):
8373 def GetValidValues(self
):
8376 def GetValidValuesES3(self
):
8377 return self
.valid_es3
8379 def GetDeprecatedValuesES3(self
):
8380 return self
.deprecated_es3
8382 def IsConstant(self
):
8383 if not 'is_complete' in self
.info
:
8386 return len(self
.GetValidValues()) == 1
8388 def GetConstantValue(self
):
8389 return self
.GetValidValues()[0]
8391 class Argument(object):
8392 """A class that represents a function argument."""
8395 'GLenum': 'uint32_t',
8397 'GLintptr': 'int32_t',
8398 'GLsizei': 'int32_t',
8399 'GLsizeiptr': 'int32_t',
8401 'GLclampf': 'float',
8403 need_validation_
= ['GLsizei*', 'GLboolean*', 'GLenum*', 'GLint*']
8405 def __init__(self
, name
, type):
8407 self
.optional
= type.endswith("Optional*")
8409 type = type[:-9] + "*"
8412 if type in self
.cmd_type_map_
:
8413 self
.cmd_type
= self
.cmd_type_map_
[type]
8415 self
.cmd_type
= 'uint32_t'
8417 def IsPointer(self
):
8418 """Returns true if argument is a pointer."""
8421 def IsPointer2D(self
):
8422 """Returns true if argument is a 2D pointer."""
8425 def IsConstant(self
):
8426 """Returns true if the argument has only one valid value."""
8429 def AddCmdArgs(self
, args
):
8430 """Adds command arguments for this argument to the given list."""
8431 if not self
.IsConstant():
8432 return args
.append(self
)
8434 def AddInitArgs(self
, args
):
8435 """Adds init arguments for this argument to the given list."""
8436 if not self
.IsConstant():
8437 return args
.append(self
)
8439 def GetValidArg(self
, func
):
8440 """Gets a valid value for this argument."""
8441 valid_arg
= func
.GetValidArg(self
)
8442 if valid_arg
!= None:
8445 index
= func
.GetOriginalArgs().index(self
)
8446 return str(index
+ 1)
8448 def GetValidClientSideArg(self
, func
):
8449 """Gets a valid value for this argument."""
8450 valid_arg
= func
.GetValidArg(self
)
8451 if valid_arg
!= None:
8454 if self
.IsPointer():
8456 index
= func
.GetOriginalArgs().index(self
)
8457 if self
.type == 'GLsync':
8458 return ("reinterpret_cast<GLsync>(%d)" % (index
+ 1))
8459 return str(index
+ 1)
8461 def GetValidClientSideCmdArg(self
, func
):
8462 """Gets a valid value for this argument."""
8463 valid_arg
= func
.GetValidArg(self
)
8464 if valid_arg
!= None:
8467 index
= func
.GetOriginalArgs().index(self
)
8468 return str(index
+ 1)
8471 index
= func
.GetCmdArgs().index(self
)
8472 return str(index
+ 1)
8474 def GetValidGLArg(self
, func
):
8475 """Gets a valid GL value for this argument."""
8476 value
= self
.GetValidArg(func
)
8477 if self
.type == 'GLsync':
8478 return ("reinterpret_cast<GLsync>(%s)" % value
)
8481 def GetValidNonCachedClientSideArg(self
, func
):
8482 """Returns a valid value for this argument in a GL call.
8483 Using the value will produce a command buffer service invocation.
8484 Returns None if there is no such value."""
8486 if self
.type == 'GLsync':
8487 return ("reinterpret_cast<GLsync>(%s)" % value
)
8490 def GetValidNonCachedClientSideCmdArg(self
, func
):
8491 """Returns a valid value for this argument in a command buffer command.
8492 Calling the GL function with the value returned by
8493 GetValidNonCachedClientSideArg will result in a command buffer command
8494 that contains the value returned by this function. """
8497 def GetNumInvalidValues(self
, func
):
8498 """returns the number of invalid values to be tested."""
8501 def GetInvalidArg(self
, index
):
8502 """returns an invalid value and expected parse result by index."""
8503 return ("---ERROR0---", "---ERROR2---", None)
8505 def GetLogArg(self
):
8506 """Get argument appropriate for LOG macro."""
8507 if self
.type == 'GLboolean':
8508 return 'GLES2Util::GetStringBool(%s)' % self
.name
8509 if self
.type == 'GLenum':
8510 return 'GLES2Util::GetStringEnum(%s)' % self
.name
8513 def WriteGetCode(self
, file):
8514 """Writes the code to get an argument from a command structure."""
8515 if self
.type == 'GLsync':
8519 file.Write(" %s %s = static_cast<%s>(c.%s);\n" %
8520 (my_type
, self
.name
, my_type
, self
.name
))
8522 def WriteValidationCode(self
, file, func
):
8523 """Writes the validation code for an argument."""
8526 def WriteClientSideValidationCode(self
, file, func
):
8527 """Writes the validation code for an argument."""
8530 def WriteDestinationInitalizationValidation(self
, file, func
):
8531 """Writes the client side destintion initialization validation."""
8534 def WriteDestinationInitalizationValidatationIfNeeded(self
, file, func
):
8535 """Writes the client side destintion initialization validation if needed."""
8536 parts
= self
.type.split(" ")
8539 if parts
[0] in self
.need_validation_
:
8541 " GPU_CLIENT_VALIDATE_DESTINATION_%sINITALIZATION(%s, %s);\n" %
8542 ("OPTIONAL_" if self
.optional
else "", self
.type[:-1], self
.name
))
8545 def WriteGetAddress(self
, file):
8546 """Writes the code to get the address this argument refers to."""
8549 def GetImmediateVersion(self
):
8550 """Gets the immediate version of this argument."""
8553 def GetBucketVersion(self
):
8554 """Gets the bucket version of this argument."""
8558 class BoolArgument(Argument
):
8559 """class for GLboolean"""
8561 def __init__(self
, name
, type):
8562 Argument
.__init
__(self
, name
, 'GLboolean')
8564 def GetValidArg(self
, func
):
8565 """Gets a valid value for this argument."""
8568 def GetValidClientSideArg(self
, func
):
8569 """Gets a valid value for this argument."""
8572 def GetValidClientSideCmdArg(self
, func
):
8573 """Gets a valid value for this argument."""
8576 def GetValidGLArg(self
, func
):
8577 """Gets a valid GL value for this argument."""
8581 class UniformLocationArgument(Argument
):
8582 """class for uniform locations."""
8584 def __init__(self
, name
):
8585 Argument
.__init
__(self
, name
, "GLint")
8587 def WriteGetCode(self
, file):
8588 """Writes the code to get an argument from a command structure."""
8589 code
= """ %s %s = static_cast<%s>(c.%s);
8591 file.Write(code
% (self
.type, self
.name
, self
.type, self
.name
))
8593 class DataSizeArgument(Argument
):
8594 """class for data_size which Bucket commands do not need."""
8596 def __init__(self
, name
):
8597 Argument
.__init
__(self
, name
, "uint32_t")
8599 def GetBucketVersion(self
):
8603 class SizeArgument(Argument
):
8604 """class for GLsizei and GLsizeiptr."""
8606 def __init__(self
, name
, type):
8607 Argument
.__init
__(self
, name
, type)
8609 def GetNumInvalidValues(self
, func
):
8610 """overridden from Argument."""
8611 if func
.IsImmediate():
8615 def GetInvalidArg(self
, index
):
8616 """overridden from Argument."""
8617 return ("-1", "kNoError", "GL_INVALID_VALUE")
8619 def WriteValidationCode(self
, file, func
):
8620 """overridden from Argument."""
8623 code
= """ if (%(var_name)s < 0) {
8624 LOCAL_SET_GL_ERROR(GL_INVALID_VALUE, "gl%(func_name)s", "%(var_name)s < 0");
8625 return error::kNoError;
8629 "var_name": self
.name
,
8630 "func_name": func
.original_name
,
8633 def WriteClientSideValidationCode(self
, file, func
):
8634 """overridden from Argument."""
8635 code
= """ if (%(var_name)s < 0) {
8636 SetGLError(GL_INVALID_VALUE, "gl%(func_name)s", "%(var_name)s < 0");
8641 "var_name": self
.name
,
8642 "func_name": func
.original_name
,
8646 class SizeNotNegativeArgument(SizeArgument
):
8647 """class for GLsizeiNotNegative. It's NEVER allowed to be negative"""
8649 def __init__(self
, name
, type, gl_type
):
8650 SizeArgument
.__init
__(self
, name
, gl_type
)
8652 def GetInvalidArg(self
, index
):
8653 """overridden from SizeArgument."""
8654 return ("-1", "kOutOfBounds", "GL_NO_ERROR")
8656 def WriteValidationCode(self
, file, func
):
8657 """overridden from SizeArgument."""
8661 class EnumBaseArgument(Argument
):
8662 """Base class for EnumArgument, IntArgument, BitfieldArgument, and
8663 ValidatedBoolArgument."""
8665 def __init__(self
, name
, gl_type
, type, gl_error
):
8666 Argument
.__init
__(self
, name
, gl_type
)
8668 self
.local_type
= type
8669 self
.gl_error
= gl_error
8670 name
= type[len(gl_type
):]
8671 self
.type_name
= name
8672 self
.named_type
= NamedType(_NAMED_TYPE_INFO
[name
])
8674 def IsConstant(self
):
8675 return self
.named_type
.IsConstant()
8677 def GetConstantValue(self
):
8678 return self
.named_type
.GetConstantValue()
8680 def WriteValidationCode(self
, file, func
):
8683 if self
.named_type
.IsConstant():
8685 file.Write(" if (!validators_->%s.IsValid(%s)) {\n" %
8686 (ToUnderscore(self
.type_name
), self
.name
))
8687 if self
.gl_error
== "GL_INVALID_ENUM":
8689 " LOCAL_SET_GL_ERROR_INVALID_ENUM(\"gl%s\", %s, \"%s\");\n" %
8690 (func
.original_name
, self
.name
, self
.name
))
8693 " LOCAL_SET_GL_ERROR(%s, \"gl%s\", \"%s %s\");\n" %
8694 (self
.gl_error
, func
.original_name
, self
.name
, self
.gl_error
))
8695 file.Write(" return error::kNoError;\n")
8698 def WriteClientSideValidationCode(self
, file, func
):
8699 if not self
.named_type
.IsConstant():
8701 file.Write(" if (%s != %s) {" % (self
.name
,
8702 self
.GetConstantValue()))
8704 " SetGLError(%s, \"gl%s\", \"%s %s\");\n" %
8705 (self
.gl_error
, func
.original_name
, self
.name
, self
.gl_error
))
8706 if func
.return_type
== "void":
8707 file.Write(" return;\n")
8709 file.Write(" return %s;\n" % func
.GetErrorReturnString())
8712 def GetValidArg(self
, func
):
8713 valid_arg
= func
.GetValidArg(self
)
8714 if valid_arg
!= None:
8716 valid
= self
.named_type
.GetValidValues()
8718 num_valid
= len(valid
)
8721 index
= func
.GetOriginalArgs().index(self
)
8722 return str(index
+ 1)
8724 def GetValidClientSideArg(self
, func
):
8725 """Gets a valid value for this argument."""
8726 return self
.GetValidArg(func
)
8728 def GetValidClientSideCmdArg(self
, func
):
8729 """Gets a valid value for this argument."""
8730 valid_arg
= func
.GetValidArg(self
)
8731 if valid_arg
!= None:
8734 valid
= self
.named_type
.GetValidValues()
8736 num_valid
= len(valid
)
8740 index
= func
.GetOriginalArgs().index(self
)
8741 return str(index
+ 1)
8744 index
= func
.GetCmdArgs().index(self
)
8745 return str(index
+ 1)
8747 def GetValidGLArg(self
, func
):
8748 """Gets a valid value for this argument."""
8749 return self
.GetValidArg(func
)
8751 def GetNumInvalidValues(self
, func
):
8752 """returns the number of invalid values to be tested."""
8753 return len(self
.named_type
.GetInvalidValues())
8755 def GetInvalidArg(self
, index
):
8756 """returns an invalid value by index."""
8757 invalid
= self
.named_type
.GetInvalidValues()
8759 num_invalid
= len(invalid
)
8760 if index
>= num_invalid
:
8761 index
= num_invalid
- 1
8762 return (invalid
[index
], "kNoError", self
.gl_error
)
8763 return ("---ERROR1---", "kNoError", self
.gl_error
)
8766 class EnumArgument(EnumBaseArgument
):
8767 """A class that represents a GLenum argument"""
8769 def __init__(self
, name
, type):
8770 EnumBaseArgument
.__init
__(self
, name
, "GLenum", type, "GL_INVALID_ENUM")
8772 def GetLogArg(self
):
8773 """Overridden from Argument."""
8774 return ("GLES2Util::GetString%s(%s)" %
8775 (self
.type_name
, self
.name
))
8778 class IntArgument(EnumBaseArgument
):
8779 """A class for a GLint argument that can only accept specific values.
8781 For example glTexImage2D takes a GLint for its internalformat
8782 argument instead of a GLenum.
8785 def __init__(self
, name
, type):
8786 EnumBaseArgument
.__init
__(self
, name
, "GLint", type, "GL_INVALID_VALUE")
8789 class ValidatedBoolArgument(EnumBaseArgument
):
8790 """A class for a GLboolean argument that can only accept specific values.
8792 For example glUniformMatrix takes a GLboolean for it's transpose but it
8796 def __init__(self
, name
, type):
8797 EnumBaseArgument
.__init
__(self
, name
, "GLboolean", type, "GL_INVALID_VALUE")
8799 def GetLogArg(self
):
8800 """Overridden from Argument."""
8801 return 'GLES2Util::GetStringBool(%s)' % self
.name
8804 class BitFieldArgument(EnumBaseArgument
):
8805 """A class for a GLbitfield argument that can only accept specific values.
8807 For example glFenceSync takes a GLbitfield for its flags argument bit it
8811 def __init__(self
, name
, type):
8812 EnumBaseArgument
.__init
__(self
, name
, "GLbitfield", type,
8816 class ImmediatePointerArgument(Argument
):
8817 """A class that represents an immediate argument to a function.
8819 An immediate argument is one where the data follows the command.
8822 def __init__(self
, name
, type):
8823 Argument
.__init
__(self
, name
, type)
8825 def IsPointer(self
):
8828 def GetPointedType(self
):
8829 match
= re
.match('(const\s+)?(?P<element_type>[\w]+)\s*\*', self
.type)
8831 return match
.groupdict()['element_type']
8833 def AddCmdArgs(self
, args
):
8834 """Overridden from Argument."""
8837 def WriteGetCode(self
, file):
8838 """Overridden from Argument."""
8840 " %s %s = GetImmediateDataAs<%s>(\n" %
8841 (self
.type, self
.name
, self
.type))
8842 file.Write(" c, data_size, immediate_data_size);\n")
8844 def WriteValidationCode(self
, file, func
):
8845 """Overridden from Argument."""
8848 file.Write(" if (%s == NULL) {\n" % self
.name
)
8849 file.Write(" return error::kOutOfBounds;\n")
8852 def GetImmediateVersion(self
):
8853 """Overridden from Argument."""
8856 def WriteDestinationInitalizationValidation(self
, file, func
):
8857 """Overridden from Argument."""
8858 self
.WriteDestinationInitalizationValidatationIfNeeded(file, func
)
8860 def GetLogArg(self
):
8861 """Overridden from Argument."""
8862 return "static_cast<const void*>(%s)" % self
.name
8865 class PointerArgument(Argument
):
8866 """A class that represents a pointer argument to a function."""
8868 def __init__(self
, name
, type):
8869 Argument
.__init
__(self
, name
, type)
8871 def IsPointer(self
):
8872 """Overridden from Argument."""
8875 def IsPointer2D(self
):
8876 """Overridden from Argument."""
8877 return self
.type.count('*') == 2
8879 def GetPointedType(self
):
8880 match
= re
.match('(const\s+)?(?P<element_type>[\w]+)\s*\*', self
.type)
8882 return match
.groupdict()['element_type']
8884 def GetValidArg(self
, func
):
8885 """Overridden from Argument."""
8886 return "shared_memory_id_, shared_memory_offset_"
8888 def GetValidGLArg(self
, func
):
8889 """Overridden from Argument."""
8890 return "reinterpret_cast<%s>(shared_memory_address_)" % self
.type
8892 def GetNumInvalidValues(self
, func
):
8893 """Overridden from Argument."""
8896 def GetInvalidArg(self
, index
):
8897 """Overridden from Argument."""
8899 return ("kInvalidSharedMemoryId, 0", "kOutOfBounds", None)
8901 return ("shared_memory_id_, kInvalidSharedMemoryOffset",
8902 "kOutOfBounds", None)
8904 def GetLogArg(self
):
8905 """Overridden from Argument."""
8906 return "static_cast<const void*>(%s)" % self
.name
8908 def AddCmdArgs(self
, args
):
8909 """Overridden from Argument."""
8910 args
.append(Argument("%s_shm_id" % self
.name
, 'uint32_t'))
8911 args
.append(Argument("%s_shm_offset" % self
.name
, 'uint32_t'))
8913 def WriteGetCode(self
, file):
8914 """Overridden from Argument."""
8916 " %s %s = GetSharedMemoryAs<%s>(\n" %
8917 (self
.type, self
.name
, self
.type))
8919 " c.%s_shm_id, c.%s_shm_offset, data_size);\n" %
8920 (self
.name
, self
.name
))
8922 def WriteGetAddress(self
, file):
8923 """Overridden from Argument."""
8925 " %s %s = GetSharedMemoryAs<%s>(\n" %
8926 (self
.type, self
.name
, self
.type))
8928 " %s_shm_id, %s_shm_offset, %s_size);\n" %
8929 (self
.name
, self
.name
, self
.name
))
8931 def WriteValidationCode(self
, file, func
):
8932 """Overridden from Argument."""
8935 file.Write(" if (%s == NULL) {\n" % self
.name
)
8936 file.Write(" return error::kOutOfBounds;\n")
8939 def GetImmediateVersion(self
):
8940 """Overridden from Argument."""
8941 return ImmediatePointerArgument(self
.name
, self
.type)
8943 def GetBucketVersion(self
):
8944 """Overridden from Argument."""
8945 if self
.type.find('char') >= 0:
8946 if self
.IsPointer2D():
8947 return InputStringArrayBucketArgument(self
.name
, self
.type)
8948 return InputStringBucketArgument(self
.name
, self
.type)
8949 return BucketPointerArgument(self
.name
, self
.type)
8951 def WriteDestinationInitalizationValidation(self
, file, func
):
8952 """Overridden from Argument."""
8953 self
.WriteDestinationInitalizationValidatationIfNeeded(file, func
)
8956 class BucketPointerArgument(PointerArgument
):
8957 """A class that represents an bucket argument to a function."""
8959 def __init__(self
, name
, type):
8960 Argument
.__init
__(self
, name
, type)
8962 def AddCmdArgs(self
, args
):
8963 """Overridden from Argument."""
8966 def WriteGetCode(self
, file):
8967 """Overridden from Argument."""
8969 " %s %s = bucket->GetData(0, data_size);\n" %
8970 (self
.type, self
.name
))
8972 def WriteValidationCode(self
, file, func
):
8973 """Overridden from Argument."""
8976 def GetImmediateVersion(self
):
8977 """Overridden from Argument."""
8980 def WriteDestinationInitalizationValidation(self
, file, func
):
8981 """Overridden from Argument."""
8982 self
.WriteDestinationInitalizationValidatationIfNeeded(file, func
)
8984 def GetLogArg(self
):
8985 """Overridden from Argument."""
8986 return "static_cast<const void*>(%s)" % self
.name
8989 class InputStringBucketArgument(Argument
):
8990 """A string input argument where the string is passed in a bucket."""
8992 def __init__(self
, name
, type):
8993 Argument
.__init
__(self
, name
+ "_bucket_id", "uint32_t")
8995 def IsPointer(self
):
8996 """Overridden from Argument."""
8999 def IsPointer2D(self
):
9000 """Overridden from Argument."""
9004 class InputStringArrayBucketArgument(Argument
):
9005 """A string array input argument where the strings are passed in a bucket."""
9007 def __init__(self
, name
, type):
9008 Argument
.__init
__(self
, name
+ "_bucket_id", "uint32_t")
9009 self
._original
_name
= name
9011 def WriteGetCode(self
, file):
9012 """Overridden from Argument."""
9014 Bucket* bucket = GetBucket(c.%(name)s);
9016 return error::kInvalidArguments;
9019 std::vector<char*> strs;
9020 std::vector<GLint> len;
9021 if (!bucket->GetAsStrings(&count, &strs, &len)) {
9022 return error::kInvalidArguments;
9024 const char** %(original_name)s =
9025 strs.size() > 0 ? const_cast<const char**>(&strs[0]) : NULL;
9026 const GLint* length =
9027 len.size() > 0 ? const_cast<const GLint*>(&len[0]) : NULL;
9032 'original_name': self
._original
_name
,
9035 def GetValidArg(self
, func
):
9036 return "kNameBucketId"
9038 def GetValidGLArg(self
, func
):
9041 def IsPointer(self
):
9042 """Overridden from Argument."""
9045 def IsPointer2D(self
):
9046 """Overridden from Argument."""
9050 class ResourceIdArgument(Argument
):
9051 """A class that represents a resource id argument to a function."""
9053 def __init__(self
, name
, type):
9054 match
= re
.match("(GLid\w+)", type)
9055 self
.resource_type
= match
.group(1)[4:]
9056 if self
.resource_type
== "Sync":
9057 type = type.replace(match
.group(1), "GLsync")
9059 type = type.replace(match
.group(1), "GLuint")
9060 Argument
.__init
__(self
, name
, type)
9062 def WriteGetCode(self
, file):
9063 """Overridden from Argument."""
9064 if self
.type == "GLsync":
9068 file.Write(" %s %s = c.%s;\n" % (my_type
, self
.name
, self
.name
))
9070 def GetValidArg(self
, func
):
9071 return "client_%s_id_" % self
.resource_type
.lower()
9073 def GetValidGLArg(self
, func
):
9074 if self
.resource_type
== "Sync":
9075 return "reinterpret_cast<GLsync>(kService%sId)" % self
.resource_type
9076 return "kService%sId" % self
.resource_type
9079 class ResourceIdBindArgument(Argument
):
9080 """Represents a resource id argument to a bind function."""
9082 def __init__(self
, name
, type):
9083 match
= re
.match("(GLidBind\w+)", type)
9084 self
.resource_type
= match
.group(1)[8:]
9085 type = type.replace(match
.group(1), "GLuint")
9086 Argument
.__init
__(self
, name
, type)
9088 def WriteGetCode(self
, file):
9089 """Overridden from Argument."""
9090 code
= """ %(type)s %(name)s = c.%(name)s;
9092 file.Write(code
% {'type': self
.type, 'name': self
.name
})
9094 def GetValidArg(self
, func
):
9095 return "client_%s_id_" % self
.resource_type
.lower()
9097 def GetValidGLArg(self
, func
):
9098 return "kService%sId" % self
.resource_type
9101 class ResourceIdZeroArgument(Argument
):
9102 """Represents a resource id argument to a function that can be zero."""
9104 def __init__(self
, name
, type):
9105 match
= re
.match("(GLidZero\w+)", type)
9106 self
.resource_type
= match
.group(1)[8:]
9107 type = type.replace(match
.group(1), "GLuint")
9108 Argument
.__init
__(self
, name
, type)
9110 def WriteGetCode(self
, file):
9111 """Overridden from Argument."""
9112 file.Write(" %s %s = c.%s;\n" % (self
.type, self
.name
, self
.name
))
9114 def GetValidArg(self
, func
):
9115 return "client_%s_id_" % self
.resource_type
.lower()
9117 def GetValidGLArg(self
, func
):
9118 return "kService%sId" % self
.resource_type
9120 def GetNumInvalidValues(self
, func
):
9121 """returns the number of invalid values to be tested."""
9124 def GetInvalidArg(self
, index
):
9125 """returns an invalid value by index."""
9126 return ("kInvalidClientId", "kNoError", "GL_INVALID_VALUE")
9129 class Function(object):
9130 """A class that represents a function."""
9134 'Bind': BindHandler(),
9135 'Create': CreateHandler(),
9136 'Custom': CustomHandler(),
9137 'Data': DataHandler(),
9138 'Delete': DeleteHandler(),
9139 'DELn': DELnHandler(),
9140 'GENn': GENnHandler(),
9141 'GETn': GETnHandler(),
9142 'GLchar': GLcharHandler(),
9143 'GLcharN': GLcharNHandler(),
9144 'HandWritten': HandWrittenHandler(),
9146 'Manual': ManualHandler(),
9147 'PUT': PUTHandler(),
9148 'PUTn': PUTnHandler(),
9149 'PUTSTR': PUTSTRHandler(),
9150 'PUTXn': PUTXnHandler(),
9151 'StateSet': StateSetHandler(),
9152 'StateSetRGBAlpha': StateSetRGBAlphaHandler(),
9153 'StateSetFrontBack': StateSetFrontBackHandler(),
9154 'StateSetFrontBackSeparate': StateSetFrontBackSeparateHandler(),
9155 'StateSetNamedParameter': StateSetNamedParameter(),
9156 'STRn': STRnHandler(),
9157 'Todo': TodoHandler(),
9160 def __init__(self
, name
, info
):
9162 self
.original_name
= info
['original_name']
9164 self
.original_args
= self
.ParseArgs(info
['original_args'])
9166 if 'cmd_args' in info
:
9167 self
.args_for_cmds
= self
.ParseArgs(info
['cmd_args'])
9169 self
.args_for_cmds
= self
.original_args
[:]
9171 self
.return_type
= info
['return_type']
9172 if self
.return_type
!= 'void':
9173 self
.return_arg
= CreateArg(info
['return_type'] + " result")
9175 self
.return_arg
= None
9177 self
.num_pointer_args
= sum(
9178 [1 for arg
in self
.args_for_cmds
if arg
.IsPointer()])
9179 if self
.num_pointer_args
> 0:
9180 for arg
in reversed(self
.original_args
):
9182 self
.last_original_pointer_arg
= arg
9185 self
.last_original_pointer_arg
= None
9187 self
.type_handler
= self
.type_handlers
[info
['type']]
9188 self
.can_auto_generate
= (self
.num_pointer_args
== 0 and
9189 info
['return_type'] == "void")
9192 def ParseArgs(self
, arg_string
):
9193 """Parses a function arg string."""
9195 parts
= arg_string
.split(',')
9196 for arg_string
in parts
:
9197 arg
= CreateArg(arg_string
)
9202 def IsType(self
, type_name
):
9203 """Returns true if function is a certain type."""
9204 return self
.info
['type'] == type_name
9206 def InitFunction(self
):
9207 """Creates command args and calls the init function for the type handler.
9209 Creates argument lists for command buffer commands, eg. self.cmd_args and
9211 Calls the type function initialization.
9212 Override to create different kind of command buffer command argument lists.
9215 for arg
in self
.args_for_cmds
:
9216 arg
.AddCmdArgs(self
.cmd_args
)
9219 for arg
in self
.args_for_cmds
:
9220 arg
.AddInitArgs(self
.init_args
)
9223 self
.init_args
.append(self
.return_arg
)
9225 self
.type_handler
.InitFunction(self
)
9227 def IsImmediate(self
):
9228 """Returns whether the function is immediate data function or not."""
9232 """Returns whether the function has service side validation or not."""
9233 return self
.GetInfo('unsafe', False)
9235 def GetInfo(self
, name
, default
= None):
9236 """Returns a value from the function info for this function."""
9237 if name
in self
.info
:
9238 return self
.info
[name
]
9241 def GetValidArg(self
, arg
):
9242 """Gets a valid argument value for the parameter arg from the function info
9245 index
= self
.GetOriginalArgs().index(arg
)
9249 valid_args
= self
.GetInfo('valid_args')
9250 if valid_args
and str(index
) in valid_args
:
9251 return valid_args
[str(index
)]
9254 def AddInfo(self
, name
, value
):
9256 self
.info
[name
] = value
9258 def IsExtension(self
):
9259 return self
.GetInfo('extension') or self
.GetInfo('extension_flag')
9261 def IsCoreGLFunction(self
):
9262 return (not self
.IsExtension() and
9263 not self
.GetInfo('pepper_interface') and
9264 not self
.IsUnsafe())
9266 def InPepperInterface(self
, interface
):
9267 ext
= self
.GetInfo('pepper_interface')
9268 if not interface
.GetName():
9269 return self
.IsCoreGLFunction()
9270 return ext
== interface
.GetName()
9272 def InAnyPepperExtension(self
):
9273 return self
.IsCoreGLFunction() or self
.GetInfo('pepper_interface')
9275 def GetErrorReturnString(self
):
9276 if self
.GetInfo("error_return"):
9277 return self
.GetInfo("error_return")
9278 elif self
.return_type
== "GLboolean":
9280 elif "*" in self
.return_type
:
9284 def GetGLFunctionName(self
):
9285 """Gets the function to call to execute GL for this command."""
9286 if self
.GetInfo('decoder_func'):
9287 return self
.GetInfo('decoder_func')
9288 return "gl%s" % self
.original_name
9290 def GetGLTestFunctionName(self
):
9291 gl_func_name
= self
.GetInfo('gl_test_func')
9292 if gl_func_name
== None:
9293 gl_func_name
= self
.GetGLFunctionName()
9294 if gl_func_name
.startswith("gl"):
9295 gl_func_name
= gl_func_name
[2:]
9297 gl_func_name
= self
.original_name
9300 def GetDataTransferMethods(self
):
9301 return self
.GetInfo('data_transfer_methods',
9302 ['immediate' if self
.num_pointer_args
== 1 else 'shm'])
9304 def AddCmdArg(self
, arg
):
9305 """Adds a cmd argument to this function."""
9306 self
.cmd_args
.append(arg
)
9308 def GetCmdArgs(self
):
9309 """Gets the command args for this function."""
9310 return self
.cmd_args
9312 def ClearCmdArgs(self
):
9313 """Clears the command args for this function."""
9316 def GetCmdConstants(self
):
9317 """Gets the constants for this function."""
9318 return [arg
for arg
in self
.args_for_cmds
if arg
.IsConstant()]
9320 def GetInitArgs(self
):
9321 """Gets the init args for this function."""
9322 return self
.init_args
9324 def GetOriginalArgs(self
):
9325 """Gets the original arguments to this function."""
9326 return self
.original_args
9328 def GetLastOriginalArg(self
):
9329 """Gets the last original argument to this function."""
9330 return self
.original_args
[len(self
.original_args
) - 1]
9332 def GetLastOriginalPointerArg(self
):
9333 return self
.last_original_pointer_arg
9335 def GetResourceIdArg(self
):
9336 for arg
in self
.original_args
:
9337 if hasattr(arg
, 'resource_type'):
9341 def _MaybePrependComma(self
, arg_string
, add_comma
):
9342 """Adds a comma if arg_string is not empty and add_comma is true."""
9344 if add_comma
and len(arg_string
):
9346 return "%s%s" % (comma
, arg_string
)
9348 def MakeTypedOriginalArgString(self
, prefix
, add_comma
= False):
9349 """Gets a list of arguments as they are in GL."""
9350 args
= self
.GetOriginalArgs()
9351 arg_string
= ", ".join(
9352 ["%s %s%s" % (arg
.type, prefix
, arg
.name
) for arg
in args
])
9353 return self
._MaybePrependComma
(arg_string
, add_comma
)
9355 def MakeOriginalArgString(self
, prefix
, add_comma
= False, separator
= ", "):
9356 """Gets the list of arguments as they are in GL."""
9357 args
= self
.GetOriginalArgs()
9358 arg_string
= separator
.join(
9359 ["%s%s" % (prefix
, arg
.name
) for arg
in args
])
9360 return self
._MaybePrependComma
(arg_string
, add_comma
)
9362 def MakeTypedHelperArgString(self
, prefix
, add_comma
= False):
9363 """Gets a list of typed GL arguments after removing unneeded arguments."""
9364 args
= self
.GetOriginalArgs()
9365 arg_string
= ", ".join(
9370 ) for arg
in args
if not arg
.IsConstant()])
9371 return self
._MaybePrependComma
(arg_string
, add_comma
)
9373 def MakeHelperArgString(self
, prefix
, add_comma
= False, separator
= ", "):
9374 """Gets a list of GL arguments after removing unneeded arguments."""
9375 args
= self
.GetOriginalArgs()
9376 arg_string
= separator
.join(
9377 ["%s%s" % (prefix
, arg
.name
)
9378 for arg
in args
if not arg
.IsConstant()])
9379 return self
._MaybePrependComma
(arg_string
, add_comma
)
9381 def MakeTypedPepperArgString(self
, prefix
):
9382 """Gets a list of arguments as they need to be for Pepper."""
9383 if self
.GetInfo("pepper_args"):
9384 return self
.GetInfo("pepper_args")
9386 return self
.MakeTypedOriginalArgString(prefix
, False)
9388 def MapCTypeToPepperIdlType(self
, ctype
, is_for_return_type
=False):
9389 """Converts a C type name to the corresponding Pepper IDL type."""
9391 'char*': '[out] str_t',
9392 'const GLchar* const*': '[out] cstr_t',
9393 'const char*': 'cstr_t',
9394 'const void*': 'mem_t',
9395 'void*': '[out] mem_t',
9396 'void**': '[out] mem_ptr_t',
9398 # We use "GLxxx_ptr_t" for "GLxxx*".
9399 matched
= re
.match(r
'(const )?(GL\w+)\*$', ctype
)
9401 idltype
= matched
.group(2) + '_ptr_t'
9402 if not matched
.group(1):
9403 idltype
= '[out] ' + idltype
9404 # If an in/out specifier is not specified yet, prepend [in].
9405 if idltype
[0] != '[':
9406 idltype
= '[in] ' + idltype
9407 # Strip the in/out specifier for a return type.
9408 if is_for_return_type
:
9409 idltype
= re
.sub(r
'\[\w+\] ', '', idltype
)
9412 def MakeTypedPepperIdlArgStrings(self
):
9413 """Gets a list of arguments as they need to be for Pepper IDL."""
9414 args
= self
.GetOriginalArgs()
9415 return ["%s %s" % (self
.MapCTypeToPepperIdlType(arg
.type), arg
.name
)
9418 def GetPepperName(self
):
9419 if self
.GetInfo("pepper_name"):
9420 return self
.GetInfo("pepper_name")
9423 def MakeTypedCmdArgString(self
, prefix
, add_comma
= False):
9424 """Gets a typed list of arguments as they need to be for command buffers."""
9425 args
= self
.GetCmdArgs()
9426 arg_string
= ", ".join(
9427 ["%s %s%s" % (arg
.type, prefix
, arg
.name
) for arg
in args
])
9428 return self
._MaybePrependComma
(arg_string
, add_comma
)
9430 def MakeCmdArgString(self
, prefix
, add_comma
= False):
9431 """Gets the list of arguments as they need to be for command buffers."""
9432 args
= self
.GetCmdArgs()
9433 arg_string
= ", ".join(
9434 ["%s%s" % (prefix
, arg
.name
) for arg
in args
])
9435 return self
._MaybePrependComma
(arg_string
, add_comma
)
9437 def MakeTypedInitString(self
, prefix
, add_comma
= False):
9438 """Gets a typed list of arguments as they need to be for cmd Init/Set."""
9439 args
= self
.GetInitArgs()
9440 arg_string
= ", ".join(
9441 ["%s %s%s" % (arg
.type, prefix
, arg
.name
) for arg
in args
])
9442 return self
._MaybePrependComma
(arg_string
, add_comma
)
9444 def MakeInitString(self
, prefix
, add_comma
= False):
9445 """Gets the list of arguments as they need to be for cmd Init/Set."""
9446 args
= self
.GetInitArgs()
9447 arg_string
= ", ".join(
9448 ["%s%s" % (prefix
, arg
.name
) for arg
in args
])
9449 return self
._MaybePrependComma
(arg_string
, add_comma
)
9451 def MakeLogArgString(self
):
9452 """Makes a string of the arguments for the LOG macros"""
9453 args
= self
.GetOriginalArgs()
9454 return ' << ", " << '.join([arg
.GetLogArg() for arg
in args
])
9456 def WriteCommandDescription(self
, file):
9457 """Writes a description of the command."""
9458 file.Write("//! Command that corresponds to gl%s.\n" % self
.original_name
)
9460 def WriteHandlerValidation(self
, file):
9461 """Writes validation code for the function."""
9462 for arg
in self
.GetOriginalArgs():
9463 arg
.WriteValidationCode(file, self
)
9464 self
.WriteValidationCode(file)
9466 def WriteHandlerImplementation(self
, file):
9467 """Writes the handler implementation for this command."""
9468 self
.type_handler
.WriteHandlerImplementation(self
, file)
9470 def WriteValidationCode(self
, file):
9471 """Writes the validation code for a command."""
9474 def WriteCmdFlag(self
, file):
9475 """Writes the cmd cmd_flags constant."""
9477 # By default trace only at the highest level 3.
9478 trace_level
= int(self
.GetInfo('trace_level', default
= 3))
9479 if trace_level
not in xrange(0, 4):
9480 raise KeyError("Unhandled trace_level: %d" % trace_level
)
9482 flags
.append('CMD_FLAG_SET_TRACE_LEVEL(%d)' % trace_level
)
9485 cmd_flags
= ' | '.join(flags
)
9489 file.Write(" static const uint8 cmd_flags = %s;\n" % cmd_flags
)
9492 def WriteCmdArgFlag(self
, file):
9493 """Writes the cmd kArgFlags constant."""
9494 file.Write(" static const cmd::ArgFlags kArgFlags = cmd::kFixed;\n")
9496 def WriteCmdComputeSize(self
, file):
9497 """Writes the ComputeSize function for the command."""
9498 file.Write(" static uint32_t ComputeSize() {\n")
9500 " return static_cast<uint32_t>(sizeof(ValueType)); // NOLINT\n")
9504 def WriteCmdSetHeader(self
, file):
9505 """Writes the cmd's SetHeader function."""
9506 file.Write(" void SetHeader() {\n")
9507 file.Write(" header.SetCmd<ValueType>();\n")
9511 def WriteCmdInit(self
, file):
9512 """Writes the cmd's Init function."""
9513 file.Write(" void Init(%s) {\n" % self
.MakeTypedCmdArgString("_"))
9514 file.Write(" SetHeader();\n")
9515 args
= self
.GetCmdArgs()
9517 file.Write(" %s = _%s;\n" % (arg
.name
, arg
.name
))
9521 def WriteCmdSet(self
, file):
9522 """Writes the cmd's Set function."""
9523 copy_args
= self
.MakeCmdArgString("_", False)
9524 file.Write(" void* Set(void* cmd%s) {\n" %
9525 self
.MakeTypedCmdArgString("_", True))
9526 file.Write(" static_cast<ValueType*>(cmd)->Init(%s);\n" % copy_args
)
9527 file.Write(" return NextCmdAddress<ValueType>(cmd);\n")
9531 def WriteStruct(self
, file):
9532 self
.type_handler
.WriteStruct(self
, file)
9534 def WriteDocs(self
, file):
9535 self
.type_handler
.WriteDocs(self
, file)
9537 def WriteCmdHelper(self
, file):
9538 """Writes the cmd's helper."""
9539 self
.type_handler
.WriteCmdHelper(self
, file)
9541 def WriteServiceImplementation(self
, file):
9542 """Writes the service implementation for a command."""
9543 self
.type_handler
.WriteServiceImplementation(self
, file)
9545 def WriteServiceUnitTest(self
, file, *extras
):
9546 """Writes the service implementation for a command."""
9547 self
.type_handler
.WriteServiceUnitTest(self
, file, *extras
)
9549 def WriteGLES2CLibImplementation(self
, file):
9550 """Writes the GLES2 C Lib Implemention."""
9551 self
.type_handler
.WriteGLES2CLibImplementation(self
, file)
9553 def WriteGLES2InterfaceHeader(self
, file):
9554 """Writes the GLES2 Interface declaration."""
9555 self
.type_handler
.WriteGLES2InterfaceHeader(self
, file)
9557 def WriteMojoGLES2ImplHeader(self
, file):
9558 """Writes the Mojo GLES2 implementation header declaration."""
9559 self
.type_handler
.WriteMojoGLES2ImplHeader(self
, file)
9561 def WriteMojoGLES2Impl(self
, file):
9562 """Writes the Mojo GLES2 implementation declaration."""
9563 self
.type_handler
.WriteMojoGLES2Impl(self
, file)
9565 def WriteGLES2InterfaceStub(self
, file):
9566 """Writes the GLES2 Interface Stub declaration."""
9567 self
.type_handler
.WriteGLES2InterfaceStub(self
, file)
9569 def WriteGLES2InterfaceStubImpl(self
, file):
9570 """Writes the GLES2 Interface Stub declaration."""
9571 self
.type_handler
.WriteGLES2InterfaceStubImpl(self
, file)
9573 def WriteGLES2ImplementationHeader(self
, file):
9574 """Writes the GLES2 Implemention declaration."""
9575 self
.type_handler
.WriteGLES2ImplementationHeader(self
, file)
9577 def WriteGLES2Implementation(self
, file):
9578 """Writes the GLES2 Implemention definition."""
9579 self
.type_handler
.WriteGLES2Implementation(self
, file)
9581 def WriteGLES2TraceImplementationHeader(self
, file):
9582 """Writes the GLES2 Trace Implemention declaration."""
9583 self
.type_handler
.WriteGLES2TraceImplementationHeader(self
, file)
9585 def WriteGLES2TraceImplementation(self
, file):
9586 """Writes the GLES2 Trace Implemention definition."""
9587 self
.type_handler
.WriteGLES2TraceImplementation(self
, file)
9589 def WriteGLES2Header(self
, file):
9590 """Writes the GLES2 Implemention unit test."""
9591 self
.type_handler
.WriteGLES2Header(self
, file)
9593 def WriteGLES2ImplementationUnitTest(self
, file):
9594 """Writes the GLES2 Implemention unit test."""
9595 self
.type_handler
.WriteGLES2ImplementationUnitTest(self
, file)
9597 def WriteDestinationInitalizationValidation(self
, file):
9598 """Writes the client side destintion initialization validation."""
9599 self
.type_handler
.WriteDestinationInitalizationValidation(self
, file)
9601 def WriteFormatTest(self
, file):
9602 """Writes the cmd's format test."""
9603 self
.type_handler
.WriteFormatTest(self
, file)
9606 class PepperInterface(object):
9607 """A class that represents a function."""
9609 def __init__(self
, info
):
9610 self
.name
= info
["name"]
9611 self
.dev
= info
["dev"]
9616 def GetInterfaceName(self
):
9620 upperint
= "_" + self
.name
.upper()
9623 return "PPB_OPENGLES2%s%s_INTERFACE" % (upperint
, dev
)
9625 def GetInterfaceString(self
):
9629 return "PPB_OpenGLES2%s%s" % (self
.name
, dev
)
9631 def GetStructName(self
):
9635 return "PPB_OpenGLES2%s%s" % (self
.name
, dev
)
9638 class ImmediateFunction(Function
):
9639 """A class that represnets an immediate function command."""
9641 def __init__(self
, func
):
9644 "%sImmediate" % func
.name
,
9647 def InitFunction(self
):
9648 # Override args in original_args and args_for_cmds with immediate versions
9651 new_original_args
= []
9652 for arg
in self
.original_args
:
9653 new_arg
= arg
.GetImmediateVersion()
9655 new_original_args
.append(new_arg
)
9656 self
.original_args
= new_original_args
9658 new_args_for_cmds
= []
9659 for arg
in self
.args_for_cmds
:
9660 new_arg
= arg
.GetImmediateVersion()
9662 new_args_for_cmds
.append(new_arg
)
9664 self
.args_for_cmds
= new_args_for_cmds
9666 Function
.InitFunction(self
)
9668 def IsImmediate(self
):
9671 def WriteCommandDescription(self
, file):
9672 """Overridden from Function"""
9673 file.Write("//! Immediate version of command that corresponds to gl%s.\n" %
9676 def WriteServiceImplementation(self
, file):
9677 """Overridden from Function"""
9678 self
.type_handler
.WriteImmediateServiceImplementation(self
, file)
9680 def WriteHandlerImplementation(self
, file):
9681 """Overridden from Function"""
9682 self
.type_handler
.WriteImmediateHandlerImplementation(self
, file)
9684 def WriteServiceUnitTest(self
, file, *extras
):
9685 """Writes the service implementation for a command."""
9686 self
.type_handler
.WriteImmediateServiceUnitTest(self
, file, *extras
)
9688 def WriteValidationCode(self
, file):
9689 """Overridden from Function"""
9690 self
.type_handler
.WriteImmediateValidationCode(self
, file)
9692 def WriteCmdArgFlag(self
, file):
9693 """Overridden from Function"""
9694 file.Write(" static const cmd::ArgFlags kArgFlags = cmd::kAtLeastN;\n")
9696 def WriteCmdComputeSize(self
, file):
9697 """Overridden from Function"""
9698 self
.type_handler
.WriteImmediateCmdComputeSize(self
, file)
9700 def WriteCmdSetHeader(self
, file):
9701 """Overridden from Function"""
9702 self
.type_handler
.WriteImmediateCmdSetHeader(self
, file)
9704 def WriteCmdInit(self
, file):
9705 """Overridden from Function"""
9706 self
.type_handler
.WriteImmediateCmdInit(self
, file)
9708 def WriteCmdSet(self
, file):
9709 """Overridden from Function"""
9710 self
.type_handler
.WriteImmediateCmdSet(self
, file)
9712 def WriteCmdHelper(self
, file):
9713 """Overridden from Function"""
9714 self
.type_handler
.WriteImmediateCmdHelper(self
, file)
9716 def WriteFormatTest(self
, file):
9717 """Overridden from Function"""
9718 self
.type_handler
.WriteImmediateFormatTest(self
, file)
9721 class BucketFunction(Function
):
9722 """A class that represnets a bucket version of a function command."""
9724 def __init__(self
, func
):
9727 "%sBucket" % func
.name
,
9730 def InitFunction(self
):
9731 # Override args in original_args and args_for_cmds with bucket versions
9734 new_original_args
= []
9735 for arg
in self
.original_args
:
9736 new_arg
= arg
.GetBucketVersion()
9738 new_original_args
.append(new_arg
)
9739 self
.original_args
= new_original_args
9741 new_args_for_cmds
= []
9742 for arg
in self
.args_for_cmds
:
9743 new_arg
= arg
.GetBucketVersion()
9745 new_args_for_cmds
.append(new_arg
)
9747 self
.args_for_cmds
= new_args_for_cmds
9749 Function
.InitFunction(self
)
9751 def WriteCommandDescription(self
, file):
9752 """Overridden from Function"""
9753 file.Write("//! Bucket version of command that corresponds to gl%s.\n" %
9756 def WriteServiceImplementation(self
, file):
9757 """Overridden from Function"""
9758 self
.type_handler
.WriteBucketServiceImplementation(self
, file)
9760 def WriteHandlerImplementation(self
, file):
9761 """Overridden from Function"""
9762 self
.type_handler
.WriteBucketHandlerImplementation(self
, file)
9764 def WriteServiceUnitTest(self
, file, *extras
):
9765 """Overridden from Function"""
9766 self
.type_handler
.WriteBucketServiceUnitTest(self
, file, *extras
)
9768 def MakeOriginalArgString(self
, prefix
, add_comma
= False, separator
= ", "):
9769 """Overridden from Function"""
9770 args
= self
.GetOriginalArgs()
9771 arg_string
= separator
.join(
9772 ["%s%s" % (prefix
, arg
.name
[0:-10] if arg
.name
.endswith("_bucket_id")
9773 else arg
.name
) for arg
in args
])
9774 return super(BucketFunction
, self
)._MaybePrependComma
(arg_string
, add_comma
)
9777 def CreateArg(arg_string
):
9778 """Creates an Argument."""
9779 arg_parts
= arg_string
.split()
9780 if len(arg_parts
) == 1 and arg_parts
[0] == 'void':
9782 # Is this a pointer argument?
9783 elif arg_string
.find('*') >= 0:
9784 return PointerArgument(
9786 " ".join(arg_parts
[0:-1]))
9787 # Is this a resource argument? Must come after pointer check.
9788 elif arg_parts
[0].startswith('GLidBind'):
9789 return ResourceIdBindArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
9790 elif arg_parts
[0].startswith('GLidZero'):
9791 return ResourceIdZeroArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
9792 elif arg_parts
[0].startswith('GLid'):
9793 return ResourceIdArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
9794 elif arg_parts
[0].startswith('GLenum') and len(arg_parts
[0]) > 6:
9795 return EnumArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
9796 elif arg_parts
[0].startswith('GLbitfield') and len(arg_parts
[0]) > 10:
9797 return BitFieldArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
9798 elif arg_parts
[0].startswith('GLboolean') and len(arg_parts
[0]) > 9:
9799 return ValidatedBoolArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
9800 elif arg_parts
[0].startswith('GLboolean'):
9801 return BoolArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
9802 elif arg_parts
[0].startswith('GLintUniformLocation'):
9803 return UniformLocationArgument(arg_parts
[-1])
9804 elif (arg_parts
[0].startswith('GLint') and len(arg_parts
[0]) > 5 and
9805 not arg_parts
[0].startswith('GLintptr')):
9806 return IntArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
9807 elif (arg_parts
[0].startswith('GLsizeiNotNegative') or
9808 arg_parts
[0].startswith('GLintptrNotNegative')):
9809 return SizeNotNegativeArgument(arg_parts
[-1],
9810 " ".join(arg_parts
[0:-1]),
9811 arg_parts
[0][0:-11])
9812 elif arg_parts
[0].startswith('GLsize'):
9813 return SizeArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
9815 return Argument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
9818 class GLGenerator(object):
9819 """A class to generate GL command buffers."""
9821 _function_re
= re
.compile(r
'GL_APICALL(.*?)GL_APIENTRY (.*?) \((.*?)\);')
9823 def __init__(self
, verbose
):
9824 self
.original_functions
= []
9826 self
.verbose
= verbose
9828 self
.pepper_interfaces
= []
9829 self
.interface_info
= {}
9830 self
.generated_cpp_filenames
= []
9832 for interface
in _PEPPER_INTERFACES
:
9833 interface
= PepperInterface(interface
)
9834 self
.pepper_interfaces
.append(interface
)
9835 self
.interface_info
[interface
.GetName()] = interface
9837 def AddFunction(self
, func
):
9838 """Adds a function."""
9839 self
.functions
.append(func
)
9841 def GetFunctionInfo(self
, name
):
9842 """Gets a type info for the given function name."""
9843 if name
in _FUNCTION_INFO
:
9844 func_info
= _FUNCTION_INFO
[name
].copy()
9848 if not 'type' in func_info
:
9849 func_info
['type'] = ''
9854 """Prints something if verbose is true."""
9858 def Error(self
, msg
):
9859 """Prints an error."""
9860 print "Error: %s" % msg
9863 def WriteLicense(self
, file):
9864 """Writes the license."""
9865 file.Write(_LICENSE
)
9867 def WriteNamespaceOpen(self
, file):
9868 """Writes the code for the namespace."""
9869 file.Write("namespace gpu {\n")
9870 file.Write("namespace gles2 {\n")
9873 def WriteNamespaceClose(self
, file):
9874 """Writes the code to close the namespace."""
9875 file.Write("} // namespace gles2\n")
9876 file.Write("} // namespace gpu\n")
9879 def ParseGLH(self
, filename
):
9880 """Parses the cmd_buffer_functions.txt file and extracts the functions"""
9881 f
= open(filename
, "r")
9882 functions
= f
.read()
9884 for line
in functions
.splitlines():
9885 match
= self
._function
_re
.match(line
)
9887 func_name
= match
.group(2)[2:]
9888 func_info
= self
.GetFunctionInfo(func_name
)
9889 if func_info
['type'] == 'Noop':
9892 parsed_func_info
= {
9893 'original_name': func_name
,
9894 'original_args': match
.group(3),
9895 'return_type': match
.group(1).strip(),
9898 for k
in parsed_func_info
.keys():
9899 if not k
in func_info
:
9900 func_info
[k
] = parsed_func_info
[k
]
9902 f
= Function(func_name
, func_info
)
9903 self
.original_functions
.append(f
)
9905 #for arg in f.GetOriginalArgs():
9906 # if not isinstance(arg, EnumArgument) and arg.type == 'GLenum':
9907 # self.Log("%s uses bare GLenum %s." % (func_name, arg.name))
9909 gen_cmd
= f
.GetInfo('gen_cmd')
9910 if gen_cmd
== True or gen_cmd
== None:
9911 if f
.type_handler
.NeedsDataTransferFunction(f
):
9912 methods
= f
.GetDataTransferMethods()
9913 if 'immediate' in methods
:
9914 self
.AddFunction(ImmediateFunction(f
))
9915 if 'bucket' in methods
:
9916 self
.AddFunction(BucketFunction(f
))
9917 if 'shm' in methods
:
9922 self
.Log("Auto Generated Functions : %d" %
9923 len([f
for f
in self
.functions
if f
.can_auto_generate
or
9924 (not f
.IsType('') and not f
.IsType('Custom') and
9925 not f
.IsType('Todo'))]))
9927 funcs
= [f
for f
in self
.functions
if not f
.can_auto_generate
and
9928 (f
.IsType('') or f
.IsType('Custom') or f
.IsType('Todo'))]
9929 self
.Log("Non Auto Generated Functions: %d" % len(funcs
))
9932 self
.Log(" %-10s %-20s gl%s" % (f
.info
['type'], f
.return_type
, f
.name
))
9934 def WriteCommandIds(self
, filename
):
9935 """Writes the command buffer format"""
9936 file = CHeaderWriter(filename
)
9937 file.Write("#define GLES2_COMMAND_LIST(OP) \\\n")
9939 for func
in self
.functions
:
9940 file.Write(" %-60s /* %d */ \\\n" %
9941 ("OP(%s)" % func
.name
, id))
9945 file.Write("enum CommandId {\n")
9946 file.Write(" kStartPoint = cmd::kLastCommonId, "
9947 "// All GLES2 commands start after this.\n")
9948 file.Write("#define GLES2_CMD_OP(name) k ## name,\n")
9949 file.Write(" GLES2_COMMAND_LIST(GLES2_CMD_OP)\n")
9950 file.Write("#undef GLES2_CMD_OP\n")
9951 file.Write(" kNumCommands\n")
9955 self
.generated_cpp_filenames
.append(file.filename
)
9957 def WriteFormat(self
, filename
):
9958 """Writes the command buffer format"""
9959 file = CHeaderWriter(filename
)
9960 # Forward declaration of a few enums used in constant argument
9961 # to avoid including GL header files.
9963 'GL_SYNC_GPU_COMMANDS_COMPLETE': '0x9117',
9964 'GL_SYNC_FLUSH_COMMANDS_BIT': '0x00000001',
9967 for enum
in enum_defines
:
9968 file.Write("#define %s %s\n" % (enum
, enum_defines
[enum
]))
9970 for func
in self
.functions
:
9972 #gen_cmd = func.GetInfo('gen_cmd')
9973 #if gen_cmd == True or gen_cmd == None:
9974 func
.WriteStruct(file)
9977 self
.generated_cpp_filenames
.append(file.filename
)
9979 def WriteDocs(self
, filename
):
9980 """Writes the command buffer doc version of the commands"""
9981 file = CWriter(filename
)
9982 for func
in self
.functions
:
9984 #gen_cmd = func.GetInfo('gen_cmd')
9985 #if gen_cmd == True or gen_cmd == None:
9986 func
.WriteDocs(file)
9989 self
.generated_cpp_filenames
.append(file.filename
)
9991 def WriteFormatTest(self
, filename
):
9992 """Writes the command buffer format test."""
9993 file = CHeaderWriter(
9995 "// This file contains unit tests for gles2 commmands\n"
9996 "// It is included by gles2_cmd_format_test.cc\n"
9999 for func
in self
.functions
:
10001 #gen_cmd = func.GetInfo('gen_cmd')
10002 #if gen_cmd == True or gen_cmd == None:
10003 func
.WriteFormatTest(file)
10006 self
.generated_cpp_filenames
.append(file.filename
)
10008 def WriteCmdHelperHeader(self
, filename
):
10009 """Writes the gles2 command helper."""
10010 file = CHeaderWriter(filename
)
10012 for func
in self
.functions
:
10014 #gen_cmd = func.GetInfo('gen_cmd')
10015 #if gen_cmd == True or gen_cmd == None:
10016 func
.WriteCmdHelper(file)
10019 self
.generated_cpp_filenames
.append(file.filename
)
10021 def WriteServiceContextStateHeader(self
, filename
):
10022 """Writes the service context state header."""
10023 file = CHeaderWriter(
10025 "// It is included by context_state.h\n")
10026 file.Write("struct EnableFlags {\n")
10027 file.Write(" EnableFlags();\n")
10028 for capability
in _CAPABILITY_FLAGS
:
10029 file.Write(" bool %s;\n" % capability
['name'])
10030 file.Write(" bool cached_%s;\n" % capability
['name'])
10031 file.Write("};\n\n")
10033 for state_name
in sorted(_STATES
.keys()):
10034 state
= _STATES
[state_name
]
10035 for item
in state
['states']:
10036 if isinstance(item
['default'], list):
10037 file.Write("%s %s[%d];\n" % (item
['type'], item
['name'],
10038 len(item
['default'])))
10040 file.Write("%s %s;\n" % (item
['type'], item
['name']))
10042 if item
.get('cached', False):
10043 if isinstance(item
['default'], list):
10044 file.Write("%s cached_%s[%d];\n" % (item
['type'], item
['name'],
10045 len(item
['default'])))
10047 file.Write("%s cached_%s;\n" % (item
['type'], item
['name']))
10052 inline void SetDeviceCapabilityState(GLenum cap, bool enable) {
10055 for capability
in _CAPABILITY_FLAGS
:
10058 """ % capability
['name'].upper())
10060 if (enable_flags.cached_%(name)s == enable &&
10061 !ignore_cached_state)
10063 enable_flags.cached_%(name)s = enable;
10080 self
.generated_cpp_filenames
.append(file.filename
)
10082 def WriteClientContextStateHeader(self
, filename
):
10083 """Writes the client context state header."""
10084 file = CHeaderWriter(
10086 "// It is included by client_context_state.h\n")
10087 file.Write("struct EnableFlags {\n")
10088 file.Write(" EnableFlags();\n")
10089 for capability
in _CAPABILITY_FLAGS
:
10090 file.Write(" bool %s;\n" % capability
['name'])
10091 file.Write("};\n\n")
10094 self
.generated_cpp_filenames
.append(file.filename
)
10096 def WriteContextStateGetters(self
, file, class_name
):
10097 """Writes the state getters."""
10098 for gl_type
in ["GLint", "GLfloat"]:
10100 bool %s::GetStateAs%s(
10101 GLenum pname, %s* params, GLsizei* num_written) const {
10103 """ % (class_name
, gl_type
, gl_type
))
10104 for state_name
in sorted(_STATES
.keys()):
10105 state
= _STATES
[state_name
]
10106 if 'enum' in state
:
10107 file.Write(" case %s:\n" % state
['enum'])
10108 file.Write(" *num_written = %d;\n" % len(state
['states']))
10109 file.Write(" if (params) {\n")
10110 for ndx
,item
in enumerate(state
['states']):
10111 file.Write(" params[%d] = static_cast<%s>(%s);\n" %
10112 (ndx
, gl_type
, item
['name']))
10114 file.Write(" return true;\n")
10116 for item
in state
['states']:
10117 file.Write(" case %s:\n" % item
['enum'])
10118 if isinstance(item
['default'], list):
10119 item_len
= len(item
['default'])
10120 file.Write(" *num_written = %d;\n" % item_len
)
10121 file.Write(" if (params) {\n")
10122 if item
['type'] == gl_type
:
10123 file.Write(" memcpy(params, %s, sizeof(%s) * %d);\n" %
10124 (item
['name'], item
['type'], item_len
))
10126 file.Write(" for (size_t i = 0; i < %s; ++i) {\n" %
10128 file.Write(" params[i] = %s;\n" %
10129 (GetGLGetTypeConversion(gl_type
, item
['type'],
10130 "%s[i]" % item
['name'])))
10131 file.Write(" }\n");
10133 file.Write(" *num_written = 1;\n")
10134 file.Write(" if (params) {\n")
10135 file.Write(" params[0] = %s;\n" %
10136 (GetGLGetTypeConversion(gl_type
, item
['type'],
10139 file.Write(" return true;\n")
10140 for capability
in _CAPABILITY_FLAGS
:
10141 file.Write(" case GL_%s:\n" % capability
['name'].upper())
10142 file.Write(" *num_written = 1;\n")
10143 file.Write(" if (params) {\n")
10145 " params[0] = static_cast<%s>(enable_flags.%s);\n" %
10146 (gl_type
, capability
['name']))
10148 file.Write(" return true;\n")
10149 file.Write(""" default:
10155 def WriteServiceContextStateImpl(self
, filename
):
10156 """Writes the context state service implementation."""
10157 file = CHeaderWriter(
10159 "// It is included by context_state.cc\n")
10161 for capability
in _CAPABILITY_FLAGS
:
10162 code
.append("%s(%s)" %
10163 (capability
['name'],
10164 ('false', 'true')['default' in capability
]))
10165 code
.append("cached_%s(%s)" %
10166 (capability
['name'],
10167 ('false', 'true')['default' in capability
]))
10168 file.Write("ContextState::EnableFlags::EnableFlags()\n : %s {\n}\n" %
10172 file.Write("void ContextState::Initialize() {\n")
10173 for state_name
in sorted(_STATES
.keys()):
10174 state
= _STATES
[state_name
]
10175 for item
in state
['states']:
10176 if isinstance(item
['default'], list):
10177 for ndx
, value
in enumerate(item
['default']):
10178 file.Write(" %s[%d] = %s;\n" % (item
['name'], ndx
, value
))
10180 file.Write(" %s = %s;\n" % (item
['name'], item
['default']))
10181 if item
.get('cached', False):
10182 if isinstance(item
['default'], list):
10183 for ndx
, value
in enumerate(item
['default']):
10184 file.Write(" cached_%s[%d] = %s;\n" % (item
['name'], ndx
, value
))
10186 file.Write(" cached_%s = %s;\n" % (item
['name'], item
['default']))
10190 void ContextState::InitCapabilities(const ContextState* prev_state) const {
10192 def WriteCapabilities(test_prev
, es3_caps
):
10193 for capability
in _CAPABILITY_FLAGS
:
10194 capability_name
= capability
['name']
10195 capability_es3
= 'es3' in capability
and capability
['es3'] == True
10196 if capability_es3
and not es3_caps
or not capability_es3
and es3_caps
:
10199 file.Write(""" if (prev_state->enable_flags.cached_%s !=
10200 enable_flags.cached_%s) {\n""" %
10201 (capability_name
, capability_name
))
10202 file.Write(" EnableDisable(GL_%s, enable_flags.cached_%s);\n" %
10203 (capability_name
.upper(), capability_name
))
10207 file.Write(" if (prev_state) {")
10208 WriteCapabilities(True, False)
10209 file.Write(" if (feature_info_->IsES3Capable()) {\n")
10210 WriteCapabilities(True, True)
10212 file.Write(" } else {")
10213 WriteCapabilities(False, False)
10214 file.Write(" if (feature_info_->IsES3Capable()) {\n")
10215 WriteCapabilities(False, True)
10221 void ContextState::InitState(const ContextState *prev_state) const {
10224 def WriteStates(test_prev
):
10225 # We need to sort the keys so the expectations match
10226 for state_name
in sorted(_STATES
.keys()):
10227 state
= _STATES
[state_name
]
10228 if state
['type'] == 'FrontBack':
10229 num_states
= len(state
['states'])
10230 for ndx
, group
in enumerate(Grouper(num_states
/ 2, state
['states'])):
10232 file.Write(" if (")
10234 for place
, item
in enumerate(group
):
10235 item_name
= CachedStateName(item
)
10236 args
.append('%s' % item_name
)
10239 file.Write(' ||\n')
10240 file.Write("(%s != prev_state->%s)" % (item_name
, item_name
))
10244 " gl%s(%s, %s);\n" %
10245 (state
['func'], ('GL_FRONT', 'GL_BACK')[ndx
], ", ".join(args
)))
10246 elif state
['type'] == 'NamedParameter':
10247 for item
in state
['states']:
10248 item_name
= CachedStateName(item
)
10250 if 'extension_flag' in item
:
10251 file.Write(" if (feature_info_->feature_flags().%s) {\n " %
10252 item
['extension_flag'])
10254 if isinstance(item
['default'], list):
10255 file.Write(" if (memcmp(prev_state->%s, %s, "
10256 "sizeof(%s) * %d)) {\n" %
10257 (item_name
, item_name
, item
['type'],
10258 len(item
['default'])))
10260 file.Write(" if (prev_state->%s != %s) {\n " %
10261 (item_name
, item_name
))
10262 if 'gl_version_flag' in item
:
10263 item_name
= item
['gl_version_flag']
10265 if item_name
[0] == '!':
10267 item_name
= item_name
[1:]
10268 file.Write(" if (%sfeature_info_->gl_version_info().%s) {\n" %
10269 (inverted
, item_name
))
10270 file.Write(" gl%s(%s, %s);\n" %
10273 if 'enum_set' in item
else item
['enum']),
10275 if 'gl_version_flag' in item
:
10278 if 'extension_flag' in item
:
10281 if 'extension_flag' in item
:
10284 if 'extension_flag' in state
:
10285 file.Write(" if (feature_info_->feature_flags().%s)\n " %
10286 state
['extension_flag'])
10288 file.Write(" if (")
10290 for place
, item
in enumerate(state
['states']):
10291 item_name
= CachedStateName(item
)
10292 args
.append('%s' % item_name
)
10295 file.Write(' ||\n')
10296 file.Write("(%s != prev_state->%s)" %
10297 (item_name
, item_name
))
10300 file.Write(" gl%s(%s);\n" % (state
['func'], ", ".join(args
)))
10302 file.Write(" if (prev_state) {")
10304 file.Write(" } else {")
10309 file.Write("""bool ContextState::GetEnabled(GLenum cap) const {
10312 for capability
in _CAPABILITY_FLAGS
:
10313 file.Write(" case GL_%s:\n" % capability
['name'].upper())
10314 file.Write(" return enable_flags.%s;\n" % capability
['name'])
10315 file.Write(""" default:
10322 self
.WriteContextStateGetters(file, "ContextState")
10324 self
.generated_cpp_filenames
.append(file.filename
)
10326 def WriteClientContextStateImpl(self
, filename
):
10327 """Writes the context state client side implementation."""
10328 file = CHeaderWriter(
10330 "// It is included by client_context_state.cc\n")
10332 for capability
in _CAPABILITY_FLAGS
:
10333 code
.append("%s(%s)" %
10334 (capability
['name'],
10335 ('false', 'true')['default' in capability
]))
10337 "ClientContextState::EnableFlags::EnableFlags()\n : %s {\n}\n" %
10342 bool ClientContextState::SetCapabilityState(
10343 GLenum cap, bool enabled, bool* changed) {
10347 for capability
in _CAPABILITY_FLAGS
:
10348 file.Write(" case GL_%s:\n" % capability
['name'].upper())
10349 file.Write(""" if (enable_flags.%(name)s != enabled) {
10351 enable_flags.%(name)s = enabled;
10355 file.Write(""" default:
10360 file.Write("""bool ClientContextState::GetEnabled(
10361 GLenum cap, bool* enabled) const {
10364 for capability
in _CAPABILITY_FLAGS
:
10365 file.Write(" case GL_%s:\n" % capability
['name'].upper())
10366 file.Write(" *enabled = enable_flags.%s;\n" % capability
['name'])
10367 file.Write(" return true;\n")
10368 file.Write(""" default:
10374 self
.generated_cpp_filenames
.append(file.filename
)
10376 def WriteServiceImplementation(self
, filename
):
10377 """Writes the service decorder implementation."""
10378 file = CHeaderWriter(
10380 "// It is included by gles2_cmd_decoder.cc\n")
10382 for func
in self
.functions
:
10384 #gen_cmd = func.GetInfo('gen_cmd')
10385 #if gen_cmd == True or gen_cmd == None:
10386 func
.WriteServiceImplementation(file)
10389 bool GLES2DecoderImpl::SetCapabilityState(GLenum cap, bool enabled) {
10392 for capability
in _CAPABILITY_FLAGS
:
10393 file.Write(" case GL_%s:\n" % capability
['name'].upper())
10394 if 'state_flag' in capability
:
10397 state_.enable_flags.%(name)s = enabled;
10398 if (state_.enable_flags.cached_%(name)s != enabled
10399 || state_.ignore_cached_state) {
10400 %(state_flag)s = true;
10406 state_.enable_flags.%(name)s = enabled;
10407 if (state_.enable_flags.cached_%(name)s != enabled
10408 || state_.ignore_cached_state) {
10409 state_.enable_flags.cached_%(name)s = enabled;
10414 file.Write(""" default:
10421 self
.generated_cpp_filenames
.append(file.filename
)
10423 def WriteServiceUnitTests(self
, filename
):
10424 """Writes the service decorder unit tests."""
10425 num_tests
= len(self
.functions
)
10426 FUNCTIONS_PER_FILE
= 98 # hard code this so it doesn't change.
10428 for test_num
in range(0, num_tests
, FUNCTIONS_PER_FILE
):
10430 name
= filename
% count
10431 file = CHeaderWriter(
10433 "// It is included by gles2_cmd_decoder_unittest_%d.cc\n" % count
)
10434 test_name
= 'GLES2DecoderTest%d' % count
10435 end
= test_num
+ FUNCTIONS_PER_FILE
10436 if end
> num_tests
:
10438 for idx
in range(test_num
, end
):
10439 func
= self
.functions
[idx
]
10441 # Do any filtering of the functions here, so that the functions
10442 # will not move between the numbered files if filtering properties
10444 if func
.GetInfo('extension_flag'):
10448 #gen_cmd = func.GetInfo('gen_cmd')
10449 #if gen_cmd == True or gen_cmd == None:
10450 if func
.GetInfo('unit_test') == False:
10451 file.Write("// TODO(gman): %s\n" % func
.name
)
10453 func
.WriteServiceUnitTest(file, {
10454 'test_name': test_name
10457 self
.generated_cpp_filenames
.append(file.filename
)
10458 file = CHeaderWriter(
10460 "// It is included by gles2_cmd_decoder_unittest_base.cc\n")
10462 """void GLES2DecoderTestBase::SetupInitCapabilitiesExpectations(
10463 bool es3_capable) {""")
10464 for capability
in _CAPABILITY_FLAGS
:
10465 capability_es3
= 'es3' in capability
and capability
['es3'] == True
10466 if not capability_es3
:
10467 file.Write(" ExpectEnableDisable(GL_%s, %s);\n" %
10468 (capability
['name'].upper(),
10469 ('false', 'true')['default' in capability
]))
10471 file.Write(" if (es3_capable) {")
10472 for capability
in _CAPABILITY_FLAGS
:
10473 capability_es3
= 'es3' in capability
and capability
['es3'] == True
10475 file.Write(" ExpectEnableDisable(GL_%s, %s);\n" %
10476 (capability
['name'].upper(),
10477 ('false', 'true')['default' in capability
]))
10481 void GLES2DecoderTestBase::SetupInitStateExpectations() {
10484 # We need to sort the keys so the expectations match
10485 for state_name
in sorted(_STATES
.keys()):
10486 state
= _STATES
[state_name
]
10487 if state
['type'] == 'FrontBack':
10488 num_states
= len(state
['states'])
10489 for ndx
, group
in enumerate(Grouper(num_states
/ 2, state
['states'])):
10492 if 'expected' in item
:
10493 args
.append(item
['expected'])
10495 args
.append(item
['default'])
10497 " EXPECT_CALL(*gl_, %s(%s, %s))\n" %
10498 (state
['func'], ('GL_FRONT', 'GL_BACK')[ndx
], ", ".join(args
)))
10499 file.Write(" .Times(1)\n")
10500 file.Write(" .RetiresOnSaturation();\n")
10501 elif state
['type'] == 'NamedParameter':
10502 for item
in state
['states']:
10503 if 'extension_flag' in item
:
10504 file.Write(" if (group_->feature_info()->feature_flags().%s) {\n" %
10505 item
['extension_flag'])
10507 expect_value
= item
['default']
10508 if isinstance(expect_value
, list):
10509 # TODO: Currently we do not check array values.
10513 " EXPECT_CALL(*gl_, %s(%s, %s))\n" %
10516 if 'enum_set' in item
else item
['enum']),
10518 file.Write(" .Times(1)\n")
10519 file.Write(" .RetiresOnSaturation();\n")
10520 if 'extension_flag' in item
:
10523 if 'extension_flag' in state
:
10524 file.Write(" if (group_->feature_info()->feature_flags().%s) {\n" %
10525 state
['extension_flag'])
10528 for item
in state
['states']:
10529 if 'expected' in item
:
10530 args
.append(item
['expected'])
10532 args
.append(item
['default'])
10533 # TODO: Currently we do not check array values.
10534 args
= ["_" if isinstance(arg
, list) else arg
for arg
in args
]
10535 file.Write(" EXPECT_CALL(*gl_, %s(%s))\n" %
10536 (state
['func'], ", ".join(args
)))
10537 file.Write(" .Times(1)\n")
10538 file.Write(" .RetiresOnSaturation();\n")
10539 if 'extension_flag' in state
:
10544 self
.generated_cpp_filenames
.append(file.filename
)
10546 def WriteServiceUnitTestsForExtensions(self
, filename
):
10547 """Writes the service decorder unit tests for functions with extension_flag.
10549 The functions are special in that they need a specific unit test
10550 baseclass to turn on the extension.
10552 functions
= [f
for f
in self
.functions
if f
.GetInfo('extension_flag')]
10553 file = CHeaderWriter(
10555 "// It is included by gles2_cmd_decoder_unittest_extensions.cc\n")
10556 for func
in functions
:
10558 if func
.GetInfo('unit_test') == False:
10559 file.Write("// TODO(gman): %s\n" % func
.name
)
10561 extension
= ToCamelCase(
10562 ToGLExtensionString(func
.GetInfo('extension_flag')))
10563 func
.WriteServiceUnitTest(file, {
10564 'test_name': 'GLES2DecoderTestWith%s' % extension
10568 self
.generated_cpp_filenames
.append(file.filename
)
10570 def WriteGLES2Header(self
, filename
):
10571 """Writes the GLES2 header."""
10572 file = CHeaderWriter(
10574 "// This file contains Chromium-specific GLES2 declarations.\n\n")
10576 for func
in self
.original_functions
:
10577 func
.WriteGLES2Header(file)
10581 self
.generated_cpp_filenames
.append(file.filename
)
10583 def WriteGLES2CLibImplementation(self
, filename
):
10584 """Writes the GLES2 c lib implementation."""
10585 file = CHeaderWriter(
10587 "// These functions emulate GLES2 over command buffers.\n")
10589 for func
in self
.original_functions
:
10590 func
.WriteGLES2CLibImplementation(file)
10595 extern const NameToFunc g_gles2_function_table[] = {
10597 for func
in self
.original_functions
:
10599 ' { "gl%s", reinterpret_cast<GLES2FunctionPointer>(gl%s), },\n' %
10600 (func
.name
, func
.name
))
10601 file.Write(""" { NULL, NULL, },
10604 } // namespace gles2
10607 self
.generated_cpp_filenames
.append(file.filename
)
10609 def WriteGLES2InterfaceHeader(self
, filename
):
10610 """Writes the GLES2 interface header."""
10611 file = CHeaderWriter(
10613 "// This file is included by gles2_interface.h to declare the\n"
10614 "// GL api functions.\n")
10615 for func
in self
.original_functions
:
10616 func
.WriteGLES2InterfaceHeader(file)
10618 self
.generated_cpp_filenames
.append(file.filename
)
10620 def WriteMojoGLES2ImplHeader(self
, filename
):
10621 """Writes the Mojo GLES2 implementation header."""
10622 file = CHeaderWriter(
10624 "// This file is included by gles2_interface.h to declare the\n"
10625 "// GL api functions.\n")
10628 #include "gpu/command_buffer/client/gles2_interface.h"
10629 #include "third_party/mojo/src/mojo/public/c/gles2/gles2.h"
10633 class MojoGLES2Impl : public gpu::gles2::GLES2Interface {
10635 explicit MojoGLES2Impl(MojoGLES2Context context) {
10636 context_ = context;
10638 ~MojoGLES2Impl() override {}
10641 for func
in self
.original_functions
:
10642 func
.WriteMojoGLES2ImplHeader(file)
10645 MojoGLES2Context context_;
10648 } // namespace mojo
10652 self
.generated_cpp_filenames
.append(file.filename
)
10654 def WriteMojoGLES2Impl(self
, filename
):
10655 """Writes the Mojo GLES2 implementation."""
10656 file = CWriter(filename
)
10657 file.Write(_LICENSE
)
10658 file.Write(_DO_NOT_EDIT_WARNING
)
10661 #include "mojo/gpu/mojo_gles2_impl_autogen.h"
10663 #include "base/logging.h"
10664 #include "third_party/mojo/src/mojo/public/c/gles2/chromium_copy_texture.h"
10665 #include "third_party/mojo/src/mojo/public/c/gles2/chromium_image.h"
10666 #include "third_party/mojo/src/mojo/public/c/gles2/chromium_miscellaneous.h"
10667 #include "third_party/mojo/src/mojo/public/c/gles2/chromium_pixel_transfer_buffer_object.h"
10668 #include "third_party/mojo/src/mojo/public/c/gles2/chromium_sub_image.h"
10669 #include "third_party/mojo/src/mojo/public/c/gles2/chromium_sync_point.h"
10670 #include "third_party/mojo/src/mojo/public/c/gles2/chromium_texture_mailbox.h"
10671 #include "third_party/mojo/src/mojo/public/c/gles2/gles2.h"
10672 #include "third_party/mojo/src/mojo/public/c/gles2/occlusion_query_ext.h"
10678 for func
in self
.original_functions
:
10679 func
.WriteMojoGLES2Impl(file)
10682 } // namespace mojo
10686 self
.generated_cpp_filenames
.append(file.filename
)
10688 def WriteGLES2InterfaceStub(self
, filename
):
10689 """Writes the GLES2 interface stub header."""
10690 file = CHeaderWriter(
10692 "// This file is included by gles2_interface_stub.h.\n")
10693 for func
in self
.original_functions
:
10694 func
.WriteGLES2InterfaceStub(file)
10696 self
.generated_cpp_filenames
.append(file.filename
)
10698 def WriteGLES2InterfaceStubImpl(self
, filename
):
10699 """Writes the GLES2 interface header."""
10700 file = CHeaderWriter(
10702 "// This file is included by gles2_interface_stub.cc.\n")
10703 for func
in self
.original_functions
:
10704 func
.WriteGLES2InterfaceStubImpl(file)
10706 self
.generated_cpp_filenames
.append(file.filename
)
10708 def WriteGLES2ImplementationHeader(self
, filename
):
10709 """Writes the GLES2 Implementation header."""
10710 file = CHeaderWriter(
10712 "// This file is included by gles2_implementation.h to declare the\n"
10713 "// GL api functions.\n")
10714 for func
in self
.original_functions
:
10715 func
.WriteGLES2ImplementationHeader(file)
10717 self
.generated_cpp_filenames
.append(file.filename
)
10719 def WriteGLES2Implementation(self
, filename
):
10720 """Writes the GLES2 Implementation."""
10721 file = CHeaderWriter(
10723 "// This file is included by gles2_implementation.cc to define the\n"
10724 "// GL api functions.\n")
10725 for func
in self
.original_functions
:
10726 func
.WriteGLES2Implementation(file)
10728 self
.generated_cpp_filenames
.append(file.filename
)
10730 def WriteGLES2TraceImplementationHeader(self
, filename
):
10731 """Writes the GLES2 Trace Implementation header."""
10732 file = CHeaderWriter(
10734 "// This file is included by gles2_trace_implementation.h\n")
10735 for func
in self
.original_functions
:
10736 func
.WriteGLES2TraceImplementationHeader(file)
10738 self
.generated_cpp_filenames
.append(file.filename
)
10740 def WriteGLES2TraceImplementation(self
, filename
):
10741 """Writes the GLES2 Trace Implementation."""
10742 file = CHeaderWriter(
10744 "// This file is included by gles2_trace_implementation.cc\n")
10745 for func
in self
.original_functions
:
10746 func
.WriteGLES2TraceImplementation(file)
10748 self
.generated_cpp_filenames
.append(file.filename
)
10750 def WriteGLES2ImplementationUnitTests(self
, filename
):
10751 """Writes the GLES2 helper header."""
10752 file = CHeaderWriter(
10754 "// This file is included by gles2_implementation.h to declare the\n"
10755 "// GL api functions.\n")
10756 for func
in self
.original_functions
:
10757 func
.WriteGLES2ImplementationUnitTest(file)
10759 self
.generated_cpp_filenames
.append(file.filename
)
10761 def WriteServiceUtilsHeader(self
, filename
):
10762 """Writes the gles2 auto generated utility header."""
10763 file = CHeaderWriter(filename
)
10764 for name
in sorted(_NAMED_TYPE_INFO
.keys()):
10765 named_type
= NamedType(_NAMED_TYPE_INFO
[name
])
10766 if named_type
.IsConstant():
10768 file.Write("ValueValidator<%s> %s;\n" %
10769 (named_type
.GetType(), ToUnderscore(name
)))
10772 self
.generated_cpp_filenames
.append(file.filename
)
10774 def WriteServiceUtilsImplementation(self
, filename
):
10775 """Writes the gles2 auto generated utility implementation."""
10776 file = CHeaderWriter(filename
)
10777 names
= sorted(_NAMED_TYPE_INFO
.keys())
10779 named_type
= NamedType(_NAMED_TYPE_INFO
[name
])
10780 if named_type
.IsConstant():
10782 if named_type
.GetValidValues():
10783 file.Write("static const %s valid_%s_table[] = {\n" %
10784 (named_type
.GetType(), ToUnderscore(name
)))
10785 for value
in named_type
.GetValidValues():
10786 file.Write(" %s,\n" % value
)
10789 if named_type
.GetValidValuesES3():
10790 file.Write("static const %s valid_%s_table_es3[] = {\n" %
10791 (named_type
.GetType(), ToUnderscore(name
)))
10792 for value
in named_type
.GetValidValuesES3():
10793 file.Write(" %s,\n" % value
)
10796 if named_type
.GetDeprecatedValuesES3():
10797 file.Write("static const %s deprecated_%s_table_es3[] = {\n" %
10798 (named_type
.GetType(), ToUnderscore(name
)))
10799 for value
in named_type
.GetDeprecatedValuesES3():
10800 file.Write(" %s,\n" % value
)
10803 file.Write("Validators::Validators()")
10805 for count
, name
in enumerate(names
):
10806 named_type
= NamedType(_NAMED_TYPE_INFO
[name
])
10807 if named_type
.IsConstant():
10809 if named_type
.GetValidValues():
10810 code
= """%(pre)s%(name)s(
10811 valid_%(name)s_table, arraysize(valid_%(name)s_table))"""
10813 code
= "%(pre)s%(name)s()"
10814 file.Write(code
% {
10815 'name': ToUnderscore(name
),
10819 file.Write(" {\n");
10820 file.Write("}\n\n");
10822 file.Write("void Validators::UpdateValuesES3() {\n")
10824 named_type
= NamedType(_NAMED_TYPE_INFO
[name
])
10825 if named_type
.GetDeprecatedValuesES3():
10826 code
= """ %(name)s.RemoveValues(
10827 deprecated_%(name)s_table_es3, arraysize(deprecated_%(name)s_table_es3));
10829 file.Write(code
% {
10830 'name': ToUnderscore(name
),
10832 if named_type
.GetValidValuesES3():
10833 code
= """ %(name)s.AddValues(
10834 valid_%(name)s_table_es3, arraysize(valid_%(name)s_table_es3));
10836 file.Write(code
% {
10837 'name': ToUnderscore(name
),
10839 file.Write("}\n\n");
10841 self
.generated_cpp_filenames
.append(file.filename
)
10843 def WriteCommonUtilsHeader(self
, filename
):
10844 """Writes the gles2 common utility header."""
10845 file = CHeaderWriter(filename
)
10846 type_infos
= sorted(_NAMED_TYPE_INFO
.keys())
10847 for type_info
in type_infos
:
10848 if _NAMED_TYPE_INFO
[type_info
]['type'] == 'GLenum':
10849 file.Write("static std::string GetString%s(uint32_t value);\n" %
10853 self
.generated_cpp_filenames
.append(file.filename
)
10855 def WriteCommonUtilsImpl(self
, filename
):
10856 """Writes the gles2 common utility header."""
10857 enum_re
= re
.compile(r
'\#define\s+(GL_[a-zA-Z0-9_]+)\s+([0-9A-Fa-fx]+)')
10859 for fname
in ['third_party/khronos/GLES2/gl2.h',
10860 'third_party/khronos/GLES2/gl2ext.h',
10861 'third_party/khronos/GLES3/gl3.h',
10862 'gpu/GLES2/gl2chromium.h',
10863 'gpu/GLES2/gl2extchromium.h']:
10864 lines
= open(fname
).readlines()
10866 m
= enum_re
.match(line
)
10870 if len(value
) <= 10:
10871 if not value
in dict:
10873 # check our own _CHROMIUM macro conflicts with khronos GL headers.
10874 elif dict[value
] != name
and (name
.endswith('_CHROMIUM') or
10875 dict[value
].endswith('_CHROMIUM')):
10876 self
.Error("code collision: %s and %s have the same code %s" %
10877 (dict[value
], name
, value
))
10879 file = CHeaderWriter(filename
)
10880 file.Write("static const GLES2Util::EnumToString "
10881 "enum_to_string_table[] = {\n")
10883 file.Write(' { %s, "%s", },\n' % (value
, dict[value
]))
10886 const GLES2Util::EnumToString* const GLES2Util::enum_to_string_table_ =
10887 enum_to_string_table;
10888 const size_t GLES2Util::enum_to_string_table_len_ =
10889 sizeof(enum_to_string_table) / sizeof(enum_to_string_table[0]);
10893 enums
= sorted(_NAMED_TYPE_INFO
.keys())
10895 if _NAMED_TYPE_INFO
[enum
]['type'] == 'GLenum':
10896 file.Write("std::string GLES2Util::GetString%s(uint32_t value) {\n" %
10898 valid_list
= _NAMED_TYPE_INFO
[enum
]['valid']
10899 if 'valid_es3' in _NAMED_TYPE_INFO
[enum
]:
10900 valid_list
= valid_list
+ _NAMED_TYPE_INFO
[enum
]['valid_es3']
10901 assert len(valid_list
) == len(set(valid_list
))
10902 if len(valid_list
) > 0:
10903 file.Write(" static const EnumToString string_table[] = {\n")
10904 for value
in valid_list
:
10905 file.Write(' { %s, "%s" },\n' % (value
, value
))
10907 return GLES2Util::GetQualifiedEnumString(
10908 string_table, arraysize(string_table), value);
10913 file.Write(""" return GLES2Util::GetQualifiedEnumString(
10919 self
.generated_cpp_filenames
.append(file.filename
)
10921 def WritePepperGLES2Interface(self
, filename
, dev
):
10922 """Writes the Pepper OpenGLES interface definition."""
10923 file = CWriter(filename
)
10924 file.Write(_LICENSE
)
10925 file.Write(_DO_NOT_EDIT_WARNING
)
10927 file.Write("label Chrome {\n")
10928 file.Write(" M39 = 1.0\n")
10929 file.Write("};\n\n")
10932 # Declare GL types.
10933 file.Write("[version=1.0]\n")
10934 file.Write("describe {\n")
10935 for gltype
in ['GLbitfield', 'GLboolean', 'GLbyte', 'GLclampf',
10936 'GLclampx', 'GLenum', 'GLfixed', 'GLfloat', 'GLint',
10937 'GLintptr', 'GLshort', 'GLsizei', 'GLsizeiptr',
10938 'GLubyte', 'GLuint', 'GLushort']:
10939 file.Write(" %s;\n" % gltype
)
10940 file.Write(" %s_ptr_t;\n" % gltype
)
10941 file.Write("};\n\n")
10943 # C level typedefs.
10944 file.Write("#inline c\n")
10945 file.Write("#include \"ppapi/c/pp_resource.h\"\n")
10947 file.Write("#include \"ppapi/c/ppb_opengles2.h\"\n\n")
10949 file.Write("\n#ifndef __gl2_h_\n")
10950 for (k
, v
) in _GL_TYPES
.iteritems():
10951 file.Write("typedef %s %s;\n" % (v
, k
))
10952 file.Write("#ifdef _WIN64\n")
10953 for (k
, v
) in _GL_TYPES_64
.iteritems():
10954 file.Write("typedef %s %s;\n" % (v
, k
))
10955 file.Write("#else\n")
10956 for (k
, v
) in _GL_TYPES_32
.iteritems():
10957 file.Write("typedef %s %s;\n" % (v
, k
))
10958 file.Write("#endif // _WIN64\n")
10959 file.Write("#endif // __gl2_h_\n\n")
10960 file.Write("#endinl\n")
10962 for interface
in self
.pepper_interfaces
:
10963 if interface
.dev
!= dev
:
10965 # Historically, we provide OpenGLES2 interfaces with struct
10966 # namespace. Not to break code which uses the interface as
10967 # "struct OpenGLES2", we put it in struct namespace.
10968 file.Write('\n[macro="%s", force_struct_namespace]\n' %
10969 interface
.GetInterfaceName())
10970 file.Write("interface %s {\n" % interface
.GetStructName())
10971 for func
in self
.original_functions
:
10972 if not func
.InPepperInterface(interface
):
10975 ret_type
= func
.MapCTypeToPepperIdlType(func
.return_type
,
10976 is_for_return_type
=True)
10977 func_prefix
= " %s %s(" % (ret_type
, func
.GetPepperName())
10978 file.Write(func_prefix
)
10979 file.Write("[in] PP_Resource context")
10980 for arg
in func
.MakeTypedPepperIdlArgStrings():
10981 file.Write(",\n" + " " * len(func_prefix
) + arg
)
10983 file.Write("};\n\n")
10988 def WritePepperGLES2Implementation(self
, filename
):
10989 """Writes the Pepper OpenGLES interface implementation."""
10991 file = CWriter(filename
)
10992 file.Write(_LICENSE
)
10993 file.Write(_DO_NOT_EDIT_WARNING
)
10995 file.Write("#include \"ppapi/shared_impl/ppb_opengles2_shared.h\"\n\n")
10996 file.Write("#include \"base/logging.h\"\n")
10997 file.Write("#include \"gpu/command_buffer/client/gles2_implementation.h\"\n")
10998 file.Write("#include \"ppapi/shared_impl/ppb_graphics_3d_shared.h\"\n")
10999 file.Write("#include \"ppapi/thunk/enter.h\"\n\n")
11001 file.Write("namespace ppapi {\n\n")
11002 file.Write("namespace {\n\n")
11004 file.Write("typedef thunk::EnterResource<thunk::PPB_Graphics3D_API>"
11007 file.Write("gpu::gles2::GLES2Implementation* ToGles2Impl(Enter3D*"
11009 file.Write(" DCHECK(enter);\n")
11010 file.Write(" DCHECK(enter->succeeded());\n")
11011 file.Write(" return static_cast<PPB_Graphics3D_Shared*>(enter->object())->"
11012 "gles2_impl();\n");
11013 file.Write("}\n\n");
11015 for func
in self
.original_functions
:
11016 if not func
.InAnyPepperExtension():
11019 original_arg
= func
.MakeTypedPepperArgString("")
11020 context_arg
= "PP_Resource context_id"
11021 if len(original_arg
):
11022 arg
= context_arg
+ ", " + original_arg
11025 file.Write("%s %s(%s) {\n" %
11026 (func
.return_type
, func
.GetPepperName(), arg
))
11027 file.Write(" Enter3D enter(context_id, true);\n")
11028 file.Write(" if (enter.succeeded()) {\n")
11030 return_str
= "" if func
.return_type
== "void" else "return "
11031 file.Write(" %sToGles2Impl(&enter)->%s(%s);\n" %
11032 (return_str
, func
.original_name
,
11033 func
.MakeOriginalArgString("")))
11035 if func
.return_type
== "void":
11038 file.Write(" else {\n")
11039 file.Write(" return %s;\n" % func
.GetErrorReturnString())
11041 file.Write("}\n\n")
11043 file.Write("} // namespace\n")
11045 for interface
in self
.pepper_interfaces
:
11046 file.Write("const %s* PPB_OpenGLES2_Shared::Get%sInterface() {\n" %
11047 (interface
.GetStructName(), interface
.GetName()))
11048 file.Write(" static const struct %s "
11049 "ppb_opengles2 = {\n" % interface
.GetStructName())
11051 file.Write(",\n &".join(
11052 f
.GetPepperName() for f
in self
.original_functions
11053 if f
.InPepperInterface(interface
)))
11056 file.Write(" };\n")
11057 file.Write(" return &ppb_opengles2;\n")
11060 file.Write("} // namespace ppapi\n")
11062 self
.generated_cpp_filenames
.append(file.filename
)
11064 def WriteGLES2ToPPAPIBridge(self
, filename
):
11065 """Connects GLES2 helper library to PPB_OpenGLES2 interface"""
11067 file = CWriter(filename
)
11068 file.Write(_LICENSE
)
11069 file.Write(_DO_NOT_EDIT_WARNING
)
11071 file.Write("#ifndef GL_GLEXT_PROTOTYPES\n")
11072 file.Write("#define GL_GLEXT_PROTOTYPES\n")
11073 file.Write("#endif\n")
11074 file.Write("#include <GLES2/gl2.h>\n")
11075 file.Write("#include <GLES2/gl2ext.h>\n")
11076 file.Write("#include \"ppapi/lib/gl/gles2/gl2ext_ppapi.h\"\n\n")
11078 for func
in self
.original_functions
:
11079 if not func
.InAnyPepperExtension():
11082 interface
= self
.interface_info
[func
.GetInfo('pepper_interface') or '']
11084 file.Write("%s GL_APIENTRY gl%s(%s) {\n" %
11085 (func
.return_type
, func
.GetPepperName(),
11086 func
.MakeTypedPepperArgString("")))
11087 return_str
= "" if func
.return_type
== "void" else "return "
11088 interface_str
= "glGet%sInterfacePPAPI()" % interface
.GetName()
11089 original_arg
= func
.MakeOriginalArgString("")
11090 context_arg
= "glGetCurrentContextPPAPI()"
11091 if len(original_arg
):
11092 arg
= context_arg
+ ", " + original_arg
11095 if interface
.GetName():
11096 file.Write(" const struct %s* ext = %s;\n" %
11097 (interface
.GetStructName(), interface_str
))
11098 file.Write(" if (ext)\n")
11099 file.Write(" %sext->%s(%s);\n" %
11100 (return_str
, func
.GetPepperName(), arg
))
11102 file.Write(" %s0;\n" % return_str
)
11104 file.Write(" %s%s->%s(%s);\n" %
11105 (return_str
, interface_str
, func
.GetPepperName(), arg
))
11106 file.Write("}\n\n")
11108 self
.generated_cpp_filenames
.append(file.filename
)
11110 def WriteMojoGLCallVisitor(self
, filename
):
11111 """Provides the GL implementation for mojo"""
11112 file = CWriter(filename
)
11113 file.Write(_LICENSE
)
11114 file.Write(_DO_NOT_EDIT_WARNING
)
11116 for func
in self
.original_functions
:
11117 if not func
.IsCoreGLFunction():
11119 file.Write("VISIT_GL_CALL(%s, %s, (%s), (%s))\n" %
11120 (func
.name
, func
.return_type
,
11121 func
.MakeTypedOriginalArgString(""),
11122 func
.MakeOriginalArgString("")))
11125 self
.generated_cpp_filenames
.append(file.filename
)
11127 def WriteMojoGLCallVisitorForExtension(self
, filename
, extension
):
11128 """Provides the GL implementation for mojo for a particular extension"""
11129 file = CWriter(filename
)
11130 file.Write(_LICENSE
)
11131 file.Write(_DO_NOT_EDIT_WARNING
)
11133 for func
in self
.original_functions
:
11134 if func
.GetInfo("extension") != extension
:
11136 file.Write("VISIT_GL_CALL(%s, %s, (%s), (%s))\n" %
11137 (func
.name
, func
.return_type
,
11138 func
.MakeTypedOriginalArgString(""),
11139 func
.MakeOriginalArgString("")))
11142 self
.generated_cpp_filenames
.append(file.filename
)
11144 def Format(generated_files
):
11145 formatter
= "clang-format"
11146 if platform
.system() == "Windows":
11147 formatter
+= ".bat"
11148 for filename
in generated_files
:
11149 call([formatter
, "-i", "-style=chromium", filename
])
11152 """This is the main function."""
11153 parser
= OptionParser()
11156 help="base directory for resulting files, under chrome/src. default is "
11157 "empty. Use this if you want the result stored under gen.")
11159 "-v", "--verbose", action
="store_true",
11160 help="prints more output.")
11162 (options
, args
) = parser
.parse_args(args
=argv
)
11164 # Add in states and capabilites to GLState
11165 gl_state_valid
= _NAMED_TYPE_INFO
['GLState']['valid']
11166 for state_name
in sorted(_STATES
.keys()):
11167 state
= _STATES
[state_name
]
11168 if 'extension_flag' in state
:
11170 if 'enum' in state
:
11171 if not state
['enum'] in gl_state_valid
:
11172 gl_state_valid
.append(state
['enum'])
11174 for item
in state
['states']:
11175 if 'extension_flag' in item
:
11177 if not item
['enum'] in gl_state_valid
:
11178 gl_state_valid
.append(item
['enum'])
11179 for capability
in _CAPABILITY_FLAGS
:
11180 valid_value
= "GL_%s" % capability
['name'].upper()
11181 if not valid_value
in gl_state_valid
:
11182 gl_state_valid
.append(valid_value
)
11184 # This script lives under gpu/command_buffer, cd to base directory.
11185 os
.chdir(os
.path
.dirname(__file__
) + "/../..")
11186 base_dir
= os
.getcwd()
11187 gen
= GLGenerator(options
.verbose
)
11188 gen
.ParseGLH("gpu/command_buffer/cmd_buffer_functions.txt")
11190 # Support generating files under gen/
11191 if options
.output_dir
!= None:
11192 os
.chdir(options
.output_dir
)
11194 gen
.WritePepperGLES2Interface("ppapi/api/ppb_opengles2.idl", False)
11195 gen
.WritePepperGLES2Interface("ppapi/api/dev/ppb_opengles2ext_dev.idl", True)
11196 gen
.WriteGLES2ToPPAPIBridge("ppapi/lib/gl/gles2/gles2.c")
11197 gen
.WritePepperGLES2Implementation(
11198 "ppapi/shared_impl/ppb_opengles2_shared.cc")
11200 gen
.WriteCommandIds("gpu/command_buffer/common/gles2_cmd_ids_autogen.h")
11201 gen
.WriteFormat("gpu/command_buffer/common/gles2_cmd_format_autogen.h")
11202 gen
.WriteFormatTest(
11203 "gpu/command_buffer/common/gles2_cmd_format_test_autogen.h")
11204 gen
.WriteGLES2InterfaceHeader(
11205 "gpu/command_buffer/client/gles2_interface_autogen.h")
11206 gen
.WriteMojoGLES2ImplHeader(
11207 "mojo/gpu/mojo_gles2_impl_autogen.h")
11208 gen
.WriteMojoGLES2Impl(
11209 "mojo/gpu/mojo_gles2_impl_autogen.cc")
11210 gen
.WriteGLES2InterfaceStub(
11211 "gpu/command_buffer/client/gles2_interface_stub_autogen.h")
11212 gen
.WriteGLES2InterfaceStubImpl(
11213 "gpu/command_buffer/client/gles2_interface_stub_impl_autogen.h")
11214 gen
.WriteGLES2ImplementationHeader(
11215 "gpu/command_buffer/client/gles2_implementation_autogen.h")
11216 gen
.WriteGLES2Implementation(
11217 "gpu/command_buffer/client/gles2_implementation_impl_autogen.h")
11218 gen
.WriteGLES2ImplementationUnitTests(
11219 "gpu/command_buffer/client/gles2_implementation_unittest_autogen.h")
11220 gen
.WriteGLES2TraceImplementationHeader(
11221 "gpu/command_buffer/client/gles2_trace_implementation_autogen.h")
11222 gen
.WriteGLES2TraceImplementation(
11223 "gpu/command_buffer/client/gles2_trace_implementation_impl_autogen.h")
11224 gen
.WriteGLES2CLibImplementation(
11225 "gpu/command_buffer/client/gles2_c_lib_autogen.h")
11226 gen
.WriteCmdHelperHeader(
11227 "gpu/command_buffer/client/gles2_cmd_helper_autogen.h")
11228 gen
.WriteServiceImplementation(
11229 "gpu/command_buffer/service/gles2_cmd_decoder_autogen.h")
11230 gen
.WriteServiceContextStateHeader(
11231 "gpu/command_buffer/service/context_state_autogen.h")
11232 gen
.WriteServiceContextStateImpl(
11233 "gpu/command_buffer/service/context_state_impl_autogen.h")
11234 gen
.WriteClientContextStateHeader(
11235 "gpu/command_buffer/client/client_context_state_autogen.h")
11236 gen
.WriteClientContextStateImpl(
11237 "gpu/command_buffer/client/client_context_state_impl_autogen.h")
11238 gen
.WriteServiceUnitTests(
11239 "gpu/command_buffer/service/gles2_cmd_decoder_unittest_%d_autogen.h")
11240 gen
.WriteServiceUnitTestsForExtensions(
11241 "gpu/command_buffer/service/"
11242 "gles2_cmd_decoder_unittest_extensions_autogen.h")
11243 gen
.WriteServiceUtilsHeader(
11244 "gpu/command_buffer/service/gles2_cmd_validation_autogen.h")
11245 gen
.WriteServiceUtilsImplementation(
11246 "gpu/command_buffer/service/"
11247 "gles2_cmd_validation_implementation_autogen.h")
11248 gen
.WriteCommonUtilsHeader(
11249 "gpu/command_buffer/common/gles2_cmd_utils_autogen.h")
11250 gen
.WriteCommonUtilsImpl(
11251 "gpu/command_buffer/common/gles2_cmd_utils_implementation_autogen.h")
11252 gen
.WriteGLES2Header("gpu/GLES2/gl2chromium_autogen.h")
11253 mojo_gles2_prefix
= ("third_party/mojo/src/mojo/public/c/gles2/"
11254 "gles2_call_visitor")
11255 gen
.WriteMojoGLCallVisitor(mojo_gles2_prefix
+ "_autogen.h")
11256 gen
.WriteMojoGLCallVisitorForExtension(
11257 mojo_gles2_prefix
+ "_chromium_texture_mailbox_autogen.h",
11258 "CHROMIUM_texture_mailbox")
11259 gen
.WriteMojoGLCallVisitorForExtension(
11260 mojo_gles2_prefix
+ "_chromium_sync_point_autogen.h",
11261 "CHROMIUM_sync_point")
11262 gen
.WriteMojoGLCallVisitorForExtension(
11263 mojo_gles2_prefix
+ "_chromium_sub_image_autogen.h",
11264 "CHROMIUM_sub_image")
11265 gen
.WriteMojoGLCallVisitorForExtension(
11266 mojo_gles2_prefix
+ "_chromium_miscellaneous_autogen.h",
11267 "CHROMIUM_miscellaneous")
11268 gen
.WriteMojoGLCallVisitorForExtension(
11269 mojo_gles2_prefix
+ "_occlusion_query_ext_autogen.h",
11270 "occlusion_query_EXT")
11271 gen
.WriteMojoGLCallVisitorForExtension(
11272 mojo_gles2_prefix
+ "_chromium_image_autogen.h",
11274 gen
.WriteMojoGLCallVisitorForExtension(
11275 mojo_gles2_prefix
+ "_chromium_copy_texture_autogen.h",
11276 "CHROMIUM_copy_texture")
11277 gen
.WriteMojoGLCallVisitorForExtension(
11278 mojo_gles2_prefix
+ "_chromium_pixel_transfer_buffer_object_autogen.h",
11279 "CHROMIUM_pixel_transfer_buffer_object")
11281 Format(gen
.generated_cpp_filenames
)
11284 print "%d errors" % gen
.errors
11289 if __name__
== '__main__':
11290 sys
.exit(main(sys
.argv
[1:]))