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',
912 'GL_COLOR_ATTACHMENT0',
913 'GL_COLOR_ATTACHMENT1',
914 'GL_COLOR_ATTACHMENT2',
915 'GL_COLOR_ATTACHMENT3',
916 'GL_COLOR_ATTACHMENT4',
917 'GL_COLOR_ATTACHMENT5',
918 'GL_COLOR_ATTACHMENT6',
919 'GL_COLOR_ATTACHMENT7',
920 'GL_COLOR_ATTACHMENT8',
921 'GL_COLOR_ATTACHMENT9',
922 'GL_COLOR_ATTACHMENT10',
923 'GL_COLOR_ATTACHMENT11',
924 'GL_COLOR_ATTACHMENT12',
925 'GL_COLOR_ATTACHMENT13',
926 'GL_COLOR_ATTACHMENT14',
927 'GL_COLOR_ATTACHMENT15',
937 'GL_TEXTURE_CUBE_MAP_POSITIVE_X',
938 'GL_TEXTURE_CUBE_MAP_NEGATIVE_X',
939 'GL_TEXTURE_CUBE_MAP_POSITIVE_Y',
940 'GL_TEXTURE_CUBE_MAP_NEGATIVE_Y',
941 'GL_TEXTURE_CUBE_MAP_POSITIVE_Z',
942 'GL_TEXTURE_CUBE_MAP_NEGATIVE_Z',
945 'GL_PROXY_TEXTURE_CUBE_MAP',
952 'GL_TEXTURE_2D_ARRAY',
958 'TextureBindTarget': {
962 'GL_TEXTURE_CUBE_MAP',
966 'GL_TEXTURE_2D_ARRAY',
973 'TransformFeedbackBindTarget': {
976 'GL_TRANSFORM_FEEDBACK',
982 'TransformFeedbackPrimitiveMode': {
997 'GL_FRAGMENT_SHADER',
1000 'GL_GEOMETRY_SHADER',
1008 'GL_FRONT_AND_BACK',
1036 'GL_FUNC_REVERSE_SUBTRACT',
1052 'GL_ONE_MINUS_SRC_COLOR',
1054 'GL_ONE_MINUS_DST_COLOR',
1056 'GL_ONE_MINUS_SRC_ALPHA',
1058 'GL_ONE_MINUS_DST_ALPHA',
1059 'GL_CONSTANT_COLOR',
1060 'GL_ONE_MINUS_CONSTANT_COLOR',
1061 'GL_CONSTANT_ALPHA',
1062 'GL_ONE_MINUS_CONSTANT_ALPHA',
1063 'GL_SRC_ALPHA_SATURATE',
1072 'GL_ONE_MINUS_SRC_COLOR',
1074 'GL_ONE_MINUS_DST_COLOR',
1076 'GL_ONE_MINUS_SRC_ALPHA',
1078 'GL_ONE_MINUS_DST_ALPHA',
1079 'GL_CONSTANT_COLOR',
1080 'GL_ONE_MINUS_CONSTANT_COLOR',
1081 'GL_CONSTANT_ALPHA',
1082 'GL_ONE_MINUS_CONSTANT_ALPHA',
1087 'valid': ["GL_%s" % cap
['name'].upper() for cap
in _CAPABILITY_FLAGS
1088 if 'es3' not in cap
or cap
['es3'] != True],
1089 'valid_es3': ["GL_%s" % cap
['name'].upper() for cap
in _CAPABILITY_FLAGS
1090 if 'es3' in cap
and cap
['es3'] == True],
1103 'GL_TRIANGLE_STRIP',
1116 'GL_UNSIGNED_SHORT',
1125 'GetMaxIndexType': {
1129 'GL_UNSIGNED_SHORT',
1139 'GL_COLOR_ATTACHMENT0',
1140 'GL_DEPTH_ATTACHMENT',
1141 'GL_STENCIL_ATTACHMENT',
1144 'GL_DEPTH_STENCIL_ATTACHMENT',
1147 'BackbufferAttachment': {
1155 'BufferParameter': {
1162 'GL_BUFFER_ACCESS_FLAGS',
1166 'GL_PIXEL_PACK_BUFFER',
1169 'BufferParameter64': {
1173 'GL_BUFFER_MAP_LENGTH',
1174 'GL_BUFFER_MAP_OFFSET',
1177 'GL_PIXEL_PACK_BUFFER',
1183 'GL_INTERLEAVED_ATTRIBS',
1184 'GL_SEPARATE_ATTRIBS',
1187 'GL_PIXEL_PACK_BUFFER',
1190 'FrameBufferParameter': {
1193 'GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE',
1194 'GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME',
1195 'GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL',
1196 'GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE',
1199 'GL_FRAMEBUFFER_ATTACHMENT_RED_SIZE',
1200 'GL_FRAMEBUFFER_ATTACHMENT_GREEN_SIZE',
1201 'GL_FRAMEBUFFER_ATTACHMENT_BLUE_SIZE',
1202 'GL_FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE',
1203 'GL_FRAMEBUFFER_ATTACHMENT_DEPTH_SIZE',
1204 'GL_FRAMEBUFFER_ATTACHMENT_STENCIL_SIZE',
1205 'GL_FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE',
1206 'GL_FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING',
1207 'GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER',
1213 'GL_PATH_PROJECTION_CHROMIUM',
1214 'GL_PATH_MODELVIEW_CHROMIUM',
1217 'ProgramParameter': {
1222 'GL_VALIDATE_STATUS',
1223 'GL_INFO_LOG_LENGTH',
1224 'GL_ATTACHED_SHADERS',
1225 'GL_ACTIVE_ATTRIBUTES',
1226 'GL_ACTIVE_ATTRIBUTE_MAX_LENGTH',
1227 'GL_ACTIVE_UNIFORMS',
1228 'GL_ACTIVE_UNIFORM_MAX_LENGTH',
1231 'GL_ACTIVE_UNIFORM_BLOCKS',
1232 'GL_ACTIVE_UNIFORM_BLOCK_MAX_NAME_LENGTH',
1233 'GL_TRANSFORM_FEEDBACK_BUFFER_MODE',
1234 'GL_TRANSFORM_FEEDBACK_VARYINGS',
1235 'GL_TRANSFORM_FEEDBACK_VARYING_MAX_LENGTH',
1238 'GL_PROGRAM_BINARY_RETRIEVABLE_HINT', # not supported in Chromium.
1241 'QueryObjectParameter': {
1244 'GL_QUERY_RESULT_EXT',
1245 'GL_QUERY_RESULT_AVAILABLE_EXT',
1251 'GL_CURRENT_QUERY_EXT',
1257 'GL_ANY_SAMPLES_PASSED_EXT',
1258 'GL_ANY_SAMPLES_PASSED_CONSERVATIVE_EXT',
1259 'GL_COMMANDS_ISSUED_CHROMIUM',
1260 'GL_LATENCY_QUERY_CHROMIUM',
1261 'GL_ASYNC_PIXEL_UNPACK_COMPLETED_CHROMIUM',
1262 'GL_ASYNC_PIXEL_PACK_COMPLETED_CHROMIUM',
1263 'GL_COMMANDS_COMPLETED_CHROMIUM',
1266 'RenderBufferParameter': {
1269 'GL_RENDERBUFFER_RED_SIZE',
1270 'GL_RENDERBUFFER_GREEN_SIZE',
1271 'GL_RENDERBUFFER_BLUE_SIZE',
1272 'GL_RENDERBUFFER_ALPHA_SIZE',
1273 'GL_RENDERBUFFER_DEPTH_SIZE',
1274 'GL_RENDERBUFFER_STENCIL_SIZE',
1275 'GL_RENDERBUFFER_WIDTH',
1276 'GL_RENDERBUFFER_HEIGHT',
1277 'GL_RENDERBUFFER_INTERNAL_FORMAT',
1280 'GL_RENDERBUFFER_SAMPLES',
1283 'InternalFormatParameter': {
1286 'GL_NUM_SAMPLE_COUNTS',
1290 'SamplerParameter': {
1293 'GL_TEXTURE_MAG_FILTER',
1294 'GL_TEXTURE_MIN_FILTER',
1295 'GL_TEXTURE_MIN_LOD',
1296 'GL_TEXTURE_MAX_LOD',
1297 'GL_TEXTURE_WRAP_S',
1298 'GL_TEXTURE_WRAP_T',
1299 'GL_TEXTURE_WRAP_R',
1300 'GL_TEXTURE_COMPARE_MODE',
1301 'GL_TEXTURE_COMPARE_FUNC',
1304 'GL_GENERATE_MIPMAP',
1307 'ShaderParameter': {
1312 'GL_COMPILE_STATUS',
1313 'GL_INFO_LOG_LENGTH',
1314 'GL_SHADER_SOURCE_LENGTH',
1315 'GL_TRANSLATED_SHADER_SOURCE_LENGTH_ANGLE',
1318 'ShaderPrecision': {
1335 'GL_SHADING_LANGUAGE_VERSION',
1339 'TextureParameter': {
1342 'GL_TEXTURE_MAG_FILTER',
1343 'GL_TEXTURE_MIN_FILTER',
1344 'GL_TEXTURE_POOL_CHROMIUM',
1345 'GL_TEXTURE_WRAP_S',
1346 'GL_TEXTURE_WRAP_T',
1349 'GL_TEXTURE_BASE_LEVEL',
1350 'GL_TEXTURE_COMPARE_FUNC',
1351 'GL_TEXTURE_COMPARE_MODE',
1352 'GL_TEXTURE_IMMUTABLE_FORMAT',
1353 'GL_TEXTURE_IMMUTABLE_LEVELS',
1354 'GL_TEXTURE_MAX_LEVEL',
1355 'GL_TEXTURE_MAX_LOD',
1356 'GL_TEXTURE_MIN_LOD',
1357 'GL_TEXTURE_WRAP_R',
1360 'GL_GENERATE_MIPMAP',
1366 'GL_TEXTURE_POOL_MANAGED_CHROMIUM',
1367 'GL_TEXTURE_POOL_UNMANAGED_CHROMIUM',
1370 'TextureWrapMode': {
1374 'GL_MIRRORED_REPEAT',
1378 'TextureMinFilterMode': {
1383 'GL_NEAREST_MIPMAP_NEAREST',
1384 'GL_LINEAR_MIPMAP_NEAREST',
1385 'GL_NEAREST_MIPMAP_LINEAR',
1386 'GL_LINEAR_MIPMAP_LINEAR',
1389 'TextureMagFilterMode': {
1396 'TextureCompareFunc': {
1409 'TextureCompareMode': {
1413 'GL_COMPARE_REF_TO_TEXTURE',
1420 'GL_FRAMEBUFFER_ATTACHMENT_ANGLE',
1423 'VertexAttribute': {
1426 # some enum that the decoder actually passes through to GL needs
1427 # to be the first listed here since it's used in unit tests.
1428 'GL_VERTEX_ATTRIB_ARRAY_NORMALIZED',
1429 'GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING',
1430 'GL_VERTEX_ATTRIB_ARRAY_ENABLED',
1431 'GL_VERTEX_ATTRIB_ARRAY_SIZE',
1432 'GL_VERTEX_ATTRIB_ARRAY_STRIDE',
1433 'GL_VERTEX_ATTRIB_ARRAY_TYPE',
1434 'GL_CURRENT_VERTEX_ATTRIB',
1437 'GL_VERTEX_ATTRIB_ARRAY_INTEGER',
1438 'GL_VERTEX_ATTRIB_ARRAY_DIVISOR',
1444 'GL_VERTEX_ATTRIB_ARRAY_POINTER',
1450 'GL_GENERATE_MIPMAP_HINT',
1453 'GL_FRAGMENT_SHADER_DERIVATIVE_HINT',
1456 'GL_PERSPECTIVE_CORRECTION_HINT',
1470 'GL_PACK_ALIGNMENT',
1471 'GL_UNPACK_ALIGNMENT',
1474 'GL_PACK_ROW_LENGTH',
1475 'GL_PACK_SKIP_PIXELS',
1476 'GL_PACK_SKIP_ROWS',
1477 'GL_UNPACK_ROW_LENGTH',
1478 'GL_UNPACK_IMAGE_HEIGHT',
1479 'GL_UNPACK_SKIP_PIXELS',
1480 'GL_UNPACK_SKIP_ROWS',
1481 'GL_UNPACK_SKIP_IMAGES',
1484 'GL_PACK_SWAP_BYTES',
1485 'GL_UNPACK_SWAP_BYTES',
1488 'PixelStoreAlignment': {
1501 'ReadPixelFormat': {
1520 'GL_UNSIGNED_SHORT_5_6_5',
1521 'GL_UNSIGNED_SHORT_4_4_4_4',
1522 'GL_UNSIGNED_SHORT_5_5_5_1',
1526 'GL_UNSIGNED_SHORT',
1532 'GL_UNSIGNED_INT_2_10_10_10_REV',
1533 'GL_UNSIGNED_INT_10F_11F_11F_REV',
1534 'GL_UNSIGNED_INT_5_9_9_9_REV',
1535 'GL_UNSIGNED_INT_24_8',
1536 'GL_FLOAT_32_UNSIGNED_INT_24_8_REV',
1539 'GL_UNSIGNED_BYTE_3_3_2',
1548 'GL_UNSIGNED_SHORT',
1555 'GL_CONVEX_HULL_CHROMIUM',
1556 'GL_BOUNDING_BOX_CHROMIUM',
1563 'GL_COUNT_UP_CHROMIUM',
1564 'GL_COUNT_DOWN_CHROMIUM',
1570 'GL_PATH_STROKE_WIDTH_CHROMIUM',
1571 'GL_PATH_END_CAPS_CHROMIUM',
1572 'GL_PATH_JOIN_STYLE_CHROMIUM',
1573 'GL_PATH_MITER_LIMIT_CHROMIUM',
1574 'GL_PATH_STROKE_BOUND_CHROMIUM',
1577 'PathParameterCapValues': {
1581 'GL_SQUARE_CHROMIUM',
1582 'GL_ROUND_CHROMIUM',
1585 'PathParameterJoinValues': {
1588 'GL_MITER_REVERT_CHROMIUM',
1589 'GL_BEVEL_CHROMIUM',
1590 'GL_ROUND_CHROMIUM',
1597 'GL_UNSIGNED_SHORT_5_6_5',
1598 'GL_UNSIGNED_SHORT_4_4_4_4',
1599 'GL_UNSIGNED_SHORT_5_5_5_1',
1610 'GL_UNSIGNED_SHORT_5_6_5',
1611 'GL_UNSIGNED_SHORT_4_4_4_4',
1612 'GL_UNSIGNED_SHORT_5_5_5_1',
1615 'RenderBufferFormat': {
1621 'GL_DEPTH_COMPONENT16',
1622 'GL_STENCIL_INDEX8',
1650 'GL_DEPTH_COMPONENT24',
1651 'GL_DEPTH_COMPONENT32F',
1652 'GL_DEPTH24_STENCIL8',
1653 'GL_DEPTH32F_STENCIL8',
1656 'ShaderBinaryFormat': {
1679 'GL_LUMINANCE_ALPHA',
1690 'GL_DEPTH_COMPONENT',
1698 'TextureInternalFormat': {
1703 'GL_LUMINANCE_ALPHA',
1732 'GL_R11F_G11F_B10F',
1757 # The DEPTH/STENCIL formats are not supported in CopyTexImage2D.
1758 # We will reject them dynamically in GPU command buffer.
1759 'GL_DEPTH_COMPONENT16',
1760 'GL_DEPTH_COMPONENT24',
1761 'GL_DEPTH_COMPONENT32F',
1762 'GL_DEPTH24_STENCIL8',
1763 'GL_DEPTH32F_STENCIL8',
1770 'TextureInternalFormatStorage': {
1777 'GL_LUMINANCE8_EXT',
1778 'GL_LUMINANCE8_ALPHA8_EXT',
1806 'GL_R11F_G11F_B10F',
1829 'GL_DEPTH_COMPONENT16',
1830 'GL_DEPTH_COMPONENT24',
1831 'GL_DEPTH_COMPONENT32F',
1832 'GL_DEPTH24_STENCIL8',
1833 'GL_DEPTH32F_STENCIL8',
1834 'GL_COMPRESSED_R11_EAC',
1835 'GL_COMPRESSED_SIGNED_R11_EAC',
1836 'GL_COMPRESSED_RG11_EAC',
1837 'GL_COMPRESSED_SIGNED_RG11_EAC',
1838 'GL_COMPRESSED_RGB8_ETC2',
1839 'GL_COMPRESSED_SRGB8_ETC2',
1840 'GL_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2',
1841 'GL_COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2',
1842 'GL_COMPRESSED_RGBA8_ETC2_EAC',
1843 'GL_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC',
1847 'GL_LUMINANCE8_EXT',
1848 'GL_LUMINANCE8_ALPHA8_EXT',
1850 'GL_LUMINANCE16F_EXT',
1851 'GL_LUMINANCE_ALPHA16F_EXT',
1853 'GL_LUMINANCE32F_EXT',
1854 'GL_LUMINANCE_ALPHA32F_EXT',
1857 'ImageInternalFormat': {
1861 'GL_RGB_YUV_420_CHROMIUM',
1869 'GL_SCANOUT_CHROMIUM'
1872 'ValueBufferTarget': {
1875 'GL_SUBSCRIBED_VALUES_BUFFER_CHROMIUM',
1878 'SubscriptionTarget': {
1881 'GL_MOUSE_POSITION_CHROMIUM',
1884 'UniformParameter': {
1889 'GL_UNIFORM_NAME_LENGTH',
1890 'GL_UNIFORM_BLOCK_INDEX',
1891 'GL_UNIFORM_OFFSET',
1892 'GL_UNIFORM_ARRAY_STRIDE',
1893 'GL_UNIFORM_MATRIX_STRIDE',
1894 'GL_UNIFORM_IS_ROW_MAJOR',
1897 'GL_UNIFORM_BLOCK_NAME_LENGTH',
1900 'UniformBlockParameter': {
1903 'GL_UNIFORM_BLOCK_BINDING',
1904 'GL_UNIFORM_BLOCK_DATA_SIZE',
1905 'GL_UNIFORM_BLOCK_NAME_LENGTH',
1906 'GL_UNIFORM_BLOCK_ACTIVE_UNIFORMS',
1907 'GL_UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES',
1908 'GL_UNIFORM_BLOCK_REFERENCED_BY_VERTEX_SHADER',
1909 'GL_UNIFORM_BLOCK_REFERENCED_BY_FRAGMENT_SHADER',
1915 'VertexAttribType': {
1921 'GL_UNSIGNED_SHORT',
1922 # 'GL_FIXED', // This is not available on Desktop GL.
1929 'GL_INT_2_10_10_10_REV',
1930 'GL_UNSIGNED_INT_2_10_10_10_REV',
1936 'VertexAttribIType': {
1942 'GL_UNSIGNED_SHORT',
1953 'is_complete': True,
1961 'VertexAttribSize': {
1976 'is_complete': True,
1985 'type': 'GLboolean',
1986 'is_complete': True,
1997 'GL_GUILTY_CONTEXT_RESET_ARB',
1998 'GL_INNOCENT_CONTEXT_RESET_ARB',
1999 'GL_UNKNOWN_CONTEXT_RESET_ARB',
2004 'is_complete': True,
2006 'GL_SYNC_GPU_COMMANDS_COMPLETE',
2013 'type': 'GLbitfield',
2014 'is_complete': True,
2023 'type': 'GLbitfield',
2025 'GL_SYNC_FLUSH_COMMANDS_BIT',
2035 'GL_SYNC_STATUS', # This needs to be the 1st; all others are cached.
2037 'GL_SYNC_CONDITION',
2046 # This table specifies the different pepper interfaces that are supported for
2047 # GL commands. 'dev' is true if it's a dev interface.
2048 _PEPPER_INTERFACES
= [
2049 {'name': '', 'dev': False},
2050 {'name': 'InstancedArrays', 'dev': False},
2051 {'name': 'FramebufferBlit', 'dev': False},
2052 {'name': 'FramebufferMultisample', 'dev': False},
2053 {'name': 'ChromiumEnableFeature', 'dev': False},
2054 {'name': 'ChromiumMapSub', 'dev': False},
2055 {'name': 'Query', 'dev': False},
2056 {'name': 'VertexArrayObject', 'dev': False},
2057 {'name': 'DrawBuffers', 'dev': True},
2060 # A function info object specifies the type and other special data for the
2061 # command that will be generated. A base function info object is generated by
2062 # parsing the "cmd_buffer_functions.txt", one for each function in the
2063 # file. These function info objects can be augmented and their values can be
2064 # overridden by adding an object to the table below.
2066 # Must match function names specified in "cmd_buffer_functions.txt".
2068 # cmd_comment: A comment added to the cmd format.
2069 # type: defines which handler will be used to generate code.
2070 # decoder_func: defines which function to call in the decoder to execute the
2071 # corresponding GL command. If not specified the GL command will
2072 # be called directly.
2073 # gl_test_func: GL function that is expected to be called when testing.
2074 # cmd_args: The arguments to use for the command. This overrides generating
2075 # them based on the GL function arguments.
2076 # gen_cmd: Whether or not this function geneates a command. Default = True.
2077 # data_transfer_methods: Array of methods that are used for transfering the
2078 # pointer data. Possible values: 'immediate', 'shm', 'bucket'.
2079 # The default is 'immediate' if the command has one pointer
2080 # argument, otherwise 'shm'. One command is generated for each
2081 # transfer method. Affects only commands which are not of type
2082 # 'HandWritten', 'GETn' or 'GLcharN'.
2083 # Note: the command arguments that affect this are the final args,
2084 # taking cmd_args override into consideration.
2085 # impl_func: Whether or not to generate the GLES2Implementation part of this
2087 # impl_decl: Whether or not to generate the GLES2Implementation declaration
2089 # needs_size: If True a data_size field is added to the command.
2090 # count: The number of units per element. For PUTn or PUT types.
2091 # use_count_func: If True the actual data count needs to be computed; the count
2092 # argument specifies the maximum count.
2093 # unit_test: If False no service side unit test will be generated.
2094 # client_test: If False no client side unit test will be generated.
2095 # expectation: If False the unit test will have no expected calls.
2096 # gen_func: Name of function that generates GL resource for corresponding
2098 # states: array of states that get set by this function corresponding to
2099 # the given arguments
2100 # state_flag: name of flag that is set to true when function is called.
2101 # no_gl: no GL function is called.
2102 # valid_args: A dictionary of argument indices to args to use in unit tests
2103 # when they can not be automatically determined.
2104 # pepper_interface: The pepper interface that is used for this extension
2105 # pepper_name: The name of the function as exposed to pepper.
2106 # pepper_args: A string representing the argument list (what would appear in
2107 # C/C++ between the parentheses for the function declaration)
2108 # that the Pepper API expects for this function. Use this only if
2109 # the stable Pepper API differs from the GLES2 argument list.
2110 # invalid_test: False if no invalid test needed.
2111 # shadowed: True = the value is shadowed so no glGetXXX call will be made.
2112 # first_element_only: For PUT types, True if only the first element of an
2113 # array is used and we end up calling the single value
2114 # corresponding function. eg. TexParameteriv -> TexParameteri
2115 # extension: Function is an extension to GL and should not be exposed to
2116 # pepper unless pepper_interface is defined.
2117 # extension_flag: Function is an extension and should be enabled only when
2118 # the corresponding feature info flag is enabled. Implies
2119 # 'extension': True.
2120 # not_shared: For GENn types, True if objects can't be shared between contexts
2121 # unsafe: True = no validation is implemented on the service side and the
2122 # command is only available with --enable-unsafe-es3-apis.
2123 # id_mapping: A list of resource type names whose client side IDs need to be
2124 # mapped to service side IDs. This is only used for unsafe APIs.
2128 'decoder_func': 'DoActiveTexture',
2131 'client_test': False,
2133 'AttachShader': {'decoder_func': 'DoAttachShader'},
2134 'BindAttribLocation': {
2136 'data_transfer_methods': ['bucket'],
2141 'decoder_func': 'DoBindBuffer',
2142 'gen_func': 'GenBuffersARB',
2146 'id_mapping': [ 'Buffer' ],
2147 'gen_func': 'GenBuffersARB',
2150 'BindBufferRange': {
2152 'id_mapping': [ 'Buffer' ],
2153 'gen_func': 'GenBuffersARB',
2160 'BindFramebuffer': {
2162 'decoder_func': 'DoBindFramebuffer',
2163 'gl_test_func': 'glBindFramebufferEXT',
2164 'gen_func': 'GenFramebuffersEXT',
2167 'BindRenderbuffer': {
2169 'decoder_func': 'DoBindRenderbuffer',
2170 'gl_test_func': 'glBindRenderbufferEXT',
2171 'gen_func': 'GenRenderbuffersEXT',
2175 'id_mapping': [ 'Sampler' ],
2180 'decoder_func': 'DoBindTexture',
2181 'gen_func': 'GenTextures',
2182 # TODO(gman): remove this once client side caching works.
2183 'client_test': False,
2186 'BindTransformFeedback': {
2188 'id_mapping': [ 'TransformFeedback' ],
2191 'BlitFramebufferCHROMIUM': {
2192 'decoder_func': 'DoBlitFramebufferCHROMIUM',
2194 'extension_flag': 'chromium_framebuffer_multisample',
2195 'pepper_interface': 'FramebufferBlit',
2196 'pepper_name': 'BlitFramebufferEXT',
2197 'defer_reads': True,
2198 'defer_draws': True,
2203 'data_transfer_methods': ['shm'],
2204 'client_test': False,
2209 'client_test': False,
2210 'decoder_func': 'DoBufferSubData',
2211 'data_transfer_methods': ['shm'],
2214 'CheckFramebufferStatus': {
2216 'decoder_func': 'DoCheckFramebufferStatus',
2217 'gl_test_func': 'glCheckFramebufferStatusEXT',
2218 'error_value': 'GL_FRAMEBUFFER_UNSUPPORTED',
2219 'result': ['GLenum'],
2222 'decoder_func': 'DoClear',
2223 'defer_draws': True,
2228 'use_count_func': True,
2241 'use_count_func': True,
2252 'state': 'ClearColor',
2256 'state': 'ClearDepthf',
2257 'decoder_func': 'glClearDepth',
2258 'gl_test_func': 'glClearDepth',
2265 'data_transfer_methods': ['shm'],
2266 'cmd_args': 'GLuint sync, GLbitfieldSyncFlushFlags flags, '
2267 'GLuint timeout_0, GLuint timeout_1, GLenum* result',
2269 'result': ['GLenum'],
2274 'state': 'ColorMask',
2276 'expectation': False,
2278 'ConsumeTextureCHROMIUM': {
2279 'decoder_func': 'DoConsumeTextureCHROMIUM',
2282 'count': 64, # GL_MAILBOX_SIZE_CHROMIUM
2284 'client_test': False,
2285 'extension': "CHROMIUM_texture_mailbox",
2289 'CopyBufferSubData': {
2292 'CreateAndConsumeTextureCHROMIUM': {
2293 'decoder_func': 'DoCreateAndConsumeTextureCHROMIUM',
2295 'type': 'HandWritten',
2296 'data_transfer_methods': ['immediate'],
2298 'client_test': False,
2299 'extension': "CHROMIUM_texture_mailbox",
2303 'GenValuebuffersCHROMIUM': {
2305 'gl_test_func': 'glGenValuebuffersCHROMIUM',
2306 'resource_type': 'Valuebuffer',
2307 'resource_types': 'Valuebuffers',
2312 'DeleteValuebuffersCHROMIUM': {
2314 'gl_test_func': 'glDeleteValuebuffersCHROMIUM',
2315 'resource_type': 'Valuebuffer',
2316 'resource_types': 'Valuebuffers',
2321 'IsValuebufferCHROMIUM': {
2323 'decoder_func': 'DoIsValuebufferCHROMIUM',
2324 'expectation': False,
2328 'BindValuebufferCHROMIUM': {
2330 'decoder_func': 'DoBindValueBufferCHROMIUM',
2331 'gen_func': 'GenValueBuffersCHROMIUM',
2336 'SubscribeValueCHROMIUM': {
2337 'decoder_func': 'DoSubscribeValueCHROMIUM',
2342 'PopulateSubscribedValuesCHROMIUM': {
2343 'decoder_func': 'DoPopulateSubscribedValuesCHROMIUM',
2348 'UniformValuebufferCHROMIUM': {
2349 'decoder_func': 'DoUniformValueBufferCHROMIUM',
2356 'state': 'ClearStencil',
2358 'EnableFeatureCHROMIUM': {
2360 'data_transfer_methods': ['shm'],
2361 'decoder_func': 'DoEnableFeatureCHROMIUM',
2362 'expectation': False,
2363 'cmd_args': 'GLuint bucket_id, GLint* result',
2364 'result': ['GLint'],
2367 'pepper_interface': 'ChromiumEnableFeature',
2369 'CompileShader': {'decoder_func': 'DoCompileShader', 'unit_test': False},
2370 'CompressedTexImage2D': {
2372 'data_transfer_methods': ['bucket', 'shm'],
2375 'CompressedTexSubImage2D': {
2377 'data_transfer_methods': ['bucket', 'shm'],
2378 'decoder_func': 'DoCompressedTexSubImage2D',
2382 'decoder_func': 'DoCopyTexImage2D',
2384 'defer_reads': True,
2387 'CopyTexSubImage2D': {
2388 'decoder_func': 'DoCopyTexSubImage2D',
2389 'defer_reads': True,
2392 'CompressedTexImage3D': {
2394 'data_transfer_methods': ['bucket', 'shm'],
2398 'CompressedTexSubImage3D': {
2400 'data_transfer_methods': ['bucket', 'shm'],
2401 'decoder_func': 'DoCompressedTexSubImage3D',
2405 'CopyTexSubImage3D': {
2406 'defer_reads': True,
2410 'CreateImageCHROMIUM': {
2413 'ClientBuffer buffer, GLsizei width, GLsizei height, '
2414 'GLenum internalformat',
2415 'result': ['GLuint'],
2416 'client_test': False,
2418 'expectation': False,
2419 'extension': "CHROMIUM_image",
2423 'DestroyImageCHROMIUM': {
2425 'client_test': False,
2427 'extension': "CHROMIUM_image",
2431 'CreateGpuMemoryBufferImageCHROMIUM': {
2434 'GLsizei width, GLsizei height, GLenum internalformat, GLenum usage',
2435 'result': ['GLuint'],
2436 'client_test': False,
2438 'expectation': False,
2439 'extension': "CHROMIUM_image",
2445 'client_test': False,
2449 'client_test': False,
2453 'state': 'BlendColor',
2456 'type': 'StateSetRGBAlpha',
2457 'state': 'BlendEquation',
2459 '0': 'GL_FUNC_SUBTRACT'
2462 'BlendEquationSeparate': {
2464 'state': 'BlendEquation',
2466 '0': 'GL_FUNC_SUBTRACT'
2470 'type': 'StateSetRGBAlpha',
2471 'state': 'BlendFunc',
2473 'BlendFuncSeparate': {
2475 'state': 'BlendFunc',
2477 'BlendBarrierKHR': {
2478 'gl_test_func': 'glBlendBarrierKHR',
2480 'extension_flag': 'blend_equation_advanced',
2481 'client_test': False,
2483 'SampleCoverage': {'decoder_func': 'DoSampleCoverage'},
2485 'type': 'StateSetFrontBack',
2486 'state': 'StencilFunc',
2488 'StencilFuncSeparate': {
2489 'type': 'StateSetFrontBackSeparate',
2490 'state': 'StencilFunc',
2493 'type': 'StateSetFrontBack',
2494 'state': 'StencilOp',
2499 'StencilOpSeparate': {
2500 'type': 'StateSetFrontBackSeparate',
2501 'state': 'StencilOp',
2507 'type': 'StateSetNamedParameter',
2510 'CullFace': {'type': 'StateSet', 'state': 'CullFace'},
2511 'FrontFace': {'type': 'StateSet', 'state': 'FrontFace'},
2512 'DepthFunc': {'type': 'StateSet', 'state': 'DepthFunc'},
2515 'state': 'LineWidth',
2522 'state': 'PolygonOffset',
2526 'gl_test_func': 'glDeleteBuffersARB',
2527 'resource_type': 'Buffer',
2528 'resource_types': 'Buffers',
2530 'DeleteFramebuffers': {
2532 'gl_test_func': 'glDeleteFramebuffersEXT',
2533 'resource_type': 'Framebuffer',
2534 'resource_types': 'Framebuffers',
2537 'DeleteProgram': { 'type': 'Delete' },
2538 'DeleteRenderbuffers': {
2540 'gl_test_func': 'glDeleteRenderbuffersEXT',
2541 'resource_type': 'Renderbuffer',
2542 'resource_types': 'Renderbuffers',
2547 'resource_type': 'Sampler',
2548 'resource_types': 'Samplers',
2551 'DeleteShader': { 'type': 'Delete' },
2554 'cmd_args': 'GLuint sync',
2555 'resource_type': 'Sync',
2560 'resource_type': 'Texture',
2561 'resource_types': 'Textures',
2563 'DeleteTransformFeedbacks': {
2565 'resource_type': 'TransformFeedback',
2566 'resource_types': 'TransformFeedbacks',
2570 'decoder_func': 'DoDepthRangef',
2571 'gl_test_func': 'glDepthRange',
2575 'state': 'DepthMask',
2577 'expectation': False,
2579 'DetachShader': {'decoder_func': 'DoDetachShader'},
2581 'decoder_func': 'DoDisable',
2583 'client_test': False,
2585 'DisableVertexAttribArray': {
2586 'decoder_func': 'DoDisableVertexAttribArray',
2591 'cmd_args': 'GLenumDrawMode mode, GLint first, GLsizei count',
2592 'defer_draws': True,
2597 'cmd_args': 'GLenumDrawMode mode, GLsizei count, '
2598 'GLenumIndexType type, GLuint index_offset',
2599 'client_test': False,
2600 'defer_draws': True,
2603 'DrawRangeElements': {
2609 'decoder_func': 'DoEnable',
2611 'client_test': False,
2613 'EnableVertexAttribArray': {
2614 'decoder_func': 'DoEnableVertexAttribArray',
2619 'client_test': False,
2625 'client_test': False,
2626 'decoder_func': 'DoFinish',
2627 'defer_reads': True,
2632 'decoder_func': 'DoFlush',
2635 'FramebufferRenderbuffer': {
2636 'decoder_func': 'DoFramebufferRenderbuffer',
2637 'gl_test_func': 'glFramebufferRenderbufferEXT',
2640 'FramebufferTexture2D': {
2641 'decoder_func': 'DoFramebufferTexture2D',
2642 'gl_test_func': 'glFramebufferTexture2DEXT',
2645 'FramebufferTexture2DMultisampleEXT': {
2646 'decoder_func': 'DoFramebufferTexture2DMultisample',
2647 'gl_test_func': 'glFramebufferTexture2DMultisampleEXT',
2648 'expectation': False,
2650 'extension_flag': 'multisampled_render_to_texture',
2653 'FramebufferTextureLayer': {
2654 'decoder_func': 'DoFramebufferTextureLayer',
2659 'decoder_func': 'DoGenerateMipmap',
2660 'gl_test_func': 'glGenerateMipmapEXT',
2665 'gl_test_func': 'glGenBuffersARB',
2666 'resource_type': 'Buffer',
2667 'resource_types': 'Buffers',
2669 'GenMailboxCHROMIUM': {
2670 'type': 'HandWritten',
2672 'extension': "CHROMIUM_texture_mailbox",
2675 'GenFramebuffers': {
2677 'gl_test_func': 'glGenFramebuffersEXT',
2678 'resource_type': 'Framebuffer',
2679 'resource_types': 'Framebuffers',
2681 'GenRenderbuffers': {
2682 'type': 'GENn', 'gl_test_func': 'glGenRenderbuffersEXT',
2683 'resource_type': 'Renderbuffer',
2684 'resource_types': 'Renderbuffers',
2688 'gl_test_func': 'glGenSamplers',
2689 'resource_type': 'Sampler',
2690 'resource_types': 'Samplers',
2695 'gl_test_func': 'glGenTextures',
2696 'resource_type': 'Texture',
2697 'resource_types': 'Textures',
2699 'GenTransformFeedbacks': {
2701 'gl_test_func': 'glGenTransformFeedbacks',
2702 'resource_type': 'TransformFeedback',
2703 'resource_types': 'TransformFeedbacks',
2706 'GetActiveAttrib': {
2708 'data_transfer_methods': ['shm'],
2710 'GLidProgram program, GLuint index, uint32_t name_bucket_id, '
2718 'GetActiveUniform': {
2720 'data_transfer_methods': ['shm'],
2722 'GLidProgram program, GLuint index, uint32_t name_bucket_id, '
2730 'GetActiveUniformBlockiv': {
2732 'data_transfer_methods': ['shm'],
2733 'result': ['SizedResult<GLint>'],
2736 'GetActiveUniformBlockName': {
2738 'data_transfer_methods': ['shm'],
2740 'GLidProgram program, GLuint index, uint32_t name_bucket_id, '
2742 'result': ['int32_t'],
2745 'GetActiveUniformsiv': {
2747 'data_transfer_methods': ['shm'],
2749 'GLidProgram program, uint32_t indices_bucket_id, GLenum pname, '
2751 'result': ['SizedResult<GLint>'],
2754 'GetAttachedShaders': {
2756 'data_transfer_methods': ['shm'],
2757 'cmd_args': 'GLidProgram program, void* result, uint32_t result_size',
2758 'result': ['SizedResult<GLuint>'],
2760 'GetAttribLocation': {
2762 'data_transfer_methods': ['shm'],
2764 'GLidProgram program, uint32_t name_bucket_id, GLint* location',
2765 'result': ['GLint'],
2768 'GetFragDataLocation': {
2770 'data_transfer_methods': ['shm'],
2772 'GLidProgram program, uint32_t name_bucket_id, GLint* location',
2773 'result': ['GLint'],
2779 'result': ['SizedResult<GLboolean>'],
2780 'decoder_func': 'DoGetBooleanv',
2781 'gl_test_func': 'glGetBooleanv',
2783 'GetBufferParameteri64v': {
2785 'result': ['SizedResult<GLint64>'],
2786 'decoder_func': 'DoGetBufferParameteri64v',
2787 'expectation': False,
2791 'GetBufferParameteriv': {
2793 'result': ['SizedResult<GLint>'],
2794 'decoder_func': 'DoGetBufferParameteriv',
2795 'expectation': False,
2800 'decoder_func': 'GetErrorState()->GetGLError',
2802 'result': ['GLenum'],
2803 'client_test': False,
2807 'result': ['SizedResult<GLfloat>'],
2808 'decoder_func': 'DoGetFloatv',
2809 'gl_test_func': 'glGetFloatv',
2811 'GetFramebufferAttachmentParameteriv': {
2813 'decoder_func': 'DoGetFramebufferAttachmentParameteriv',
2814 'gl_test_func': 'glGetFramebufferAttachmentParameterivEXT',
2815 'result': ['SizedResult<GLint>'],
2817 'GetGraphicsResetStatusKHR': {
2819 'client_test': False,
2825 'result': ['SizedResult<GLint64>'],
2826 'client_test': False,
2827 'decoder_func': 'DoGetInteger64v',
2832 'result': ['SizedResult<GLint>'],
2833 'decoder_func': 'DoGetIntegerv',
2834 'client_test': False,
2836 'GetInteger64i_v': {
2838 'result': ['SizedResult<GLint64>'],
2839 'client_test': False,
2844 'result': ['SizedResult<GLint>'],
2845 'client_test': False,
2848 'GetInternalformativ': {
2850 'data_transfer_methods': ['shm'],
2851 'result': ['SizedResult<GLint>'],
2853 'GLenumRenderBufferTarget target, GLenumRenderBufferFormat format, '
2854 'GLenumInternalFormatParameter pname, GLint* params',
2857 'GetMaxValueInBufferCHROMIUM': {
2859 'decoder_func': 'DoGetMaxValueInBufferCHROMIUM',
2860 'result': ['GLuint'],
2862 'client_test': False,
2869 'decoder_func': 'DoGetProgramiv',
2870 'result': ['SizedResult<GLint>'],
2871 'expectation': False,
2873 'GetProgramInfoCHROMIUM': {
2875 'expectation': False,
2879 'client_test': False,
2880 'cmd_args': 'GLidProgram program, uint32_t bucket_id',
2882 'uint32_t link_status',
2883 'uint32_t num_attribs',
2884 'uint32_t num_uniforms',
2887 'GetProgramInfoLog': {
2889 'expectation': False,
2891 'GetRenderbufferParameteriv': {
2893 'decoder_func': 'DoGetRenderbufferParameteriv',
2894 'gl_test_func': 'glGetRenderbufferParameterivEXT',
2895 'result': ['SizedResult<GLint>'],
2897 'GetSamplerParameterfv': {
2899 'result': ['SizedResult<GLfloat>'],
2900 'id_mapping': [ 'Sampler' ],
2903 'GetSamplerParameteriv': {
2905 'result': ['SizedResult<GLint>'],
2906 'id_mapping': [ 'Sampler' ],
2911 'decoder_func': 'DoGetShaderiv',
2912 'result': ['SizedResult<GLint>'],
2914 'GetShaderInfoLog': {
2916 'get_len_func': 'glGetShaderiv',
2917 'get_len_enum': 'GL_INFO_LOG_LENGTH',
2920 'GetShaderPrecisionFormat': {
2922 'data_transfer_methods': ['shm'],
2924 'GLenumShaderType shadertype, GLenumShaderPrecision precisiontype, '
2928 'int32_t min_range',
2929 'int32_t max_range',
2930 'int32_t precision',
2933 'GetShaderSource': {
2935 'get_len_func': 'DoGetShaderiv',
2936 'get_len_enum': 'GL_SHADER_SOURCE_LENGTH',
2938 'client_test': False,
2942 'client_test': False,
2943 'cmd_args': 'GLenumStringType name, uint32_t bucket_id',
2947 'cmd_args': 'GLuint sync, GLenumSyncParameter pname, void* values',
2948 'result': ['SizedResult<GLint>'],
2949 'id_mapping': ['Sync'],
2952 'GetTexParameterfv': {
2954 'decoder_func': 'DoGetTexParameterfv',
2955 'result': ['SizedResult<GLfloat>']
2957 'GetTexParameteriv': {
2959 'decoder_func': 'DoGetTexParameteriv',
2960 'result': ['SizedResult<GLint>']
2962 'GetTranslatedShaderSourceANGLE': {
2964 'get_len_func': 'DoGetShaderiv',
2965 'get_len_enum': 'GL_TRANSLATED_SHADER_SOURCE_LENGTH_ANGLE',
2969 'GetUniformBlockIndex': {
2971 'data_transfer_methods': ['shm'],
2973 'GLidProgram program, uint32_t name_bucket_id, GLuint* index',
2974 'result': ['GLuint'],
2975 'error_return': 'GL_INVALID_INDEX',
2978 'GetUniformBlocksCHROMIUM': {
2980 'expectation': False,
2984 'client_test': False,
2985 'cmd_args': 'GLidProgram program, uint32_t bucket_id',
2986 'result': ['uint32_t'],
2989 'GetUniformsES3CHROMIUM': {
2991 'expectation': False,
2995 'client_test': False,
2996 'cmd_args': 'GLidProgram program, uint32_t bucket_id',
2997 'result': ['uint32_t'],
3000 'GetTransformFeedbackVarying': {
3002 'data_transfer_methods': ['shm'],
3004 'GLidProgram program, GLuint index, uint32_t name_bucket_id, '
3013 'GetTransformFeedbackVaryingsCHROMIUM': {
3015 'expectation': False,
3019 'client_test': False,
3020 'cmd_args': 'GLidProgram program, uint32_t bucket_id',
3021 'result': ['uint32_t'],
3026 'data_transfer_methods': ['shm'],
3027 'result': ['SizedResult<GLfloat>'],
3031 'data_transfer_methods': ['shm'],
3032 'result': ['SizedResult<GLint>'],
3036 'data_transfer_methods': ['shm'],
3037 'result': ['SizedResult<GLuint>'],
3040 'GetUniformIndices': {
3042 'data_transfer_methods': ['shm'],
3043 'result': ['SizedResult<GLuint>'],
3044 'cmd_args': 'GLidProgram program, uint32_t names_bucket_id, '
3048 'GetUniformLocation': {
3050 'data_transfer_methods': ['shm'],
3052 'GLidProgram program, uint32_t name_bucket_id, GLint* location',
3053 'result': ['GLint'],
3054 'error_return': -1, # http://www.opengl.org/sdk/docs/man/xhtml/glGetUniformLocation.xml
3056 'GetVertexAttribfv': {
3058 'result': ['SizedResult<GLfloat>'],
3060 'decoder_func': 'DoGetVertexAttribfv',
3061 'expectation': False,
3062 'client_test': False,
3064 'GetVertexAttribiv': {
3066 'result': ['SizedResult<GLint>'],
3068 'decoder_func': 'DoGetVertexAttribiv',
3069 'expectation': False,
3070 'client_test': False,
3072 'GetVertexAttribIiv': {
3074 'result': ['SizedResult<GLint>'],
3076 'decoder_func': 'DoGetVertexAttribIiv',
3077 'expectation': False,
3078 'client_test': False,
3081 'GetVertexAttribIuiv': {
3083 'result': ['SizedResult<GLuint>'],
3085 'decoder_func': 'DoGetVertexAttribIuiv',
3086 'expectation': False,
3087 'client_test': False,
3090 'GetVertexAttribPointerv': {
3092 'data_transfer_methods': ['shm'],
3093 'result': ['SizedResult<GLuint>'],
3094 'client_test': False,
3096 'InvalidateFramebuffer': {
3099 'client_test': False,
3103 'InvalidateSubFramebuffer': {
3106 'client_test': False,
3112 'decoder_func': 'DoIsBuffer',
3113 'expectation': False,
3117 'decoder_func': 'DoIsEnabled',
3118 'client_test': False,
3120 'expectation': False,
3124 'decoder_func': 'DoIsFramebuffer',
3125 'expectation': False,
3129 'decoder_func': 'DoIsProgram',
3130 'expectation': False,
3134 'decoder_func': 'DoIsRenderbuffer',
3135 'expectation': False,
3139 'decoder_func': 'DoIsShader',
3140 'expectation': False,
3144 'id_mapping': [ 'Sampler' ],
3145 'expectation': False,
3150 'id_mapping': [ 'Sync' ],
3151 'cmd_args': 'GLuint sync',
3152 'expectation': False,
3157 'decoder_func': 'DoIsTexture',
3158 'expectation': False,
3160 'IsTransformFeedback': {
3162 'id_mapping': [ 'TransformFeedback' ],
3163 'expectation': False,
3167 'decoder_func': 'DoLinkProgram',
3171 'MapBufferCHROMIUM': {
3173 'extension': "CHROMIUM_pixel_transfer_buffer_object",
3175 'client_test': False,
3178 'MapBufferSubDataCHROMIUM': {
3182 'client_test': False,
3183 'pepper_interface': 'ChromiumMapSub',
3186 'MapTexSubImage2DCHROMIUM': {
3188 'extension': "CHROMIUM_sub_image",
3190 'client_test': False,
3191 'pepper_interface': 'ChromiumMapSub',
3196 'data_transfer_methods': ['shm'],
3197 'cmd_args': 'GLenumBufferTarget target, GLintptrNotNegative offset, '
3198 'GLsizeiptr size, GLbitfieldMapBufferAccess access, '
3199 'uint32_t data_shm_id, uint32_t data_shm_offset, '
3200 'uint32_t result_shm_id, uint32_t result_shm_offset',
3202 'result': ['uint32_t'],
3205 'PauseTransformFeedback': {
3208 'PixelStorei': {'type': 'Manual'},
3209 'PostSubBufferCHROMIUM': {
3213 'client_test': False,
3217 'ProduceTextureCHROMIUM': {
3218 'decoder_func': 'DoProduceTextureCHROMIUM',
3221 'count': 64, # GL_MAILBOX_SIZE_CHROMIUM
3223 'client_test': False,
3224 'extension': "CHROMIUM_texture_mailbox",
3228 'ProduceTextureDirectCHROMIUM': {
3229 'decoder_func': 'DoProduceTextureDirectCHROMIUM',
3232 'count': 64, # GL_MAILBOX_SIZE_CHROMIUM
3234 'client_test': False,
3235 'extension': "CHROMIUM_texture_mailbox",
3239 'RenderbufferStorage': {
3240 'decoder_func': 'DoRenderbufferStorage',
3241 'gl_test_func': 'glRenderbufferStorageEXT',
3242 'expectation': False,
3245 'RenderbufferStorageMultisampleCHROMIUM': {
3247 '// GL_CHROMIUM_framebuffer_multisample\n',
3248 'decoder_func': 'DoRenderbufferStorageMultisampleCHROMIUM',
3249 'gl_test_func': 'glRenderbufferStorageMultisampleCHROMIUM',
3250 'expectation': False,
3252 'extension_flag': 'chromium_framebuffer_multisample',
3253 'pepper_interface': 'FramebufferMultisample',
3254 'pepper_name': 'RenderbufferStorageMultisampleEXT',
3257 'RenderbufferStorageMultisampleEXT': {
3259 '// GL_EXT_multisampled_render_to_texture\n',
3260 'decoder_func': 'DoRenderbufferStorageMultisampleEXT',
3261 'gl_test_func': 'glRenderbufferStorageMultisampleEXT',
3262 'expectation': False,
3264 'extension_flag': 'multisampled_render_to_texture',
3269 'decoder_func': 'DoReadBuffer',
3274 '// ReadPixels has the result separated from the pixel buffer so that\n'
3275 '// it is easier to specify the result going to some specific place\n'
3276 '// that exactly fits the rectangle of pixels.\n',
3278 'data_transfer_methods': ['shm'],
3280 'client_test': False,
3282 'GLint x, GLint y, GLsizei width, GLsizei height, '
3283 'GLenumReadPixelFormat format, GLenumReadPixelType type, '
3284 'uint32_t pixels_shm_id, uint32_t pixels_shm_offset, '
3285 'uint32_t result_shm_id, uint32_t result_shm_offset, '
3287 'result': ['uint32_t'],
3288 'defer_reads': True,
3291 'ReleaseShaderCompiler': {
3292 'decoder_func': 'DoReleaseShaderCompiler',
3295 'ResumeTransformFeedback': {
3298 'SamplerParameterf': {
3302 'id_mapping': [ 'Sampler' ],
3305 'SamplerParameterfv': {
3307 'data_value': 'GL_NEAREST',
3309 'gl_test_func': 'glSamplerParameterf',
3310 'decoder_func': 'DoSamplerParameterfv',
3311 'first_element_only': True,
3312 'id_mapping': [ 'Sampler' ],
3315 'SamplerParameteri': {
3319 'id_mapping': [ 'Sampler' ],
3322 'SamplerParameteriv': {
3324 'data_value': 'GL_NEAREST',
3326 'gl_test_func': 'glSamplerParameteri',
3327 'decoder_func': 'DoSamplerParameteriv',
3328 'first_element_only': True,
3333 'client_test': False,
3337 'decoder_func': 'DoShaderSource',
3338 'expectation': False,
3339 'data_transfer_methods': ['bucket'],
3341 'GLuint shader, const char** str',
3343 'GLuint shader, GLsizei count, const char** str, const GLint* length',
3346 'type': 'StateSetFrontBack',
3347 'state': 'StencilMask',
3349 'expectation': False,
3351 'StencilMaskSeparate': {
3352 'type': 'StateSetFrontBackSeparate',
3353 'state': 'StencilMask',
3355 'expectation': False,
3359 'decoder_func': 'DoSwapBuffers',
3361 'client_test': False,
3367 'decoder_func': 'DoSwapInterval',
3369 'client_test': False,
3375 'data_transfer_methods': ['shm'],
3376 'client_test': False,
3381 'data_transfer_methods': ['shm'],
3382 'client_test': False,
3387 'decoder_func': 'DoTexParameterf',
3393 'decoder_func': 'DoTexParameteri',
3400 'data_value': 'GL_NEAREST',
3402 'decoder_func': 'DoTexParameterfv',
3403 'gl_test_func': 'glTexParameterf',
3404 'first_element_only': True,
3408 'data_value': 'GL_NEAREST',
3410 'decoder_func': 'DoTexParameteriv',
3411 'gl_test_func': 'glTexParameteri',
3412 'first_element_only': True,
3420 'data_transfer_methods': ['shm'],
3421 'client_test': False,
3423 'cmd_args': 'GLenumTextureTarget target, GLint level, '
3424 'GLint xoffset, GLint yoffset, '
3425 'GLsizei width, GLsizei height, '
3426 'GLenumTextureFormat format, GLenumPixelType type, '
3427 'const void* pixels, GLboolean internal'
3431 'data_transfer_methods': ['shm'],
3432 'client_test': False,
3434 'cmd_args': 'GLenumTextureTarget target, GLint level, '
3435 'GLint xoffset, GLint yoffset, GLint zoffset, '
3436 'GLsizei width, GLsizei height, GLsizei depth, '
3437 'GLenumTextureFormat format, GLenumPixelType type, '
3438 'const void* pixels, GLboolean internal',
3441 'TransformFeedbackVaryings': {
3443 'data_transfer_methods': ['bucket'],
3444 'decoder_func': 'DoTransformFeedbackVaryings',
3446 'GLuint program, const char** varyings, GLenum buffermode',
3449 'Uniform1f': {'type': 'PUTXn', 'count': 1},
3453 'decoder_func': 'DoUniform1fv',
3455 'Uniform1i': {'decoder_func': 'DoUniform1i', 'unit_test': False},
3459 'decoder_func': 'DoUniform1iv',
3472 'Uniform2i': {'type': 'PUTXn', 'count': 2},
3473 'Uniform2f': {'type': 'PUTXn', 'count': 2},
3477 'decoder_func': 'DoUniform2fv',
3482 'decoder_func': 'DoUniform2iv',
3494 'Uniform3i': {'type': 'PUTXn', 'count': 3},
3495 'Uniform3f': {'type': 'PUTXn', 'count': 3},
3499 'decoder_func': 'DoUniform3fv',
3504 'decoder_func': 'DoUniform3iv',
3516 'Uniform4i': {'type': 'PUTXn', 'count': 4},
3517 'Uniform4f': {'type': 'PUTXn', 'count': 4},
3521 'decoder_func': 'DoUniform4fv',
3526 'decoder_func': 'DoUniform4iv',
3538 'UniformMatrix2fv': {
3541 'decoder_func': 'DoUniformMatrix2fv',
3543 'UniformMatrix2x3fv': {
3548 'UniformMatrix2x4fv': {
3553 'UniformMatrix3fv': {
3556 'decoder_func': 'DoUniformMatrix3fv',
3558 'UniformMatrix3x2fv': {
3563 'UniformMatrix3x4fv': {
3568 'UniformMatrix4fv': {
3571 'decoder_func': 'DoUniformMatrix4fv',
3573 'UniformMatrix4x2fv': {
3578 'UniformMatrix4x3fv': {
3583 'UniformBlockBinding': {
3588 'UnmapBufferCHROMIUM': {
3590 'extension': "CHROMIUM_pixel_transfer_buffer_object",
3592 'client_test': False,
3595 'UnmapBufferSubDataCHROMIUM': {
3599 'client_test': False,
3600 'pepper_interface': 'ChromiumMapSub',
3608 'UnmapTexSubImage2DCHROMIUM': {
3610 'extension': "CHROMIUM_sub_image",
3612 'client_test': False,
3613 'pepper_interface': 'ChromiumMapSub',
3618 'decoder_func': 'DoUseProgram',
3620 'ValidateProgram': {'decoder_func': 'DoValidateProgram'},
3621 'VertexAttrib1f': {'decoder_func': 'DoVertexAttrib1f'},
3622 'VertexAttrib1fv': {
3625 'decoder_func': 'DoVertexAttrib1fv',
3627 'VertexAttrib2f': {'decoder_func': 'DoVertexAttrib2f'},
3628 'VertexAttrib2fv': {
3631 'decoder_func': 'DoVertexAttrib2fv',
3633 'VertexAttrib3f': {'decoder_func': 'DoVertexAttrib3f'},
3634 'VertexAttrib3fv': {
3637 'decoder_func': 'DoVertexAttrib3fv',
3639 'VertexAttrib4f': {'decoder_func': 'DoVertexAttrib4f'},
3640 'VertexAttrib4fv': {
3643 'decoder_func': 'DoVertexAttrib4fv',
3645 'VertexAttribI4i': {
3647 'decoder_func': 'DoVertexAttribI4i',
3649 'VertexAttribI4iv': {
3653 'decoder_func': 'DoVertexAttribI4iv',
3655 'VertexAttribI4ui': {
3657 'decoder_func': 'DoVertexAttribI4ui',
3659 'VertexAttribI4uiv': {
3663 'decoder_func': 'DoVertexAttribI4uiv',
3665 'VertexAttribIPointer': {
3667 'cmd_args': 'GLuint indx, GLintVertexAttribSize size, '
3668 'GLenumVertexAttribIType type, GLsizei stride, '
3670 'client_test': False,
3673 'VertexAttribPointer': {
3675 'cmd_args': 'GLuint indx, GLintVertexAttribSize size, '
3676 'GLenumVertexAttribType type, GLboolean normalized, '
3677 'GLsizei stride, GLuint offset',
3678 'client_test': False,
3682 'cmd_args': 'GLuint sync, GLbitfieldSyncFlushFlags flags, '
3683 'GLuint timeout_0, GLuint timeout_1',
3685 'client_test': False,
3694 'decoder_func': 'DoViewport',
3704 'GetRequestableExtensionsCHROMIUM': {
3707 'cmd_args': 'uint32_t bucket_id',
3711 'RequestExtensionCHROMIUM': {
3714 'client_test': False,
3715 'cmd_args': 'uint32_t bucket_id',
3719 'RateLimitOffscreenContextCHROMIUM': {
3723 'client_test': False,
3725 'CreateStreamTextureCHROMIUM': {
3726 'type': 'HandWritten',
3733 'TexImageIOSurface2DCHROMIUM': {
3734 'decoder_func': 'DoTexImageIOSurface2DCHROMIUM',
3740 'CopyTextureCHROMIUM': {
3741 'decoder_func': 'DoCopyTextureCHROMIUM',
3743 'extension': "CHROMIUM_copy_texture",
3747 'CopySubTextureCHROMIUM': {
3748 'decoder_func': 'DoCopySubTextureCHROMIUM',
3750 'extension': "CHROMIUM_copy_texture",
3754 'CompressedCopyTextureCHROMIUM': {
3755 'decoder_func': 'DoCompressedCopyTextureCHROMIUM',
3760 'TexStorage2DEXT': {
3763 'decoder_func': 'DoTexStorage2DEXT',
3766 'DrawArraysInstancedANGLE': {
3768 'cmd_args': 'GLenumDrawMode mode, GLint first, GLsizei count, '
3769 'GLsizei primcount',
3772 'pepper_interface': 'InstancedArrays',
3773 'defer_draws': True,
3778 'decoder_func': 'DoDrawBuffersEXT',
3780 'client_test': False,
3782 # could use 'extension_flag': 'ext_draw_buffers' but currently expected to
3785 'pepper_interface': 'DrawBuffers',
3788 'DrawElementsInstancedANGLE': {
3790 'cmd_args': 'GLenumDrawMode mode, GLsizei count, '
3791 'GLenumIndexType type, GLuint index_offset, GLsizei primcount',
3794 'client_test': False,
3795 'pepper_interface': 'InstancedArrays',
3796 'defer_draws': True,
3799 'VertexAttribDivisorANGLE': {
3801 'cmd_args': 'GLuint index, GLuint divisor',
3804 'pepper_interface': 'InstancedArrays',
3808 'gl_test_func': 'glGenQueriesARB',
3809 'resource_type': 'Query',
3810 'resource_types': 'Queries',
3812 'pepper_interface': 'Query',
3813 'not_shared': 'True',
3814 'extension': "occlusion_query_EXT",
3816 'DeleteQueriesEXT': {
3818 'gl_test_func': 'glDeleteQueriesARB',
3819 'resource_type': 'Query',
3820 'resource_types': 'Queries',
3822 'pepper_interface': 'Query',
3823 'extension': "occlusion_query_EXT",
3827 'client_test': False,
3828 'pepper_interface': 'Query',
3829 'extension': "occlusion_query_EXT",
3833 'cmd_args': 'GLenumQueryTarget target, GLidQuery id, void* sync_data',
3834 'data_transfer_methods': ['shm'],
3835 'gl_test_func': 'glBeginQuery',
3836 'pepper_interface': 'Query',
3837 'extension': "occlusion_query_EXT",
3839 'BeginTransformFeedback': {
3844 'cmd_args': 'GLenumQueryTarget target, GLuint submit_count',
3845 'gl_test_func': 'glEndnQuery',
3846 'client_test': False,
3847 'pepper_interface': 'Query',
3848 'extension': "occlusion_query_EXT",
3850 'EndTransformFeedback': {
3853 'FlushDriverCachesCHROMIUM': {
3854 'decoder_func': 'DoFlushDriverCachesCHROMIUM',
3862 'client_test': False,
3863 'gl_test_func': 'glGetQueryiv',
3864 'pepper_interface': 'Query',
3865 'extension': "occlusion_query_EXT",
3867 'QueryCounterEXT' : {
3869 'cmd_args': 'GLidQuery id, GLenumQueryTarget target, '
3870 'void* sync_data, GLuint submit_count',
3871 'data_transfer_methods': ['shm'],
3872 'gl_test_func': 'glQueryCounter',
3873 'extension': "disjoint_timer_query_EXT",
3875 'GetQueryObjectuivEXT': {
3877 'client_test': False,
3878 'gl_test_func': 'glGetQueryObjectuiv',
3879 'pepper_interface': 'Query',
3880 'extension': "occlusion_query_EXT",
3882 'GetQueryObjectui64vEXT': {
3884 'client_test': False,
3885 'gl_test_func': 'glGetQueryObjectui64v',
3886 'extension': "disjoint_timer_query_EXT",
3888 'BindUniformLocationCHROMIUM': {
3891 'data_transfer_methods': ['bucket'],
3893 'gl_test_func': 'DoBindUniformLocationCHROMIUM',
3895 'InsertEventMarkerEXT': {
3897 'decoder_func': 'DoInsertEventMarkerEXT',
3898 'expectation': False,
3901 'PushGroupMarkerEXT': {
3903 'decoder_func': 'DoPushGroupMarkerEXT',
3904 'expectation': False,
3907 'PopGroupMarkerEXT': {
3908 'decoder_func': 'DoPopGroupMarkerEXT',
3909 'expectation': False,
3914 'GenVertexArraysOES': {
3917 'gl_test_func': 'glGenVertexArraysOES',
3918 'resource_type': 'VertexArray',
3919 'resource_types': 'VertexArrays',
3921 'pepper_interface': 'VertexArrayObject',
3923 'BindVertexArrayOES': {
3926 'gl_test_func': 'glBindVertexArrayOES',
3927 'decoder_func': 'DoBindVertexArrayOES',
3928 'gen_func': 'GenVertexArraysOES',
3930 'client_test': False,
3931 'pepper_interface': 'VertexArrayObject',
3933 'DeleteVertexArraysOES': {
3936 'gl_test_func': 'glDeleteVertexArraysOES',
3937 'resource_type': 'VertexArray',
3938 'resource_types': 'VertexArrays',
3940 'pepper_interface': 'VertexArrayObject',
3942 'IsVertexArrayOES': {
3945 'gl_test_func': 'glIsVertexArrayOES',
3946 'decoder_func': 'DoIsVertexArrayOES',
3947 'expectation': False,
3949 'pepper_interface': 'VertexArrayObject',
3951 'BindTexImage2DCHROMIUM': {
3952 'decoder_func': 'DoBindTexImage2DCHROMIUM',
3954 'extension': "CHROMIUM_image",
3957 'ReleaseTexImage2DCHROMIUM': {
3958 'decoder_func': 'DoReleaseTexImage2DCHROMIUM',
3960 'extension': "CHROMIUM_image",
3963 'ShallowFinishCHROMIUM': {
3968 'client_test': False,
3970 'ShallowFlushCHROMIUM': {
3973 'extension': "CHROMIUM_miscellaneous",
3975 'client_test': False,
3977 'OrderingBarrierCHROMIUM': {
3982 'client_test': False,
3984 'TraceBeginCHROMIUM': {
3987 'client_test': False,
3988 'cmd_args': 'GLuint category_bucket_id, GLuint name_bucket_id',
3992 'TraceEndCHROMIUM': {
3994 'client_test': False,
3995 'decoder_func': 'DoTraceEndCHROMIUM',
4000 'AsyncTexImage2DCHROMIUM': {
4002 'data_transfer_methods': ['shm'],
4003 'client_test': False,
4004 'cmd_args': 'GLenumTextureTarget target, GLint level, '
4005 'GLintTextureInternalFormat internalformat, '
4006 'GLsizei width, GLsizei height, '
4007 'GLintTextureBorder border, '
4008 'GLenumTextureFormat format, GLenumPixelType type, '
4009 'const void* pixels, '
4010 'uint32_t async_upload_token, '
4016 'AsyncTexSubImage2DCHROMIUM': {
4018 'data_transfer_methods': ['shm'],
4019 'client_test': False,
4020 'cmd_args': 'GLenumTextureTarget target, GLint level, '
4021 'GLint xoffset, GLint yoffset, '
4022 'GLsizei width, GLsizei height, '
4023 'GLenumTextureFormat format, GLenumPixelType type, '
4024 'const void* data, '
4025 'uint32_t async_upload_token, '
4031 'WaitAsyncTexImage2DCHROMIUM': {
4033 'client_test': False,
4038 'WaitAllAsyncTexImage2DCHROMIUM': {
4040 'client_test': False,
4045 'DiscardFramebufferEXT': {
4048 'decoder_func': 'DoDiscardFramebufferEXT',
4050 'client_test': False,
4051 'extension_flag': 'ext_discard_framebuffer',
4054 'LoseContextCHROMIUM': {
4055 'decoder_func': 'DoLoseContextCHROMIUM',
4061 'InsertSyncPointCHROMIUM': {
4062 'type': 'HandWritten',
4064 'extension': "CHROMIUM_sync_point",
4068 'WaitSyncPointCHROMIUM': {
4071 'extension': "CHROMIUM_sync_point",
4075 'DiscardBackbufferCHROMIUM': {
4082 'ScheduleOverlayPlaneCHROMIUM': {
4086 'client_test': False,
4090 'MatrixLoadfCHROMIUM': {
4093 'data_type': 'GLfloat',
4094 'decoder_func': 'DoMatrixLoadfCHROMIUM',
4095 'gl_test_func': 'glMatrixLoadfEXT',
4098 'extension_flag': 'chromium_path_rendering',
4100 'MatrixLoadIdentityCHROMIUM': {
4101 'decoder_func': 'DoMatrixLoadIdentityCHROMIUM',
4102 'gl_test_func': 'glMatrixLoadIdentityEXT',
4105 'extension_flag': 'chromium_path_rendering',
4107 'GenPathsCHROMIUM': {
4109 'cmd_args': 'GLuint first_client_id, GLsizei range',
4112 'extension_flag': 'chromium_path_rendering',
4114 'DeletePathsCHROMIUM': {
4116 'cmd_args': 'GLuint first_client_id, GLsizei range',
4121 'extension_flag': 'chromium_path_rendering',
4125 'decoder_func': 'DoIsPathCHROMIUM',
4126 'gl_test_func': 'glIsPathNV',
4129 'extension_flag': 'chromium_path_rendering',
4131 'PathCommandsCHROMIUM': {
4136 'extension_flag': 'chromium_path_rendering',
4138 'PathParameterfCHROMIUM': {
4142 'extension_flag': 'chromium_path_rendering',
4144 'PathParameteriCHROMIUM': {
4148 'extension_flag': 'chromium_path_rendering',
4150 'PathStencilFuncCHROMIUM': {
4152 'state': 'PathStencilFuncCHROMIUM',
4153 'decoder_func': 'glPathStencilFuncNV',
4156 'extension_flag': 'chromium_path_rendering',
4158 'StencilFillPathCHROMIUM': {
4162 'extension_flag': 'chromium_path_rendering',
4164 'StencilStrokePathCHROMIUM': {
4168 'extension_flag': 'chromium_path_rendering',
4170 'CoverFillPathCHROMIUM': {
4174 'extension_flag': 'chromium_path_rendering',
4176 'CoverStrokePathCHROMIUM': {
4180 'extension_flag': 'chromium_path_rendering',
4182 'StencilThenCoverFillPathCHROMIUM': {
4186 'extension_flag': 'chromium_path_rendering',
4188 'StencilThenCoverStrokePathCHROMIUM': {
4192 'extension_flag': 'chromium_path_rendering',
4198 def Grouper(n
, iterable
, fillvalue
=None):
4199 """Collect data into fixed-length chunks or blocks"""
4200 args
= [iter(iterable
)] * n
4201 return itertools
.izip_longest(fillvalue
=fillvalue
, *args
)
4204 def SplitWords(input_string
):
4205 """Split by '_' if found, otherwise split at uppercase/numeric chars.
4207 Will split "some_TEXT" into ["some", "TEXT"], "CamelCase" into ["Camel",
4208 "Case"], and "Vector3" into ["Vector", "3"].
4210 if input_string
.find('_') > -1:
4211 # 'some_TEXT_' -> 'some TEXT'
4212 return input_string
.replace('_', ' ').strip().split()
4214 if re
.search('[A-Z]', input_string
) and re
.search('[a-z]', input_string
):
4216 # look for capitalization to cut input_strings
4217 # 'SomeText' -> 'Some Text'
4218 input_string
= re
.sub('([A-Z])', r
' \1', input_string
).strip()
4219 # 'Vector3' -> 'Vector 3'
4220 input_string
= re
.sub('([^0-9])([0-9])', r
'\1 \2', input_string
)
4221 return input_string
.split()
4223 def ToUnderscore(input_string
):
4224 """converts CamelCase to camel_case."""
4225 words
= SplitWords(input_string
)
4226 return '_'.join([word
.lower() for word
in words
])
4228 def CachedStateName(item
):
4229 if item
.get('cached', False):
4230 return 'cached_' + item
['name']
4233 def ToGLExtensionString(extension_flag
):
4234 """Returns GL-type extension string of a extension flag."""
4235 if extension_flag
== "oes_compressed_etc1_rgb8_texture":
4236 return "OES_compressed_ETC1_RGB8_texture" # Fixup inconsitency with rgb8,
4238 uppercase_words
= [ 'img', 'ext', 'arb', 'chromium', 'oes', 'amd', 'bgra8888',
4239 'egl', 'atc', 'etc1', 'angle']
4240 parts
= extension_flag
.split('_')
4242 [part
.upper() if part
in uppercase_words
else part
for part
in parts
])
4244 def ToCamelCase(input_string
):
4245 """converts ABC_underscore_case to ABCUnderscoreCase."""
4246 return ''.join(w
[0].upper() + w
[1:] for w
in input_string
.split('_'))
4248 def GetGLGetTypeConversion(result_type
, value_type
, value
):
4249 """Makes a gl compatible type conversion string for accessing state variables.
4251 Useful when accessing state variables through glGetXXX calls.
4252 glGet documetation (for example, the manual pages):
4253 [...] If glGetIntegerv is called, [...] most floating-point values are
4254 rounded to the nearest integer value. [...]
4257 result_type: the gl type to be obtained
4258 value_type: the GL type of the state variable
4259 value: the name of the state variable
4262 String that converts the state variable to desired GL type according to GL
4266 if result_type
== 'GLint':
4267 if value_type
== 'GLfloat':
4268 return 'static_cast<GLint>(round(%s))' % value
4269 return 'static_cast<%s>(%s)' % (result_type
, value
)
4272 class CWriter(object):
4273 """Context manager that creates a C source file.
4275 To be used with the `with` statement. Returns a normal `file` type, open only
4276 for writing - any existing files with that name will be overwritten. It will
4277 automatically write the contents of `_LICENSE` and `_DO_NOT_EDIT_WARNING`
4281 with CWriter("file.cpp") as myfile:
4282 myfile.write("hello")
4283 # type(myfile) == file
4285 def __init__(self
, filename
):
4286 self
.filename
= filename
4287 self
._file
= open(filename
, 'w')
4288 self
._ENTER
_MSG
= _LICENSE
+ _DO_NOT_EDIT_WARNING
4291 def __enter__(self
):
4292 self
._file
.write(self
._ENTER
_MSG
)
4295 def __exit__(self
, exc_type
, exc_value
, traceback
):
4296 self
._file
.write(self
._EXIT
_MSG
)
4300 class CHeaderWriter(CWriter
):
4301 """Context manager that creates a C header file.
4303 Works the same way as CWriter, except it will also add the #ifdef guard
4304 around it. If `file_comment` is set, it will write that before the #ifdef
4307 def __init__(self
, filename
, file_comment
=None):
4308 super(CHeaderWriter
, self
).__init
__(filename
)
4309 guard
= self
._get
_guard
()
4310 if file_comment
is None:
4312 self
._ENTER
_MSG
= self
._ENTER
_MSG
+ file_comment \
4313 + "#ifndef %s\n#define %s\n\n" % (guard
, guard
)
4314 self
._EXIT
_MSG
= self
._EXIT
_MSG
+ "#endif // %s\n" % guard
4316 def _get_guard(self
):
4317 non_alnum_re
= re
.compile(r
'[^a-zA-Z0-9]')
4318 base
= os
.path
.abspath(self
.filename
)
4319 while os
.path
.basename(base
) != 'src':
4320 new_base
= os
.path
.dirname(base
)
4321 assert new_base
!= base
# Prevent infinite loop.
4323 hpath
= os
.path
.relpath(self
.filename
, base
)
4324 return non_alnum_re
.sub('_', hpath
).upper() + '_'
4327 class TypeHandler(object):
4328 """This class emits code for a particular type of function."""
4330 _remove_expected_call_re
= re
.compile(r
' EXPECT_CALL.*?;\n', re
.S
)
4335 def InitFunction(self
, func
):
4336 """Add or adjust anything type specific for this function."""
4337 if func
.GetInfo('needs_size') and not func
.name
.endswith('Bucket'):
4338 func
.AddCmdArg(DataSizeArgument('data_size'))
4340 def NeedsDataTransferFunction(self
, func
):
4341 """Overriden from TypeHandler."""
4342 return func
.num_pointer_args
>= 1
4344 def WriteStruct(self
, func
, f
):
4345 """Writes a structure that matches the arguments to a function."""
4346 comment
= func
.GetInfo('cmd_comment')
4347 if not comment
== None:
4349 f
.write("struct %s {\n" % func
.name
)
4350 f
.write(" typedef %s ValueType;\n" % func
.name
)
4351 f
.write(" static const CommandId kCmdId = k%s;\n" % func
.name
)
4352 func
.WriteCmdArgFlag(f
)
4353 func
.WriteCmdFlag(f
)
4355 result
= func
.GetInfo('result')
4356 if not result
== None:
4357 if len(result
) == 1:
4358 f
.write(" typedef %s Result;\n\n" % result
[0])
4360 f
.write(" struct Result {\n")
4362 f
.write(" %s;\n" % line
)
4365 func
.WriteCmdComputeSize(f
)
4366 func
.WriteCmdSetHeader(f
)
4367 func
.WriteCmdInit(f
)
4370 f
.write(" gpu::CommandHeader header;\n")
4371 args
= func
.GetCmdArgs()
4373 f
.write(" %s %s;\n" % (arg
.cmd_type
, arg
.name
))
4375 consts
= func
.GetCmdConstants()
4376 for const
in consts
:
4377 f
.write(" static const %s %s = %s;\n" %
4378 (const
.cmd_type
, const
.name
, const
.GetConstantValue()))
4383 size
= len(args
) * _SIZE_OF_UINT32
+ _SIZE_OF_COMMAND_HEADER
4384 f
.write("static_assert(sizeof(%s) == %d,\n" % (func
.name
, size
))
4385 f
.write(" \"size of %s should be %d\");\n" %
4387 f
.write("static_assert(offsetof(%s, header) == 0,\n" % func
.name
)
4388 f
.write(" \"offset of %s header should be 0\");\n" %
4390 offset
= _SIZE_OF_COMMAND_HEADER
4392 f
.write("static_assert(offsetof(%s, %s) == %d,\n" %
4393 (func
.name
, arg
.name
, offset
))
4394 f
.write(" \"offset of %s %s should be %d\");\n" %
4395 (func
.name
, arg
.name
, offset
))
4396 offset
+= _SIZE_OF_UINT32
4397 if not result
== None and len(result
) > 1:
4400 parts
= line
.split()
4403 static_assert(offsetof(%(cmd_name)s::Result, %(field_name)s) == %(offset)d,
4404 "offset of %(cmd_name)s Result %(field_name)s should be "
4407 f
.write((check
.strip() + "\n") % {
4408 'cmd_name': func
.name
,
4412 offset
+= _SIZE_OF_UINT32
4415 def WriteHandlerImplementation(self
, func
, f
):
4416 """Writes the handler implementation for this command."""
4417 if func
.IsUnsafe() and func
.GetInfo('id_mapping'):
4418 code_no_gen
= """ if (!group_->Get%(type)sServiceId(
4419 %(var)s, &%(service_var)s)) {
4420 LOCAL_SET_GL_ERROR(GL_INVALID_OPERATION, "%(func)s", "invalid %(var)s id");
4421 return error::kNoError;
4424 code_gen
= """ if (!group_->Get%(type)sServiceId(
4425 %(var)s, &%(service_var)s)) {
4426 if (!group_->bind_generates_resource()) {
4428 GL_INVALID_OPERATION, "%(func)s", "invalid %(var)s id");
4429 return error::kNoError;
4431 GLuint client_id = %(var)s;
4432 gl%(gen_func)s(1, &%(service_var)s);
4433 Create%(type)s(client_id, %(service_var)s);
4436 gen_func
= func
.GetInfo('gen_func')
4437 for id_type
in func
.GetInfo('id_mapping'):
4438 service_var
= id_type
.lower()
4439 if id_type
== 'Sync':
4440 service_var
= "service_%s" % service_var
4441 f
.write(" GLsync %s = 0;\n" % service_var
)
4442 if gen_func
and id_type
in gen_func
:
4443 f
.write(code_gen
% { 'type': id_type
,
4444 'var': id_type
.lower(),
4445 'service_var': service_var
,
4446 'func': func
.GetGLFunctionName(),
4447 'gen_func': gen_func
})
4449 f
.write(code_no_gen
% { 'type': id_type
,
4450 'var': id_type
.lower(),
4451 'service_var': service_var
,
4452 'func': func
.GetGLFunctionName() })
4454 for arg
in func
.GetOriginalArgs():
4455 if arg
.type == "GLsync":
4456 args
.append("service_%s" % arg
.name
)
4457 elif arg
.name
.endswith("size") and arg
.type == "GLsizei":
4458 args
.append("num_%s" % func
.GetLastOriginalArg().name
)
4459 elif arg
.name
== "length":
4460 args
.append("nullptr")
4462 args
.append(arg
.name
)
4463 f
.write(" %s(%s);\n" %
4464 (func
.GetGLFunctionName(), ", ".join(args
)))
4466 def WriteCmdSizeTest(self
, func
, f
):
4467 """Writes the size test for a command."""
4468 f
.write(" EXPECT_EQ(sizeof(cmd), cmd.header.size * 4u);\n")
4470 def WriteFormatTest(self
, func
, f
):
4471 """Writes a format test for a command."""
4472 f
.write("TEST_F(GLES2FormatTest, %s) {\n" % func
.name
)
4473 f
.write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
4474 (func
.name
, func
.name
))
4475 f
.write(" void* next_cmd = cmd.Set(\n")
4477 args
= func
.GetCmdArgs()
4478 for value
, arg
in enumerate(args
):
4479 f
.write(",\n static_cast<%s>(%d)" % (arg
.type, value
+ 11))
4481 f
.write(" EXPECT_EQ(static_cast<uint32_t>(cmds::%s::kCmdId),\n" %
4483 f
.write(" cmd.header.command);\n")
4484 func
.type_handler
.WriteCmdSizeTest(func
, f
)
4485 for value
, arg
in enumerate(args
):
4486 f
.write(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);\n" %
4487 (arg
.type, value
+ 11, arg
.name
))
4488 f
.write(" CheckBytesWrittenMatchesExpectedSize(\n")
4489 f
.write(" next_cmd, sizeof(cmd));\n")
4493 def WriteImmediateFormatTest(self
, func
, f
):
4494 """Writes a format test for an immediate version of a command."""
4497 def WriteBucketFormatTest(self
, func
, f
):
4498 """Writes a format test for a bucket version of a command."""
4501 def WriteGetDataSizeCode(self
, func
, f
):
4502 """Writes the code to set data_size used in validation"""
4505 def WriteImmediateCmdSizeTest(self
, func
, f
):
4506 """Writes a size test for an immediate version of a command."""
4507 f
.write(" // TODO(gman): Compute correct size.\n")
4508 f
.write(" EXPECT_EQ(sizeof(cmd), cmd.header.size * 4u);\n")
4510 def __WriteIdMapping(self
, func
, f
):
4511 """Writes client side / service side ID mapping."""
4512 if not func
.IsUnsafe() or not func
.GetInfo('id_mapping'):
4514 for id_type
in func
.GetInfo('id_mapping'):
4515 f
.write(" group_->Get%sServiceId(%s, &%s);\n" %
4516 (id_type
, id_type
.lower(), id_type
.lower()))
4518 def WriteImmediateHandlerImplementation (self
, func
, f
):
4519 """Writes the handler impl for the immediate version of a command."""
4520 self
.__WriteIdMapping
(func
, f
)
4521 f
.write(" %s(%s);\n" %
4522 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
4524 def WriteBucketHandlerImplementation (self
, func
, f
):
4525 """Writes the handler impl for the bucket version of a command."""
4526 self
.__WriteIdMapping
(func
, f
)
4527 f
.write(" %s(%s);\n" %
4528 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
4530 def WriteServiceHandlerFunctionHeader(self
, func
, f
):
4531 """Writes function header for service implementation handlers."""
4532 f
.write("""error::Error GLES2DecoderImpl::Handle%(name)s(
4533 uint32_t immediate_data_size, const void* cmd_data) {
4534 """ % {'name': func
.name
})
4536 f
.write("""if (!unsafe_es3_apis_enabled())
4537 return error::kUnknownCommand;
4539 f
.write("""const gles2::cmds::%(name)s& c =
4540 *static_cast<const gles2::cmds::%(name)s*>(cmd_data);
4542 """ % {'name': func
.name
})
4544 def WriteServiceImplementation(self
, func
, f
):
4545 """Writes the service implementation for a command."""
4546 self
.WriteServiceHandlerFunctionHeader(func
, f
)
4547 self
.WriteHandlerExtensionCheck(func
, f
)
4548 self
.WriteHandlerDeferReadWrite(func
, f
);
4549 if len(func
.GetOriginalArgs()) > 0:
4550 last_arg
= func
.GetLastOriginalArg()
4551 all_but_last_arg
= func
.GetOriginalArgs()[:-1]
4552 for arg
in all_but_last_arg
:
4554 self
.WriteGetDataSizeCode(func
, f
)
4555 last_arg
.WriteGetCode(f
)
4556 func
.WriteHandlerValidation(f
)
4557 func
.WriteHandlerImplementation(f
)
4558 f
.write(" return error::kNoError;\n")
4562 def WriteImmediateServiceImplementation(self
, func
, f
):
4563 """Writes the service implementation for an immediate version of command."""
4564 self
.WriteServiceHandlerFunctionHeader(func
, f
)
4565 self
.WriteHandlerExtensionCheck(func
, f
)
4566 self
.WriteHandlerDeferReadWrite(func
, f
);
4567 for arg
in func
.GetOriginalArgs():
4569 self
.WriteGetDataSizeCode(func
, f
)
4571 func
.WriteHandlerValidation(f
)
4572 func
.WriteHandlerImplementation(f
)
4573 f
.write(" return error::kNoError;\n")
4577 def WriteBucketServiceImplementation(self
, func
, f
):
4578 """Writes the service implementation for a bucket version of command."""
4579 self
.WriteServiceHandlerFunctionHeader(func
, f
)
4580 self
.WriteHandlerExtensionCheck(func
, f
)
4581 self
.WriteHandlerDeferReadWrite(func
, f
);
4582 for arg
in func
.GetCmdArgs():
4584 func
.WriteHandlerValidation(f
)
4585 func
.WriteHandlerImplementation(f
)
4586 f
.write(" return error::kNoError;\n")
4590 def WriteHandlerExtensionCheck(self
, func
, f
):
4591 if func
.GetInfo('extension_flag'):
4592 f
.write(" if (!features().%s) {\n" % func
.GetInfo('extension_flag'))
4593 f
.write(" LOCAL_SET_GL_ERROR(GL_INVALID_OPERATION, \"gl%s\","
4594 " \"function not available\");\n" % func
.original_name
)
4595 f
.write(" return error::kNoError;")
4598 def WriteHandlerDeferReadWrite(self
, func
, f
):
4599 """Writes the code to handle deferring reads or writes."""
4600 defer_draws
= func
.GetInfo('defer_draws')
4601 defer_reads
= func
.GetInfo('defer_reads')
4602 if defer_draws
or defer_reads
:
4603 f
.write(" error::Error error;\n")
4605 f
.write(" error = WillAccessBoundFramebufferForDraw();\n")
4606 f
.write(" if (error != error::kNoError)\n")
4607 f
.write(" return error;\n")
4609 f
.write(" error = WillAccessBoundFramebufferForRead();\n")
4610 f
.write(" if (error != error::kNoError)\n")
4611 f
.write(" return error;\n")
4613 def WriteValidUnitTest(self
, func
, f
, test
, *extras
):
4614 """Writes a valid unit test for the service implementation."""
4615 if func
.GetInfo('expectation') == False:
4616 test
= self
._remove
_expected
_call
_re
.sub('', test
)
4619 arg
.GetValidArg(func
) \
4620 for arg
in func
.GetOriginalArgs() if not arg
.IsConstant()
4623 arg
.GetValidGLArg(func
) \
4624 for arg
in func
.GetOriginalArgs()
4626 gl_func_name
= func
.GetGLTestFunctionName()
4629 'gl_func_name': gl_func_name
,
4630 'args': ", ".join(arg_strings
),
4631 'gl_args': ", ".join(gl_arg_strings
),
4633 for extra
in extras
:
4636 while (old_test
!= test
):
4639 f
.write(test
% vars)
4641 def WriteInvalidUnitTest(self
, func
, f
, test
, *extras
):
4642 """Writes an invalid unit test for the service implementation."""
4645 for invalid_arg_index
, invalid_arg
in enumerate(func
.GetOriginalArgs()):
4646 # Service implementation does not test constants, as they are not part of
4647 # the call in the service side.
4648 if invalid_arg
.IsConstant():
4651 num_invalid_values
= invalid_arg
.GetNumInvalidValues(func
)
4652 for value_index
in range(0, num_invalid_values
):
4654 parse_result
= "kNoError"
4656 for arg
in func
.GetOriginalArgs():
4657 if arg
.IsConstant():
4659 if invalid_arg
is arg
:
4660 (arg_string
, parse_result
, gl_error
) = arg
.GetInvalidArg(
4663 arg_string
= arg
.GetValidArg(func
)
4664 arg_strings
.append(arg_string
)
4666 for arg
in func
.GetOriginalArgs():
4667 gl_arg_strings
.append("_")
4668 gl_func_name
= func
.GetGLTestFunctionName()
4670 if not gl_error
== None:
4671 gl_error_test
= '\n EXPECT_EQ(%s, GetGLError());' % gl_error
4675 'arg_index': invalid_arg_index
,
4676 'value_index': value_index
,
4677 'gl_func_name': gl_func_name
,
4678 'args': ", ".join(arg_strings
),
4679 'all_but_last_args': ", ".join(arg_strings
[:-1]),
4680 'gl_args': ", ".join(gl_arg_strings
),
4681 'parse_result': parse_result
,
4682 'gl_error_test': gl_error_test
,
4684 for extra
in extras
:
4686 f
.write(test
% vars)
4688 def WriteServiceUnitTest(self
, func
, f
, *extras
):
4689 """Writes the service unit test for a command."""
4691 if func
.name
== 'Enable':
4693 TEST_P(%(test_name)s, %(name)sValidArgs) {
4694 SetupExpectationsForEnableDisable(%(gl_args)s, true);
4695 SpecializedSetup<cmds::%(name)s, 0>(true);
4697 cmd.Init(%(args)s);"""
4698 elif func
.name
== 'Disable':
4700 TEST_P(%(test_name)s, %(name)sValidArgs) {
4701 SetupExpectationsForEnableDisable(%(gl_args)s, false);
4702 SpecializedSetup<cmds::%(name)s, 0>(true);
4704 cmd.Init(%(args)s);"""
4707 TEST_P(%(test_name)s, %(name)sValidArgs) {
4708 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
4709 SpecializedSetup<cmds::%(name)s, 0>(true);
4711 cmd.Init(%(args)s);"""
4714 decoder_->set_unsafe_es3_apis_enabled(true);
4715 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4716 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4717 decoder_->set_unsafe_es3_apis_enabled(false);
4718 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));
4723 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4724 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4727 self
.WriteValidUnitTest(func
, f
, valid_test
, *extras
)
4729 if not func
.IsUnsafe():
4731 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
4732 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
4733 SpecializedSetup<cmds::%(name)s, 0>(false);
4736 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
4739 self
.WriteInvalidUnitTest(func
, f
, invalid_test
, *extras
)
4741 def WriteImmediateServiceUnitTest(self
, func
, f
, *extras
):
4742 """Writes the service unit test for an immediate command."""
4743 f
.write("// TODO(gman): %s\n" % func
.name
)
4745 def WriteImmediateValidationCode(self
, func
, f
):
4746 """Writes the validation code for an immediate version of a command."""
4749 def WriteBucketServiceUnitTest(self
, func
, f
, *extras
):
4750 """Writes the service unit test for a bucket command."""
4751 f
.write("// TODO(gman): %s\n" % func
.name
)
4753 def WriteBucketValidationCode(self
, func
, f
):
4754 """Writes the validation code for a bucket version of a command."""
4755 f
.write("// TODO(gman): %s\n" % func
.name
)
4757 def WriteGLES2ImplementationDeclaration(self
, func
, f
):
4758 """Writes the GLES2 Implemention declaration."""
4759 impl_decl
= func
.GetInfo('impl_decl')
4760 if impl_decl
== None or impl_decl
== True:
4761 f
.write("%s %s(%s) override;\n" %
4762 (func
.return_type
, func
.original_name
,
4763 func
.MakeTypedOriginalArgString("")))
4766 def WriteGLES2CLibImplementation(self
, func
, f
):
4767 f
.write("%s GL_APIENTRY GLES2%s(%s) {\n" %
4768 (func
.return_type
, func
.name
,
4769 func
.MakeTypedOriginalArgString("")))
4770 result_string
= "return "
4771 if func
.return_type
== "void":
4773 f
.write(" %sgles2::GetGLContext()->%s(%s);\n" %
4774 (result_string
, func
.original_name
,
4775 func
.MakeOriginalArgString("")))
4778 def WriteGLES2Header(self
, func
, f
):
4779 """Writes a re-write macro for GLES"""
4780 f
.write("#define gl%s GLES2_GET_FUN(%s)\n" %(func
.name
, func
.name
))
4782 def WriteClientGLCallLog(self
, func
, f
):
4783 """Writes a logging macro for the client side code."""
4785 if len(func
.GetOriginalArgs()):
4788 ' GPU_CLIENT_LOG("[" << GetLogPrefix() << "] gl%s("%s%s << ")");\n' %
4789 (func
.original_name
, comma
, func
.MakeLogArgString()))
4791 def WriteClientGLReturnLog(self
, func
, f
):
4792 """Writes the return value logging code."""
4793 if func
.return_type
!= "void":
4794 f
.write(' GPU_CLIENT_LOG("return:" << result)\n')
4796 def WriteGLES2ImplementationHeader(self
, func
, f
):
4797 """Writes the GLES2 Implemention."""
4798 self
.WriteGLES2ImplementationDeclaration(func
, f
)
4800 def WriteGLES2TraceImplementationHeader(self
, func
, f
):
4801 """Writes the GLES2 Trace Implemention header."""
4802 f
.write("%s %s(%s) override;\n" %
4803 (func
.return_type
, func
.original_name
,
4804 func
.MakeTypedOriginalArgString("")))
4806 def WriteGLES2TraceImplementation(self
, func
, f
):
4807 """Writes the GLES2 Trace Implemention."""
4808 f
.write("%s GLES2TraceImplementation::%s(%s) {\n" %
4809 (func
.return_type
, func
.original_name
,
4810 func
.MakeTypedOriginalArgString("")))
4811 result_string
= "return "
4812 if func
.return_type
== "void":
4814 f
.write(' TRACE_EVENT_BINARY_EFFICIENT0("gpu", "GLES2Trace::%s");\n' %
4816 f
.write(" %sgl_->%s(%s);\n" %
4817 (result_string
, func
.name
, func
.MakeOriginalArgString("")))
4821 def WriteGLES2Implementation(self
, func
, f
):
4822 """Writes the GLES2 Implemention."""
4823 impl_func
= func
.GetInfo('impl_func')
4824 impl_decl
= func
.GetInfo('impl_decl')
4825 gen_cmd
= func
.GetInfo('gen_cmd')
4826 if (func
.can_auto_generate
and
4827 (impl_func
== None or impl_func
== True) and
4828 (impl_decl
== None or impl_decl
== True) and
4829 (gen_cmd
== None or gen_cmd
== True)):
4830 f
.write("%s GLES2Implementation::%s(%s) {\n" %
4831 (func
.return_type
, func
.original_name
,
4832 func
.MakeTypedOriginalArgString("")))
4833 f
.write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
4834 self
.WriteClientGLCallLog(func
, f
)
4835 func
.WriteDestinationInitalizationValidation(f
)
4836 for arg
in func
.GetOriginalArgs():
4837 arg
.WriteClientSideValidationCode(f
, func
)
4838 f
.write(" helper_->%s(%s);\n" %
4839 (func
.name
, func
.MakeHelperArgString("")))
4840 f
.write(" CheckGLError();\n")
4841 self
.WriteClientGLReturnLog(func
, f
)
4845 def WriteGLES2InterfaceHeader(self
, func
, f
):
4846 """Writes the GLES2 Interface."""
4847 f
.write("virtual %s %s(%s) = 0;\n" %
4848 (func
.return_type
, func
.original_name
,
4849 func
.MakeTypedOriginalArgString("")))
4851 def WriteMojoGLES2ImplHeader(self
, func
, f
):
4852 """Writes the Mojo GLES2 implementation header."""
4853 f
.write("%s %s(%s) override;\n" %
4854 (func
.return_type
, func
.original_name
,
4855 func
.MakeTypedOriginalArgString("")))
4857 def WriteMojoGLES2Impl(self
, func
, f
):
4858 """Writes the Mojo GLES2 implementation."""
4859 f
.write("%s MojoGLES2Impl::%s(%s) {\n" %
4860 (func
.return_type
, func
.original_name
,
4861 func
.MakeTypedOriginalArgString("")))
4862 extensions
= ["CHROMIUM_sync_point", "CHROMIUM_texture_mailbox",
4863 "CHROMIUM_sub_image", "CHROMIUM_miscellaneous",
4864 "occlusion_query_EXT", "CHROMIUM_image",
4865 "CHROMIUM_copy_texture",
4866 "CHROMIUM_pixel_transfer_buffer_object"]
4867 if func
.IsCoreGLFunction() or func
.GetInfo("extension") in extensions
:
4868 f
.write("MojoGLES2MakeCurrent(context_);");
4869 func_return
= "gl" + func
.original_name
+ "(" + \
4870 func
.MakeOriginalArgString("") + ");"
4871 if func
.return_type
== "void":
4872 f
.write(func_return
);
4874 f
.write("return " + func_return
);
4876 f
.write("NOTREACHED() << \"Unimplemented %s.\";\n" %
4877 func
.original_name
);
4878 if func
.return_type
!= "void":
4879 f
.write("return 0;")
4882 def WriteGLES2InterfaceStub(self
, func
, f
):
4883 """Writes the GLES2 Interface stub declaration."""
4884 f
.write("%s %s(%s) override;\n" %
4885 (func
.return_type
, func
.original_name
,
4886 func
.MakeTypedOriginalArgString("")))
4888 def WriteGLES2InterfaceStubImpl(self
, func
, f
):
4889 """Writes the GLES2 Interface stub declaration."""
4890 args
= func
.GetOriginalArgs()
4891 arg_string
= ", ".join(
4892 ["%s /* %s */" % (arg
.type, arg
.name
) for arg
in args
])
4893 f
.write("%s GLES2InterfaceStub::%s(%s) {\n" %
4894 (func
.return_type
, func
.original_name
, arg_string
))
4895 if func
.return_type
!= "void":
4896 f
.write(" return 0;\n")
4899 def WriteGLES2ImplementationUnitTest(self
, func
, f
):
4900 """Writes the GLES2 Implemention unit test."""
4901 client_test
= func
.GetInfo('client_test')
4902 if (func
.can_auto_generate
and
4903 (client_test
== None or client_test
== True)):
4905 TEST_F(GLES2ImplementationTest, %(name)s) {
4910 expected.cmd.Init(%(cmd_args)s);
4912 gl_->%(name)s(%(args)s);
4913 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
4917 arg
.GetValidClientSideCmdArg(func
) for arg
in func
.GetCmdArgs()
4921 arg
.GetValidClientSideArg(func
) for arg
in func
.GetOriginalArgs()
4926 'args': ", ".join(gl_arg_strings
),
4927 'cmd_args': ", ".join(cmd_arg_strings
),
4930 # Test constants for invalid values, as they are not tested by the
4932 constants
= [arg
for arg
in func
.GetOriginalArgs() if arg
.IsConstant()]
4935 TEST_F(GLES2ImplementationTest, %(name)sInvalidConstantArg%(invalid_index)d) {
4936 gl_->%(name)s(%(args)s);
4937 EXPECT_TRUE(NoCommandsWritten());
4938 EXPECT_EQ(%(gl_error)s, CheckError());
4941 for invalid_arg
in constants
:
4943 invalid
= invalid_arg
.GetInvalidArg(func
)
4944 for arg
in func
.GetOriginalArgs():
4945 if arg
is invalid_arg
:
4946 gl_arg_strings
.append(invalid
[0])
4948 gl_arg_strings
.append(arg
.GetValidClientSideArg(func
))
4952 'invalid_index': func
.GetOriginalArgs().index(invalid_arg
),
4953 'args': ", ".join(gl_arg_strings
),
4954 'gl_error': invalid
[2],
4957 if client_test
!= False:
4958 f
.write("// TODO(zmo): Implement unit test for %s\n" % func
.name
)
4960 def WriteDestinationInitalizationValidation(self
, func
, f
):
4961 """Writes the client side destintion initialization validation."""
4962 for arg
in func
.GetOriginalArgs():
4963 arg
.WriteDestinationInitalizationValidation(f
, func
)
4965 def WriteTraceEvent(self
, func
, f
):
4966 f
.write(' TRACE_EVENT0("gpu", "GLES2Implementation::%s");\n' %
4969 def WriteImmediateCmdComputeSize(self
, func
, f
):
4970 """Writes the size computation code for the immediate version of a cmd."""
4971 f
.write(" static uint32_t ComputeSize(uint32_t size_in_bytes) {\n")
4972 f
.write(" return static_cast<uint32_t>(\n")
4973 f
.write(" sizeof(ValueType) + // NOLINT\n")
4974 f
.write(" RoundSizeToMultipleOfEntries(size_in_bytes));\n")
4978 def WriteImmediateCmdSetHeader(self
, func
, f
):
4979 """Writes the SetHeader function for the immediate version of a cmd."""
4980 f
.write(" void SetHeader(uint32_t size_in_bytes) {\n")
4981 f
.write(" header.SetCmdByTotalSize<ValueType>(size_in_bytes);\n")
4985 def WriteImmediateCmdInit(self
, func
, f
):
4986 """Writes the Init function for the immediate version of a command."""
4987 raise NotImplementedError(func
.name
)
4989 def WriteImmediateCmdSet(self
, func
, f
):
4990 """Writes the Set function for the immediate version of a command."""
4991 raise NotImplementedError(func
.name
)
4993 def WriteCmdHelper(self
, func
, f
):
4994 """Writes the cmd helper definition for a cmd."""
4995 code
= """ void %(name)s(%(typed_args)s) {
4996 gles2::cmds::%(name)s* c = GetCmdSpace<gles2::cmds::%(name)s>();
5005 "typed_args": func
.MakeTypedCmdArgString(""),
5006 "args": func
.MakeCmdArgString(""),
5009 def WriteImmediateCmdHelper(self
, func
, f
):
5010 """Writes the cmd helper definition for the immediate version of a cmd."""
5011 code
= """ void %(name)s(%(typed_args)s) {
5012 const uint32_t s = 0; // TODO(gman): compute correct size
5013 gles2::cmds::%(name)s* c =
5014 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(s);
5023 "typed_args": func
.MakeTypedCmdArgString(""),
5024 "args": func
.MakeCmdArgString(""),
5028 class StateSetHandler(TypeHandler
):
5029 """Handler for commands that simply set state."""
5032 TypeHandler
.__init
__(self
)
5034 def WriteHandlerImplementation(self
, func
, f
):
5035 """Overrriden from TypeHandler."""
5036 state_name
= func
.GetInfo('state')
5037 state
= _STATES
[state_name
]
5038 states
= state
['states']
5039 args
= func
.GetOriginalArgs()
5040 for ndx
,item
in enumerate(states
):
5042 if 'range_checks' in item
:
5043 for range_check
in item
['range_checks']:
5044 code
.append("%s %s" % (args
[ndx
].name
, range_check
['check']))
5045 if 'nan_check' in item
:
5046 # Drivers might generate an INVALID_VALUE error when a value is set
5047 # to NaN. This is allowed behavior under GLES 3.0 section 2.1.1 or
5048 # OpenGL 4.5 section 2.3.4.1 - providing NaN allows undefined results.
5049 # Make this behavior consistent within Chromium, and avoid leaking GL
5050 # errors by generating the error in the command buffer instead of
5051 # letting the GL driver generate it.
5052 code
.append("std::isnan(%s)" % args
[ndx
].name
)
5054 f
.write(" if (%s) {\n" % " ||\n ".join(code
))
5056 ' LOCAL_SET_GL_ERROR(GL_INVALID_VALUE,'
5057 ' "%s", "%s out of range");\n' %
5058 (func
.name
, args
[ndx
].name
))
5059 f
.write(" return error::kNoError;\n")
5062 for ndx
,item
in enumerate(states
):
5063 code
.append("state_.%s != %s" % (item
['name'], args
[ndx
].name
))
5064 f
.write(" if (%s) {\n" % " ||\n ".join(code
))
5065 for ndx
,item
in enumerate(states
):
5066 f
.write(" state_.%s = %s;\n" % (item
['name'], args
[ndx
].name
))
5067 if 'state_flag' in state
:
5068 f
.write(" %s = true;\n" % state
['state_flag'])
5069 if not func
.GetInfo("no_gl"):
5070 for ndx
,item
in enumerate(states
):
5071 if item
.get('cached', False):
5072 f
.write(" state_.%s = %s;\n" %
5073 (CachedStateName(item
), args
[ndx
].name
))
5074 f
.write(" %s(%s);\n" %
5075 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
5078 def WriteServiceUnitTest(self
, func
, f
, *extras
):
5079 """Overrriden from TypeHandler."""
5080 TypeHandler
.WriteServiceUnitTest(self
, func
, f
, *extras
)
5081 state_name
= func
.GetInfo('state')
5082 state
= _STATES
[state_name
]
5083 states
= state
['states']
5084 for ndx
,item
in enumerate(states
):
5085 if 'range_checks' in item
:
5086 for check_ndx
, range_check
in enumerate(item
['range_checks']):
5088 TEST_P(%(test_name)s, %(name)sInvalidValue%(ndx)d_%(check_ndx)d) {
5089 SpecializedSetup<cmds::%(name)s, 0>(false);
5092 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5093 EXPECT_EQ(GL_INVALID_VALUE, GetGLError());
5098 arg
.GetValidArg(func
) \
5099 for arg
in func
.GetOriginalArgs() if not arg
.IsConstant()
5102 arg_strings
[ndx
] = range_check
['test_value']
5106 'check_ndx': check_ndx
,
5107 'args': ", ".join(arg_strings
),
5109 for extra
in extras
:
5111 f
.write(valid_test
% vars)
5112 if 'nan_check' in item
:
5114 TEST_P(%(test_name)s, %(name)sNaNValue%(ndx)d) {
5115 SpecializedSetup<cmds::%(name)s, 0>(false);
5118 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5119 EXPECT_EQ(GL_INVALID_VALUE, GetGLError());
5124 arg
.GetValidArg(func
) \
5125 for arg
in func
.GetOriginalArgs() if not arg
.IsConstant()
5128 arg_strings
[ndx
] = 'nanf("")'
5132 'args': ", ".join(arg_strings
),
5134 for extra
in extras
:
5136 f
.write(valid_test
% vars)
5139 class StateSetRGBAlphaHandler(TypeHandler
):
5140 """Handler for commands that simply set state that have rgb/alpha."""
5143 TypeHandler
.__init
__(self
)
5145 def WriteHandlerImplementation(self
, func
, f
):
5146 """Overrriden from TypeHandler."""
5147 state_name
= func
.GetInfo('state')
5148 state
= _STATES
[state_name
]
5149 states
= state
['states']
5150 args
= func
.GetOriginalArgs()
5151 num_args
= len(args
)
5153 for ndx
,item
in enumerate(states
):
5154 code
.append("state_.%s != %s" % (item
['name'], args
[ndx
% num_args
].name
))
5155 f
.write(" if (%s) {\n" % " ||\n ".join(code
))
5156 for ndx
, item
in enumerate(states
):
5157 f
.write(" state_.%s = %s;\n" %
5158 (item
['name'], args
[ndx
% num_args
].name
))
5159 if 'state_flag' in state
:
5160 f
.write(" %s = true;\n" % state
['state_flag'])
5161 if not func
.GetInfo("no_gl"):
5162 f
.write(" %s(%s);\n" %
5163 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
5167 class StateSetFrontBackSeparateHandler(TypeHandler
):
5168 """Handler for commands that simply set state that have front/back."""
5171 TypeHandler
.__init
__(self
)
5173 def WriteHandlerImplementation(self
, func
, f
):
5174 """Overrriden from TypeHandler."""
5175 state_name
= func
.GetInfo('state')
5176 state
= _STATES
[state_name
]
5177 states
= state
['states']
5178 args
= func
.GetOriginalArgs()
5180 num_args
= len(args
)
5181 f
.write(" bool changed = false;\n")
5182 for group_ndx
, group
in enumerate(Grouper(num_args
- 1, states
)):
5183 f
.write(" if (%s == %s || %s == GL_FRONT_AND_BACK) {\n" %
5184 (face
, ('GL_FRONT', 'GL_BACK')[group_ndx
], face
))
5186 for ndx
, item
in enumerate(group
):
5187 code
.append("state_.%s != %s" % (item
['name'], args
[ndx
+ 1].name
))
5188 f
.write(" changed |= %s;\n" % " ||\n ".join(code
))
5190 f
.write(" if (changed) {\n")
5191 for group_ndx
, group
in enumerate(Grouper(num_args
- 1, states
)):
5192 f
.write(" if (%s == %s || %s == GL_FRONT_AND_BACK) {\n" %
5193 (face
, ('GL_FRONT', 'GL_BACK')[group_ndx
], face
))
5194 for ndx
, item
in enumerate(group
):
5195 f
.write(" state_.%s = %s;\n" %
5196 (item
['name'], args
[ndx
+ 1].name
))
5198 if 'state_flag' in state
:
5199 f
.write(" %s = true;\n" % state
['state_flag'])
5200 if not func
.GetInfo("no_gl"):
5201 f
.write(" %s(%s);\n" %
5202 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
5206 class StateSetFrontBackHandler(TypeHandler
):
5207 """Handler for commands that simply set state that set both front/back."""
5210 TypeHandler
.__init
__(self
)
5212 def WriteHandlerImplementation(self
, func
, f
):
5213 """Overrriden from TypeHandler."""
5214 state_name
= func
.GetInfo('state')
5215 state
= _STATES
[state_name
]
5216 states
= state
['states']
5217 args
= func
.GetOriginalArgs()
5218 num_args
= len(args
)
5220 for group_ndx
, group
in enumerate(Grouper(num_args
, states
)):
5221 for ndx
, item
in enumerate(group
):
5222 code
.append("state_.%s != %s" % (item
['name'], args
[ndx
].name
))
5223 f
.write(" if (%s) {\n" % " ||\n ".join(code
))
5224 for group_ndx
, group
in enumerate(Grouper(num_args
, states
)):
5225 for ndx
, item
in enumerate(group
):
5226 f
.write(" state_.%s = %s;\n" % (item
['name'], args
[ndx
].name
))
5227 if 'state_flag' in state
:
5228 f
.write(" %s = true;\n" % state
['state_flag'])
5229 if not func
.GetInfo("no_gl"):
5230 f
.write(" %s(%s);\n" %
5231 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
5235 class StateSetNamedParameter(TypeHandler
):
5236 """Handler for commands that set a state chosen with an enum parameter."""
5239 TypeHandler
.__init
__(self
)
5241 def WriteHandlerImplementation(self
, func
, f
):
5242 """Overridden from TypeHandler."""
5243 state_name
= func
.GetInfo('state')
5244 state
= _STATES
[state_name
]
5245 states
= state
['states']
5246 args
= func
.GetOriginalArgs()
5247 num_args
= len(args
)
5248 assert num_args
== 2
5249 f
.write(" switch (%s) {\n" % args
[0].name
)
5250 for state
in states
:
5251 f
.write(" case %s:\n" % state
['enum'])
5252 f
.write(" if (state_.%s != %s) {\n" %
5253 (state
['name'], args
[1].name
))
5254 f
.write(" state_.%s = %s;\n" % (state
['name'], args
[1].name
))
5255 if not func
.GetInfo("no_gl"):
5256 f
.write(" %s(%s);\n" %
5257 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
5259 f
.write(" break;\n")
5260 f
.write(" default:\n")
5261 f
.write(" NOTREACHED();\n")
5265 class CustomHandler(TypeHandler
):
5266 """Handler for commands that are auto-generated but require minor tweaks."""
5269 TypeHandler
.__init
__(self
)
5271 def WriteServiceImplementation(self
, func
, f
):
5272 """Overrriden from TypeHandler."""
5275 def WriteImmediateServiceImplementation(self
, func
, f
):
5276 """Overrriden from TypeHandler."""
5279 def WriteBucketServiceImplementation(self
, func
, f
):
5280 """Overrriden from TypeHandler."""
5283 def WriteServiceUnitTest(self
, func
, f
, *extras
):
5284 """Overrriden from TypeHandler."""
5285 f
.write("// TODO(gman): %s\n\n" % func
.name
)
5287 def WriteImmediateServiceUnitTest(self
, func
, f
, *extras
):
5288 """Overrriden from TypeHandler."""
5289 f
.write("// TODO(gman): %s\n\n" % func
.name
)
5291 def WriteImmediateCmdGetTotalSize(self
, func
, f
):
5292 """Overrriden from TypeHandler."""
5294 " uint32_t total_size = 0; // TODO(gman): get correct size.\n")
5296 def WriteImmediateCmdInit(self
, func
, f
):
5297 """Overrriden from TypeHandler."""
5298 f
.write(" void Init(%s) {\n" % func
.MakeTypedCmdArgString("_"))
5299 self
.WriteImmediateCmdGetTotalSize(func
, f
)
5300 f
.write(" SetHeader(total_size);\n")
5301 args
= func
.GetCmdArgs()
5303 f
.write(" %s = _%s;\n" % (arg
.name
, arg
.name
))
5307 def WriteImmediateCmdSet(self
, func
, f
):
5308 """Overrriden from TypeHandler."""
5309 copy_args
= func
.MakeCmdArgString("_", False)
5310 f
.write(" void* Set(void* cmd%s) {\n" %
5311 func
.MakeTypedCmdArgString("_", True))
5312 self
.WriteImmediateCmdGetTotalSize(func
, f
)
5313 f
.write(" static_cast<ValueType*>(cmd)->Init(%s);\n" % copy_args
)
5314 f
.write(" return NextImmediateCmdAddressTotalSize<ValueType>("
5315 "cmd, total_size);\n")
5320 class TodoHandler(CustomHandler
):
5321 """Handle for commands that are not yet implemented."""
5323 def NeedsDataTransferFunction(self
, func
):
5324 """Overriden from TypeHandler."""
5327 def WriteImmediateFormatTest(self
, func
, f
):
5328 """Overrriden from TypeHandler."""
5331 def WriteGLES2ImplementationUnitTest(self
, func
, f
):
5332 """Overrriden from TypeHandler."""
5335 def WriteGLES2Implementation(self
, func
, f
):
5336 """Overrriden from TypeHandler."""
5337 f
.write("%s GLES2Implementation::%s(%s) {\n" %
5338 (func
.return_type
, func
.original_name
,
5339 func
.MakeTypedOriginalArgString("")))
5340 f
.write(" // TODO: for now this is a no-op\n")
5343 "GL_INVALID_OPERATION, \"gl%s\", \"not implemented\");\n" %
5345 if func
.return_type
!= "void":
5346 f
.write(" return 0;\n")
5350 def WriteServiceImplementation(self
, func
, f
):
5351 """Overrriden from TypeHandler."""
5352 self
.WriteServiceHandlerFunctionHeader(func
, f
)
5353 f
.write(" // TODO: for now this is a no-op\n")
5355 " LOCAL_SET_GL_ERROR("
5356 "GL_INVALID_OPERATION, \"gl%s\", \"not implemented\");\n" %
5358 f
.write(" return error::kNoError;\n")
5363 class HandWrittenHandler(CustomHandler
):
5364 """Handler for comands where everything must be written by hand."""
5366 def InitFunction(self
, func
):
5367 """Add or adjust anything type specific for this function."""
5368 CustomHandler
.InitFunction(self
, func
)
5369 func
.can_auto_generate
= False
5371 def NeedsDataTransferFunction(self
, func
):
5372 """Overriden from TypeHandler."""
5373 # If specified explicitly, force the data transfer method.
5374 if func
.GetInfo('data_transfer_methods'):
5378 def WriteStruct(self
, func
, f
):
5379 """Overrriden from TypeHandler."""
5382 def WriteDocs(self
, func
, f
):
5383 """Overrriden from TypeHandler."""
5386 def WriteServiceUnitTest(self
, func
, f
, *extras
):
5387 """Overrriden from TypeHandler."""
5388 f
.write("// TODO(gman): %s\n\n" % func
.name
)
5390 def WriteImmediateServiceUnitTest(self
, func
, f
, *extras
):
5391 """Overrriden from TypeHandler."""
5392 f
.write("// TODO(gman): %s\n\n" % func
.name
)
5394 def WriteBucketServiceUnitTest(self
, func
, f
, *extras
):
5395 """Overrriden from TypeHandler."""
5396 f
.write("// TODO(gman): %s\n\n" % func
.name
)
5398 def WriteServiceImplementation(self
, func
, f
):
5399 """Overrriden from TypeHandler."""
5402 def WriteImmediateServiceImplementation(self
, func
, f
):
5403 """Overrriden from TypeHandler."""
5406 def WriteBucketServiceImplementation(self
, func
, f
):
5407 """Overrriden from TypeHandler."""
5410 def WriteImmediateCmdHelper(self
, func
, f
):
5411 """Overrriden from TypeHandler."""
5414 def WriteCmdHelper(self
, func
, f
):
5415 """Overrriden from TypeHandler."""
5418 def WriteFormatTest(self
, func
, f
):
5419 """Overrriden from TypeHandler."""
5420 f
.write("// TODO(gman): Write test for %s\n" % func
.name
)
5422 def WriteImmediateFormatTest(self
, func
, f
):
5423 """Overrriden from TypeHandler."""
5424 f
.write("// TODO(gman): Write test for %s\n" % func
.name
)
5426 def WriteBucketFormatTest(self
, func
, f
):
5427 """Overrriden from TypeHandler."""
5428 f
.write("// TODO(gman): Write test for %s\n" % func
.name
)
5432 class ManualHandler(CustomHandler
):
5433 """Handler for commands who's handlers must be written by hand."""
5436 CustomHandler
.__init
__(self
)
5438 def InitFunction(self
, func
):
5439 """Overrriden from TypeHandler."""
5440 if (func
.name
== 'CompressedTexImage2DBucket' or
5441 func
.name
== 'CompressedTexImage3DBucket'):
5442 func
.cmd_args
= func
.cmd_args
[:-1]
5443 func
.AddCmdArg(Argument('bucket_id', 'GLuint'))
5445 CustomHandler
.InitFunction(self
, func
)
5447 def WriteServiceImplementation(self
, func
, f
):
5448 """Overrriden from TypeHandler."""
5451 def WriteBucketServiceImplementation(self
, func
, f
):
5452 """Overrriden from TypeHandler."""
5455 def WriteServiceUnitTest(self
, func
, f
, *extras
):
5456 """Overrriden from TypeHandler."""
5457 f
.write("// TODO(gman): %s\n\n" % func
.name
)
5459 def WriteImmediateServiceUnitTest(self
, func
, f
, *extras
):
5460 """Overrriden from TypeHandler."""
5461 f
.write("// TODO(gman): %s\n\n" % func
.name
)
5463 def WriteImmediateServiceImplementation(self
, func
, f
):
5464 """Overrriden from TypeHandler."""
5467 def WriteImmediateFormatTest(self
, func
, f
):
5468 """Overrriden from TypeHandler."""
5469 f
.write("// TODO(gman): Implement test for %s\n" % func
.name
)
5471 def WriteGLES2Implementation(self
, func
, f
):
5472 """Overrriden from TypeHandler."""
5473 if func
.GetInfo('impl_func'):
5474 super(ManualHandler
, self
).WriteGLES2Implementation(func
, f
)
5476 def WriteGLES2ImplementationHeader(self
, func
, f
):
5477 """Overrriden from TypeHandler."""
5478 f
.write("%s %s(%s) override;\n" %
5479 (func
.return_type
, func
.original_name
,
5480 func
.MakeTypedOriginalArgString("")))
5483 def WriteImmediateCmdGetTotalSize(self
, func
, f
):
5484 """Overrriden from TypeHandler."""
5485 # TODO(gman): Move this data to _FUNCTION_INFO?
5486 CustomHandler
.WriteImmediateCmdGetTotalSize(self
, func
, f
)
5489 class DataHandler(TypeHandler
):
5490 """Handler for glBufferData, glBufferSubData, glTexImage*D, glTexSubImage*D,
5491 glCompressedTexImage*D, glCompressedTexImageSub*D."""
5493 TypeHandler
.__init
__(self
)
5495 def InitFunction(self
, func
):
5496 """Overrriden from TypeHandler."""
5497 if (func
.name
== 'CompressedTexSubImage2DBucket' or
5498 func
.name
== 'CompressedTexSubImage3DBucket'):
5499 func
.cmd_args
= func
.cmd_args
[:-1]
5500 func
.AddCmdArg(Argument('bucket_id', 'GLuint'))
5502 def WriteGetDataSizeCode(self
, func
, f
):
5503 """Overrriden from TypeHandler."""
5504 # TODO(gman): Move this data to _FUNCTION_INFO?
5506 if name
.endswith("Immediate"):
5508 if name
== 'BufferData' or name
== 'BufferSubData':
5509 f
.write(" uint32_t data_size = size;\n")
5510 elif (name
== 'CompressedTexImage2D' or
5511 name
== 'CompressedTexSubImage2D' or
5512 name
== 'CompressedTexImage3D' or
5513 name
== 'CompressedTexSubImage3D'):
5514 f
.write(" uint32_t data_size = imageSize;\n")
5515 elif (name
== 'CompressedTexSubImage2DBucket' or
5516 name
== 'CompressedTexSubImage3DBucket'):
5517 f
.write(" Bucket* bucket = GetBucket(c.bucket_id);\n")
5518 f
.write(" uint32_t data_size = bucket->size();\n")
5519 f
.write(" GLsizei imageSize = data_size;\n")
5520 elif name
== 'TexImage2D' or name
== 'TexSubImage2D':
5521 code
= """ uint32_t data_size;
5522 if (!GLES2Util::ComputeImageDataSize(
5523 width, height, format, type, unpack_alignment_, &data_size)) {
5524 return error::kOutOfBounds;
5530 "// uint32_t data_size = 0; // TODO(gman): get correct size!\n")
5532 def WriteImmediateCmdGetTotalSize(self
, func
, f
):
5533 """Overrriden from TypeHandler."""
5536 def WriteImmediateCmdSizeTest(self
, func
, f
):
5537 """Overrriden from TypeHandler."""
5538 f
.write(" EXPECT_EQ(sizeof(cmd), total_size);\n")
5540 def WriteImmediateCmdInit(self
, func
, f
):
5541 """Overrriden from TypeHandler."""
5542 f
.write(" void Init(%s) {\n" % func
.MakeTypedCmdArgString("_"))
5543 self
.WriteImmediateCmdGetTotalSize(func
, f
)
5544 f
.write(" SetHeader(total_size);\n")
5545 args
= func
.GetCmdArgs()
5547 f
.write(" %s = _%s;\n" % (arg
.name
, arg
.name
))
5551 def WriteImmediateCmdSet(self
, func
, f
):
5552 """Overrriden from TypeHandler."""
5553 copy_args
= func
.MakeCmdArgString("_", False)
5554 f
.write(" void* Set(void* cmd%s) {\n" %
5555 func
.MakeTypedCmdArgString("_", True))
5556 self
.WriteImmediateCmdGetTotalSize(func
, f
)
5557 f
.write(" static_cast<ValueType*>(cmd)->Init(%s);\n" % copy_args
)
5558 f
.write(" return NextImmediateCmdAddressTotalSize<ValueType>("
5559 "cmd, total_size);\n")
5563 def WriteImmediateFormatTest(self
, func
, f
):
5564 """Overrriden from TypeHandler."""
5565 # TODO(gman): Remove this exception.
5566 f
.write("// TODO(gman): Implement test for %s\n" % func
.name
)
5569 def WriteServiceUnitTest(self
, func
, f
, *extras
):
5570 """Overrriden from TypeHandler."""
5571 f
.write("// TODO(gman): %s\n\n" % func
.name
)
5573 def WriteImmediateServiceUnitTest(self
, func
, f
, *extras
):
5574 """Overrriden from TypeHandler."""
5575 f
.write("// TODO(gman): %s\n\n" % func
.name
)
5577 def WriteBucketServiceImplementation(self
, func
, f
):
5578 """Overrriden from TypeHandler."""
5579 if ((not func
.name
== 'CompressedTexSubImage2DBucket') and
5580 (not func
.name
== 'CompressedTexSubImage3DBucket')):
5581 TypeHandler
.WriteBucketServiceImplemenation(self
, func
, f
)
5584 class BindHandler(TypeHandler
):
5585 """Handler for glBind___ type functions."""
5588 TypeHandler
.__init
__(self
)
5590 def WriteServiceUnitTest(self
, func
, f
, *extras
):
5591 """Overrriden from TypeHandler."""
5593 if len(func
.GetOriginalArgs()) == 1:
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) {
5618 EXPECT_CALL(*gl_, %(gl_func_name)s(kNewServiceId));
5619 EXPECT_CALL(*gl_, %(gl_gen_func_name)s(1, _))
5620 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
5621 SpecializedSetup<cmds::%(name)s, 0>(true);
5623 cmd.Init(kNewClientId);
5624 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5625 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5626 EXPECT_TRUE(Get%(resource_type)s(kNewClientId) != NULL);
5629 self
.WriteValidUnitTest(func
, f
, valid_test
, {
5630 'resource_type': func
.GetOriginalArgs()[0].resource_type
,
5631 'gl_gen_func_name': func
.GetInfo("gen_func"),
5635 TEST_P(%(test_name)s, %(name)sValidArgs) {
5636 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
5637 SpecializedSetup<cmds::%(name)s, 0>(true);
5639 cmd.Init(%(args)s);"""
5642 decoder_->set_unsafe_es3_apis_enabled(true);
5643 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5644 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5645 decoder_->set_unsafe_es3_apis_enabled(false);
5646 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));
5651 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5652 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5655 if func
.GetInfo("gen_func"):
5657 TEST_P(%(test_name)s, %(name)sValidArgsNewId) {
5659 %(gl_func_name)s(%(gl_args_with_new_id)s));
5660 EXPECT_CALL(*gl_, %(gl_gen_func_name)s(1, _))
5661 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
5662 SpecializedSetup<cmds::%(name)s, 0>(true);
5664 cmd.Init(%(args_with_new_id)s);"""
5667 decoder_->set_unsafe_es3_apis_enabled(true);
5668 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5669 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5670 EXPECT_TRUE(Get%(resource_type)s(kNewClientId) != NULL);
5671 decoder_->set_unsafe_es3_apis_enabled(false);
5672 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));
5677 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5678 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5679 EXPECT_TRUE(Get%(resource_type)s(kNewClientId) != NULL);
5683 gl_args_with_new_id
= []
5684 args_with_new_id
= []
5685 for arg
in func
.GetOriginalArgs():
5686 if hasattr(arg
, 'resource_type'):
5687 gl_args_with_new_id
.append('kNewServiceId')
5688 args_with_new_id
.append('kNewClientId')
5690 gl_args_with_new_id
.append(arg
.GetValidGLArg(func
))
5691 args_with_new_id
.append(arg
.GetValidArg(func
))
5692 self
.WriteValidUnitTest(func
, f
, valid_test
, {
5693 'args_with_new_id': ", ".join(args_with_new_id
),
5694 'gl_args_with_new_id': ", ".join(gl_args_with_new_id
),
5695 'resource_type': func
.GetResourceIdArg().resource_type
,
5696 'gl_gen_func_name': func
.GetInfo("gen_func"),
5700 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
5701 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
5702 SpecializedSetup<cmds::%(name)s, 0>(false);
5705 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
5708 self
.WriteInvalidUnitTest(func
, f
, invalid_test
, *extras
)
5710 def WriteGLES2Implementation(self
, func
, f
):
5711 """Writes the GLES2 Implemention."""
5713 impl_func
= func
.GetInfo('impl_func')
5714 impl_decl
= func
.GetInfo('impl_decl')
5716 if (func
.can_auto_generate
and
5717 (impl_func
== None or impl_func
== True) and
5718 (impl_decl
== None or impl_decl
== True)):
5720 f
.write("%s GLES2Implementation::%s(%s) {\n" %
5721 (func
.return_type
, func
.original_name
,
5722 func
.MakeTypedOriginalArgString("")))
5723 f
.write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
5724 func
.WriteDestinationInitalizationValidation(f
)
5725 self
.WriteClientGLCallLog(func
, f
)
5726 for arg
in func
.GetOriginalArgs():
5727 arg
.WriteClientSideValidationCode(f
, func
)
5729 code
= """ if (Is%(type)sReservedId(%(id)s)) {
5730 SetGLError(GL_INVALID_OPERATION, "%(name)s\", \"%(id)s reserved id");
5733 %(name)sHelper(%(arg_string)s);
5738 name_arg
= func
.GetResourceIdArg()
5741 'arg_string': func
.MakeOriginalArgString(""),
5742 'id': name_arg
.name
,
5743 'type': name_arg
.resource_type
,
5744 'lc_type': name_arg
.resource_type
.lower(),
5747 def WriteGLES2ImplementationUnitTest(self
, func
, f
):
5748 """Overrriden from TypeHandler."""
5749 client_test
= func
.GetInfo('client_test')
5750 if client_test
== False:
5753 TEST_F(GLES2ImplementationTest, %(name)s) {
5758 expected.cmd.Init(%(cmd_args)s);
5760 gl_->%(name)s(%(args)s);
5761 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));"""
5762 if not func
.IsUnsafe():
5765 gl_->%(name)s(%(args)s);
5766 EXPECT_TRUE(NoCommandsWritten());"""
5771 arg
.GetValidClientSideCmdArg(func
) for arg
in func
.GetCmdArgs()
5774 arg
.GetValidClientSideArg(func
) for arg
in func
.GetOriginalArgs()
5779 'args': ", ".join(gl_arg_strings
),
5780 'cmd_args': ", ".join(cmd_arg_strings
),
5784 class GENnHandler(TypeHandler
):
5785 """Handler for glGen___ type functions."""
5788 TypeHandler
.__init
__(self
)
5790 def InitFunction(self
, func
):
5791 """Overrriden from TypeHandler."""
5794 def WriteGetDataSizeCode(self
, func
, f
):
5795 """Overrriden from TypeHandler."""
5796 code
= """ uint32_t data_size;
5797 if (!SafeMultiplyUint32(n, sizeof(GLuint), &data_size)) {
5798 return error::kOutOfBounds;
5803 def WriteHandlerImplementation (self
, func
, f
):
5804 """Overrriden from TypeHandler."""
5805 f
.write(" if (!%sHelper(n, %s)) {\n"
5806 " return error::kInvalidArguments;\n"
5808 (func
.name
, func
.GetLastOriginalArg().name
))
5810 def WriteImmediateHandlerImplementation(self
, func
, f
):
5811 """Overrriden from TypeHandler."""
5813 f
.write(""" for (GLsizei ii = 0; ii < n; ++ii) {
5814 if (group_->Get%(resource_name)sServiceId(%(last_arg_name)s[ii], NULL)) {
5815 return error::kInvalidArguments;
5818 scoped_ptr<GLuint[]> service_ids(new GLuint[n]);
5819 gl%(func_name)s(n, service_ids.get());
5820 for (GLsizei ii = 0; ii < n; ++ii) {
5821 group_->Add%(resource_name)sId(%(last_arg_name)s[ii], service_ids[ii]);
5823 """ % { 'func_name': func
.original_name
,
5824 'last_arg_name': func
.GetLastOriginalArg().name
,
5825 'resource_name': func
.GetInfo('resource_type') })
5827 f
.write(" if (!%sHelper(n, %s)) {\n"
5828 " return error::kInvalidArguments;\n"
5830 (func
.original_name
, func
.GetLastOriginalArg().name
))
5832 def WriteGLES2Implementation(self
, func
, f
):
5833 """Overrriden from TypeHandler."""
5834 log_code
= (""" GPU_CLIENT_LOG_CODE_BLOCK({
5835 for (GLsizei i = 0; i < n; ++i) {
5836 GPU_CLIENT_LOG(" " << i << ": " << %s[i]);
5838 });""" % func
.GetOriginalArgs()[1].name
)
5840 'log_code': log_code
,
5841 'return_type': func
.return_type
,
5842 'name': func
.original_name
,
5843 'typed_args': func
.MakeTypedOriginalArgString(""),
5844 'args': func
.MakeOriginalArgString(""),
5845 'resource_types': func
.GetInfo('resource_types'),
5846 'count_name': func
.GetOriginalArgs()[0].name
,
5849 "%(return_type)s GLES2Implementation::%(name)s(%(typed_args)s) {\n" %
5851 func
.WriteDestinationInitalizationValidation(f
)
5852 self
.WriteClientGLCallLog(func
, f
)
5853 for arg
in func
.GetOriginalArgs():
5854 arg
.WriteClientSideValidationCode(f
, func
)
5855 not_shared
= func
.GetInfo('not_shared')
5859 """ IdAllocator* id_allocator = GetIdAllocator(id_namespaces::k%s);
5860 for (GLsizei ii = 0; ii < n; ++ii)
5861 %s[ii] = id_allocator->AllocateID();""" %
5862 (func
.GetInfo('resource_types'), func
.GetOriginalArgs()[1].name
))
5864 alloc_code
= (""" GetIdHandler(id_namespaces::k%(resource_types)s)->
5865 MakeIds(this, 0, %(args)s);""" % args
)
5866 args
['alloc_code'] = alloc_code
5868 code
= """ GPU_CLIENT_SINGLE_THREAD_CHECK();
5870 %(name)sHelper(%(args)s);
5871 helper_->%(name)sImmediate(%(args)s);
5872 if (share_group_->bind_generates_resource())
5873 helper_->CommandBufferHelper::Flush();
5879 f
.write(code
% args
)
5881 def WriteGLES2ImplementationUnitTest(self
, func
, f
):
5882 """Overrriden from TypeHandler."""
5884 TEST_F(GLES2ImplementationTest, %(name)s) {
5885 GLuint ids[2] = { 0, };
5887 cmds::%(name)sImmediate gen;
5891 expected.gen.Init(arraysize(ids), &ids[0]);
5892 expected.data[0] = k%(types)sStartId;
5893 expected.data[1] = k%(types)sStartId + 1;
5894 gl_->%(name)s(arraysize(ids), &ids[0]);
5895 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
5896 EXPECT_EQ(k%(types)sStartId, ids[0]);
5897 EXPECT_EQ(k%(types)sStartId + 1, ids[1]);
5902 'types': func
.GetInfo('resource_types'),
5905 def WriteServiceUnitTest(self
, func
, f
, *extras
):
5906 """Overrriden from TypeHandler."""
5908 TEST_P(%(test_name)s, %(name)sValidArgs) {
5909 EXPECT_CALL(*gl_, %(gl_func_name)s(1, _))
5910 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
5911 GetSharedMemoryAs<GLuint*>()[0] = kNewClientId;
5912 SpecializedSetup<cmds::%(name)s, 0>(true);
5915 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5916 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
5920 EXPECT_TRUE(Get%(resource_name)sServiceId(kNewClientId, &service_id));
5921 EXPECT_EQ(kNewServiceId, service_id)
5926 EXPECT_TRUE(Get%(resource_name)s(kNewClientId, &service_id) != NULL);
5929 self
.WriteValidUnitTest(func
, f
, valid_test
, {
5930 'resource_name': func
.GetInfo('resource_type'),
5933 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
5934 EXPECT_CALL(*gl_, %(gl_func_name)s(_, _)).Times(0);
5935 GetSharedMemoryAs<GLuint*>()[0] = client_%(resource_name)s_id_;
5936 SpecializedSetup<cmds::%(name)s, 0>(false);
5939 EXPECT_EQ(error::kInvalidArguments, ExecuteCmd(cmd));
5942 self
.WriteValidUnitTest(func
, f
, invalid_test
, {
5943 'resource_name': func
.GetInfo('resource_type').lower(),
5946 def WriteImmediateServiceUnitTest(self
, func
, f
, *extras
):
5947 """Overrriden from TypeHandler."""
5949 TEST_P(%(test_name)s, %(name)sValidArgs) {
5950 EXPECT_CALL(*gl_, %(gl_func_name)s(1, _))
5951 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
5952 cmds::%(name)s* cmd = GetImmediateAs<cmds::%(name)s>();
5953 GLuint temp = kNewClientId;
5954 SpecializedSetup<cmds::%(name)s, 0>(true);"""
5957 decoder_->set_unsafe_es3_apis_enabled(true);"""
5959 cmd->Init(1, &temp);
5960 EXPECT_EQ(error::kNoError,
5961 ExecuteImmediateCmd(*cmd, sizeof(temp)));
5962 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
5966 EXPECT_TRUE(Get%(resource_name)sServiceId(kNewClientId, &service_id));
5967 EXPECT_EQ(kNewServiceId, service_id);
5968 decoder_->set_unsafe_es3_apis_enabled(false);
5969 EXPECT_EQ(error::kUnknownCommand,
5970 ExecuteImmediateCmd(*cmd, sizeof(temp)));
5975 EXPECT_TRUE(Get%(resource_name)s(kNewClientId) != NULL);
5978 self
.WriteValidUnitTest(func
, f
, valid_test
, {
5979 'resource_name': func
.GetInfo('resource_type'),
5982 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
5983 EXPECT_CALL(*gl_, %(gl_func_name)s(_, _)).Times(0);
5984 cmds::%(name)s* cmd = GetImmediateAs<cmds::%(name)s>();
5985 SpecializedSetup<cmds::%(name)s, 0>(false);
5986 cmd->Init(1, &client_%(resource_name)s_id_);"""
5989 decoder_->set_unsafe_es3_apis_enabled(true);
5990 EXPECT_EQ(error::kInvalidArguments,
5991 ExecuteImmediateCmd(*cmd, sizeof(&client_%(resource_name)s_id_)));
5992 decoder_->set_unsafe_es3_apis_enabled(false);
5997 EXPECT_EQ(error::kInvalidArguments,
5998 ExecuteImmediateCmd(*cmd, sizeof(&client_%(resource_name)s_id_)));
6001 self
.WriteValidUnitTest(func
, f
, invalid_test
, {
6002 'resource_name': func
.GetInfo('resource_type').lower(),
6005 def WriteImmediateCmdComputeSize(self
, func
, f
):
6006 """Overrriden from TypeHandler."""
6007 f
.write(" static uint32_t ComputeDataSize(GLsizei n) {\n")
6009 " return static_cast<uint32_t>(sizeof(GLuint) * n); // NOLINT\n")
6012 f
.write(" static uint32_t ComputeSize(GLsizei n) {\n")
6013 f
.write(" return static_cast<uint32_t>(\n")
6014 f
.write(" sizeof(ValueType) + ComputeDataSize(n)); // NOLINT\n")
6018 def WriteImmediateCmdSetHeader(self
, func
, f
):
6019 """Overrriden from TypeHandler."""
6020 f
.write(" void SetHeader(GLsizei n) {\n")
6021 f
.write(" header.SetCmdByTotalSize<ValueType>(ComputeSize(n));\n")
6025 def WriteImmediateCmdInit(self
, func
, f
):
6026 """Overrriden from TypeHandler."""
6027 last_arg
= func
.GetLastOriginalArg()
6028 f
.write(" void Init(%s, %s _%s) {\n" %
6029 (func
.MakeTypedCmdArgString("_"),
6030 last_arg
.type, last_arg
.name
))
6031 f
.write(" SetHeader(_n);\n")
6032 args
= func
.GetCmdArgs()
6034 f
.write(" %s = _%s;\n" % (arg
.name
, arg
.name
))
6035 f
.write(" memcpy(ImmediateDataAddress(this),\n")
6036 f
.write(" _%s, ComputeDataSize(_n));\n" % last_arg
.name
)
6040 def WriteImmediateCmdSet(self
, func
, f
):
6041 """Overrriden from TypeHandler."""
6042 last_arg
= func
.GetLastOriginalArg()
6043 copy_args
= func
.MakeCmdArgString("_", False)
6044 f
.write(" void* Set(void* cmd%s, %s _%s) {\n" %
6045 (func
.MakeTypedCmdArgString("_", True),
6046 last_arg
.type, last_arg
.name
))
6047 f
.write(" static_cast<ValueType*>(cmd)->Init(%s, _%s);\n" %
6048 (copy_args
, last_arg
.name
))
6049 f
.write(" const uint32_t size = ComputeSize(_n);\n")
6050 f
.write(" return NextImmediateCmdAddressTotalSize<ValueType>("
6055 def WriteImmediateCmdHelper(self
, func
, f
):
6056 """Overrriden from TypeHandler."""
6057 code
= """ void %(name)s(%(typed_args)s) {
6058 const uint32_t size = gles2::cmds::%(name)s::ComputeSize(n);
6059 gles2::cmds::%(name)s* c =
6060 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
6069 "typed_args": func
.MakeTypedOriginalArgString(""),
6070 "args": func
.MakeOriginalArgString(""),
6073 def WriteImmediateFormatTest(self
, func
, f
):
6074 """Overrriden from TypeHandler."""
6075 f
.write("TEST_F(GLES2FormatTest, %s) {\n" % func
.name
)
6076 f
.write(" static GLuint ids[] = { 12, 23, 34, };\n")
6077 f
.write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
6078 (func
.name
, func
.name
))
6079 f
.write(" void* next_cmd = cmd.Set(\n")
6080 f
.write(" &cmd, static_cast<GLsizei>(arraysize(ids)), ids);\n")
6081 f
.write(" EXPECT_EQ(static_cast<uint32_t>(cmds::%s::kCmdId),\n" %
6083 f
.write(" cmd.header.command);\n")
6084 f
.write(" EXPECT_EQ(sizeof(cmd) +\n")
6085 f
.write(" RoundSizeToMultipleOfEntries(cmd.n * 4u),\n")
6086 f
.write(" cmd.header.size * 4u);\n")
6087 f
.write(" EXPECT_EQ(static_cast<GLsizei>(arraysize(ids)), cmd.n);\n");
6088 f
.write(" CheckBytesWrittenMatchesExpectedSize(\n")
6089 f
.write(" next_cmd, sizeof(cmd) +\n")
6090 f
.write(" RoundSizeToMultipleOfEntries(arraysize(ids) * 4u));\n")
6091 f
.write(" // TODO(gman): Check that ids were inserted;\n")
6096 class CreateHandler(TypeHandler
):
6097 """Handler for glCreate___ type functions."""
6100 TypeHandler
.__init
__(self
)
6102 def InitFunction(self
, func
):
6103 """Overrriden from TypeHandler."""
6104 func
.AddCmdArg(Argument("client_id", 'uint32_t'))
6106 def __GetResourceType(self
, func
):
6107 if func
.return_type
== "GLsync":
6110 return func
.name
[6:] # Create*
6112 def WriteServiceUnitTest(self
, func
, f
, *extras
):
6113 """Overrriden from TypeHandler."""
6115 TEST_P(%(test_name)s, %(name)sValidArgs) {
6116 %(id_type_cast)sEXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s))
6117 .WillOnce(Return(%(const_service_id)s));
6118 SpecializedSetup<cmds::%(name)s, 0>(true);
6120 cmd.Init(%(args)s%(comma)skNewClientId);"""
6123 decoder_->set_unsafe_es3_apis_enabled(true);"""
6125 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
6126 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
6129 %(return_type)s service_id = 0;
6130 EXPECT_TRUE(Get%(resource_type)sServiceId(kNewClientId, &service_id));
6131 EXPECT_EQ(%(const_service_id)s, service_id);
6132 decoder_->set_unsafe_es3_apis_enabled(false);
6133 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));
6138 EXPECT_TRUE(Get%(resource_type)s(kNewClientId));
6143 for arg
in func
.GetOriginalArgs():
6144 if not arg
.IsConstant():
6148 if func
.return_type
== 'GLsync':
6149 id_type_cast
= ("const GLsync kNewServiceIdGLuint = reinterpret_cast"
6150 "<GLsync>(kNewServiceId);\n ")
6151 const_service_id
= "kNewServiceIdGLuint"
6154 const_service_id
= "kNewServiceId"
6155 self
.WriteValidUnitTest(func
, f
, valid_test
, {
6157 'resource_type': self
.__GetResourceType
(func
),
6158 'return_type': func
.return_type
,
6159 'id_type_cast': id_type_cast
,
6160 'const_service_id': const_service_id
,
6163 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
6164 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
6165 SpecializedSetup<cmds::%(name)s, 0>(false);
6167 cmd.Init(%(args)s%(comma)skNewClientId);
6168 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));%(gl_error_test)s
6171 self
.WriteInvalidUnitTest(func
, f
, invalid_test
, {
6175 def WriteHandlerImplementation (self
, func
, f
):
6176 """Overrriden from TypeHandler."""
6178 code
= """ uint32_t client_id = c.client_id;
6179 %(return_type)s service_id = 0;
6180 if (group_->Get%(resource_name)sServiceId(client_id, &service_id)) {
6181 return error::kInvalidArguments;
6183 service_id = %(gl_func_name)s(%(gl_args)s);
6185 group_->Add%(resource_name)sId(client_id, service_id);
6189 code
= """ uint32_t client_id = c.client_id;
6190 if (Get%(resource_name)s(client_id)) {
6191 return error::kInvalidArguments;
6193 %(return_type)s service_id = %(gl_func_name)s(%(gl_args)s);
6195 Create%(resource_name)s(client_id, service_id%(gl_args_with_comma)s);
6199 'resource_name': self
.__GetResourceType
(func
),
6200 'return_type': func
.return_type
,
6201 'gl_func_name': func
.GetGLFunctionName(),
6202 'gl_args': func
.MakeOriginalArgString(""),
6203 'gl_args_with_comma': func
.MakeOriginalArgString("", True) })
6205 def WriteGLES2Implementation(self
, func
, f
):
6206 """Overrriden from TypeHandler."""
6207 f
.write("%s GLES2Implementation::%s(%s) {\n" %
6208 (func
.return_type
, func
.original_name
,
6209 func
.MakeTypedOriginalArgString("")))
6210 f
.write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
6211 func
.WriteDestinationInitalizationValidation(f
)
6212 self
.WriteClientGLCallLog(func
, f
)
6213 for arg
in func
.GetOriginalArgs():
6214 arg
.WriteClientSideValidationCode(f
, func
)
6215 f
.write(" GLuint client_id;\n")
6216 if func
.return_type
== "GLsync":
6218 " GetIdHandler(id_namespaces::kSyncs)->\n")
6221 " GetIdHandler(id_namespaces::kProgramsAndShaders)->\n")
6222 f
.write(" MakeIds(this, 0, 1, &client_id);\n")
6223 f
.write(" helper_->%s(%s);\n" %
6224 (func
.name
, func
.MakeCmdArgString("")))
6225 f
.write(' GPU_CLIENT_LOG("returned " << client_id);\n')
6226 f
.write(" CheckGLError();\n")
6227 if func
.return_type
== "GLsync":
6228 f
.write(" return reinterpret_cast<GLsync>(client_id);\n")
6230 f
.write(" return client_id;\n")
6235 class DeleteHandler(TypeHandler
):
6236 """Handler for glDelete___ single resource type functions."""
6239 TypeHandler
.__init
__(self
)
6241 def WriteServiceImplementation(self
, func
, f
):
6242 """Overrriden from TypeHandler."""
6244 TypeHandler
.WriteServiceImplementation(self
, func
, f
)
6245 # HandleDeleteShader and HandleDeleteProgram are manually written.
6248 def WriteGLES2Implementation(self
, func
, f
):
6249 """Overrriden from TypeHandler."""
6250 f
.write("%s GLES2Implementation::%s(%s) {\n" %
6251 (func
.return_type
, func
.original_name
,
6252 func
.MakeTypedOriginalArgString("")))
6253 f
.write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
6254 func
.WriteDestinationInitalizationValidation(f
)
6255 self
.WriteClientGLCallLog(func
, f
)
6256 for arg
in func
.GetOriginalArgs():
6257 arg
.WriteClientSideValidationCode(f
, func
)
6259 " GPU_CLIENT_DCHECK(%s != 0);\n" % func
.GetOriginalArgs()[-1].name
)
6260 f
.write(" %sHelper(%s);\n" %
6261 (func
.original_name
, func
.GetOriginalArgs()[-1].name
))
6262 f
.write(" CheckGLError();\n")
6266 def WriteHandlerImplementation (self
, func
, f
):
6267 """Overrriden from TypeHandler."""
6268 assert len(func
.GetOriginalArgs()) == 1
6269 arg
= func
.GetOriginalArgs()[0]
6271 f
.write(""" %(arg_type)s service_id = 0;
6272 if (group_->Get%(resource_type)sServiceId(%(arg_name)s, &service_id)) {
6273 glDelete%(resource_type)s(service_id);
6274 group_->Remove%(resource_type)sId(%(arg_name)s);
6277 GL_INVALID_VALUE, "gl%(func_name)s", "unknown %(arg_name)s");
6279 """ % { 'resource_type': func
.GetInfo('resource_type'),
6280 'arg_name': arg
.name
,
6281 'arg_type': arg
.type,
6282 'func_name': func
.original_name
})
6284 f
.write(" %sHelper(%s);\n" % (func
.original_name
, arg
.name
))
6286 class DELnHandler(TypeHandler
):
6287 """Handler for glDelete___ type functions."""
6290 TypeHandler
.__init
__(self
)
6292 def WriteGetDataSizeCode(self
, func
, f
):
6293 """Overrriden from TypeHandler."""
6294 code
= """ uint32_t data_size;
6295 if (!SafeMultiplyUint32(n, sizeof(GLuint), &data_size)) {
6296 return error::kOutOfBounds;
6301 def WriteGLES2ImplementationUnitTest(self
, func
, f
):
6302 """Overrriden from TypeHandler."""
6304 TEST_F(GLES2ImplementationTest, %(name)s) {
6305 GLuint ids[2] = { k%(types)sStartId, k%(types)sStartId + 1 };
6307 cmds::%(name)sImmediate del;
6311 expected.del.Init(arraysize(ids), &ids[0]);
6312 expected.data[0] = k%(types)sStartId;
6313 expected.data[1] = k%(types)sStartId + 1;
6314 gl_->%(name)s(arraysize(ids), &ids[0]);
6315 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
6320 'types': func
.GetInfo('resource_types'),
6323 def WriteServiceUnitTest(self
, func
, f
, *extras
):
6324 """Overrriden from TypeHandler."""
6326 TEST_P(%(test_name)s, %(name)sValidArgs) {
6329 %(gl_func_name)s(1, Pointee(kService%(upper_resource_name)sId)))
6331 GetSharedMemoryAs<GLuint*>()[0] = client_%(resource_name)s_id_;
6332 SpecializedSetup<cmds::%(name)s, 0>(true);
6335 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
6336 EXPECT_EQ(GL_NO_ERROR, GetGLError());
6338 Get%(upper_resource_name)s(client_%(resource_name)s_id_) == NULL);
6341 self
.WriteValidUnitTest(func
, f
, valid_test
, {
6342 'resource_name': func
.GetInfo('resource_type').lower(),
6343 'upper_resource_name': func
.GetInfo('resource_type'),
6346 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
6347 GetSharedMemoryAs<GLuint*>()[0] = kInvalidClientId;
6348 SpecializedSetup<cmds::%(name)s, 0>(false);
6351 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
6354 self
.WriteValidUnitTest(func
, f
, invalid_test
, *extras
)
6356 def WriteImmediateServiceUnitTest(self
, func
, f
, *extras
):
6357 """Overrriden from TypeHandler."""
6359 TEST_P(%(test_name)s, %(name)sValidArgs) {
6362 %(gl_func_name)s(1, Pointee(kService%(upper_resource_name)sId)))
6364 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
6365 SpecializedSetup<cmds::%(name)s, 0>(true);
6366 cmd.Init(1, &client_%(resource_name)s_id_);"""
6369 decoder_->set_unsafe_es3_apis_enabled(true);"""
6371 EXPECT_EQ(error::kNoError,
6372 ExecuteImmediateCmd(cmd, sizeof(client_%(resource_name)s_id_)));
6373 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
6376 EXPECT_FALSE(Get%(upper_resource_name)sServiceId(
6377 client_%(resource_name)s_id_, NULL));
6378 decoder_->set_unsafe_es3_apis_enabled(false);
6379 EXPECT_EQ(error::kUnknownCommand,
6380 ExecuteImmediateCmd(cmd, sizeof(client_%(resource_name)s_id_)));
6386 Get%(upper_resource_name)s(client_%(resource_name)s_id_) == NULL);
6389 self
.WriteValidUnitTest(func
, f
, valid_test
, {
6390 'resource_name': func
.GetInfo('resource_type').lower(),
6391 'upper_resource_name': func
.GetInfo('resource_type'),
6394 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
6395 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
6396 SpecializedSetup<cmds::%(name)s, 0>(false);
6397 GLuint temp = kInvalidClientId;
6398 cmd.Init(1, &temp);"""
6401 decoder_->set_unsafe_es3_apis_enabled(true);
6402 EXPECT_EQ(error::kNoError,
6403 ExecuteImmediateCmd(cmd, sizeof(temp)));
6404 decoder_->set_unsafe_es3_apis_enabled(false);
6405 EXPECT_EQ(error::kUnknownCommand,
6406 ExecuteImmediateCmd(cmd, sizeof(temp)));
6411 EXPECT_EQ(error::kNoError,
6412 ExecuteImmediateCmd(cmd, sizeof(temp)));
6415 self
.WriteValidUnitTest(func
, f
, invalid_test
, *extras
)
6417 def WriteHandlerImplementation (self
, func
, f
):
6418 """Overrriden from TypeHandler."""
6419 f
.write(" %sHelper(n, %s);\n" %
6420 (func
.name
, func
.GetLastOriginalArg().name
))
6422 def WriteImmediateHandlerImplementation (self
, func
, f
):
6423 """Overrriden from TypeHandler."""
6425 f
.write(""" for (GLsizei ii = 0; ii < n; ++ii) {
6426 GLuint service_id = 0;
6427 if (group_->Get%(resource_type)sServiceId(
6428 %(last_arg_name)s[ii], &service_id)) {
6429 glDelete%(resource_type)ss(1, &service_id);
6430 group_->Remove%(resource_type)sId(%(last_arg_name)s[ii]);
6433 """ % { 'resource_type': func
.GetInfo('resource_type'),
6434 'last_arg_name': func
.GetLastOriginalArg().name
})
6436 f
.write(" %sHelper(n, %s);\n" %
6437 (func
.original_name
, func
.GetLastOriginalArg().name
))
6439 def WriteGLES2Implementation(self
, func
, f
):
6440 """Overrriden from TypeHandler."""
6441 impl_decl
= func
.GetInfo('impl_decl')
6442 if impl_decl
== None or impl_decl
== True:
6444 'return_type': func
.return_type
,
6445 'name': func
.original_name
,
6446 'typed_args': func
.MakeTypedOriginalArgString(""),
6447 'args': func
.MakeOriginalArgString(""),
6448 'resource_type': func
.GetInfo('resource_type').lower(),
6449 'count_name': func
.GetOriginalArgs()[0].name
,
6452 "%(return_type)s GLES2Implementation::%(name)s(%(typed_args)s) {\n" %
6454 f
.write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
6455 func
.WriteDestinationInitalizationValidation(f
)
6456 self
.WriteClientGLCallLog(func
, f
)
6457 f
.write(""" GPU_CLIENT_LOG_CODE_BLOCK({
6458 for (GLsizei i = 0; i < n; ++i) {
6459 GPU_CLIENT_LOG(" " << i << ": " << %s[i]);
6462 """ % func
.GetOriginalArgs()[1].name
)
6463 f
.write(""" GPU_CLIENT_DCHECK_CODE_BLOCK({
6464 for (GLsizei i = 0; i < n; ++i) {
6468 """ % func
.GetOriginalArgs()[1].name
)
6469 for arg
in func
.GetOriginalArgs():
6470 arg
.WriteClientSideValidationCode(f
, func
)
6471 code
= """ %(name)sHelper(%(args)s);
6476 f
.write(code
% args
)
6478 def WriteImmediateCmdComputeSize(self
, func
, f
):
6479 """Overrriden from TypeHandler."""
6480 f
.write(" static uint32_t ComputeDataSize(GLsizei n) {\n")
6482 " return static_cast<uint32_t>(sizeof(GLuint) * n); // NOLINT\n")
6485 f
.write(" static uint32_t ComputeSize(GLsizei n) {\n")
6486 f
.write(" return static_cast<uint32_t>(\n")
6487 f
.write(" sizeof(ValueType) + ComputeDataSize(n)); // NOLINT\n")
6491 def WriteImmediateCmdSetHeader(self
, func
, f
):
6492 """Overrriden from TypeHandler."""
6493 f
.write(" void SetHeader(GLsizei n) {\n")
6494 f
.write(" header.SetCmdByTotalSize<ValueType>(ComputeSize(n));\n")
6498 def WriteImmediateCmdInit(self
, func
, f
):
6499 """Overrriden from TypeHandler."""
6500 last_arg
= func
.GetLastOriginalArg()
6501 f
.write(" void Init(%s, %s _%s) {\n" %
6502 (func
.MakeTypedCmdArgString("_"),
6503 last_arg
.type, last_arg
.name
))
6504 f
.write(" SetHeader(_n);\n")
6505 args
= func
.GetCmdArgs()
6507 f
.write(" %s = _%s;\n" % (arg
.name
, arg
.name
))
6508 f
.write(" memcpy(ImmediateDataAddress(this),\n")
6509 f
.write(" _%s, ComputeDataSize(_n));\n" % last_arg
.name
)
6513 def WriteImmediateCmdSet(self
, func
, f
):
6514 """Overrriden from TypeHandler."""
6515 last_arg
= func
.GetLastOriginalArg()
6516 copy_args
= func
.MakeCmdArgString("_", False)
6517 f
.write(" void* Set(void* cmd%s, %s _%s) {\n" %
6518 (func
.MakeTypedCmdArgString("_", True),
6519 last_arg
.type, last_arg
.name
))
6520 f
.write(" static_cast<ValueType*>(cmd)->Init(%s, _%s);\n" %
6521 (copy_args
, last_arg
.name
))
6522 f
.write(" const uint32_t size = ComputeSize(_n);\n")
6523 f
.write(" return NextImmediateCmdAddressTotalSize<ValueType>("
6528 def WriteImmediateCmdHelper(self
, func
, f
):
6529 """Overrriden from TypeHandler."""
6530 code
= """ void %(name)s(%(typed_args)s) {
6531 const uint32_t size = gles2::cmds::%(name)s::ComputeSize(n);
6532 gles2::cmds::%(name)s* c =
6533 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
6542 "typed_args": func
.MakeTypedOriginalArgString(""),
6543 "args": func
.MakeOriginalArgString(""),
6546 def WriteImmediateFormatTest(self
, func
, f
):
6547 """Overrriden from TypeHandler."""
6548 f
.write("TEST_F(GLES2FormatTest, %s) {\n" % func
.name
)
6549 f
.write(" static GLuint ids[] = { 12, 23, 34, };\n")
6550 f
.write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
6551 (func
.name
, func
.name
))
6552 f
.write(" void* next_cmd = cmd.Set(\n")
6553 f
.write(" &cmd, static_cast<GLsizei>(arraysize(ids)), ids);\n")
6554 f
.write(" EXPECT_EQ(static_cast<uint32_t>(cmds::%s::kCmdId),\n" %
6556 f
.write(" cmd.header.command);\n")
6557 f
.write(" EXPECT_EQ(sizeof(cmd) +\n")
6558 f
.write(" RoundSizeToMultipleOfEntries(cmd.n * 4u),\n")
6559 f
.write(" cmd.header.size * 4u);\n")
6560 f
.write(" EXPECT_EQ(static_cast<GLsizei>(arraysize(ids)), cmd.n);\n");
6561 f
.write(" CheckBytesWrittenMatchesExpectedSize(\n")
6562 f
.write(" next_cmd, sizeof(cmd) +\n")
6563 f
.write(" RoundSizeToMultipleOfEntries(arraysize(ids) * 4u));\n")
6564 f
.write(" // TODO(gman): Check that ids were inserted;\n")
6569 class GETnHandler(TypeHandler
):
6570 """Handler for GETn for glGetBooleanv, glGetFloatv, ... type functions."""
6573 TypeHandler
.__init
__(self
)
6575 def NeedsDataTransferFunction(self
, func
):
6576 """Overriden from TypeHandler."""
6579 def WriteServiceImplementation(self
, func
, f
):
6580 """Overrriden from TypeHandler."""
6581 self
.WriteServiceHandlerFunctionHeader(func
, f
)
6582 last_arg
= func
.GetLastOriginalArg()
6583 # All except shm_id and shm_offset.
6584 all_but_last_args
= func
.GetCmdArgs()[:-2]
6585 for arg
in all_but_last_args
:
6588 code
= """ typedef cmds::%(func_name)s::Result Result;
6589 GLsizei num_values = 0;
6590 GetNumValuesReturnedForGLGet(pname, &num_values);
6591 Result* result = GetSharedMemoryAs<Result*>(
6592 c.%(last_arg_name)s_shm_id, c.%(last_arg_name)s_shm_offset,
6593 Result::ComputeSize(num_values));
6594 %(last_arg_type)s %(last_arg_name)s = result ? result->GetData() : NULL;
6597 'last_arg_type': last_arg
.type,
6598 'last_arg_name': last_arg
.name
,
6599 'func_name': func
.name
,
6601 func
.WriteHandlerValidation(f
)
6602 code
= """ // Check that the client initialized the result.
6603 if (result->size != 0) {
6604 return error::kInvalidArguments;
6607 shadowed
= func
.GetInfo('shadowed')
6609 f
.write(' LOCAL_COPY_REAL_GL_ERRORS_TO_WRAPPER("%s");\n' % func
.name
)
6611 func
.WriteHandlerImplementation(f
)
6613 code
= """ result->SetNumResults(num_values);
6614 return error::kNoError;
6618 code
= """ GLenum error = LOCAL_PEEK_GL_ERROR("%(func_name)s");
6619 if (error == GL_NO_ERROR) {
6620 result->SetNumResults(num_values);
6622 return error::kNoError;
6626 f
.write(code
% {'func_name': func
.name
})
6628 def WriteGLES2Implementation(self
, func
, f
):
6629 """Overrriden from TypeHandler."""
6630 impl_decl
= func
.GetInfo('impl_decl')
6631 if impl_decl
== None or impl_decl
== True:
6632 f
.write("%s GLES2Implementation::%s(%s) {\n" %
6633 (func
.return_type
, func
.original_name
,
6634 func
.MakeTypedOriginalArgString("")))
6635 f
.write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
6636 func
.WriteDestinationInitalizationValidation(f
)
6637 self
.WriteClientGLCallLog(func
, f
)
6638 for arg
in func
.GetOriginalArgs():
6639 arg
.WriteClientSideValidationCode(f
, func
)
6640 all_but_last_args
= func
.GetOriginalArgs()[:-1]
6642 has_length_arg
= False
6643 for arg
in all_but_last_args
:
6644 if arg
.type == 'GLsync':
6645 args
.append('ToGLuint(%s)' % arg
.name
)
6646 elif arg
.name
.endswith('size') and arg
.type == 'GLsizei':
6648 elif arg
.name
== 'length':
6649 has_length_arg
= True
6652 args
.append(arg
.name
)
6653 arg_string
= ", ".join(args
)
6657 for arg
in func
.GetOriginalArgs() if not arg
.IsConstant()]))
6658 self
.WriteTraceEvent(func
, f
)
6659 code
= """ if (%(func_name)sHelper(%(all_arg_string)s)) {
6662 typedef cmds::%(func_name)s::Result Result;
6663 Result* result = GetResultAs<Result*>();
6667 result->SetNumResults(0);
6668 helper_->%(func_name)s(%(arg_string)s,
6669 GetResultShmId(), GetResultShmOffset());
6671 result->CopyResult(%(last_arg_name)s);
6672 GPU_CLIENT_LOG_CODE_BLOCK({
6673 for (int32_t i = 0; i < result->GetNumResults(); ++i) {
6674 GPU_CLIENT_LOG(" " << i << ": " << result->GetData()[i]);
6680 *length = result->GetNumResults();
6687 'func_name': func
.name
,
6688 'arg_string': arg_string
,
6689 'all_arg_string': all_arg_string
,
6690 'last_arg_name': func
.GetLastOriginalArg().name
,
6693 def WriteGLES2ImplementationUnitTest(self
, func
, f
):
6694 """Writes the GLES2 Implemention unit test."""
6696 TEST_F(GLES2ImplementationTest, %(name)s) {
6700 typedef cmds::%(name)s::Result::Type ResultType;
6701 ResultType result = 0;
6703 ExpectedMemoryInfo result1 = GetExpectedResultMemory(
6704 sizeof(uint32_t) + sizeof(ResultType));
6705 expected.cmd.Init(%(cmd_args)s, result1.id, result1.offset);
6706 EXPECT_CALL(*command_buffer(), OnFlush())
6707 .WillOnce(SetMemory(result1.ptr, SizedResultHelper<ResultType>(1)))
6708 .RetiresOnSaturation();
6709 gl_->%(name)s(%(args)s, &result);
6710 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
6711 EXPECT_EQ(static_cast<ResultType>(1), result);
6714 first_cmd_arg
= func
.GetCmdArgs()[0].GetValidNonCachedClientSideCmdArg(func
)
6715 if not first_cmd_arg
:
6718 first_gl_arg
= func
.GetOriginalArgs()[0].GetValidNonCachedClientSideArg(
6721 cmd_arg_strings
= [first_cmd_arg
]
6722 for arg
in func
.GetCmdArgs()[1:-2]:
6723 cmd_arg_strings
.append(arg
.GetValidClientSideCmdArg(func
))
6724 gl_arg_strings
= [first_gl_arg
]
6725 for arg
in func
.GetOriginalArgs()[1:-1]:
6726 gl_arg_strings
.append(arg
.GetValidClientSideArg(func
))
6730 'args': ", ".join(gl_arg_strings
),
6731 'cmd_args': ", ".join(cmd_arg_strings
),
6734 def WriteServiceUnitTest(self
, func
, f
, *extras
):
6735 """Overrriden from TypeHandler."""
6737 TEST_P(%(test_name)s, %(name)sValidArgs) {
6738 EXPECT_CALL(*gl_, GetError())
6739 .WillOnce(Return(GL_NO_ERROR))
6740 .WillOnce(Return(GL_NO_ERROR))
6741 .RetiresOnSaturation();
6742 SpecializedSetup<cmds::%(name)s, 0>(true);
6743 typedef cmds::%(name)s::Result Result;
6744 Result* result = static_cast<Result*>(shared_memory_address_);
6745 EXPECT_CALL(*gl_, %(gl_func_name)s(%(local_gl_args)s));
6748 cmd.Init(%(cmd_args)s);"""
6751 decoder_->set_unsafe_es3_apis_enabled(true);"""
6753 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
6754 EXPECT_EQ(decoder_->GetGLES2Util()->GLGetNumValuesReturned(
6756 result->GetNumResults());
6757 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
6760 decoder_->set_unsafe_es3_apis_enabled(false);
6761 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));"""
6766 cmd_arg_strings
= []
6768 for arg
in func
.GetOriginalArgs()[:-1]:
6769 if arg
.name
== 'length':
6770 gl_arg_value
= 'nullptr'
6771 elif arg
.name
.endswith('size'):
6772 gl_arg_value
= ("decoder_->GetGLES2Util()->GLGetNumValuesReturned(%s)" %
6774 elif arg
.type == 'GLsync':
6775 gl_arg_value
= 'reinterpret_cast<GLsync>(kServiceSyncId)'
6777 gl_arg_value
= arg
.GetValidGLArg(func
)
6778 gl_arg_strings
.append(gl_arg_value
)
6779 if arg
.name
== 'pname':
6780 valid_pname
= gl_arg_value
6781 if arg
.name
.endswith('size') or arg
.name
== 'length':
6783 if arg
.type == 'GLsync':
6784 arg_value
= 'client_sync_id_'
6786 arg_value
= arg
.GetValidArg(func
)
6787 cmd_arg_strings
.append(arg_value
)
6788 if func
.GetInfo('gl_test_func') == 'glGetIntegerv':
6789 gl_arg_strings
.append("_")
6791 gl_arg_strings
.append("result->GetData()")
6792 cmd_arg_strings
.append("shared_memory_id_")
6793 cmd_arg_strings
.append("shared_memory_offset_")
6795 self
.WriteValidUnitTest(func
, f
, valid_test
, {
6796 'local_gl_args': ", ".join(gl_arg_strings
),
6797 'cmd_args': ", ".join(cmd_arg_strings
),
6798 'valid_pname': valid_pname
,
6801 if not func
.IsUnsafe():
6803 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
6804 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
6805 SpecializedSetup<cmds::%(name)s, 0>(false);
6806 cmds::%(name)s::Result* result =
6807 static_cast<cmds::%(name)s::Result*>(shared_memory_address_);
6811 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));
6812 EXPECT_EQ(0u, result->size);%(gl_error_test)s
6815 self
.WriteInvalidUnitTest(func
, f
, invalid_test
, *extras
)
6817 class ArrayArgTypeHandler(TypeHandler
):
6818 """Base class for type handlers that handle args that are arrays"""
6821 TypeHandler
.__init
__(self
)
6823 def GetArrayType(self
, func
):
6824 """Returns the type of the element in the element array being PUT to."""
6825 for arg
in func
.GetOriginalArgs():
6827 element_type
= arg
.GetPointedType()
6830 # Special case: array type handler is used for a function that is forwarded
6831 # to the actual array type implementation
6832 element_type
= func
.GetOriginalArgs()[-1].type
6833 assert all(arg
.type == element_type \
6834 for arg
in func
.GetOriginalArgs()[-self
.GetArrayCount(func
):])
6837 def GetArrayCount(self
, func
):
6838 """Returns the count of the elements in the array being PUT to."""
6839 return func
.GetInfo('count')
6841 class PUTHandler(ArrayArgTypeHandler
):
6842 """Handler for glTexParameter_v, glVertexAttrib_v functions."""
6845 ArrayArgTypeHandler
.__init
__(self
)
6847 def WriteServiceUnitTest(self
, func
, f
, *extras
):
6848 """Writes the service unit test for a command."""
6849 expected_call
= "EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));"
6850 if func
.GetInfo("first_element_only"):
6852 arg
.GetValidGLArg(func
) for arg
in func
.GetOriginalArgs()
6854 gl_arg_strings
[-1] = "*" + gl_arg_strings
[-1]
6855 expected_call
= ("EXPECT_CALL(*gl_, %%(gl_func_name)s(%s));" %
6856 ", ".join(gl_arg_strings
))
6858 TEST_P(%(test_name)s, %(name)sValidArgs) {
6859 SpecializedSetup<cmds::%(name)s, 0>(true);
6862 GetSharedMemoryAs<%(data_type)s*>()[0] = %(data_value)s;
6864 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
6865 EXPECT_EQ(GL_NO_ERROR, GetGLError());
6869 'data_type': self
.GetArrayType(func
),
6870 'data_value': func
.GetInfo('data_value') or '0',
6871 'expected_call': expected_call
,
6873 self
.WriteValidUnitTest(func
, f
, valid_test
, extra
, *extras
)
6876 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
6877 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
6878 SpecializedSetup<cmds::%(name)s, 0>(false);
6881 GetSharedMemoryAs<%(data_type)s*>()[0] = %(data_value)s;
6882 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
6885 self
.WriteInvalidUnitTest(func
, f
, invalid_test
, extra
, *extras
)
6887 def WriteImmediateServiceUnitTest(self
, func
, f
, *extras
):
6888 """Writes the service unit test for a command."""
6890 TEST_P(%(test_name)s, %(name)sValidArgs) {
6891 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
6892 SpecializedSetup<cmds::%(name)s, 0>(true);
6893 %(data_type)s temp[%(data_count)s] = { %(data_value)s, };
6894 cmd.Init(%(gl_args)s, &temp[0]);
6897 %(gl_func_name)s(%(gl_args)s, %(data_ref)sreinterpret_cast<
6898 %(data_type)s*>(ImmediateDataAddress(&cmd))));"""
6901 decoder_->set_unsafe_es3_apis_enabled(true);"""
6903 EXPECT_EQ(error::kNoError,
6904 ExecuteImmediateCmd(cmd, sizeof(temp)));
6905 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
6908 decoder_->set_unsafe_es3_apis_enabled(false);
6909 EXPECT_EQ(error::kUnknownCommand,
6910 ExecuteImmediateCmd(cmd, sizeof(temp)));"""
6915 arg
.GetValidGLArg(func
) for arg
in func
.GetOriginalArgs()[0:-1]
6917 gl_any_strings
= ["_"] * len(gl_arg_strings
)
6920 'data_ref': ("*" if func
.GetInfo('first_element_only') else ""),
6921 'data_type': self
.GetArrayType(func
),
6922 'data_count': self
.GetArrayCount(func
),
6923 'data_value': func
.GetInfo('data_value') or '0',
6924 'gl_args': ", ".join(gl_arg_strings
),
6925 'gl_any_args': ", ".join(gl_any_strings
),
6927 self
.WriteValidUnitTest(func
, f
, valid_test
, extra
, *extras
)
6930 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
6931 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();"""
6934 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_any_args)s, _)).Times(1);
6938 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_any_args)s, _)).Times(0);
6941 SpecializedSetup<cmds::%(name)s, 0>(false);
6942 %(data_type)s temp[%(data_count)s] = { %(data_value)s, };
6943 cmd.Init(%(all_but_last_args)s, &temp[0]);"""
6946 decoder_->set_unsafe_es3_apis_enabled(true);
6947 EXPECT_EQ(error::%(parse_result)s,
6948 ExecuteImmediateCmd(cmd, sizeof(temp)));
6949 decoder_->set_unsafe_es3_apis_enabled(false);
6954 EXPECT_EQ(error::%(parse_result)s,
6955 ExecuteImmediateCmd(cmd, sizeof(temp)));
6959 self
.WriteInvalidUnitTest(func
, f
, invalid_test
, extra
, *extras
)
6961 def WriteGetDataSizeCode(self
, func
, f
):
6962 """Overrriden from TypeHandler."""
6963 code
= """ uint32_t data_size;
6964 if (!ComputeDataSize(1, sizeof(%s), %d, &data_size)) {
6965 return error::kOutOfBounds;
6968 f
.write(code
% (self
.GetArrayType(func
), self
.GetArrayCount(func
)))
6969 if func
.IsImmediate():
6970 f
.write(" if (data_size > immediate_data_size) {\n")
6971 f
.write(" return error::kOutOfBounds;\n")
6974 def __NeedsToCalcDataCount(self
, func
):
6975 use_count_func
= func
.GetInfo('use_count_func')
6976 return use_count_func
!= None and use_count_func
!= False
6978 def WriteGLES2Implementation(self
, func
, f
):
6979 """Overrriden from TypeHandler."""
6980 impl_func
= func
.GetInfo('impl_func')
6981 if (impl_func
!= None and impl_func
!= True):
6983 f
.write("%s GLES2Implementation::%s(%s) {\n" %
6984 (func
.return_type
, func
.original_name
,
6985 func
.MakeTypedOriginalArgString("")))
6986 f
.write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
6987 func
.WriteDestinationInitalizationValidation(f
)
6988 self
.WriteClientGLCallLog(func
, f
)
6990 if self
.__NeedsToCalcDataCount
(func
):
6991 f
.write(" size_t count = GLES2Util::Calc%sDataCount(%s);\n" %
6992 (func
.name
, func
.GetOriginalArgs()[0].name
))
6993 f
.write(" DCHECK_LE(count, %du);\n" % self
.GetArrayCount(func
))
6995 f
.write(" size_t count = %d;" % self
.GetArrayCount(func
))
6996 f
.write(" for (size_t ii = 0; ii < count; ++ii)\n")
6997 f
.write(' GPU_CLIENT_LOG("value[" << ii << "]: " << %s[ii]);\n' %
6998 func
.GetLastOriginalArg().name
)
6999 for arg
in func
.GetOriginalArgs():
7000 arg
.WriteClientSideValidationCode(f
, func
)
7001 f
.write(" helper_->%sImmediate(%s);\n" %
7002 (func
.name
, func
.MakeOriginalArgString("")))
7003 f
.write(" CheckGLError();\n")
7007 def WriteGLES2ImplementationUnitTest(self
, func
, f
):
7008 """Writes the GLES2 Implemention unit test."""
7009 client_test
= func
.GetInfo('client_test')
7010 if (client_test
!= None and client_test
!= True):
7013 TEST_F(GLES2ImplementationTest, %(name)s) {
7014 %(type)s data[%(count)d] = {0};
7016 cmds::%(name)sImmediate cmd;
7017 %(type)s data[%(count)d];
7020 for (int jj = 0; jj < %(count)d; ++jj) {
7021 data[jj] = static_cast<%(type)s>(jj);
7024 expected.cmd.Init(%(cmd_args)s, &data[0]);
7025 gl_->%(name)s(%(args)s, &data[0]);
7026 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
7030 arg
.GetValidClientSideCmdArg(func
) for arg
in func
.GetCmdArgs()[0:-2]
7033 arg
.GetValidClientSideArg(func
) for arg
in func
.GetOriginalArgs()[0:-1]
7038 'type': self
.GetArrayType(func
),
7039 'count': self
.GetArrayCount(func
),
7040 'args': ", ".join(gl_arg_strings
),
7041 'cmd_args': ", ".join(cmd_arg_strings
),
7044 def WriteImmediateCmdComputeSize(self
, func
, f
):
7045 """Overrriden from TypeHandler."""
7046 f
.write(" static uint32_t ComputeDataSize() {\n")
7047 f
.write(" return static_cast<uint32_t>(\n")
7048 f
.write(" sizeof(%s) * %d);\n" %
7049 (self
.GetArrayType(func
), self
.GetArrayCount(func
)))
7052 if self
.__NeedsToCalcDataCount
(func
):
7053 f
.write(" static uint32_t ComputeEffectiveDataSize(%s %s) {\n" %
7054 (func
.GetOriginalArgs()[0].type,
7055 func
.GetOriginalArgs()[0].name
))
7056 f
.write(" return static_cast<uint32_t>(\n")
7057 f
.write(" sizeof(%s) * GLES2Util::Calc%sDataCount(%s));\n" %
7058 (self
.GetArrayType(func
), func
.original_name
,
7059 func
.GetOriginalArgs()[0].name
))
7062 f
.write(" static uint32_t ComputeSize() {\n")
7063 f
.write(" return static_cast<uint32_t>(\n")
7065 " sizeof(ValueType) + ComputeDataSize());\n")
7069 def WriteImmediateCmdSetHeader(self
, func
, f
):
7070 """Overrriden from TypeHandler."""
7071 f
.write(" void SetHeader() {\n")
7073 " header.SetCmdByTotalSize<ValueType>(ComputeSize());\n")
7077 def WriteImmediateCmdInit(self
, func
, f
):
7078 """Overrriden from TypeHandler."""
7079 last_arg
= func
.GetLastOriginalArg()
7080 f
.write(" void Init(%s, %s _%s) {\n" %
7081 (func
.MakeTypedCmdArgString("_"),
7082 last_arg
.type, last_arg
.name
))
7083 f
.write(" SetHeader();\n")
7084 args
= func
.GetCmdArgs()
7086 f
.write(" %s = _%s;\n" % (arg
.name
, arg
.name
))
7087 f
.write(" memcpy(ImmediateDataAddress(this),\n")
7088 if self
.__NeedsToCalcDataCount
(func
):
7089 f
.write(" _%s, ComputeEffectiveDataSize(%s));" %
7090 (last_arg
.name
, func
.GetOriginalArgs()[0].name
))
7092 DCHECK_GE(ComputeDataSize(), ComputeEffectiveDataSize(%(arg)s));
7093 char* pointer = reinterpret_cast<char*>(ImmediateDataAddress(this)) +
7094 ComputeEffectiveDataSize(%(arg)s);
7095 memset(pointer, 0, ComputeDataSize() - ComputeEffectiveDataSize(%(arg)s));
7096 """ % { 'arg': func
.GetOriginalArgs()[0].name
, })
7098 f
.write(" _%s, ComputeDataSize());\n" % last_arg
.name
)
7102 def WriteImmediateCmdSet(self
, func
, f
):
7103 """Overrriden from TypeHandler."""
7104 last_arg
= func
.GetLastOriginalArg()
7105 copy_args
= func
.MakeCmdArgString("_", False)
7106 f
.write(" void* Set(void* cmd%s, %s _%s) {\n" %
7107 (func
.MakeTypedCmdArgString("_", True),
7108 last_arg
.type, last_arg
.name
))
7109 f
.write(" static_cast<ValueType*>(cmd)->Init(%s, _%s);\n" %
7110 (copy_args
, last_arg
.name
))
7111 f
.write(" const uint32_t size = ComputeSize();\n")
7112 f
.write(" return NextImmediateCmdAddressTotalSize<ValueType>("
7117 def WriteImmediateCmdHelper(self
, func
, f
):
7118 """Overrriden from TypeHandler."""
7119 code
= """ void %(name)s(%(typed_args)s) {
7120 const uint32_t size = gles2::cmds::%(name)s::ComputeSize();
7121 gles2::cmds::%(name)s* c =
7122 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
7131 "typed_args": func
.MakeTypedOriginalArgString(""),
7132 "args": func
.MakeOriginalArgString(""),
7135 def WriteImmediateFormatTest(self
, func
, f
):
7136 """Overrriden from TypeHandler."""
7137 f
.write("TEST_F(GLES2FormatTest, %s) {\n" % func
.name
)
7138 f
.write(" const int kSomeBaseValueToTestWith = 51;\n")
7139 f
.write(" static %s data[] = {\n" % self
.GetArrayType(func
))
7140 for v
in range(0, self
.GetArrayCount(func
)):
7141 f
.write(" static_cast<%s>(kSomeBaseValueToTestWith + %d),\n" %
7142 (self
.GetArrayType(func
), v
))
7144 f
.write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
7145 (func
.name
, func
.name
))
7146 f
.write(" void* next_cmd = cmd.Set(\n")
7148 args
= func
.GetCmdArgs()
7149 for value
, arg
in enumerate(args
):
7150 f
.write(",\n static_cast<%s>(%d)" % (arg
.type, value
+ 11))
7151 f
.write(",\n data);\n")
7152 args
= func
.GetCmdArgs()
7153 f
.write(" EXPECT_EQ(static_cast<uint32_t>(cmds::%s::kCmdId),\n"
7155 f
.write(" cmd.header.command);\n")
7156 f
.write(" EXPECT_EQ(sizeof(cmd) +\n")
7157 f
.write(" RoundSizeToMultipleOfEntries(sizeof(data)),\n")
7158 f
.write(" cmd.header.size * 4u);\n")
7159 for value
, arg
in enumerate(args
):
7160 f
.write(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);\n" %
7161 (arg
.type, value
+ 11, arg
.name
))
7162 f
.write(" CheckBytesWrittenMatchesExpectedSize(\n")
7163 f
.write(" next_cmd, sizeof(cmd) +\n")
7164 f
.write(" RoundSizeToMultipleOfEntries(sizeof(data)));\n")
7165 f
.write(" // TODO(gman): Check that data was inserted;\n")
7170 class PUTnHandler(ArrayArgTypeHandler
):
7171 """Handler for PUTn 'glUniform__v' type functions."""
7174 ArrayArgTypeHandler
.__init
__(self
)
7176 def WriteServiceUnitTest(self
, func
, f
, *extras
):
7177 """Overridden from TypeHandler."""
7178 ArrayArgTypeHandler
.WriteServiceUnitTest(self
, func
, f
, *extras
)
7181 TEST_P(%(test_name)s, %(name)sValidArgsCountTooLarge) {
7182 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
7183 SpecializedSetup<cmds::%(name)s, 0>(true);
7186 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
7187 EXPECT_EQ(GL_NO_ERROR, GetGLError());
7192 for count
, arg
in enumerate(func
.GetOriginalArgs()):
7193 # hardcoded to match unit tests.
7195 # the location of the second element of the 2nd uniform.
7196 # defined in GLES2DecoderBase::SetupShaderForUniform
7197 gl_arg_strings
.append("3")
7198 arg_strings
.append("ProgramManager::MakeFakeLocation(1, 1)")
7200 # the number of elements that gl will be called with.
7201 gl_arg_strings
.append("3")
7202 # the number of elements requested in the command.
7203 arg_strings
.append("5")
7205 gl_arg_strings
.append(arg
.GetValidGLArg(func
))
7206 if not arg
.IsConstant():
7207 arg_strings
.append(arg
.GetValidArg(func
))
7209 'gl_args': ", ".join(gl_arg_strings
),
7210 'args': ", ".join(arg_strings
),
7212 self
.WriteValidUnitTest(func
, f
, valid_test
, extra
, *extras
)
7214 def WriteImmediateServiceUnitTest(self
, func
, f
, *extras
):
7215 """Overridden from TypeHandler."""
7217 TEST_P(%(test_name)s, %(name)sValidArgs) {
7218 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
7221 %(gl_func_name)s(%(gl_args)s,
7222 reinterpret_cast<%(data_type)s*>(ImmediateDataAddress(&cmd))));
7223 SpecializedSetup<cmds::%(name)s, 0>(true);
7224 %(data_type)s temp[%(data_count)s * 2] = { 0, };
7225 cmd.Init(%(args)s, &temp[0]);"""
7228 decoder_->set_unsafe_es3_apis_enabled(true);"""
7230 EXPECT_EQ(error::kNoError,
7231 ExecuteImmediateCmd(cmd, sizeof(temp)));
7232 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
7235 decoder_->set_unsafe_es3_apis_enabled(false);
7236 EXPECT_EQ(error::kUnknownCommand,
7237 ExecuteImmediateCmd(cmd, sizeof(temp)));"""
7244 for arg
in func
.GetOriginalArgs()[0:-1]:
7245 gl_arg_strings
.append(arg
.GetValidGLArg(func
))
7246 gl_any_strings
.append("_")
7247 if not arg
.IsConstant():
7248 arg_strings
.append(arg
.GetValidArg(func
))
7250 'data_type': self
.GetArrayType(func
),
7251 'data_count': self
.GetArrayCount(func
),
7252 'args': ", ".join(arg_strings
),
7253 'gl_args': ", ".join(gl_arg_strings
),
7254 'gl_any_args': ", ".join(gl_any_strings
),
7256 self
.WriteValidUnitTest(func
, f
, valid_test
, extra
, *extras
)
7259 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
7260 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
7261 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_any_args)s, _)).Times(0);
7262 SpecializedSetup<cmds::%(name)s, 0>(false);
7263 %(data_type)s temp[%(data_count)s * 2] = { 0, };
7264 cmd.Init(%(all_but_last_args)s, &temp[0]);
7265 EXPECT_EQ(error::%(parse_result)s,
7266 ExecuteImmediateCmd(cmd, sizeof(temp)));%(gl_error_test)s
7269 self
.WriteInvalidUnitTest(func
, f
, invalid_test
, extra
, *extras
)
7271 def WriteGetDataSizeCode(self
, func
, f
):
7272 """Overrriden from TypeHandler."""
7273 code
= """ uint32_t data_size;
7274 if (!ComputeDataSize(count, sizeof(%s), %d, &data_size)) {
7275 return error::kOutOfBounds;
7278 f
.write(code
% (self
.GetArrayType(func
), self
.GetArrayCount(func
)))
7279 if func
.IsImmediate():
7280 f
.write(" if (data_size > immediate_data_size) {\n")
7281 f
.write(" return error::kOutOfBounds;\n")
7284 def WriteGLES2Implementation(self
, func
, f
):
7285 """Overrriden from TypeHandler."""
7286 f
.write("%s GLES2Implementation::%s(%s) {\n" %
7287 (func
.return_type
, func
.original_name
,
7288 func
.MakeTypedOriginalArgString("")))
7289 f
.write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
7290 func
.WriteDestinationInitalizationValidation(f
)
7291 self
.WriteClientGLCallLog(func
, f
)
7292 last_pointer_name
= func
.GetLastOriginalPointerArg().name
7293 f
.write(""" GPU_CLIENT_LOG_CODE_BLOCK({
7294 for (GLsizei i = 0; i < count; ++i) {
7296 values_str
= ' << ", " << '.join(
7297 ["%s[%d + i * %d]" % (
7298 last_pointer_name
, ndx
, self
.GetArrayCount(func
)) for ndx
in range(
7299 0, self
.GetArrayCount(func
))])
7300 f
.write(' GPU_CLIENT_LOG(" " << i << ": " << %s);\n' % values_str
)
7301 f
.write(" }\n });\n")
7302 for arg
in func
.GetOriginalArgs():
7303 arg
.WriteClientSideValidationCode(f
, func
)
7304 f
.write(" helper_->%sImmediate(%s);\n" %
7305 (func
.name
, func
.MakeInitString("")))
7306 f
.write(" CheckGLError();\n")
7310 def WriteGLES2ImplementationUnitTest(self
, func
, f
):
7311 """Writes the GLES2 Implemention unit test."""
7313 TEST_F(GLES2ImplementationTest, %(name)s) {
7314 %(type)s data[%(count_param)d][%(count)d] = {{0}};
7316 cmds::%(name)sImmediate cmd;
7317 %(type)s data[%(count_param)d][%(count)d];
7321 for (int ii = 0; ii < %(count_param)d; ++ii) {
7322 for (int jj = 0; jj < %(count)d; ++jj) {
7323 data[ii][jj] = static_cast<%(type)s>(ii * %(count)d + jj);
7326 expected.cmd.Init(%(cmd_args)s);
7327 gl_->%(name)s(%(args)s);
7328 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
7331 cmd_arg_strings
= []
7332 for arg
in func
.GetCmdArgs():
7333 if arg
.name
.endswith("_shm_id"):
7334 cmd_arg_strings
.append("&data[0][0]")
7335 elif arg
.name
.endswith("_shm_offset"):
7338 cmd_arg_strings
.append(arg
.GetValidClientSideCmdArg(func
))
7341 for arg
in func
.GetOriginalArgs():
7343 valid_value
= "&data[0][0]"
7345 valid_value
= arg
.GetValidClientSideArg(func
)
7346 gl_arg_strings
.append(valid_value
)
7347 if arg
.name
== "count":
7348 count_param
= int(valid_value
)
7351 'type': self
.GetArrayType(func
),
7352 'count': self
.GetArrayCount(func
),
7353 'args': ", ".join(gl_arg_strings
),
7354 'cmd_args': ", ".join(cmd_arg_strings
),
7355 'count_param': count_param
,
7358 # Test constants for invalid values, as they are not tested by the
7361 arg
for arg
in func
.GetOriginalArgs()[0:-1] if arg
.IsConstant()
7367 TEST_F(GLES2ImplementationTest, %(name)sInvalidConstantArg%(invalid_index)d) {
7368 %(type)s data[%(count_param)d][%(count)d] = {{0}};
7369 for (int ii = 0; ii < %(count_param)d; ++ii) {
7370 for (int jj = 0; jj < %(count)d; ++jj) {
7371 data[ii][jj] = static_cast<%(type)s>(ii * %(count)d + jj);
7374 gl_->%(name)s(%(args)s);
7375 EXPECT_TRUE(NoCommandsWritten());
7376 EXPECT_EQ(%(gl_error)s, CheckError());
7379 for invalid_arg
in constants
:
7381 invalid
= invalid_arg
.GetInvalidArg(func
)
7382 for arg
in func
.GetOriginalArgs():
7383 if arg
is invalid_arg
:
7384 gl_arg_strings
.append(invalid
[0])
7385 elif arg
.IsPointer():
7386 gl_arg_strings
.append("&data[0][0]")
7388 valid_value
= arg
.GetValidClientSideArg(func
)
7389 gl_arg_strings
.append(valid_value
)
7390 if arg
.name
== "count":
7391 count_param
= int(valid_value
)
7395 'invalid_index': func
.GetOriginalArgs().index(invalid_arg
),
7396 'type': self
.GetArrayType(func
),
7397 'count': self
.GetArrayCount(func
),
7398 'args': ", ".join(gl_arg_strings
),
7399 'gl_error': invalid
[2],
7400 'count_param': count_param
,
7404 def WriteImmediateCmdComputeSize(self
, func
, f
):
7405 """Overrriden from TypeHandler."""
7406 f
.write(" static uint32_t ComputeDataSize(GLsizei count) {\n")
7407 f
.write(" return static_cast<uint32_t>(\n")
7408 f
.write(" sizeof(%s) * %d * count); // NOLINT\n" %
7409 (self
.GetArrayType(func
), self
.GetArrayCount(func
)))
7412 f
.write(" static uint32_t ComputeSize(GLsizei count) {\n")
7413 f
.write(" return static_cast<uint32_t>(\n")
7415 " sizeof(ValueType) + ComputeDataSize(count)); // NOLINT\n")
7419 def WriteImmediateCmdSetHeader(self
, func
, f
):
7420 """Overrriden from TypeHandler."""
7421 f
.write(" void SetHeader(GLsizei count) {\n")
7423 " header.SetCmdByTotalSize<ValueType>(ComputeSize(count));\n")
7427 def WriteImmediateCmdInit(self
, func
, f
):
7428 """Overrriden from TypeHandler."""
7429 f
.write(" void Init(%s) {\n" %
7430 func
.MakeTypedInitString("_"))
7431 f
.write(" SetHeader(_count);\n")
7432 args
= func
.GetCmdArgs()
7434 f
.write(" %s = _%s;\n" % (arg
.name
, arg
.name
))
7435 f
.write(" memcpy(ImmediateDataAddress(this),\n")
7436 pointer_arg
= func
.GetLastOriginalPointerArg()
7437 f
.write(" _%s, ComputeDataSize(_count));\n" % pointer_arg
.name
)
7441 def WriteImmediateCmdSet(self
, func
, f
):
7442 """Overrriden from TypeHandler."""
7443 f
.write(" void* Set(void* cmd%s) {\n" %
7444 func
.MakeTypedInitString("_", True))
7445 f
.write(" static_cast<ValueType*>(cmd)->Init(%s);\n" %
7446 func
.MakeInitString("_"))
7447 f
.write(" const uint32_t size = ComputeSize(_count);\n")
7448 f
.write(" return NextImmediateCmdAddressTotalSize<ValueType>("
7453 def WriteImmediateCmdHelper(self
, func
, f
):
7454 """Overrriden from TypeHandler."""
7455 code
= """ void %(name)s(%(typed_args)s) {
7456 const uint32_t size = gles2::cmds::%(name)s::ComputeSize(count);
7457 gles2::cmds::%(name)s* c =
7458 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
7467 "typed_args": func
.MakeTypedInitString(""),
7468 "args": func
.MakeInitString("")
7471 def WriteImmediateFormatTest(self
, func
, f
):
7472 """Overrriden from TypeHandler."""
7473 args
= func
.GetOriginalArgs()
7476 if arg
.name
== "count":
7477 count_param
= int(arg
.GetValidClientSideCmdArg(func
))
7478 f
.write("TEST_F(GLES2FormatTest, %s) {\n" % func
.name
)
7479 f
.write(" const int kSomeBaseValueToTestWith = 51;\n")
7480 f
.write(" static %s data[] = {\n" % self
.GetArrayType(func
))
7481 for v
in range(0, self
.GetArrayCount(func
) * count_param
):
7482 f
.write(" static_cast<%s>(kSomeBaseValueToTestWith + %d),\n" %
7483 (self
.GetArrayType(func
), v
))
7485 f
.write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
7486 (func
.name
, func
.name
))
7487 f
.write(" const GLsizei kNumElements = %d;\n" % count_param
)
7488 f
.write(" const size_t kExpectedCmdSize =\n")
7489 f
.write(" sizeof(cmd) + kNumElements * sizeof(%s) * %d;\n" %
7490 (self
.GetArrayType(func
), self
.GetArrayCount(func
)))
7491 f
.write(" void* next_cmd = cmd.Set(\n")
7493 for value
, arg
in enumerate(args
):
7496 elif arg
.IsConstant():
7499 f
.write(",\n static_cast<%s>(%d)" % (arg
.type, value
+ 1))
7501 f
.write(" EXPECT_EQ(static_cast<uint32_t>(cmds::%s::kCmdId),\n" %
7503 f
.write(" cmd.header.command);\n")
7504 f
.write(" EXPECT_EQ(kExpectedCmdSize, cmd.header.size * 4u);\n")
7505 for value
, arg
in enumerate(args
):
7506 if arg
.IsPointer() or arg
.IsConstant():
7508 f
.write(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);\n" %
7509 (arg
.type, value
+ 1, arg
.name
))
7510 f
.write(" CheckBytesWrittenMatchesExpectedSize(\n")
7511 f
.write(" next_cmd, sizeof(cmd) +\n")
7512 f
.write(" RoundSizeToMultipleOfEntries(sizeof(data)));\n")
7513 f
.write(" // TODO(gman): Check that data was inserted;\n")
7517 class PUTSTRHandler(ArrayArgTypeHandler
):
7518 """Handler for functions that pass a string array."""
7521 ArrayArgTypeHandler
.__init
__(self
)
7523 def __GetDataArg(self
, func
):
7524 """Return the argument that points to the 2D char arrays"""
7525 for arg
in func
.GetOriginalArgs():
7526 if arg
.IsPointer2D():
7530 def __GetLengthArg(self
, func
):
7531 """Return the argument that holds length for each char array"""
7532 for arg
in func
.GetOriginalArgs():
7533 if arg
.IsPointer() and not arg
.IsPointer2D():
7537 def WriteGLES2Implementation(self
, func
, f
):
7538 """Overrriden from TypeHandler."""
7539 f
.write("%s GLES2Implementation::%s(%s) {\n" %
7540 (func
.return_type
, func
.original_name
,
7541 func
.MakeTypedOriginalArgString("")))
7542 f
.write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
7543 func
.WriteDestinationInitalizationValidation(f
)
7544 self
.WriteClientGLCallLog(func
, f
)
7545 data_arg
= self
.__GetDataArg
(func
)
7546 length_arg
= self
.__GetLengthArg
(func
)
7547 log_code_block
= """ GPU_CLIENT_LOG_CODE_BLOCK({
7548 for (GLsizei ii = 0; ii < count; ++ii) {
7549 if (%(data)s[ii]) {"""
7550 if length_arg
== None:
7551 log_code_block
+= """
7552 GPU_CLIENT_LOG(" " << ii << ": ---\\n" << %(data)s[ii] << "\\n---");"""
7554 log_code_block
+= """
7555 if (%(length)s && %(length)s[ii] >= 0) {
7556 const std::string my_str(%(data)s[ii], %(length)s[ii]);
7557 GPU_CLIENT_LOG(" " << ii << ": ---\\n" << my_str << "\\n---");
7559 GPU_CLIENT_LOG(" " << ii << ": ---\\n" << %(data)s[ii] << "\\n---");
7561 log_code_block
+= """
7563 GPU_CLIENT_LOG(" " << ii << ": NULL");
7568 f
.write(log_code_block
% {
7569 'data': data_arg
.name
,
7570 'length': length_arg
.name
if not length_arg
== None else ''
7572 for arg
in func
.GetOriginalArgs():
7573 arg
.WriteClientSideValidationCode(f
, func
)
7576 for arg
in func
.GetOriginalArgs():
7577 if arg
.name
== 'count' or arg
== self
.__GetLengthArg
(func
):
7579 if arg
== self
.__GetDataArg
(func
):
7580 bucket_args
.append('kResultBucketId')
7582 bucket_args
.append(arg
.name
)
7584 if (!PackStringsToBucket(count, %(data)s, %(length)s, "gl%(func_name)s")) {
7587 helper_->%(func_name)sBucket(%(bucket_args)s);
7588 helper_->SetBucketSize(kResultBucketId, 0);
7593 f
.write(code_block
% {
7594 'data': data_arg
.name
,
7595 'length': length_arg
.name
if not length_arg
== None else 'NULL',
7596 'func_name': func
.name
,
7597 'bucket_args': ', '.join(bucket_args
),
7600 def WriteGLES2ImplementationUnitTest(self
, func
, f
):
7601 """Overrriden from TypeHandler."""
7603 TEST_F(GLES2ImplementationTest, %(name)s) {
7604 const uint32 kBucketId = GLES2Implementation::kResultBucketId;
7605 const char* kString1 = "happy";
7606 const char* kString2 = "ending";
7607 const size_t kString1Size = ::strlen(kString1) + 1;
7608 const size_t kString2Size = ::strlen(kString2) + 1;
7609 const size_t kHeaderSize = sizeof(GLint) * 3;
7610 const size_t kSourceSize = kHeaderSize + kString1Size + kString2Size;
7611 const size_t kPaddedHeaderSize =
7612 transfer_buffer_->RoundToAlignment(kHeaderSize);
7613 const size_t kPaddedString1Size =
7614 transfer_buffer_->RoundToAlignment(kString1Size);
7615 const size_t kPaddedString2Size =
7616 transfer_buffer_->RoundToAlignment(kString2Size);
7618 cmd::SetBucketSize set_bucket_size;
7619 cmd::SetBucketData set_bucket_header;
7620 cmd::SetToken set_token1;
7621 cmd::SetBucketData set_bucket_data1;
7622 cmd::SetToken set_token2;
7623 cmd::SetBucketData set_bucket_data2;
7624 cmd::SetToken set_token3;
7625 cmds::%(name)sBucket cmd_bucket;
7626 cmd::SetBucketSize clear_bucket_size;
7629 ExpectedMemoryInfo mem0 = GetExpectedMemory(kPaddedHeaderSize);
7630 ExpectedMemoryInfo mem1 = GetExpectedMemory(kPaddedString1Size);
7631 ExpectedMemoryInfo mem2 = GetExpectedMemory(kPaddedString2Size);
7634 expected.set_bucket_size.Init(kBucketId, kSourceSize);
7635 expected.set_bucket_header.Init(
7636 kBucketId, 0, kHeaderSize, mem0.id, mem0.offset);
7637 expected.set_token1.Init(GetNextToken());
7638 expected.set_bucket_data1.Init(
7639 kBucketId, kHeaderSize, kString1Size, mem1.id, mem1.offset);
7640 expected.set_token2.Init(GetNextToken());
7641 expected.set_bucket_data2.Init(
7642 kBucketId, kHeaderSize + kString1Size, kString2Size, mem2.id,
7644 expected.set_token3.Init(GetNextToken());
7645 expected.cmd_bucket.Init(%(bucket_args)s);
7646 expected.clear_bucket_size.Init(kBucketId, 0);
7647 const char* kStrings[] = { kString1, kString2 };
7648 gl_->%(name)s(%(gl_args)s);
7649 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
7654 for arg
in func
.GetOriginalArgs():
7655 if arg
== self
.__GetDataArg
(func
):
7656 gl_args
.append('kStrings')
7657 bucket_args
.append('kBucketId')
7658 elif arg
== self
.__GetLengthArg
(func
):
7659 gl_args
.append('NULL')
7660 elif arg
.name
== 'count':
7663 gl_args
.append(arg
.GetValidClientSideArg(func
))
7664 bucket_args
.append(arg
.GetValidClientSideArg(func
))
7667 'gl_args': ", ".join(gl_args
),
7668 'bucket_args': ", ".join(bucket_args
),
7671 if self
.__GetLengthArg
(func
) == None:
7674 TEST_F(GLES2ImplementationTest, %(name)sWithLength) {
7675 const uint32 kBucketId = GLES2Implementation::kResultBucketId;
7676 const char* kString = "foobar******";
7677 const size_t kStringSize = 6; // We only need "foobar".
7678 const size_t kHeaderSize = sizeof(GLint) * 2;
7679 const size_t kSourceSize = kHeaderSize + kStringSize + 1;
7680 const size_t kPaddedHeaderSize =
7681 transfer_buffer_->RoundToAlignment(kHeaderSize);
7682 const size_t kPaddedStringSize =
7683 transfer_buffer_->RoundToAlignment(kStringSize + 1);
7685 cmd::SetBucketSize set_bucket_size;
7686 cmd::SetBucketData set_bucket_header;
7687 cmd::SetToken set_token1;
7688 cmd::SetBucketData set_bucket_data;
7689 cmd::SetToken set_token2;
7690 cmds::ShaderSourceBucket shader_source_bucket;
7691 cmd::SetBucketSize clear_bucket_size;
7694 ExpectedMemoryInfo mem0 = GetExpectedMemory(kPaddedHeaderSize);
7695 ExpectedMemoryInfo mem1 = GetExpectedMemory(kPaddedStringSize);
7698 expected.set_bucket_size.Init(kBucketId, kSourceSize);
7699 expected.set_bucket_header.Init(
7700 kBucketId, 0, kHeaderSize, mem0.id, mem0.offset);
7701 expected.set_token1.Init(GetNextToken());
7702 expected.set_bucket_data.Init(
7703 kBucketId, kHeaderSize, kStringSize + 1, mem1.id, mem1.offset);
7704 expected.set_token2.Init(GetNextToken());
7705 expected.shader_source_bucket.Init(%(bucket_args)s);
7706 expected.clear_bucket_size.Init(kBucketId, 0);
7707 const char* kStrings[] = { kString };
7708 const GLint kLength[] = { kStringSize };
7709 gl_->%(name)s(%(gl_args)s);
7710 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
7714 for arg
in func
.GetOriginalArgs():
7715 if arg
== self
.__GetDataArg
(func
):
7716 gl_args
.append('kStrings')
7717 elif arg
== self
.__GetLengthArg
(func
):
7718 gl_args
.append('kLength')
7719 elif arg
.name
== 'count':
7722 gl_args
.append(arg
.GetValidClientSideArg(func
))
7725 'gl_args': ", ".join(gl_args
),
7726 'bucket_args': ", ".join(bucket_args
),
7729 def WriteBucketServiceUnitTest(self
, func
, f
, *extras
):
7730 """Overrriden from TypeHandler."""
7732 cmd_args_with_invalid_id
= []
7734 for index
, arg
in enumerate(func
.GetOriginalArgs()):
7735 if arg
== self
.__GetLengthArg
(func
):
7737 elif arg
.name
== 'count':
7739 elif arg
== self
.__GetDataArg
(func
):
7740 cmd_args
.append('kBucketId')
7741 cmd_args_with_invalid_id
.append('kBucketId')
7743 elif index
== 0: # Resource ID arg
7744 cmd_args
.append(arg
.GetValidArg(func
))
7745 cmd_args_with_invalid_id
.append('kInvalidClientId')
7746 gl_args
.append(arg
.GetValidGLArg(func
))
7748 cmd_args
.append(arg
.GetValidArg(func
))
7749 cmd_args_with_invalid_id
.append(arg
.GetValidArg(func
))
7750 gl_args
.append(arg
.GetValidGLArg(func
))
7753 TEST_P(%(test_name)s, %(name)sValidArgs) {
7754 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
7755 const uint32 kBucketId = 123;
7756 const char kSource0[] = "hello";
7757 const char* kSource[] = { kSource0 };
7758 const char kValidStrEnd = 0;
7759 SetBucketAsCStrings(kBucketId, 1, kSource, 1, kValidStrEnd);
7761 cmd.Init(%(cmd_args)s);
7762 decoder_->set_unsafe_es3_apis_enabled(true);
7763 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));"""
7766 decoder_->set_unsafe_es3_apis_enabled(false);
7767 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));
7772 self
.WriteValidUnitTest(func
, f
, test
, {
7773 'cmd_args': ", ".join(cmd_args
),
7774 'gl_args': ", ".join(gl_args
),
7778 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
7779 const uint32 kBucketId = 123;
7780 const char kSource0[] = "hello";
7781 const char* kSource[] = { kSource0 };
7782 const char kValidStrEnd = 0;
7783 decoder_->set_unsafe_es3_apis_enabled(true);
7786 cmd.Init(%(cmd_args)s);
7787 EXPECT_NE(error::kNoError, ExecuteCmd(cmd));
7788 // Test invalid client.
7789 SetBucketAsCStrings(kBucketId, 1, kSource, 1, kValidStrEnd);
7790 cmd.Init(%(cmd_args_with_invalid_id)s);
7791 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
7792 EXPECT_EQ(GL_INVALID_VALUE, GetGLError());
7795 self
.WriteValidUnitTest(func
, f
, test
, {
7796 'cmd_args': ", ".join(cmd_args
),
7797 'cmd_args_with_invalid_id': ", ".join(cmd_args_with_invalid_id
),
7801 TEST_P(%(test_name)s, %(name)sInvalidHeader) {
7802 const uint32 kBucketId = 123;
7803 const char kSource0[] = "hello";
7804 const char* kSource[] = { kSource0 };
7805 const char kValidStrEnd = 0;
7806 const GLsizei kCount = static_cast<GLsizei>(arraysize(kSource));
7807 const GLsizei kTests[] = {
7810 std::numeric_limits<GLsizei>::max(),
7813 decoder_->set_unsafe_es3_apis_enabled(true);
7814 for (size_t ii = 0; ii < arraysize(kTests); ++ii) {
7815 SetBucketAsCStrings(kBucketId, 1, kSource, kTests[ii], kValidStrEnd);
7817 cmd.Init(%(cmd_args)s);
7818 EXPECT_EQ(error::kInvalidArguments, ExecuteCmd(cmd));
7822 self
.WriteValidUnitTest(func
, f
, test
, {
7823 'cmd_args': ", ".join(cmd_args
),
7827 TEST_P(%(test_name)s, %(name)sInvalidStringEnding) {
7828 const uint32 kBucketId = 123;
7829 const char kSource0[] = "hello";
7830 const char* kSource[] = { kSource0 };
7831 const char kInvalidStrEnd = '*';
7832 SetBucketAsCStrings(kBucketId, 1, kSource, 1, kInvalidStrEnd);
7834 cmd.Init(%(cmd_args)s);
7835 decoder_->set_unsafe_es3_apis_enabled(true);
7836 EXPECT_EQ(error::kInvalidArguments, ExecuteCmd(cmd));
7839 self
.WriteValidUnitTest(func
, f
, test
, {
7840 'cmd_args': ", ".join(cmd_args
),
7844 class PUTXnHandler(ArrayArgTypeHandler
):
7845 """Handler for glUniform?f functions."""
7847 ArrayArgTypeHandler
.__init
__(self
)
7849 def WriteHandlerImplementation(self
, func
, f
):
7850 """Overrriden from TypeHandler."""
7851 code
= """ %(type)s temp[%(count)s] = { %(values)s};"""
7854 gl%(name)sv(%(location)s, 1, &temp[0]);
7858 Do%(name)sv(%(location)s, 1, &temp[0]);
7861 args
= func
.GetOriginalArgs()
7862 count
= int(self
.GetArrayCount(func
))
7863 num_args
= len(args
)
7864 for ii
in range(count
):
7865 values
+= "%s, " % args
[len(args
) - count
+ ii
].name
7869 'count': self
.GetArrayCount(func
),
7870 'type': self
.GetArrayType(func
),
7871 'location': args
[0].name
,
7872 'args': func
.MakeOriginalArgString(""),
7876 def WriteServiceUnitTest(self
, func
, f
, *extras
):
7877 """Overrriden from TypeHandler."""
7879 TEST_P(%(test_name)s, %(name)sValidArgs) {
7880 EXPECT_CALL(*gl_, %(name)sv(%(local_args)s));
7881 SpecializedSetup<cmds::%(name)s, 0>(true);
7883 cmd.Init(%(args)s);"""
7886 decoder_->set_unsafe_es3_apis_enabled(true);"""
7888 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
7889 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
7892 decoder_->set_unsafe_es3_apis_enabled(false);
7893 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));"""
7897 args
= func
.GetOriginalArgs()
7898 local_args
= "%s, 1, _" % args
[0].GetValidGLArg(func
)
7899 self
.WriteValidUnitTest(func
, f
, valid_test
, {
7901 'count': self
.GetArrayCount(func
),
7902 'local_args': local_args
,
7906 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
7907 EXPECT_CALL(*gl_, %(name)sv(_, _, _).Times(0);
7908 SpecializedSetup<cmds::%(name)s, 0>(false);
7911 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
7914 self
.WriteInvalidUnitTest(func
, f
, invalid_test
, {
7915 'name': func
.GetInfo('name'),
7916 'count': self
.GetArrayCount(func
),
7920 class GLcharHandler(CustomHandler
):
7921 """Handler for functions that pass a single string ."""
7924 CustomHandler
.__init
__(self
)
7926 def WriteImmediateCmdComputeSize(self
, func
, f
):
7927 """Overrriden from TypeHandler."""
7928 f
.write(" static uint32_t ComputeSize(uint32_t data_size) {\n")
7929 f
.write(" return static_cast<uint32_t>(\n")
7930 f
.write(" sizeof(ValueType) + data_size); // NOLINT\n")
7933 def WriteImmediateCmdSetHeader(self
, func
, f
):
7934 """Overrriden from TypeHandler."""
7936 void SetHeader(uint32_t data_size) {
7937 header.SetCmdBySize<ValueType>(data_size);
7942 def WriteImmediateCmdInit(self
, func
, f
):
7943 """Overrriden from TypeHandler."""
7944 last_arg
= func
.GetLastOriginalArg()
7945 args
= func
.GetCmdArgs()
7948 set_code
.append(" %s = _%s;" % (arg
.name
, arg
.name
))
7950 void Init(%(typed_args)s, uint32_t _data_size) {
7951 SetHeader(_data_size);
7953 memcpy(ImmediateDataAddress(this), _%(last_arg)s, _data_size);
7958 "typed_args": func
.MakeTypedArgString("_"),
7959 "set_code": "\n".join(set_code
),
7960 "last_arg": last_arg
.name
7963 def WriteImmediateCmdSet(self
, func
, f
):
7964 """Overrriden from TypeHandler."""
7965 last_arg
= func
.GetLastOriginalArg()
7966 f
.write(" void* Set(void* cmd%s, uint32_t _data_size) {\n" %
7967 func
.MakeTypedCmdArgString("_", True))
7968 f
.write(" static_cast<ValueType*>(cmd)->Init(%s, _data_size);\n" %
7969 func
.MakeCmdArgString("_"))
7970 f
.write(" return NextImmediateCmdAddress<ValueType>("
7971 "cmd, _data_size);\n")
7975 def WriteImmediateCmdHelper(self
, func
, f
):
7976 """Overrriden from TypeHandler."""
7977 code
= """ void %(name)s(%(typed_args)s) {
7978 const uint32_t data_size = strlen(name);
7979 gles2::cmds::%(name)s* c =
7980 GetImmediateCmdSpace<gles2::cmds::%(name)s>(data_size);
7982 c->Init(%(args)s, data_size);
7989 "typed_args": func
.MakeTypedOriginalArgString(""),
7990 "args": func
.MakeOriginalArgString(""),
7994 def WriteImmediateFormatTest(self
, func
, f
):
7995 """Overrriden from TypeHandler."""
7998 all_but_last_arg
= func
.GetCmdArgs()[:-1]
7999 for value
, arg
in enumerate(all_but_last_arg
):
8000 init_code
.append(" static_cast<%s>(%d)," % (arg
.type, value
+ 11))
8001 for value
, arg
in enumerate(all_but_last_arg
):
8002 check_code
.append(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);" %
8003 (arg
.type, value
+ 11, arg
.name
))
8005 TEST_F(GLES2FormatTest, %(func_name)s) {
8006 cmds::%(func_name)s& cmd = *GetBufferAs<cmds::%(func_name)s>();
8007 static const char* const test_str = \"test string\";
8008 void* next_cmd = cmd.Set(
8013 EXPECT_EQ(static_cast<uint32_t>(cmds::%(func_name)s::kCmdId),
8014 cmd.header.command);
8015 EXPECT_EQ(sizeof(cmd) +
8016 RoundSizeToMultipleOfEntries(strlen(test_str)),
8017 cmd.header.size * 4u);
8018 EXPECT_EQ(static_cast<char*>(next_cmd),
8019 reinterpret_cast<char*>(&cmd) + sizeof(cmd) +
8020 RoundSizeToMultipleOfEntries(strlen(test_str)));
8022 EXPECT_EQ(static_cast<uint32_t>(strlen(test_str)), cmd.data_size);
8023 EXPECT_EQ(0, memcmp(test_str, ImmediateDataAddress(&cmd), strlen(test_str)));
8026 sizeof(cmd) + RoundSizeToMultipleOfEntries(strlen(test_str)),
8027 sizeof(cmd) + strlen(test_str));
8032 'func_name': func
.name
,
8033 'init_code': "\n".join(init_code
),
8034 'check_code': "\n".join(check_code
),
8038 class GLcharNHandler(CustomHandler
):
8039 """Handler for functions that pass a single string with an optional len."""
8042 CustomHandler
.__init
__(self
)
8044 def InitFunction(self
, func
):
8045 """Overrriden from TypeHandler."""
8047 func
.AddCmdArg(Argument('bucket_id', 'GLuint'))
8049 def NeedsDataTransferFunction(self
, func
):
8050 """Overriden from TypeHandler."""
8053 def AddBucketFunction(self
, generator
, func
):
8054 """Overrriden from TypeHandler."""
8057 def WriteServiceImplementation(self
, func
, f
):
8058 """Overrriden from TypeHandler."""
8059 self
.WriteServiceHandlerFunctionHeader(func
, f
)
8061 GLuint bucket_id = static_cast<GLuint>(c.%(bucket_id)s);
8062 Bucket* bucket = GetBucket(bucket_id);
8063 if (!bucket || bucket->size() == 0) {
8064 return error::kInvalidArguments;
8067 if (!bucket->GetAsString(&str)) {
8068 return error::kInvalidArguments;
8070 %(gl_func_name)s(0, str.c_str());
8071 return error::kNoError;
8076 'gl_func_name': func
.GetGLFunctionName(),
8077 'bucket_id': func
.cmd_args
[0].name
,
8081 class IsHandler(TypeHandler
):
8082 """Handler for glIs____ type and glGetError functions."""
8085 TypeHandler
.__init
__(self
)
8087 def InitFunction(self
, func
):
8088 """Overrriden from TypeHandler."""
8089 func
.AddCmdArg(Argument("result_shm_id", 'uint32_t'))
8090 func
.AddCmdArg(Argument("result_shm_offset", 'uint32_t'))
8091 if func
.GetInfo('result') == None:
8092 func
.AddInfo('result', ['uint32_t'])
8094 def WriteServiceUnitTest(self
, func
, f
, *extras
):
8095 """Overrriden from TypeHandler."""
8097 TEST_P(%(test_name)s, %(name)sValidArgs) {
8098 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
8099 SpecializedSetup<cmds::%(name)s, 0>(true);
8101 cmd.Init(%(args)s%(comma)sshared_memory_id_, shared_memory_offset_);"""
8104 decoder_->set_unsafe_es3_apis_enabled(true);"""
8106 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
8107 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
8110 decoder_->set_unsafe_es3_apis_enabled(false);
8111 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));"""
8116 if len(func
.GetOriginalArgs()):
8118 self
.WriteValidUnitTest(func
, f
, valid_test
, {
8123 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
8124 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
8125 SpecializedSetup<cmds::%(name)s, 0>(false);
8127 cmd.Init(%(args)s%(comma)sshared_memory_id_, shared_memory_offset_);
8128 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
8131 self
.WriteInvalidUnitTest(func
, f
, invalid_test
, {
8136 TEST_P(%(test_name)s, %(name)sInvalidArgsBadSharedMemoryId) {
8137 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
8138 SpecializedSetup<cmds::%(name)s, 0>(false);"""
8141 decoder_->set_unsafe_es3_apis_enabled(true);"""
8144 cmd.Init(%(args)s%(comma)skInvalidSharedMemoryId, shared_memory_offset_);
8145 EXPECT_EQ(error::kOutOfBounds, ExecuteCmd(cmd));
8146 cmd.Init(%(args)s%(comma)sshared_memory_id_, kInvalidSharedMemoryOffset);
8147 EXPECT_EQ(error::kOutOfBounds, ExecuteCmd(cmd));"""
8150 decoder_->set_unsafe_es3_apis_enabled(true);"""
8154 self
.WriteValidUnitTest(func
, f
, invalid_test
, {
8158 def WriteServiceImplementation(self
, func
, f
):
8159 """Overrriden from TypeHandler."""
8160 self
.WriteServiceHandlerFunctionHeader(func
, f
)
8161 self
.WriteHandlerExtensionCheck(func
, f
)
8162 args
= func
.GetOriginalArgs()
8166 code
= """ typedef cmds::%(func_name)s::Result Result;
8167 Result* result_dst = GetSharedMemoryAs<Result*>(
8168 c.result_shm_id, c.result_shm_offset, sizeof(*result_dst));
8170 return error::kOutOfBounds;
8173 f
.write(code
% {'func_name': func
.name
})
8174 func
.WriteHandlerValidation(f
)
8176 assert func
.GetInfo('id_mapping')
8177 assert len(func
.GetInfo('id_mapping')) == 1
8178 assert len(args
) == 1
8179 id_type
= func
.GetInfo('id_mapping')[0]
8180 f
.write(" %s service_%s = 0;\n" % (args
[0].type, id_type
.lower()))
8181 f
.write(" *result_dst = group_->Get%sServiceId(%s, &service_%s);\n" %
8182 (id_type
, id_type
.lower(), id_type
.lower()))
8184 f
.write(" *result_dst = %s(%s);\n" %
8185 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
8186 f
.write(" return error::kNoError;\n")
8190 def WriteGLES2Implementation(self
, func
, f
):
8191 """Overrriden from TypeHandler."""
8192 impl_func
= func
.GetInfo('impl_func')
8193 if impl_func
== None or impl_func
== True:
8194 error_value
= func
.GetInfo("error_value") or "GL_FALSE"
8195 f
.write("%s GLES2Implementation::%s(%s) {\n" %
8196 (func
.return_type
, func
.original_name
,
8197 func
.MakeTypedOriginalArgString("")))
8198 f
.write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
8199 self
.WriteTraceEvent(func
, f
)
8200 func
.WriteDestinationInitalizationValidation(f
)
8201 self
.WriteClientGLCallLog(func
, f
)
8202 f
.write(" typedef cmds::%s::Result Result;\n" % func
.name
)
8203 f
.write(" Result* result = GetResultAs<Result*>();\n")
8204 f
.write(" if (!result) {\n")
8205 f
.write(" return %s;\n" % error_value
)
8207 f
.write(" *result = 0;\n")
8208 assert len(func
.GetOriginalArgs()) == 1
8209 id_arg
= func
.GetOriginalArgs()[0]
8210 if id_arg
.type == 'GLsync':
8211 arg_string
= "ToGLuint(%s)" % func
.MakeOriginalArgString("")
8213 arg_string
= func
.MakeOriginalArgString("")
8215 " helper_->%s(%s, GetResultShmId(), GetResultShmOffset());\n" %
8216 (func
.name
, arg_string
))
8217 f
.write(" WaitForCmd();\n")
8218 f
.write(" %s result_value = *result" % func
.return_type
)
8219 if func
.return_type
== "GLboolean":
8221 f
.write(';\n GPU_CLIENT_LOG("returned " << result_value);\n')
8222 f
.write(" CheckGLError();\n")
8223 f
.write(" return result_value;\n")
8227 def WriteGLES2ImplementationUnitTest(self
, func
, f
):
8228 """Overrriden from TypeHandler."""
8229 client_test
= func
.GetInfo('client_test')
8230 if client_test
== None or client_test
== True:
8232 TEST_F(GLES2ImplementationTest, %(name)s) {
8238 ExpectedMemoryInfo result1 =
8239 GetExpectedResultMemory(sizeof(cmds::%(name)s::Result));
8240 expected.cmd.Init(%(cmd_id_value)s, result1.id, result1.offset);
8242 EXPECT_CALL(*command_buffer(), OnFlush())
8243 .WillOnce(SetMemory(result1.ptr, uint32_t(GL_TRUE)))
8244 .RetiresOnSaturation();
8246 GLboolean result = gl_->%(name)s(%(gl_id_value)s);
8247 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
8248 EXPECT_TRUE(result);
8251 args
= func
.GetOriginalArgs()
8252 assert len(args
) == 1
8255 'cmd_id_value': args
[0].GetValidClientSideCmdArg(func
),
8256 'gl_id_value': args
[0].GetValidClientSideArg(func
) })
8259 class STRnHandler(TypeHandler
):
8260 """Handler for GetProgramInfoLog, GetShaderInfoLog, GetShaderSource, and
8261 GetTranslatedShaderSourceANGLE."""
8264 TypeHandler
.__init
__(self
)
8266 def InitFunction(self
, func
):
8267 """Overrriden from TypeHandler."""
8268 # remove all but the first cmd args.
8269 cmd_args
= func
.GetCmdArgs()
8271 func
.AddCmdArg(cmd_args
[0])
8272 # add on a bucket id.
8273 func
.AddCmdArg(Argument('bucket_id', 'uint32_t'))
8275 def WriteGLES2Implementation(self
, func
, f
):
8276 """Overrriden from TypeHandler."""
8277 code_1
= """%(return_type)s GLES2Implementation::%(func_name)s(%(args)s) {
8278 GPU_CLIENT_SINGLE_THREAD_CHECK();
8280 code_2
= """ GPU_CLIENT_LOG("[" << GetLogPrefix()
8281 << "] gl%(func_name)s" << "("
8284 << static_cast<void*>(%(arg2)s) << ", "
8285 << static_cast<void*>(%(arg3)s) << ")");
8286 helper_->SetBucketSize(kResultBucketId, 0);
8287 helper_->%(func_name)s(%(id_name)s, kResultBucketId);
8289 GLsizei max_size = 0;
8290 if (GetBucketAsString(kResultBucketId, &str)) {
8293 std::min(static_cast<size_t>(%(bufsize_name)s) - 1, str.size());
8294 memcpy(%(dest_name)s, str.c_str(), max_size);
8295 %(dest_name)s[max_size] = '\\0';
8296 GPU_CLIENT_LOG("------\\n" << %(dest_name)s << "\\n------");
8299 if (%(length_name)s != NULL) {
8300 *%(length_name)s = max_size;
8305 args
= func
.GetOriginalArgs()
8307 'return_type': func
.return_type
,
8308 'func_name': func
.original_name
,
8309 'args': func
.MakeTypedOriginalArgString(""),
8310 'id_name': args
[0].name
,
8311 'bufsize_name': args
[1].name
,
8312 'length_name': args
[2].name
,
8313 'dest_name': args
[3].name
,
8314 'arg0': args
[0].name
,
8315 'arg1': args
[1].name
,
8316 'arg2': args
[2].name
,
8317 'arg3': args
[3].name
,
8319 f
.write(code_1
% str_args
)
8320 func
.WriteDestinationInitalizationValidation(f
)
8321 f
.write(code_2
% str_args
)
8323 def WriteServiceUnitTest(self
, func
, f
, *extras
):
8324 """Overrriden from TypeHandler."""
8326 TEST_P(%(test_name)s, %(name)sValidArgs) {
8327 const char* kInfo = "hello";
8328 const uint32_t kBucketId = 123;
8329 SpecializedSetup<cmds::%(name)s, 0>(true);
8331 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s))
8332 .WillOnce(DoAll(SetArgumentPointee<2>(strlen(kInfo)),
8333 SetArrayArgument<3>(kInfo, kInfo + strlen(kInfo) + 1)));
8336 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
8337 CommonDecoder::Bucket* bucket = decoder_->GetBucket(kBucketId);
8338 ASSERT_TRUE(bucket != NULL);
8339 EXPECT_EQ(strlen(kInfo) + 1, bucket->size());
8340 EXPECT_EQ(0, memcmp(bucket->GetData(0, bucket->size()), kInfo,
8342 EXPECT_EQ(GL_NO_ERROR, GetGLError());
8345 args
= func
.GetOriginalArgs()
8346 id_name
= args
[0].GetValidGLArg(func
)
8347 get_len_func
= func
.GetInfo('get_len_func')
8348 get_len_enum
= func
.GetInfo('get_len_enum')
8351 'get_len_func': get_len_func
,
8352 'get_len_enum': get_len_enum
,
8353 'gl_args': '%s, strlen(kInfo) + 1, _, _' %
8354 args
[0].GetValidGLArg(func
),
8355 'args': '%s, kBucketId' % args
[0].GetValidArg(func
),
8356 'expect_len_code': '',
8358 if get_len_func
and get_len_func
[0:2] == 'gl':
8359 sub
['expect_len_code'] = (
8360 " EXPECT_CALL(*gl_, %s(%s, %s, _))\n"
8361 " .WillOnce(SetArgumentPointee<2>(strlen(kInfo) + 1));") % (
8362 get_len_func
[2:], id_name
, get_len_enum
)
8363 self
.WriteValidUnitTest(func
, f
, valid_test
, sub
, *extras
)
8366 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
8367 const uint32_t kBucketId = 123;
8368 EXPECT_CALL(*gl_, %(gl_func_name)s(_, _, _, _))
8371 cmd.Init(kInvalidClientId, kBucketId);
8372 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
8373 EXPECT_EQ(GL_INVALID_VALUE, GetGLError());
8376 self
.WriteValidUnitTest(func
, f
, invalid_test
, *extras
)
8378 def WriteServiceImplementation(self
, func
, f
):
8379 """Overrriden from TypeHandler."""
8382 class NamedType(object):
8383 """A class that represents a type of an argument in a client function.
8385 A type of an argument that is to be passed through in the command buffer
8386 command. Currently used only for the arguments that are specificly named in
8387 the 'cmd_buffer_functions.txt' f, mostly enums.
8390 def __init__(self
, info
):
8391 assert not 'is_complete' in info
or info
['is_complete'] == True
8393 self
.valid
= info
['valid']
8394 if 'invalid' in info
:
8395 self
.invalid
= info
['invalid']
8398 if 'valid_es3' in info
:
8399 self
.valid_es3
= info
['valid_es3']
8402 if 'deprecated_es3' in info
:
8403 self
.deprecated_es3
= info
['deprecated_es3']
8405 self
.deprecated_es3
= []
8408 return self
.info
['type']
8410 def GetInvalidValues(self
):
8413 def GetValidValues(self
):
8416 def GetValidValuesES3(self
):
8417 return self
.valid_es3
8419 def GetDeprecatedValuesES3(self
):
8420 return self
.deprecated_es3
8422 def IsConstant(self
):
8423 if not 'is_complete' in self
.info
:
8426 return len(self
.GetValidValues()) == 1
8428 def GetConstantValue(self
):
8429 return self
.GetValidValues()[0]
8431 class Argument(object):
8432 """A class that represents a function argument."""
8435 'GLenum': 'uint32_t',
8437 'GLintptr': 'int32_t',
8438 'GLsizei': 'int32_t',
8439 'GLsizeiptr': 'int32_t',
8441 'GLclampf': 'float',
8443 need_validation_
= ['GLsizei*', 'GLboolean*', 'GLenum*', 'GLint*']
8445 def __init__(self
, name
, type):
8447 self
.optional
= type.endswith("Optional*")
8449 type = type[:-9] + "*"
8452 if type in self
.cmd_type_map_
:
8453 self
.cmd_type
= self
.cmd_type_map_
[type]
8455 self
.cmd_type
= 'uint32_t'
8457 def IsPointer(self
):
8458 """Returns true if argument is a pointer."""
8461 def IsPointer2D(self
):
8462 """Returns true if argument is a 2D pointer."""
8465 def IsConstant(self
):
8466 """Returns true if the argument has only one valid value."""
8469 def AddCmdArgs(self
, args
):
8470 """Adds command arguments for this argument to the given list."""
8471 if not self
.IsConstant():
8472 return args
.append(self
)
8474 def AddInitArgs(self
, args
):
8475 """Adds init arguments for this argument to the given list."""
8476 if not self
.IsConstant():
8477 return args
.append(self
)
8479 def GetValidArg(self
, func
):
8480 """Gets a valid value for this argument."""
8481 valid_arg
= func
.GetValidArg(self
)
8482 if valid_arg
!= None:
8485 index
= func
.GetOriginalArgs().index(self
)
8486 return str(index
+ 1)
8488 def GetValidClientSideArg(self
, func
):
8489 """Gets a valid value for this argument."""
8490 valid_arg
= func
.GetValidArg(self
)
8491 if valid_arg
!= None:
8494 if self
.IsPointer():
8496 index
= func
.GetOriginalArgs().index(self
)
8497 if self
.type == 'GLsync':
8498 return ("reinterpret_cast<GLsync>(%d)" % (index
+ 1))
8499 return str(index
+ 1)
8501 def GetValidClientSideCmdArg(self
, func
):
8502 """Gets a valid value for this argument."""
8503 valid_arg
= func
.GetValidArg(self
)
8504 if valid_arg
!= None:
8507 index
= func
.GetOriginalArgs().index(self
)
8508 return str(index
+ 1)
8511 index
= func
.GetCmdArgs().index(self
)
8512 return str(index
+ 1)
8514 def GetValidGLArg(self
, func
):
8515 """Gets a valid GL value for this argument."""
8516 value
= self
.GetValidArg(func
)
8517 if self
.type == 'GLsync':
8518 return ("reinterpret_cast<GLsync>(%s)" % value
)
8521 def GetValidNonCachedClientSideArg(self
, func
):
8522 """Returns a valid value for this argument in a GL call.
8523 Using the value will produce a command buffer service invocation.
8524 Returns None if there is no such value."""
8526 if self
.type == 'GLsync':
8527 return ("reinterpret_cast<GLsync>(%s)" % value
)
8530 def GetValidNonCachedClientSideCmdArg(self
, func
):
8531 """Returns a valid value for this argument in a command buffer command.
8532 Calling the GL function with the value returned by
8533 GetValidNonCachedClientSideArg will result in a command buffer command
8534 that contains the value returned by this function. """
8537 def GetNumInvalidValues(self
, func
):
8538 """returns the number of invalid values to be tested."""
8541 def GetInvalidArg(self
, index
):
8542 """returns an invalid value and expected parse result by index."""
8543 return ("---ERROR0---", "---ERROR2---", None)
8545 def GetLogArg(self
):
8546 """Get argument appropriate for LOG macro."""
8547 if self
.type == 'GLboolean':
8548 return 'GLES2Util::GetStringBool(%s)' % self
.name
8549 if self
.type == 'GLenum':
8550 return 'GLES2Util::GetStringEnum(%s)' % self
.name
8553 def WriteGetCode(self
, f
):
8554 """Writes the code to get an argument from a command structure."""
8555 if self
.type == 'GLsync':
8559 f
.write(" %s %s = static_cast<%s>(c.%s);\n" %
8560 (my_type
, self
.name
, my_type
, self
.name
))
8562 def WriteValidationCode(self
, f
, func
):
8563 """Writes the validation code for an argument."""
8566 def WriteClientSideValidationCode(self
, f
, func
):
8567 """Writes the validation code for an argument."""
8570 def WriteDestinationInitalizationValidation(self
, f
, func
):
8571 """Writes the client side destintion initialization validation."""
8574 def WriteDestinationInitalizationValidatationIfNeeded(self
, f
, func
):
8575 """Writes the client side destintion initialization validation if needed."""
8576 parts
= self
.type.split(" ")
8579 if parts
[0] in self
.need_validation_
:
8581 " GPU_CLIENT_VALIDATE_DESTINATION_%sINITALIZATION(%s, %s);\n" %
8582 ("OPTIONAL_" if self
.optional
else "", self
.type[:-1], self
.name
))
8585 def WriteGetAddress(self
, f
):
8586 """Writes the code to get the address this argument refers to."""
8589 def GetImmediateVersion(self
):
8590 """Gets the immediate version of this argument."""
8593 def GetBucketVersion(self
):
8594 """Gets the bucket version of this argument."""
8598 class BoolArgument(Argument
):
8599 """class for GLboolean"""
8601 def __init__(self
, name
, type):
8602 Argument
.__init
__(self
, name
, 'GLboolean')
8604 def GetValidArg(self
, func
):
8605 """Gets a valid value for this argument."""
8608 def GetValidClientSideArg(self
, func
):
8609 """Gets a valid value for this argument."""
8612 def GetValidClientSideCmdArg(self
, func
):
8613 """Gets a valid value for this argument."""
8616 def GetValidGLArg(self
, func
):
8617 """Gets a valid GL value for this argument."""
8621 class UniformLocationArgument(Argument
):
8622 """class for uniform locations."""
8624 def __init__(self
, name
):
8625 Argument
.__init
__(self
, name
, "GLint")
8627 def WriteGetCode(self
, f
):
8628 """Writes the code to get an argument from a command structure."""
8629 code
= """ %s %s = static_cast<%s>(c.%s);
8631 f
.write(code
% (self
.type, self
.name
, self
.type, self
.name
))
8633 class DataSizeArgument(Argument
):
8634 """class for data_size which Bucket commands do not need."""
8636 def __init__(self
, name
):
8637 Argument
.__init
__(self
, name
, "uint32_t")
8639 def GetBucketVersion(self
):
8643 class SizeArgument(Argument
):
8644 """class for GLsizei and GLsizeiptr."""
8646 def __init__(self
, name
, type):
8647 Argument
.__init
__(self
, name
, type)
8649 def GetNumInvalidValues(self
, func
):
8650 """overridden from Argument."""
8651 if func
.IsImmediate():
8655 def GetInvalidArg(self
, index
):
8656 """overridden from Argument."""
8657 return ("-1", "kNoError", "GL_INVALID_VALUE")
8659 def WriteValidationCode(self
, f
, func
):
8660 """overridden from Argument."""
8663 code
= """ if (%(var_name)s < 0) {
8664 LOCAL_SET_GL_ERROR(GL_INVALID_VALUE, "gl%(func_name)s", "%(var_name)s < 0");
8665 return error::kNoError;
8669 "var_name": self
.name
,
8670 "func_name": func
.original_name
,
8673 def WriteClientSideValidationCode(self
, f
, func
):
8674 """overridden from Argument."""
8675 code
= """ if (%(var_name)s < 0) {
8676 SetGLError(GL_INVALID_VALUE, "gl%(func_name)s", "%(var_name)s < 0");
8681 "var_name": self
.name
,
8682 "func_name": func
.original_name
,
8686 class SizeNotNegativeArgument(SizeArgument
):
8687 """class for GLsizeiNotNegative. It's NEVER allowed to be negative"""
8689 def __init__(self
, name
, type, gl_type
):
8690 SizeArgument
.__init
__(self
, name
, gl_type
)
8692 def GetInvalidArg(self
, index
):
8693 """overridden from SizeArgument."""
8694 return ("-1", "kOutOfBounds", "GL_NO_ERROR")
8696 def WriteValidationCode(self
, f
, func
):
8697 """overridden from SizeArgument."""
8701 class EnumBaseArgument(Argument
):
8702 """Base class for EnumArgument, IntArgument, BitfieldArgument, and
8703 ValidatedBoolArgument."""
8705 def __init__(self
, name
, gl_type
, type, gl_error
):
8706 Argument
.__init
__(self
, name
, gl_type
)
8708 self
.local_type
= type
8709 self
.gl_error
= gl_error
8710 name
= type[len(gl_type
):]
8711 self
.type_name
= name
8712 self
.named_type
= NamedType(_NAMED_TYPE_INFO
[name
])
8714 def IsConstant(self
):
8715 return self
.named_type
.IsConstant()
8717 def GetConstantValue(self
):
8718 return self
.named_type
.GetConstantValue()
8720 def WriteValidationCode(self
, f
, func
):
8723 if self
.named_type
.IsConstant():
8725 f
.write(" if (!validators_->%s.IsValid(%s)) {\n" %
8726 (ToUnderscore(self
.type_name
), self
.name
))
8727 if self
.gl_error
== "GL_INVALID_ENUM":
8729 " LOCAL_SET_GL_ERROR_INVALID_ENUM(\"gl%s\", %s, \"%s\");\n" %
8730 (func
.original_name
, self
.name
, self
.name
))
8733 " LOCAL_SET_GL_ERROR(%s, \"gl%s\", \"%s %s\");\n" %
8734 (self
.gl_error
, func
.original_name
, self
.name
, self
.gl_error
))
8735 f
.write(" return error::kNoError;\n")
8738 def WriteClientSideValidationCode(self
, f
, func
):
8739 if not self
.named_type
.IsConstant():
8741 f
.write(" if (%s != %s) {" % (self
.name
,
8742 self
.GetConstantValue()))
8744 " SetGLError(%s, \"gl%s\", \"%s %s\");\n" %
8745 (self
.gl_error
, func
.original_name
, self
.name
, self
.gl_error
))
8746 if func
.return_type
== "void":
8747 f
.write(" return;\n")
8749 f
.write(" return %s;\n" % func
.GetErrorReturnString())
8752 def GetValidArg(self
, func
):
8753 valid_arg
= func
.GetValidArg(self
)
8754 if valid_arg
!= None:
8756 valid
= self
.named_type
.GetValidValues()
8758 num_valid
= len(valid
)
8761 index
= func
.GetOriginalArgs().index(self
)
8762 return str(index
+ 1)
8764 def GetValidClientSideArg(self
, func
):
8765 """Gets a valid value for this argument."""
8766 return self
.GetValidArg(func
)
8768 def GetValidClientSideCmdArg(self
, func
):
8769 """Gets a valid value for this argument."""
8770 valid_arg
= func
.GetValidArg(self
)
8771 if valid_arg
!= None:
8774 valid
= self
.named_type
.GetValidValues()
8776 num_valid
= len(valid
)
8780 index
= func
.GetOriginalArgs().index(self
)
8781 return str(index
+ 1)
8784 index
= func
.GetCmdArgs().index(self
)
8785 return str(index
+ 1)
8787 def GetValidGLArg(self
, func
):
8788 """Gets a valid value for this argument."""
8789 return self
.GetValidArg(func
)
8791 def GetNumInvalidValues(self
, func
):
8792 """returns the number of invalid values to be tested."""
8793 return len(self
.named_type
.GetInvalidValues())
8795 def GetInvalidArg(self
, index
):
8796 """returns an invalid value by index."""
8797 invalid
= self
.named_type
.GetInvalidValues()
8799 num_invalid
= len(invalid
)
8800 if index
>= num_invalid
:
8801 index
= num_invalid
- 1
8802 return (invalid
[index
], "kNoError", self
.gl_error
)
8803 return ("---ERROR1---", "kNoError", self
.gl_error
)
8806 class EnumArgument(EnumBaseArgument
):
8807 """A class that represents a GLenum argument"""
8809 def __init__(self
, name
, type):
8810 EnumBaseArgument
.__init
__(self
, name
, "GLenum", type, "GL_INVALID_ENUM")
8812 def GetLogArg(self
):
8813 """Overridden from Argument."""
8814 return ("GLES2Util::GetString%s(%s)" %
8815 (self
.type_name
, self
.name
))
8818 class IntArgument(EnumBaseArgument
):
8819 """A class for a GLint argument that can only accept specific values.
8821 For example glTexImage2D takes a GLint for its internalformat
8822 argument instead of a GLenum.
8825 def __init__(self
, name
, type):
8826 EnumBaseArgument
.__init
__(self
, name
, "GLint", type, "GL_INVALID_VALUE")
8829 class ValidatedBoolArgument(EnumBaseArgument
):
8830 """A class for a GLboolean argument that can only accept specific values.
8832 For example glUniformMatrix takes a GLboolean for it's transpose but it
8836 def __init__(self
, name
, type):
8837 EnumBaseArgument
.__init
__(self
, name
, "GLboolean", type, "GL_INVALID_VALUE")
8839 def GetLogArg(self
):
8840 """Overridden from Argument."""
8841 return 'GLES2Util::GetStringBool(%s)' % self
.name
8844 class BitFieldArgument(EnumBaseArgument
):
8845 """A class for a GLbitfield argument that can only accept specific values.
8847 For example glFenceSync takes a GLbitfield for its flags argument bit it
8851 def __init__(self
, name
, type):
8852 EnumBaseArgument
.__init
__(self
, name
, "GLbitfield", type,
8856 class ImmediatePointerArgument(Argument
):
8857 """A class that represents an immediate argument to a function.
8859 An immediate argument is one where the data follows the command.
8862 def __init__(self
, name
, type):
8863 Argument
.__init
__(self
, name
, type)
8865 def IsPointer(self
):
8868 def GetPointedType(self
):
8869 match
= re
.match('(const\s+)?(?P<element_type>[\w]+)\s*\*', self
.type)
8871 return match
.groupdict()['element_type']
8873 def AddCmdArgs(self
, args
):
8874 """Overridden from Argument."""
8877 def WriteGetCode(self
, f
):
8878 """Overridden from Argument."""
8880 " %s %s = GetImmediateDataAs<%s>(\n" %
8881 (self
.type, self
.name
, self
.type))
8882 f
.write(" c, data_size, immediate_data_size);\n")
8884 def WriteValidationCode(self
, f
, func
):
8885 """Overridden from Argument."""
8888 f
.write(" if (%s == NULL) {\n" % self
.name
)
8889 f
.write(" return error::kOutOfBounds;\n")
8892 def GetImmediateVersion(self
):
8893 """Overridden from Argument."""
8896 def WriteDestinationInitalizationValidation(self
, f
, func
):
8897 """Overridden from Argument."""
8898 self
.WriteDestinationInitalizationValidatationIfNeeded(f
, func
)
8900 def GetLogArg(self
):
8901 """Overridden from Argument."""
8902 return "static_cast<const void*>(%s)" % self
.name
8905 class PointerArgument(Argument
):
8906 """A class that represents a pointer argument to a function."""
8908 def __init__(self
, name
, type):
8909 Argument
.__init
__(self
, name
, type)
8911 def IsPointer(self
):
8912 """Overridden from Argument."""
8915 def IsPointer2D(self
):
8916 """Overridden from Argument."""
8917 return self
.type.count('*') == 2
8919 def GetPointedType(self
):
8920 match
= re
.match('(const\s+)?(?P<element_type>[\w]+)\s*\*', self
.type)
8922 return match
.groupdict()['element_type']
8924 def GetValidArg(self
, func
):
8925 """Overridden from Argument."""
8926 return "shared_memory_id_, shared_memory_offset_"
8928 def GetValidGLArg(self
, func
):
8929 """Overridden from Argument."""
8930 return "reinterpret_cast<%s>(shared_memory_address_)" % self
.type
8932 def GetNumInvalidValues(self
, func
):
8933 """Overridden from Argument."""
8936 def GetInvalidArg(self
, index
):
8937 """Overridden from Argument."""
8939 return ("kInvalidSharedMemoryId, 0", "kOutOfBounds", None)
8941 return ("shared_memory_id_, kInvalidSharedMemoryOffset",
8942 "kOutOfBounds", None)
8944 def GetLogArg(self
):
8945 """Overridden from Argument."""
8946 return "static_cast<const void*>(%s)" % self
.name
8948 def AddCmdArgs(self
, args
):
8949 """Overridden from Argument."""
8950 args
.append(Argument("%s_shm_id" % self
.name
, 'uint32_t'))
8951 args
.append(Argument("%s_shm_offset" % self
.name
, 'uint32_t'))
8953 def WriteGetCode(self
, f
):
8954 """Overridden from Argument."""
8956 " %s %s = GetSharedMemoryAs<%s>(\n" %
8957 (self
.type, self
.name
, self
.type))
8959 " c.%s_shm_id, c.%s_shm_offset, data_size);\n" %
8960 (self
.name
, self
.name
))
8962 def WriteGetAddress(self
, f
):
8963 """Overridden from Argument."""
8965 " %s %s = GetSharedMemoryAs<%s>(\n" %
8966 (self
.type, self
.name
, self
.type))
8968 " %s_shm_id, %s_shm_offset, %s_size);\n" %
8969 (self
.name
, self
.name
, self
.name
))
8971 def WriteValidationCode(self
, f
, func
):
8972 """Overridden from Argument."""
8975 f
.write(" if (%s == NULL) {\n" % self
.name
)
8976 f
.write(" return error::kOutOfBounds;\n")
8979 def GetImmediateVersion(self
):
8980 """Overridden from Argument."""
8981 return ImmediatePointerArgument(self
.name
, self
.type)
8983 def GetBucketVersion(self
):
8984 """Overridden from Argument."""
8985 if self
.type.find('char') >= 0:
8986 if self
.IsPointer2D():
8987 return InputStringArrayBucketArgument(self
.name
, self
.type)
8988 return InputStringBucketArgument(self
.name
, self
.type)
8989 return BucketPointerArgument(self
.name
, self
.type)
8991 def WriteDestinationInitalizationValidation(self
, f
, func
):
8992 """Overridden from Argument."""
8993 self
.WriteDestinationInitalizationValidatationIfNeeded(f
, func
)
8996 class BucketPointerArgument(PointerArgument
):
8997 """A class that represents an bucket argument to a function."""
8999 def __init__(self
, name
, type):
9000 Argument
.__init
__(self
, name
, type)
9002 def AddCmdArgs(self
, args
):
9003 """Overridden from Argument."""
9006 def WriteGetCode(self
, f
):
9007 """Overridden from Argument."""
9009 " %s %s = bucket->GetData(0, data_size);\n" %
9010 (self
.type, self
.name
))
9012 def WriteValidationCode(self
, f
, func
):
9013 """Overridden from Argument."""
9016 def GetImmediateVersion(self
):
9017 """Overridden from Argument."""
9020 def WriteDestinationInitalizationValidation(self
, f
, func
):
9021 """Overridden from Argument."""
9022 self
.WriteDestinationInitalizationValidatationIfNeeded(f
, func
)
9024 def GetLogArg(self
):
9025 """Overridden from Argument."""
9026 return "static_cast<const void*>(%s)" % self
.name
9029 class InputStringBucketArgument(Argument
):
9030 """A string input argument where the string is passed in a bucket."""
9032 def __init__(self
, name
, type):
9033 Argument
.__init
__(self
, name
+ "_bucket_id", "uint32_t")
9035 def IsPointer(self
):
9036 """Overridden from Argument."""
9039 def IsPointer2D(self
):
9040 """Overridden from Argument."""
9044 class InputStringArrayBucketArgument(Argument
):
9045 """A string array input argument where the strings are passed in a bucket."""
9047 def __init__(self
, name
, type):
9048 Argument
.__init
__(self
, name
+ "_bucket_id", "uint32_t")
9049 self
._original
_name
= name
9051 def WriteGetCode(self
, f
):
9052 """Overridden from Argument."""
9054 Bucket* bucket = GetBucket(c.%(name)s);
9056 return error::kInvalidArguments;
9059 std::vector<char*> strs;
9060 std::vector<GLint> len;
9061 if (!bucket->GetAsStrings(&count, &strs, &len)) {
9062 return error::kInvalidArguments;
9064 const char** %(original_name)s =
9065 strs.size() > 0 ? const_cast<const char**>(&strs[0]) : NULL;
9066 const GLint* length =
9067 len.size() > 0 ? const_cast<const GLint*>(&len[0]) : NULL;
9072 'original_name': self
._original
_name
,
9075 def GetValidArg(self
, func
):
9076 return "kNameBucketId"
9078 def GetValidGLArg(self
, func
):
9081 def IsPointer(self
):
9082 """Overridden from Argument."""
9085 def IsPointer2D(self
):
9086 """Overridden from Argument."""
9090 class ResourceIdArgument(Argument
):
9091 """A class that represents a resource id argument to a function."""
9093 def __init__(self
, name
, type):
9094 match
= re
.match("(GLid\w+)", type)
9095 self
.resource_type
= match
.group(1)[4:]
9096 if self
.resource_type
== "Sync":
9097 type = type.replace(match
.group(1), "GLsync")
9099 type = type.replace(match
.group(1), "GLuint")
9100 Argument
.__init
__(self
, name
, type)
9102 def WriteGetCode(self
, f
):
9103 """Overridden from Argument."""
9104 if self
.type == "GLsync":
9108 f
.write(" %s %s = c.%s;\n" % (my_type
, self
.name
, self
.name
))
9110 def GetValidArg(self
, func
):
9111 return "client_%s_id_" % self
.resource_type
.lower()
9113 def GetValidGLArg(self
, func
):
9114 if self
.resource_type
== "Sync":
9115 return "reinterpret_cast<GLsync>(kService%sId)" % self
.resource_type
9116 return "kService%sId" % self
.resource_type
9119 class ResourceIdBindArgument(Argument
):
9120 """Represents a resource id argument to a bind function."""
9122 def __init__(self
, name
, type):
9123 match
= re
.match("(GLidBind\w+)", type)
9124 self
.resource_type
= match
.group(1)[8:]
9125 type = type.replace(match
.group(1), "GLuint")
9126 Argument
.__init
__(self
, name
, type)
9128 def WriteGetCode(self
, f
):
9129 """Overridden from Argument."""
9130 code
= """ %(type)s %(name)s = c.%(name)s;
9132 f
.write(code
% {'type': self
.type, 'name': self
.name
})
9134 def GetValidArg(self
, func
):
9135 return "client_%s_id_" % self
.resource_type
.lower()
9137 def GetValidGLArg(self
, func
):
9138 return "kService%sId" % self
.resource_type
9141 class ResourceIdZeroArgument(Argument
):
9142 """Represents a resource id argument to a function that can be zero."""
9144 def __init__(self
, name
, type):
9145 match
= re
.match("(GLidZero\w+)", type)
9146 self
.resource_type
= match
.group(1)[8:]
9147 type = type.replace(match
.group(1), "GLuint")
9148 Argument
.__init
__(self
, name
, type)
9150 def WriteGetCode(self
, f
):
9151 """Overridden from Argument."""
9152 f
.write(" %s %s = c.%s;\n" % (self
.type, self
.name
, self
.name
))
9154 def GetValidArg(self
, func
):
9155 return "client_%s_id_" % self
.resource_type
.lower()
9157 def GetValidGLArg(self
, func
):
9158 return "kService%sId" % self
.resource_type
9160 def GetNumInvalidValues(self
, func
):
9161 """returns the number of invalid values to be tested."""
9164 def GetInvalidArg(self
, index
):
9165 """returns an invalid value by index."""
9166 return ("kInvalidClientId", "kNoError", "GL_INVALID_VALUE")
9169 class Function(object):
9170 """A class that represents a function."""
9174 'Bind': BindHandler(),
9175 'Create': CreateHandler(),
9176 'Custom': CustomHandler(),
9177 'Data': DataHandler(),
9178 'Delete': DeleteHandler(),
9179 'DELn': DELnHandler(),
9180 'GENn': GENnHandler(),
9181 'GETn': GETnHandler(),
9182 'GLchar': GLcharHandler(),
9183 'GLcharN': GLcharNHandler(),
9184 'HandWritten': HandWrittenHandler(),
9186 'Manual': ManualHandler(),
9187 'PUT': PUTHandler(),
9188 'PUTn': PUTnHandler(),
9189 'PUTSTR': PUTSTRHandler(),
9190 'PUTXn': PUTXnHandler(),
9191 'StateSet': StateSetHandler(),
9192 'StateSetRGBAlpha': StateSetRGBAlphaHandler(),
9193 'StateSetFrontBack': StateSetFrontBackHandler(),
9194 'StateSetFrontBackSeparate': StateSetFrontBackSeparateHandler(),
9195 'StateSetNamedParameter': StateSetNamedParameter(),
9196 'STRn': STRnHandler(),
9197 'Todo': TodoHandler(),
9200 def __init__(self
, name
, info
):
9202 self
.original_name
= info
['original_name']
9204 self
.original_args
= self
.ParseArgs(info
['original_args'])
9206 if 'cmd_args' in info
:
9207 self
.args_for_cmds
= self
.ParseArgs(info
['cmd_args'])
9209 self
.args_for_cmds
= self
.original_args
[:]
9211 self
.return_type
= info
['return_type']
9212 if self
.return_type
!= 'void':
9213 self
.return_arg
= CreateArg(info
['return_type'] + " result")
9215 self
.return_arg
= None
9217 self
.num_pointer_args
= sum(
9218 [1 for arg
in self
.args_for_cmds
if arg
.IsPointer()])
9219 if self
.num_pointer_args
> 0:
9220 for arg
in reversed(self
.original_args
):
9222 self
.last_original_pointer_arg
= arg
9225 self
.last_original_pointer_arg
= None
9227 self
.type_handler
= self
.type_handlers
[info
['type']]
9228 self
.can_auto_generate
= (self
.num_pointer_args
== 0 and
9229 info
['return_type'] == "void")
9232 def ParseArgs(self
, arg_string
):
9233 """Parses a function arg string."""
9235 parts
= arg_string
.split(',')
9236 for arg_string
in parts
:
9237 arg
= CreateArg(arg_string
)
9242 def IsType(self
, type_name
):
9243 """Returns true if function is a certain type."""
9244 return self
.info
['type'] == type_name
9246 def InitFunction(self
):
9247 """Creates command args and calls the init function for the type handler.
9249 Creates argument lists for command buffer commands, eg. self.cmd_args and
9251 Calls the type function initialization.
9252 Override to create different kind of command buffer command argument lists.
9255 for arg
in self
.args_for_cmds
:
9256 arg
.AddCmdArgs(self
.cmd_args
)
9259 for arg
in self
.args_for_cmds
:
9260 arg
.AddInitArgs(self
.init_args
)
9263 self
.init_args
.append(self
.return_arg
)
9265 self
.type_handler
.InitFunction(self
)
9267 def IsImmediate(self
):
9268 """Returns whether the function is immediate data function or not."""
9272 """Returns whether the function has service side validation or not."""
9273 return self
.GetInfo('unsafe', False)
9275 def GetInfo(self
, name
, default
= None):
9276 """Returns a value from the function info for this function."""
9277 if name
in self
.info
:
9278 return self
.info
[name
]
9281 def GetValidArg(self
, arg
):
9282 """Gets a valid argument value for the parameter arg from the function info
9285 index
= self
.GetOriginalArgs().index(arg
)
9289 valid_args
= self
.GetInfo('valid_args')
9290 if valid_args
and str(index
) in valid_args
:
9291 return valid_args
[str(index
)]
9294 def AddInfo(self
, name
, value
):
9296 self
.info
[name
] = value
9298 def IsExtension(self
):
9299 return self
.GetInfo('extension') or self
.GetInfo('extension_flag')
9301 def IsCoreGLFunction(self
):
9302 return (not self
.IsExtension() and
9303 not self
.GetInfo('pepper_interface') and
9304 not self
.IsUnsafe())
9306 def InPepperInterface(self
, interface
):
9307 ext
= self
.GetInfo('pepper_interface')
9308 if not interface
.GetName():
9309 return self
.IsCoreGLFunction()
9310 return ext
== interface
.GetName()
9312 def InAnyPepperExtension(self
):
9313 return self
.IsCoreGLFunction() or self
.GetInfo('pepper_interface')
9315 def GetErrorReturnString(self
):
9316 if self
.GetInfo("error_return"):
9317 return self
.GetInfo("error_return")
9318 elif self
.return_type
== "GLboolean":
9320 elif "*" in self
.return_type
:
9324 def GetGLFunctionName(self
):
9325 """Gets the function to call to execute GL for this command."""
9326 if self
.GetInfo('decoder_func'):
9327 return self
.GetInfo('decoder_func')
9328 return "gl%s" % self
.original_name
9330 def GetGLTestFunctionName(self
):
9331 gl_func_name
= self
.GetInfo('gl_test_func')
9332 if gl_func_name
== None:
9333 gl_func_name
= self
.GetGLFunctionName()
9334 if gl_func_name
.startswith("gl"):
9335 gl_func_name
= gl_func_name
[2:]
9337 gl_func_name
= self
.original_name
9340 def GetDataTransferMethods(self
):
9341 return self
.GetInfo('data_transfer_methods',
9342 ['immediate' if self
.num_pointer_args
== 1 else 'shm'])
9344 def AddCmdArg(self
, arg
):
9345 """Adds a cmd argument to this function."""
9346 self
.cmd_args
.append(arg
)
9348 def GetCmdArgs(self
):
9349 """Gets the command args for this function."""
9350 return self
.cmd_args
9352 def ClearCmdArgs(self
):
9353 """Clears the command args for this function."""
9356 def GetCmdConstants(self
):
9357 """Gets the constants for this function."""
9358 return [arg
for arg
in self
.args_for_cmds
if arg
.IsConstant()]
9360 def GetInitArgs(self
):
9361 """Gets the init args for this function."""
9362 return self
.init_args
9364 def GetOriginalArgs(self
):
9365 """Gets the original arguments to this function."""
9366 return self
.original_args
9368 def GetLastOriginalArg(self
):
9369 """Gets the last original argument to this function."""
9370 return self
.original_args
[len(self
.original_args
) - 1]
9372 def GetLastOriginalPointerArg(self
):
9373 return self
.last_original_pointer_arg
9375 def GetResourceIdArg(self
):
9376 for arg
in self
.original_args
:
9377 if hasattr(arg
, 'resource_type'):
9381 def _MaybePrependComma(self
, arg_string
, add_comma
):
9382 """Adds a comma if arg_string is not empty and add_comma is true."""
9384 if add_comma
and len(arg_string
):
9386 return "%s%s" % (comma
, arg_string
)
9388 def MakeTypedOriginalArgString(self
, prefix
, add_comma
= False):
9389 """Gets a list of arguments as they are in GL."""
9390 args
= self
.GetOriginalArgs()
9391 arg_string
= ", ".join(
9392 ["%s %s%s" % (arg
.type, prefix
, arg
.name
) for arg
in args
])
9393 return self
._MaybePrependComma
(arg_string
, add_comma
)
9395 def MakeOriginalArgString(self
, prefix
, add_comma
= False, separator
= ", "):
9396 """Gets the list of arguments as they are in GL."""
9397 args
= self
.GetOriginalArgs()
9398 arg_string
= separator
.join(
9399 ["%s%s" % (prefix
, arg
.name
) for arg
in args
])
9400 return self
._MaybePrependComma
(arg_string
, add_comma
)
9402 def MakeTypedHelperArgString(self
, prefix
, add_comma
= False):
9403 """Gets a list of typed GL arguments after removing unneeded arguments."""
9404 args
= self
.GetOriginalArgs()
9405 arg_string
= ", ".join(
9410 ) for arg
in args
if not arg
.IsConstant()])
9411 return self
._MaybePrependComma
(arg_string
, add_comma
)
9413 def MakeHelperArgString(self
, prefix
, add_comma
= False, separator
= ", "):
9414 """Gets a list of GL arguments after removing unneeded arguments."""
9415 args
= self
.GetOriginalArgs()
9416 arg_string
= separator
.join(
9417 ["%s%s" % (prefix
, arg
.name
)
9418 for arg
in args
if not arg
.IsConstant()])
9419 return self
._MaybePrependComma
(arg_string
, add_comma
)
9421 def MakeTypedPepperArgString(self
, prefix
):
9422 """Gets a list of arguments as they need to be for Pepper."""
9423 if self
.GetInfo("pepper_args"):
9424 return self
.GetInfo("pepper_args")
9426 return self
.MakeTypedOriginalArgString(prefix
, False)
9428 def MapCTypeToPepperIdlType(self
, ctype
, is_for_return_type
=False):
9429 """Converts a C type name to the corresponding Pepper IDL type."""
9431 'char*': '[out] str_t',
9432 'const GLchar* const*': '[out] cstr_t',
9433 'const char*': 'cstr_t',
9434 'const void*': 'mem_t',
9435 'void*': '[out] mem_t',
9436 'void**': '[out] mem_ptr_t',
9438 # We use "GLxxx_ptr_t" for "GLxxx*".
9439 matched
= re
.match(r
'(const )?(GL\w+)\*$', ctype
)
9441 idltype
= matched
.group(2) + '_ptr_t'
9442 if not matched
.group(1):
9443 idltype
= '[out] ' + idltype
9444 # If an in/out specifier is not specified yet, prepend [in].
9445 if idltype
[0] != '[':
9446 idltype
= '[in] ' + idltype
9447 # Strip the in/out specifier for a return type.
9448 if is_for_return_type
:
9449 idltype
= re
.sub(r
'\[\w+\] ', '', idltype
)
9452 def MakeTypedPepperIdlArgStrings(self
):
9453 """Gets a list of arguments as they need to be for Pepper IDL."""
9454 args
= self
.GetOriginalArgs()
9455 return ["%s %s" % (self
.MapCTypeToPepperIdlType(arg
.type), arg
.name
)
9458 def GetPepperName(self
):
9459 if self
.GetInfo("pepper_name"):
9460 return self
.GetInfo("pepper_name")
9463 def MakeTypedCmdArgString(self
, prefix
, add_comma
= False):
9464 """Gets a typed list of arguments as they need to be for command buffers."""
9465 args
= self
.GetCmdArgs()
9466 arg_string
= ", ".join(
9467 ["%s %s%s" % (arg
.type, prefix
, arg
.name
) for arg
in args
])
9468 return self
._MaybePrependComma
(arg_string
, add_comma
)
9470 def MakeCmdArgString(self
, prefix
, add_comma
= False):
9471 """Gets the list of arguments as they need to be for command buffers."""
9472 args
= self
.GetCmdArgs()
9473 arg_string
= ", ".join(
9474 ["%s%s" % (prefix
, arg
.name
) for arg
in args
])
9475 return self
._MaybePrependComma
(arg_string
, add_comma
)
9477 def MakeTypedInitString(self
, prefix
, add_comma
= False):
9478 """Gets a typed list of arguments as they need to be for cmd Init/Set."""
9479 args
= self
.GetInitArgs()
9480 arg_string
= ", ".join(
9481 ["%s %s%s" % (arg
.type, prefix
, arg
.name
) for arg
in args
])
9482 return self
._MaybePrependComma
(arg_string
, add_comma
)
9484 def MakeInitString(self
, prefix
, add_comma
= False):
9485 """Gets the list of arguments as they need to be for cmd Init/Set."""
9486 args
= self
.GetInitArgs()
9487 arg_string
= ", ".join(
9488 ["%s%s" % (prefix
, arg
.name
) for arg
in args
])
9489 return self
._MaybePrependComma
(arg_string
, add_comma
)
9491 def MakeLogArgString(self
):
9492 """Makes a string of the arguments for the LOG macros"""
9493 args
= self
.GetOriginalArgs()
9494 return ' << ", " << '.join([arg
.GetLogArg() for arg
in args
])
9496 def WriteCommandDescription(self
, f
):
9497 """Writes a description of the command."""
9498 f
.write("//! Command that corresponds to gl%s.\n" % self
.original_name
)
9500 def WriteHandlerValidation(self
, f
):
9501 """Writes validation code for the function."""
9502 for arg
in self
.GetOriginalArgs():
9503 arg
.WriteValidationCode(f
, self
)
9504 self
.WriteValidationCode(f
)
9506 def WriteHandlerImplementation(self
, f
):
9507 """Writes the handler implementation for this command."""
9508 self
.type_handler
.WriteHandlerImplementation(self
, f
)
9510 def WriteValidationCode(self
, f
):
9511 """Writes the validation code for a command."""
9514 def WriteCmdFlag(self
, f
):
9515 """Writes the cmd cmd_flags constant."""
9517 # By default trace only at the highest level 3.
9518 trace_level
= int(self
.GetInfo('trace_level', default
= 3))
9519 if trace_level
not in xrange(0, 4):
9520 raise KeyError("Unhandled trace_level: %d" % trace_level
)
9522 flags
.append('CMD_FLAG_SET_TRACE_LEVEL(%d)' % trace_level
)
9525 cmd_flags
= ' | '.join(flags
)
9529 f
.write(" static const uint8 cmd_flags = %s;\n" % cmd_flags
)
9532 def WriteCmdArgFlag(self
, f
):
9533 """Writes the cmd kArgFlags constant."""
9534 f
.write(" static const cmd::ArgFlags kArgFlags = cmd::kFixed;\n")
9536 def WriteCmdComputeSize(self
, f
):
9537 """Writes the ComputeSize function for the command."""
9538 f
.write(" static uint32_t ComputeSize() {\n")
9540 " return static_cast<uint32_t>(sizeof(ValueType)); // NOLINT\n")
9544 def WriteCmdSetHeader(self
, f
):
9545 """Writes the cmd's SetHeader function."""
9546 f
.write(" void SetHeader() {\n")
9547 f
.write(" header.SetCmd<ValueType>();\n")
9551 def WriteCmdInit(self
, f
):
9552 """Writes the cmd's Init function."""
9553 f
.write(" void Init(%s) {\n" % self
.MakeTypedCmdArgString("_"))
9554 f
.write(" SetHeader();\n")
9555 args
= self
.GetCmdArgs()
9557 f
.write(" %s = _%s;\n" % (arg
.name
, arg
.name
))
9561 def WriteCmdSet(self
, f
):
9562 """Writes the cmd's Set function."""
9563 copy_args
= self
.MakeCmdArgString("_", False)
9564 f
.write(" void* Set(void* cmd%s) {\n" %
9565 self
.MakeTypedCmdArgString("_", True))
9566 f
.write(" static_cast<ValueType*>(cmd)->Init(%s);\n" % copy_args
)
9567 f
.write(" return NextCmdAddress<ValueType>(cmd);\n")
9571 def WriteStruct(self
, f
):
9572 self
.type_handler
.WriteStruct(self
, f
)
9574 def WriteDocs(self
, f
):
9575 self
.type_handler
.WriteDocs(self
, f
)
9577 def WriteCmdHelper(self
, f
):
9578 """Writes the cmd's helper."""
9579 self
.type_handler
.WriteCmdHelper(self
, f
)
9581 def WriteServiceImplementation(self
, f
):
9582 """Writes the service implementation for a command."""
9583 self
.type_handler
.WriteServiceImplementation(self
, f
)
9585 def WriteServiceUnitTest(self
, f
, *extras
):
9586 """Writes the service implementation for a command."""
9587 self
.type_handler
.WriteServiceUnitTest(self
, f
, *extras
)
9589 def WriteGLES2CLibImplementation(self
, f
):
9590 """Writes the GLES2 C Lib Implemention."""
9591 self
.type_handler
.WriteGLES2CLibImplementation(self
, f
)
9593 def WriteGLES2InterfaceHeader(self
, f
):
9594 """Writes the GLES2 Interface declaration."""
9595 self
.type_handler
.WriteGLES2InterfaceHeader(self
, f
)
9597 def WriteMojoGLES2ImplHeader(self
, f
):
9598 """Writes the Mojo GLES2 implementation header declaration."""
9599 self
.type_handler
.WriteMojoGLES2ImplHeader(self
, f
)
9601 def WriteMojoGLES2Impl(self
, f
):
9602 """Writes the Mojo GLES2 implementation declaration."""
9603 self
.type_handler
.WriteMojoGLES2Impl(self
, f
)
9605 def WriteGLES2InterfaceStub(self
, f
):
9606 """Writes the GLES2 Interface Stub declaration."""
9607 self
.type_handler
.WriteGLES2InterfaceStub(self
, f
)
9609 def WriteGLES2InterfaceStubImpl(self
, f
):
9610 """Writes the GLES2 Interface Stub declaration."""
9611 self
.type_handler
.WriteGLES2InterfaceStubImpl(self
, f
)
9613 def WriteGLES2ImplementationHeader(self
, f
):
9614 """Writes the GLES2 Implemention declaration."""
9615 self
.type_handler
.WriteGLES2ImplementationHeader(self
, f
)
9617 def WriteGLES2Implementation(self
, f
):
9618 """Writes the GLES2 Implemention definition."""
9619 self
.type_handler
.WriteGLES2Implementation(self
, f
)
9621 def WriteGLES2TraceImplementationHeader(self
, f
):
9622 """Writes the GLES2 Trace Implemention declaration."""
9623 self
.type_handler
.WriteGLES2TraceImplementationHeader(self
, f
)
9625 def WriteGLES2TraceImplementation(self
, f
):
9626 """Writes the GLES2 Trace Implemention definition."""
9627 self
.type_handler
.WriteGLES2TraceImplementation(self
, f
)
9629 def WriteGLES2Header(self
, f
):
9630 """Writes the GLES2 Implemention unit test."""
9631 self
.type_handler
.WriteGLES2Header(self
, f
)
9633 def WriteGLES2ImplementationUnitTest(self
, f
):
9634 """Writes the GLES2 Implemention unit test."""
9635 self
.type_handler
.WriteGLES2ImplementationUnitTest(self
, f
)
9637 def WriteDestinationInitalizationValidation(self
, f
):
9638 """Writes the client side destintion initialization validation."""
9639 self
.type_handler
.WriteDestinationInitalizationValidation(self
, f
)
9641 def WriteFormatTest(self
, f
):
9642 """Writes the cmd's format test."""
9643 self
.type_handler
.WriteFormatTest(self
, f
)
9646 class PepperInterface(object):
9647 """A class that represents a function."""
9649 def __init__(self
, info
):
9650 self
.name
= info
["name"]
9651 self
.dev
= info
["dev"]
9656 def GetInterfaceName(self
):
9660 upperint
= "_" + self
.name
.upper()
9663 return "PPB_OPENGLES2%s%s_INTERFACE" % (upperint
, dev
)
9665 def GetInterfaceString(self
):
9669 return "PPB_OpenGLES2%s%s" % (self
.name
, dev
)
9671 def GetStructName(self
):
9675 return "PPB_OpenGLES2%s%s" % (self
.name
, dev
)
9678 class ImmediateFunction(Function
):
9679 """A class that represnets an immediate function command."""
9681 def __init__(self
, func
):
9684 "%sImmediate" % func
.name
,
9687 def InitFunction(self
):
9688 # Override args in original_args and args_for_cmds with immediate versions
9691 new_original_args
= []
9692 for arg
in self
.original_args
:
9693 new_arg
= arg
.GetImmediateVersion()
9695 new_original_args
.append(new_arg
)
9696 self
.original_args
= new_original_args
9698 new_args_for_cmds
= []
9699 for arg
in self
.args_for_cmds
:
9700 new_arg
= arg
.GetImmediateVersion()
9702 new_args_for_cmds
.append(new_arg
)
9704 self
.args_for_cmds
= new_args_for_cmds
9706 Function
.InitFunction(self
)
9708 def IsImmediate(self
):
9711 def WriteCommandDescription(self
, f
):
9712 """Overridden from Function"""
9713 f
.write("//! Immediate version of command that corresponds to gl%s.\n" %
9716 def WriteServiceImplementation(self
, f
):
9717 """Overridden from Function"""
9718 self
.type_handler
.WriteImmediateServiceImplementation(self
, f
)
9720 def WriteHandlerImplementation(self
, f
):
9721 """Overridden from Function"""
9722 self
.type_handler
.WriteImmediateHandlerImplementation(self
, f
)
9724 def WriteServiceUnitTest(self
, f
, *extras
):
9725 """Writes the service implementation for a command."""
9726 self
.type_handler
.WriteImmediateServiceUnitTest(self
, f
, *extras
)
9728 def WriteValidationCode(self
, f
):
9729 """Overridden from Function"""
9730 self
.type_handler
.WriteImmediateValidationCode(self
, f
)
9732 def WriteCmdArgFlag(self
, f
):
9733 """Overridden from Function"""
9734 f
.write(" static const cmd::ArgFlags kArgFlags = cmd::kAtLeastN;\n")
9736 def WriteCmdComputeSize(self
, f
):
9737 """Overridden from Function"""
9738 self
.type_handler
.WriteImmediateCmdComputeSize(self
, f
)
9740 def WriteCmdSetHeader(self
, f
):
9741 """Overridden from Function"""
9742 self
.type_handler
.WriteImmediateCmdSetHeader(self
, f
)
9744 def WriteCmdInit(self
, f
):
9745 """Overridden from Function"""
9746 self
.type_handler
.WriteImmediateCmdInit(self
, f
)
9748 def WriteCmdSet(self
, f
):
9749 """Overridden from Function"""
9750 self
.type_handler
.WriteImmediateCmdSet(self
, f
)
9752 def WriteCmdHelper(self
, f
):
9753 """Overridden from Function"""
9754 self
.type_handler
.WriteImmediateCmdHelper(self
, f
)
9756 def WriteFormatTest(self
, f
):
9757 """Overridden from Function"""
9758 self
.type_handler
.WriteImmediateFormatTest(self
, f
)
9761 class BucketFunction(Function
):
9762 """A class that represnets a bucket version of a function command."""
9764 def __init__(self
, func
):
9767 "%sBucket" % func
.name
,
9770 def InitFunction(self
):
9771 # Override args in original_args and args_for_cmds with bucket versions
9774 new_original_args
= []
9775 for arg
in self
.original_args
:
9776 new_arg
= arg
.GetBucketVersion()
9778 new_original_args
.append(new_arg
)
9779 self
.original_args
= new_original_args
9781 new_args_for_cmds
= []
9782 for arg
in self
.args_for_cmds
:
9783 new_arg
= arg
.GetBucketVersion()
9785 new_args_for_cmds
.append(new_arg
)
9787 self
.args_for_cmds
= new_args_for_cmds
9789 Function
.InitFunction(self
)
9791 def WriteCommandDescription(self
, f
):
9792 """Overridden from Function"""
9793 f
.write("//! Bucket version of command that corresponds to gl%s.\n" %
9796 def WriteServiceImplementation(self
, f
):
9797 """Overridden from Function"""
9798 self
.type_handler
.WriteBucketServiceImplementation(self
, f
)
9800 def WriteHandlerImplementation(self
, f
):
9801 """Overridden from Function"""
9802 self
.type_handler
.WriteBucketHandlerImplementation(self
, f
)
9804 def WriteServiceUnitTest(self
, f
, *extras
):
9805 """Overridden from Function"""
9806 self
.type_handler
.WriteBucketServiceUnitTest(self
, f
, *extras
)
9808 def MakeOriginalArgString(self
, prefix
, add_comma
= False, separator
= ", "):
9809 """Overridden from Function"""
9810 args
= self
.GetOriginalArgs()
9811 arg_string
= separator
.join(
9812 ["%s%s" % (prefix
, arg
.name
[0:-10] if arg
.name
.endswith("_bucket_id")
9813 else arg
.name
) for arg
in args
])
9814 return super(BucketFunction
, self
)._MaybePrependComma
(arg_string
, add_comma
)
9817 def CreateArg(arg_string
):
9818 """Creates an Argument."""
9819 arg_parts
= arg_string
.split()
9820 if len(arg_parts
) == 1 and arg_parts
[0] == 'void':
9822 # Is this a pointer argument?
9823 elif arg_string
.find('*') >= 0:
9824 return PointerArgument(
9826 " ".join(arg_parts
[0:-1]))
9827 # Is this a resource argument? Must come after pointer check.
9828 elif arg_parts
[0].startswith('GLidBind'):
9829 return ResourceIdBindArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
9830 elif arg_parts
[0].startswith('GLidZero'):
9831 return ResourceIdZeroArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
9832 elif arg_parts
[0].startswith('GLid'):
9833 return ResourceIdArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
9834 elif arg_parts
[0].startswith('GLenum') and len(arg_parts
[0]) > 6:
9835 return EnumArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
9836 elif arg_parts
[0].startswith('GLbitfield') and len(arg_parts
[0]) > 10:
9837 return BitFieldArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
9838 elif arg_parts
[0].startswith('GLboolean') and len(arg_parts
[0]) > 9:
9839 return ValidatedBoolArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
9840 elif arg_parts
[0].startswith('GLboolean'):
9841 return BoolArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
9842 elif arg_parts
[0].startswith('GLintUniformLocation'):
9843 return UniformLocationArgument(arg_parts
[-1])
9844 elif (arg_parts
[0].startswith('GLint') and len(arg_parts
[0]) > 5 and
9845 not arg_parts
[0].startswith('GLintptr')):
9846 return IntArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
9847 elif (arg_parts
[0].startswith('GLsizeiNotNegative') or
9848 arg_parts
[0].startswith('GLintptrNotNegative')):
9849 return SizeNotNegativeArgument(arg_parts
[-1],
9850 " ".join(arg_parts
[0:-1]),
9851 arg_parts
[0][0:-11])
9852 elif arg_parts
[0].startswith('GLsize'):
9853 return SizeArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
9855 return Argument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
9858 class GLGenerator(object):
9859 """A class to generate GL command buffers."""
9861 _function_re
= re
.compile(r
'GL_APICALL(.*?)GL_APIENTRY (.*?) \((.*?)\);')
9863 def __init__(self
, verbose
):
9864 self
.original_functions
= []
9866 self
.verbose
= verbose
9868 self
.pepper_interfaces
= []
9869 self
.interface_info
= {}
9870 self
.generated_cpp_filenames
= []
9872 for interface
in _PEPPER_INTERFACES
:
9873 interface
= PepperInterface(interface
)
9874 self
.pepper_interfaces
.append(interface
)
9875 self
.interface_info
[interface
.GetName()] = interface
9877 def AddFunction(self
, func
):
9878 """Adds a function."""
9879 self
.functions
.append(func
)
9881 def GetFunctionInfo(self
, name
):
9882 """Gets a type info for the given function name."""
9883 if name
in _FUNCTION_INFO
:
9884 func_info
= _FUNCTION_INFO
[name
].copy()
9888 if not 'type' in func_info
:
9889 func_info
['type'] = ''
9894 """Prints something if verbose is true."""
9898 def Error(self
, msg
):
9899 """Prints an error."""
9900 print "Error: %s" % msg
9903 def WriteLicense(self
, f
):
9904 """Writes the license."""
9907 def WriteNamespaceOpen(self
, f
):
9908 """Writes the code for the namespace."""
9909 f
.write("namespace gpu {\n")
9910 f
.write("namespace gles2 {\n")
9913 def WriteNamespaceClose(self
, f
):
9914 """Writes the code to close the namespace."""
9915 f
.write("} // namespace gles2\n")
9916 f
.write("} // namespace gpu\n")
9919 def ParseGLH(self
, filename
):
9920 """Parses the cmd_buffer_functions.txt file and extracts the functions"""
9921 with
open(filename
, "r") as f
:
9922 functions
= f
.read()
9923 for line
in functions
.splitlines():
9924 match
= self
._function
_re
.match(line
)
9926 func_name
= match
.group(2)[2:]
9927 func_info
= self
.GetFunctionInfo(func_name
)
9928 if func_info
['type'] == 'Noop':
9931 parsed_func_info
= {
9932 'original_name': func_name
,
9933 'original_args': match
.group(3),
9934 'return_type': match
.group(1).strip(),
9937 for k
in parsed_func_info
.keys():
9938 if not k
in func_info
:
9939 func_info
[k
] = parsed_func_info
[k
]
9941 f
= Function(func_name
, func_info
)
9942 self
.original_functions
.append(f
)
9944 #for arg in f.GetOriginalArgs():
9945 # if not isinstance(arg, EnumArgument) and arg.type == 'GLenum':
9946 # self.Log("%s uses bare GLenum %s." % (func_name, arg.name))
9948 gen_cmd
= f
.GetInfo('gen_cmd')
9949 if gen_cmd
== True or gen_cmd
== None:
9950 if f
.type_handler
.NeedsDataTransferFunction(f
):
9951 methods
= f
.GetDataTransferMethods()
9952 if 'immediate' in methods
:
9953 self
.AddFunction(ImmediateFunction(f
))
9954 if 'bucket' in methods
:
9955 self
.AddFunction(BucketFunction(f
))
9956 if 'shm' in methods
:
9961 self
.Log("Auto Generated Functions : %d" %
9962 len([f
for f
in self
.functions
if f
.can_auto_generate
or
9963 (not f
.IsType('') and not f
.IsType('Custom') and
9964 not f
.IsType('Todo'))]))
9966 funcs
= [f
for f
in self
.functions
if not f
.can_auto_generate
and
9967 (f
.IsType('') or f
.IsType('Custom') or f
.IsType('Todo'))]
9968 self
.Log("Non Auto Generated Functions: %d" % len(funcs
))
9971 self
.Log(" %-10s %-20s gl%s" % (f
.info
['type'], f
.return_type
, f
.name
))
9973 def WriteCommandIds(self
, filename
):
9974 """Writes the command buffer format"""
9975 with
CHeaderWriter(filename
) as f
:
9976 f
.write("#define GLES2_COMMAND_LIST(OP) \\\n")
9978 for func
in self
.functions
:
9979 f
.write(" %-60s /* %d */ \\\n" %
9980 ("OP(%s)" % func
.name
, id))
9984 f
.write("enum CommandId {\n")
9985 f
.write(" kStartPoint = cmd::kLastCommonId, "
9986 "// All GLES2 commands start after this.\n")
9987 f
.write("#define GLES2_CMD_OP(name) k ## name,\n")
9988 f
.write(" GLES2_COMMAND_LIST(GLES2_CMD_OP)\n")
9989 f
.write("#undef GLES2_CMD_OP\n")
9990 f
.write(" kNumCommands\n")
9993 self
.generated_cpp_filenames
.append(filename
)
9995 def WriteFormat(self
, filename
):
9996 """Writes the command buffer format"""
9997 with
CHeaderWriter(filename
) as f
:
9998 # Forward declaration of a few enums used in constant argument
9999 # to avoid including GL header files.
10001 'GL_SYNC_GPU_COMMANDS_COMPLETE': '0x9117',
10002 'GL_SYNC_FLUSH_COMMANDS_BIT': '0x00000001',
10005 for enum
in enum_defines
:
10006 f
.write("#define %s %s\n" % (enum
, enum_defines
[enum
]))
10008 for func
in self
.functions
:
10010 #gen_cmd = func.GetInfo('gen_cmd')
10011 #if gen_cmd == True or gen_cmd == None:
10012 func
.WriteStruct(f
)
10014 self
.generated_cpp_filenames
.append(filename
)
10016 def WriteDocs(self
, filename
):
10017 """Writes the command buffer doc version of the commands"""
10018 with
CHeaderWriter(filename
) as f
:
10019 for func
in self
.functions
:
10021 #gen_cmd = func.GetInfo('gen_cmd')
10022 #if gen_cmd == True or gen_cmd == None:
10025 self
.generated_cpp_filenames
.append(filename
)
10027 def WriteFormatTest(self
, filename
):
10028 """Writes the command buffer format test."""
10029 comment
= ("// This file contains unit tests for gles2 commmands\n"
10030 "// It is included by gles2_cmd_format_test.cc\n\n")
10031 with
CHeaderWriter(filename
, comment
) as f
:
10032 for func
in self
.functions
:
10034 #gen_cmd = func.GetInfo('gen_cmd')
10035 #if gen_cmd == True or gen_cmd == None:
10036 func
.WriteFormatTest(f
)
10037 self
.generated_cpp_filenames
.append(filename
)
10039 def WriteCmdHelperHeader(self
, filename
):
10040 """Writes the gles2 command helper."""
10041 with
CHeaderWriter(filename
) as f
:
10042 for func
in self
.functions
:
10044 #gen_cmd = func.GetInfo('gen_cmd')
10045 #if gen_cmd == True or gen_cmd == None:
10046 func
.WriteCmdHelper(f
)
10047 self
.generated_cpp_filenames
.append(filename
)
10049 def WriteServiceContextStateHeader(self
, filename
):
10050 """Writes the service context state header."""
10051 comment
= "// It is included by context_state.h\n"
10052 with
CHeaderWriter(filename
, comment
) as f
:
10053 f
.write("struct EnableFlags {\n")
10054 f
.write(" EnableFlags();\n")
10055 for capability
in _CAPABILITY_FLAGS
:
10056 f
.write(" bool %s;\n" % capability
['name'])
10057 f
.write(" bool cached_%s;\n" % capability
['name'])
10060 for state_name
in sorted(_STATES
.keys()):
10061 state
= _STATES
[state_name
]
10062 for item
in state
['states']:
10063 if isinstance(item
['default'], list):
10064 f
.write("%s %s[%d];\n" % (item
['type'], item
['name'],
10065 len(item
['default'])))
10067 f
.write("%s %s;\n" % (item
['type'], item
['name']))
10069 if item
.get('cached', False):
10070 if isinstance(item
['default'], list):
10071 f
.write("%s cached_%s[%d];\n" % (item
['type'], item
['name'],
10072 len(item
['default'])))
10074 f
.write("%s cached_%s;\n" % (item
['type'], item
['name']))
10078 inline void SetDeviceCapabilityState(GLenum cap, bool enable) {
10081 for capability
in _CAPABILITY_FLAGS
:
10084 """ % capability
['name'].upper())
10086 if (enable_flags.cached_%(name)s == enable &&
10087 !ignore_cached_state)
10089 enable_flags.cached_%(name)s = enable;
10104 self
.generated_cpp_filenames
.append(filename
)
10106 def WriteClientContextStateHeader(self
, filename
):
10107 """Writes the client context state header."""
10108 comment
= "// It is included by client_context_state.h\n"
10109 with
CHeaderWriter(filename
, comment
) as f
:
10110 f
.write("struct EnableFlags {\n")
10111 f
.write(" EnableFlags();\n")
10112 for capability
in _CAPABILITY_FLAGS
:
10113 f
.write(" bool %s;\n" % capability
['name'])
10115 self
.generated_cpp_filenames
.append(filename
)
10117 def WriteContextStateGetters(self
, f
, class_name
):
10118 """Writes the state getters."""
10119 for gl_type
in ["GLint", "GLfloat"]:
10121 bool %s::GetStateAs%s(
10122 GLenum pname, %s* params, GLsizei* num_written) const {
10124 """ % (class_name
, gl_type
, gl_type
))
10125 for state_name
in sorted(_STATES
.keys()):
10126 state
= _STATES
[state_name
]
10127 if 'enum' in state
:
10128 f
.write(" case %s:\n" % state
['enum'])
10129 f
.write(" *num_written = %d;\n" % len(state
['states']))
10130 f
.write(" if (params) {\n")
10131 for ndx
,item
in enumerate(state
['states']):
10132 f
.write(" params[%d] = static_cast<%s>(%s);\n" %
10133 (ndx
, gl_type
, item
['name']))
10135 f
.write(" return true;\n")
10137 for item
in state
['states']:
10138 f
.write(" case %s:\n" % item
['enum'])
10139 if isinstance(item
['default'], list):
10140 item_len
= len(item
['default'])
10141 f
.write(" *num_written = %d;\n" % item_len
)
10142 f
.write(" if (params) {\n")
10143 if item
['type'] == gl_type
:
10144 f
.write(" memcpy(params, %s, sizeof(%s) * %d);\n" %
10145 (item
['name'], item
['type'], item_len
))
10147 f
.write(" for (size_t i = 0; i < %s; ++i) {\n" %
10149 f
.write(" params[i] = %s;\n" %
10150 (GetGLGetTypeConversion(gl_type
, item
['type'],
10151 "%s[i]" % item
['name'])))
10154 f
.write(" *num_written = 1;\n")
10155 f
.write(" if (params) {\n")
10156 f
.write(" params[0] = %s;\n" %
10157 (GetGLGetTypeConversion(gl_type
, item
['type'],
10160 f
.write(" return true;\n")
10161 for capability
in _CAPABILITY_FLAGS
:
10162 f
.write(" case GL_%s:\n" % capability
['name'].upper())
10163 f
.write(" *num_written = 1;\n")
10164 f
.write(" if (params) {\n")
10166 " params[0] = static_cast<%s>(enable_flags.%s);\n" %
10167 (gl_type
, capability
['name']))
10169 f
.write(" return true;\n")
10170 f
.write(""" default:
10176 def WriteServiceContextStateImpl(self
, filename
):
10177 """Writes the context state service implementation."""
10178 comment
= "// It is included by context_state.cc\n"
10179 with
CHeaderWriter(filename
, comment
) as f
:
10181 for capability
in _CAPABILITY_FLAGS
:
10182 code
.append("%s(%s)" %
10183 (capability
['name'],
10184 ('false', 'true')['default' in capability
]))
10185 code
.append("cached_%s(%s)" %
10186 (capability
['name'],
10187 ('false', 'true')['default' in capability
]))
10188 f
.write("ContextState::EnableFlags::EnableFlags()\n : %s {\n}\n" %
10192 f
.write("void ContextState::Initialize() {\n")
10193 for state_name
in sorted(_STATES
.keys()):
10194 state
= _STATES
[state_name
]
10195 for item
in state
['states']:
10196 if isinstance(item
['default'], list):
10197 for ndx
, value
in enumerate(item
['default']):
10198 f
.write(" %s[%d] = %s;\n" % (item
['name'], ndx
, value
))
10200 f
.write(" %s = %s;\n" % (item
['name'], item
['default']))
10201 if item
.get('cached', False):
10202 if isinstance(item
['default'], list):
10203 for ndx
, value
in enumerate(item
['default']):
10204 f
.write(" cached_%s[%d] = %s;\n" % (item
['name'], ndx
, value
))
10206 f
.write(" cached_%s = %s;\n" % (item
['name'], item
['default']))
10210 void ContextState::InitCapabilities(const ContextState* prev_state) const {
10212 def WriteCapabilities(test_prev
, es3_caps
):
10213 for capability
in _CAPABILITY_FLAGS
:
10214 capability_name
= capability
['name']
10215 capability_es3
= 'es3' in capability
and capability
['es3'] == True
10216 if capability_es3
and not es3_caps
or not capability_es3
and es3_caps
:
10219 f
.write(""" if (prev_state->enable_flags.cached_%s !=
10220 enable_flags.cached_%s) {\n""" %
10221 (capability_name
, capability_name
))
10222 f
.write(" EnableDisable(GL_%s, enable_flags.cached_%s);\n" %
10223 (capability_name
.upper(), capability_name
))
10227 f
.write(" if (prev_state) {")
10228 WriteCapabilities(True, False)
10229 f
.write(" if (feature_info_->IsES3Capable()) {\n")
10230 WriteCapabilities(True, True)
10232 f
.write(" } else {")
10233 WriteCapabilities(False, False)
10234 f
.write(" if (feature_info_->IsES3Capable()) {\n")
10235 WriteCapabilities(False, True)
10240 void ContextState::InitState(const ContextState *prev_state) const {
10243 def WriteStates(test_prev
):
10244 # We need to sort the keys so the expectations match
10245 for state_name
in sorted(_STATES
.keys()):
10246 state
= _STATES
[state_name
]
10247 if state
['type'] == 'FrontBack':
10248 num_states
= len(state
['states'])
10249 for ndx
, group
in enumerate(Grouper(num_states
/ 2,
10254 for place
, item
in enumerate(group
):
10255 item_name
= CachedStateName(item
)
10256 args
.append('%s' % item_name
)
10260 f
.write("(%s != prev_state->%s)" % (item_name
, item_name
))
10264 " gl%s(%s, %s);\n" %
10265 (state
['func'], ('GL_FRONT', 'GL_BACK')[ndx
],
10267 elif state
['type'] == 'NamedParameter':
10268 for item
in state
['states']:
10269 item_name
= CachedStateName(item
)
10271 if 'extension_flag' in item
:
10272 f
.write(" if (feature_info_->feature_flags().%s) {\n " %
10273 item
['extension_flag'])
10275 if isinstance(item
['default'], list):
10276 f
.write(" if (memcmp(prev_state->%s, %s, "
10277 "sizeof(%s) * %d)) {\n" %
10278 (item_name
, item_name
, item
['type'],
10279 len(item
['default'])))
10281 f
.write(" if (prev_state->%s != %s) {\n " %
10282 (item_name
, item_name
))
10283 if 'gl_version_flag' in item
:
10284 item_name
= item
['gl_version_flag']
10286 if item_name
[0] == '!':
10288 item_name
= item_name
[1:]
10289 f
.write(" if (%sfeature_info_->gl_version_info().%s) {\n" %
10290 (inverted
, item_name
))
10291 f
.write(" gl%s(%s, %s);\n" %
10294 if 'enum_set' in item
else item
['enum']),
10296 if 'gl_version_flag' in item
:
10299 if 'extension_flag' in item
:
10302 if 'extension_flag' in item
:
10305 if 'extension_flag' in state
:
10306 f
.write(" if (feature_info_->feature_flags().%s)\n " %
10307 state
['extension_flag'])
10311 for place
, item
in enumerate(state
['states']):
10312 item_name
= CachedStateName(item
)
10313 args
.append('%s' % item_name
)
10317 f
.write("(%s != prev_state->%s)" %
10318 (item_name
, item_name
))
10321 f
.write(" gl%s(%s);\n" % (state
['func'], ", ".join(args
)))
10323 f
.write(" if (prev_state) {")
10325 f
.write(" } else {")
10330 f
.write("""bool ContextState::GetEnabled(GLenum cap) const {
10333 for capability
in _CAPABILITY_FLAGS
:
10334 f
.write(" case GL_%s:\n" % capability
['name'].upper())
10335 f
.write(" return enable_flags.%s;\n" % capability
['name'])
10336 f
.write(""" default:
10342 self
.WriteContextStateGetters(f
, "ContextState")
10343 self
.generated_cpp_filenames
.append(filename
)
10345 def WriteClientContextStateImpl(self
, filename
):
10346 """Writes the context state client side implementation."""
10347 comment
= "// It is included by client_context_state.cc\n"
10348 with
CHeaderWriter(filename
, comment
) as f
:
10350 for capability
in _CAPABILITY_FLAGS
:
10351 code
.append("%s(%s)" %
10352 (capability
['name'],
10353 ('false', 'true')['default' in capability
]))
10355 "ClientContextState::EnableFlags::EnableFlags()\n : %s {\n}\n" %
10360 bool ClientContextState::SetCapabilityState(
10361 GLenum cap, bool enabled, bool* changed) {
10365 for capability
in _CAPABILITY_FLAGS
:
10366 f
.write(" case GL_%s:\n" % capability
['name'].upper())
10367 f
.write(""" if (enable_flags.%(name)s != enabled) {
10369 enable_flags.%(name)s = enabled;
10373 f
.write(""" default:
10378 f
.write("""bool ClientContextState::GetEnabled(
10379 GLenum cap, bool* enabled) const {
10382 for capability
in _CAPABILITY_FLAGS
:
10383 f
.write(" case GL_%s:\n" % capability
['name'].upper())
10384 f
.write(" *enabled = enable_flags.%s;\n" % capability
['name'])
10385 f
.write(" return true;\n")
10386 f
.write(""" default:
10391 self
.generated_cpp_filenames
.append(filename
)
10393 def WriteServiceImplementation(self
, filename
):
10394 """Writes the service decorder implementation."""
10395 comment
= "// It is included by gles2_cmd_decoder.cc\n"
10396 with
CHeaderWriter(filename
, comment
) as f
:
10397 for func
in self
.functions
:
10399 #gen_cmd = func.GetInfo('gen_cmd')
10400 #if gen_cmd == True or gen_cmd == None:
10401 func
.WriteServiceImplementation(f
)
10404 bool GLES2DecoderImpl::SetCapabilityState(GLenum cap, bool enabled) {
10407 for capability
in _CAPABILITY_FLAGS
:
10408 f
.write(" case GL_%s:\n" % capability
['name'].upper())
10409 if 'state_flag' in capability
:
10412 state_.enable_flags.%(name)s = enabled;
10413 if (state_.enable_flags.cached_%(name)s != enabled
10414 || state_.ignore_cached_state) {
10415 %(state_flag)s = true;
10421 state_.enable_flags.%(name)s = enabled;
10422 if (state_.enable_flags.cached_%(name)s != enabled
10423 || state_.ignore_cached_state) {
10424 state_.enable_flags.cached_%(name)s = enabled;
10429 f
.write(""" default:
10435 self
.generated_cpp_filenames
.append(filename
)
10437 def WriteServiceUnitTests(self
, filename_pattern
):
10438 """Writes the service decorder unit tests."""
10439 num_tests
= len(self
.functions
)
10440 FUNCTIONS_PER_FILE
= 98 # hard code this so it doesn't change.
10442 for test_num
in range(0, num_tests
, FUNCTIONS_PER_FILE
):
10444 filename
= filename_pattern
% count
10445 comment
= "// It is included by gles2_cmd_decoder_unittest_%d.cc\n" \
10447 with
CHeaderWriter(filename
, comment
) as f
:
10448 test_name
= 'GLES2DecoderTest%d' % count
10449 end
= test_num
+ FUNCTIONS_PER_FILE
10450 if end
> num_tests
:
10452 for idx
in range(test_num
, end
):
10453 func
= self
.functions
[idx
]
10455 # Do any filtering of the functions here, so that the functions
10456 # will not move between the numbered files if filtering properties
10458 if func
.GetInfo('extension_flag'):
10462 #gen_cmd = func.GetInfo('gen_cmd')
10463 #if gen_cmd == True or gen_cmd == None:
10464 if func
.GetInfo('unit_test') == False:
10465 f
.write("// TODO(gman): %s\n" % func
.name
)
10467 func
.WriteServiceUnitTest(f
, {
10468 'test_name': test_name
10470 self
.generated_cpp_filenames
.append(filename
)
10472 comment
= "// It is included by gles2_cmd_decoder_unittest_base.cc\n"
10473 filename
= filename_pattern
% 0
10474 with
CHeaderWriter(filename
, comment
) as f
:
10476 """void GLES2DecoderTestBase::SetupInitCapabilitiesExpectations(
10477 bool es3_capable) {""")
10478 for capability
in _CAPABILITY_FLAGS
:
10479 capability_es3
= 'es3' in capability
and capability
['es3'] == True
10480 if not capability_es3
:
10481 f
.write(" ExpectEnableDisable(GL_%s, %s);\n" %
10482 (capability
['name'].upper(),
10483 ('false', 'true')['default' in capability
]))
10485 f
.write(" if (es3_capable) {")
10486 for capability
in _CAPABILITY_FLAGS
:
10487 capability_es3
= 'es3' in capability
and capability
['es3'] == True
10489 f
.write(" ExpectEnableDisable(GL_%s, %s);\n" %
10490 (capability
['name'].upper(),
10491 ('false', 'true')['default' in capability
]))
10495 void GLES2DecoderTestBase::SetupInitStateExpectations() {
10497 # We need to sort the keys so the expectations match
10498 for state_name
in sorted(_STATES
.keys()):
10499 state
= _STATES
[state_name
]
10500 if state
['type'] == 'FrontBack':
10501 num_states
= len(state
['states'])
10502 for ndx
, group
in enumerate(Grouper(num_states
/ 2, state
['states'])):
10505 if 'expected' in item
:
10506 args
.append(item
['expected'])
10508 args
.append(item
['default'])
10510 " EXPECT_CALL(*gl_, %s(%s, %s))\n" %
10511 (state
['func'], ('GL_FRONT', 'GL_BACK')[ndx
], ", ".join(args
)))
10512 f
.write(" .Times(1)\n")
10513 f
.write(" .RetiresOnSaturation();\n")
10514 elif state
['type'] == 'NamedParameter':
10515 for item
in state
['states']:
10516 if 'extension_flag' in item
:
10517 f
.write(" if (group_->feature_info()->feature_flags().%s) {\n" %
10518 item
['extension_flag'])
10520 expect_value
= item
['default']
10521 if isinstance(expect_value
, list):
10522 # TODO: Currently we do not check array values.
10526 " EXPECT_CALL(*gl_, %s(%s, %s))\n" %
10529 if 'enum_set' in item
else item
['enum']),
10531 f
.write(" .Times(1)\n")
10532 f
.write(" .RetiresOnSaturation();\n")
10533 if 'extension_flag' in item
:
10536 if 'extension_flag' in state
:
10537 f
.write(" if (group_->feature_info()->feature_flags().%s) {\n" %
10538 state
['extension_flag'])
10541 for item
in state
['states']:
10542 if 'expected' in item
:
10543 args
.append(item
['expected'])
10545 args
.append(item
['default'])
10546 # TODO: Currently we do not check array values.
10547 args
= ["_" if isinstance(arg
, list) else arg
for arg
in args
]
10548 f
.write(" EXPECT_CALL(*gl_, %s(%s))\n" %
10549 (state
['func'], ", ".join(args
)))
10550 f
.write(" .Times(1)\n")
10551 f
.write(" .RetiresOnSaturation();\n")
10552 if 'extension_flag' in state
:
10555 self
.generated_cpp_filenames
.append(filename
)
10557 def WriteServiceUnitTestsForExtensions(self
, filename
):
10558 """Writes the service decorder unit tests for functions with extension_flag.
10560 The functions are special in that they need a specific unit test
10561 baseclass to turn on the extension.
10563 functions
= [f
for f
in self
.functions
if f
.GetInfo('extension_flag')]
10564 comment
= "// It is included by gles2_cmd_decoder_unittest_extensions.cc\n"
10565 with
CHeaderWriter(filename
, comment
) as f
:
10566 for func
in functions
:
10568 if func
.GetInfo('unit_test') == False:
10569 f
.write("// TODO(gman): %s\n" % func
.name
)
10571 extension
= ToCamelCase(
10572 ToGLExtensionString(func
.GetInfo('extension_flag')))
10573 func
.WriteServiceUnitTest(f
, {
10574 'test_name': 'GLES2DecoderTestWith%s' % extension
10576 self
.generated_cpp_filenames
.append(filename
)
10578 def WriteGLES2Header(self
, filename
):
10579 """Writes the GLES2 header."""
10580 comment
= "// This file contains Chromium-specific GLES2 declarations.\n\n"
10581 with
CHeaderWriter(filename
, comment
) as f
:
10582 for func
in self
.original_functions
:
10583 func
.WriteGLES2Header(f
)
10585 self
.generated_cpp_filenames
.append(filename
)
10587 def WriteGLES2CLibImplementation(self
, filename
):
10588 """Writes the GLES2 c lib implementation."""
10589 comment
= "// These functions emulate GLES2 over command buffers.\n"
10590 with
CHeaderWriter(filename
, comment
) as f
:
10591 for func
in self
.original_functions
:
10592 func
.WriteGLES2CLibImplementation(f
)
10596 extern const NameToFunc g_gles2_function_table[] = {
10598 for func
in self
.original_functions
:
10600 ' { "gl%s", reinterpret_cast<GLES2FunctionPointer>(gl%s), },\n' %
10601 (func
.name
, func
.name
))
10602 f
.write(""" { NULL, NULL, },
10605 } // namespace gles2
10607 self
.generated_cpp_filenames
.append(filename
)
10609 def WriteGLES2InterfaceHeader(self
, filename
):
10610 """Writes the GLES2 interface header."""
10611 comment
= ("// This file is included by gles2_interface.h to declare the\n"
10612 "// GL api functions.\n")
10613 with
CHeaderWriter(filename
, comment
) as f
:
10614 for func
in self
.original_functions
:
10615 func
.WriteGLES2InterfaceHeader(f
)
10616 self
.generated_cpp_filenames
.append(filename
)
10618 def WriteMojoGLES2ImplHeader(self
, filename
):
10619 """Writes the Mojo GLES2 implementation header."""
10620 comment
= ("// This file is included by gles2_interface.h to declare the\n"
10621 "// GL api functions.\n")
10623 #include "gpu/command_buffer/client/gles2_interface.h"
10624 #include "third_party/mojo/src/mojo/public/c/gles2/gles2.h"
10628 class MojoGLES2Impl : public gpu::gles2::GLES2Interface {
10630 explicit MojoGLES2Impl(MojoGLES2Context context) {
10631 context_ = context;
10633 ~MojoGLES2Impl() override {}
10635 with
CHeaderWriter(filename
, comment
) as f
:
10637 for func
in self
.original_functions
:
10638 func
.WriteMojoGLES2ImplHeader(f
)
10641 MojoGLES2Context context_;
10644 } // namespace mojo
10647 self
.generated_cpp_filenames
.append(filename
)
10649 def WriteMojoGLES2Impl(self
, filename
):
10650 """Writes the Mojo GLES2 implementation."""
10652 #include "mojo/gpu/mojo_gles2_impl_autogen.h"
10654 #include "base/logging.h"
10655 #include "third_party/mojo/src/mojo/public/c/gles2/chromium_copy_texture.h"
10656 #include "third_party/mojo/src/mojo/public/c/gles2/chromium_image.h"
10657 #include "third_party/mojo/src/mojo/public/c/gles2/chromium_miscellaneous.h"
10658 #include "third_party/mojo/src/mojo/public/c/gles2/chromium_pixel_transfer_buffer_object.h"
10659 #include "third_party/mojo/src/mojo/public/c/gles2/chromium_sub_image.h"
10660 #include "third_party/mojo/src/mojo/public/c/gles2/chromium_sync_point.h"
10661 #include "third_party/mojo/src/mojo/public/c/gles2/chromium_texture_mailbox.h"
10662 #include "third_party/mojo/src/mojo/public/c/gles2/gles2.h"
10663 #include "third_party/mojo/src/mojo/public/c/gles2/occlusion_query_ext.h"
10668 with
CWriter(filename
) as f
:
10670 for func
in self
.original_functions
:
10671 func
.WriteMojoGLES2Impl(f
)
10674 } // namespace mojo
10677 self
.generated_cpp_filenames
.append(filename
)
10679 def WriteGLES2InterfaceStub(self
, filename
):
10680 """Writes the GLES2 interface stub header."""
10681 comment
= "// This file is included by gles2_interface_stub.h.\n"
10682 with
CHeaderWriter(filename
, comment
) as f
:
10683 for func
in self
.original_functions
:
10684 func
.WriteGLES2InterfaceStub(f
)
10685 self
.generated_cpp_filenames
.append(filename
)
10687 def WriteGLES2InterfaceStubImpl(self
, filename
):
10688 """Writes the GLES2 interface header."""
10689 comment
= "// This file is included by gles2_interface_stub.cc.\n"
10690 with
CHeaderWriter(filename
, comment
) as f
:
10691 for func
in self
.original_functions
:
10692 func
.WriteGLES2InterfaceStubImpl(f
)
10693 self
.generated_cpp_filenames
.append(filename
)
10695 def WriteGLES2ImplementationHeader(self
, filename
):
10696 """Writes the GLES2 Implementation header."""
10698 ("// This file is included by gles2_implementation.h to declare the\n"
10699 "// GL api functions.\n")
10700 with
CHeaderWriter(filename
, comment
) as f
:
10701 for func
in self
.original_functions
:
10702 func
.WriteGLES2ImplementationHeader(f
)
10703 self
.generated_cpp_filenames
.append(filename
)
10705 def WriteGLES2Implementation(self
, filename
):
10706 """Writes the GLES2 Implementation."""
10708 ("// This file is included by gles2_implementation.cc to define the\n"
10709 "// GL api functions.\n")
10710 with
CHeaderWriter(filename
, comment
) as f
:
10711 for func
in self
.original_functions
:
10712 func
.WriteGLES2Implementation(f
)
10713 self
.generated_cpp_filenames
.append(filename
)
10715 def WriteGLES2TraceImplementationHeader(self
, filename
):
10716 """Writes the GLES2 Trace Implementation header."""
10717 comment
= "// This file is included by gles2_trace_implementation.h\n"
10718 with
CHeaderWriter(filename
, comment
) as f
:
10719 for func
in self
.original_functions
:
10720 func
.WriteGLES2TraceImplementationHeader(f
)
10721 self
.generated_cpp_filenames
.append(filename
)
10723 def WriteGLES2TraceImplementation(self
, filename
):
10724 """Writes the GLES2 Trace Implementation."""
10725 comment
= "// This file is included by gles2_trace_implementation.cc\n"
10726 with
CHeaderWriter(filename
, comment
) as f
:
10727 for func
in self
.original_functions
:
10728 func
.WriteGLES2TraceImplementation(f
)
10729 self
.generated_cpp_filenames
.append(filename
)
10731 def WriteGLES2ImplementationUnitTests(self
, filename
):
10732 """Writes the GLES2 helper header."""
10734 ("// This file is included by gles2_implementation.h to declare the\n"
10735 "// GL api functions.\n")
10736 with
CHeaderWriter(filename
, comment
) as f
:
10737 for func
in self
.original_functions
:
10738 func
.WriteGLES2ImplementationUnitTest(f
)
10739 self
.generated_cpp_filenames
.append(filename
)
10741 def WriteServiceUtilsHeader(self
, filename
):
10742 """Writes the gles2 auto generated utility header."""
10743 with
CHeaderWriter(filename
) as f
:
10744 for name
in sorted(_NAMED_TYPE_INFO
.keys()):
10745 named_type
= NamedType(_NAMED_TYPE_INFO
[name
])
10746 if named_type
.IsConstant():
10748 f
.write("ValueValidator<%s> %s;\n" %
10749 (named_type
.GetType(), ToUnderscore(name
)))
10751 self
.generated_cpp_filenames
.append(filename
)
10753 def WriteServiceUtilsImplementation(self
, filename
):
10754 """Writes the gles2 auto generated utility implementation."""
10755 with
CHeaderWriter(filename
) as f
:
10756 names
= sorted(_NAMED_TYPE_INFO
.keys())
10758 named_type
= NamedType(_NAMED_TYPE_INFO
[name
])
10759 if named_type
.IsConstant():
10761 if named_type
.GetValidValues():
10762 f
.write("static const %s valid_%s_table[] = {\n" %
10763 (named_type
.GetType(), ToUnderscore(name
)))
10764 for value
in named_type
.GetValidValues():
10765 f
.write(" %s,\n" % value
)
10768 if named_type
.GetValidValuesES3():
10769 f
.write("static const %s valid_%s_table_es3[] = {\n" %
10770 (named_type
.GetType(), ToUnderscore(name
)))
10771 for value
in named_type
.GetValidValuesES3():
10772 f
.write(" %s,\n" % value
)
10775 if named_type
.GetDeprecatedValuesES3():
10776 f
.write("static const %s deprecated_%s_table_es3[] = {\n" %
10777 (named_type
.GetType(), ToUnderscore(name
)))
10778 for value
in named_type
.GetDeprecatedValuesES3():
10779 f
.write(" %s,\n" % value
)
10782 f
.write("Validators::Validators()")
10784 for count
, name
in enumerate(names
):
10785 named_type
= NamedType(_NAMED_TYPE_INFO
[name
])
10786 if named_type
.IsConstant():
10788 if named_type
.GetValidValues():
10789 code
= """%(pre)s%(name)s(
10790 valid_%(name)s_table, arraysize(valid_%(name)s_table))"""
10792 code
= "%(pre)s%(name)s()"
10794 'name': ToUnderscore(name
),
10801 f
.write("void Validators::UpdateValuesES3() {\n")
10803 named_type
= NamedType(_NAMED_TYPE_INFO
[name
])
10804 if named_type
.GetDeprecatedValuesES3():
10805 code
= """ %(name)s.RemoveValues(
10806 deprecated_%(name)s_table_es3, arraysize(deprecated_%(name)s_table_es3));
10809 'name': ToUnderscore(name
),
10811 if named_type
.GetValidValuesES3():
10812 code
= """ %(name)s.AddValues(
10813 valid_%(name)s_table_es3, arraysize(valid_%(name)s_table_es3));
10816 'name': ToUnderscore(name
),
10819 self
.generated_cpp_filenames
.append(filename
)
10821 def WriteCommonUtilsHeader(self
, filename
):
10822 """Writes the gles2 common utility header."""
10823 with
CHeaderWriter(filename
) as f
:
10824 type_infos
= sorted(_NAMED_TYPE_INFO
.keys())
10825 for type_info
in type_infos
:
10826 if _NAMED_TYPE_INFO
[type_info
]['type'] == 'GLenum':
10827 f
.write("static std::string GetString%s(uint32_t value);\n" %
10830 self
.generated_cpp_filenames
.append(filename
)
10832 def WriteCommonUtilsImpl(self
, filename
):
10833 """Writes the gles2 common utility header."""
10834 enum_re
= re
.compile(r
'\#define\s+(GL_[a-zA-Z0-9_]+)\s+([0-9A-Fa-fx]+)')
10836 for fname
in ['third_party/khronos/GLES2/gl2.h',
10837 'third_party/khronos/GLES2/gl2ext.h',
10838 'third_party/khronos/GLES3/gl3.h',
10839 'gpu/GLES2/gl2chromium.h',
10840 'gpu/GLES2/gl2extchromium.h']:
10841 lines
= open(fname
).readlines()
10843 m
= enum_re
.match(line
)
10847 if len(value
) <= 10:
10848 if not value
in dict:
10850 # check our own _CHROMIUM macro conflicts with khronos GL headers.
10851 elif dict[value
] != name
and (name
.endswith('_CHROMIUM') or
10852 dict[value
].endswith('_CHROMIUM')):
10853 self
.Error("code collision: %s and %s have the same code %s" %
10854 (dict[value
], name
, value
))
10856 with
CHeaderWriter(filename
) as f
:
10857 f
.write("static const GLES2Util::EnumToString "
10858 "enum_to_string_table[] = {\n")
10860 f
.write(' { %s, "%s", },\n' % (value
, dict[value
]))
10863 const GLES2Util::EnumToString* const GLES2Util::enum_to_string_table_ =
10864 enum_to_string_table;
10865 const size_t GLES2Util::enum_to_string_table_len_ =
10866 sizeof(enum_to_string_table) / sizeof(enum_to_string_table[0]);
10870 enums
= sorted(_NAMED_TYPE_INFO
.keys())
10872 if _NAMED_TYPE_INFO
[enum
]['type'] == 'GLenum':
10873 f
.write("std::string GLES2Util::GetString%s(uint32_t value) {\n" %
10875 valid_list
= _NAMED_TYPE_INFO
[enum
]['valid']
10876 if 'valid_es3' in _NAMED_TYPE_INFO
[enum
]:
10877 valid_list
= valid_list
+ _NAMED_TYPE_INFO
[enum
]['valid_es3']
10878 assert len(valid_list
) == len(set(valid_list
))
10879 if len(valid_list
) > 0:
10880 f
.write(" static const EnumToString string_table[] = {\n")
10881 for value
in valid_list
:
10882 f
.write(' { %s, "%s" },\n' % (value
, value
))
10884 return GLES2Util::GetQualifiedEnumString(
10885 string_table, arraysize(string_table), value);
10890 f
.write(""" return GLES2Util::GetQualifiedEnumString(
10895 self
.generated_cpp_filenames
.append(filename
)
10897 def WritePepperGLES2Interface(self
, filename
, dev
):
10898 """Writes the Pepper OpenGLES interface definition."""
10899 with
CWriter(filename
) as f
:
10900 f
.write("label Chrome {\n")
10901 f
.write(" M39 = 1.0\n")
10905 # Declare GL types.
10906 f
.write("[version=1.0]\n")
10907 f
.write("describe {\n")
10908 for gltype
in ['GLbitfield', 'GLboolean', 'GLbyte', 'GLclampf',
10909 'GLclampx', 'GLenum', 'GLfixed', 'GLfloat', 'GLint',
10910 'GLintptr', 'GLshort', 'GLsizei', 'GLsizeiptr',
10911 'GLubyte', 'GLuint', 'GLushort']:
10912 f
.write(" %s;\n" % gltype
)
10913 f
.write(" %s_ptr_t;\n" % gltype
)
10916 # C level typedefs.
10917 f
.write("#inline c\n")
10918 f
.write("#include \"ppapi/c/pp_resource.h\"\n")
10920 f
.write("#include \"ppapi/c/ppb_opengles2.h\"\n\n")
10922 f
.write("\n#ifndef __gl2_h_\n")
10923 for (k
, v
) in _GL_TYPES
.iteritems():
10924 f
.write("typedef %s %s;\n" % (v
, k
))
10925 f
.write("#ifdef _WIN64\n")
10926 for (k
, v
) in _GL_TYPES_64
.iteritems():
10927 f
.write("typedef %s %s;\n" % (v
, k
))
10929 for (k
, v
) in _GL_TYPES_32
.iteritems():
10930 f
.write("typedef %s %s;\n" % (v
, k
))
10931 f
.write("#endif // _WIN64\n")
10932 f
.write("#endif // __gl2_h_\n\n")
10933 f
.write("#endinl\n")
10935 for interface
in self
.pepper_interfaces
:
10936 if interface
.dev
!= dev
:
10938 # Historically, we provide OpenGLES2 interfaces with struct
10939 # namespace. Not to break code which uses the interface as
10940 # "struct OpenGLES2", we put it in struct namespace.
10941 f
.write('\n[macro="%s", force_struct_namespace]\n' %
10942 interface
.GetInterfaceName())
10943 f
.write("interface %s {\n" % interface
.GetStructName())
10944 for func
in self
.original_functions
:
10945 if not func
.InPepperInterface(interface
):
10948 ret_type
= func
.MapCTypeToPepperIdlType(func
.return_type
,
10949 is_for_return_type
=True)
10950 func_prefix
= " %s %s(" % (ret_type
, func
.GetPepperName())
10951 f
.write(func_prefix
)
10952 f
.write("[in] PP_Resource context")
10953 for arg
in func
.MakeTypedPepperIdlArgStrings():
10954 f
.write(",\n" + " " * len(func_prefix
) + arg
)
10958 def WritePepperGLES2Implementation(self
, filename
):
10959 """Writes the Pepper OpenGLES interface implementation."""
10960 with
CWriter(filename
) as f
:
10961 f
.write("#include \"ppapi/shared_impl/ppb_opengles2_shared.h\"\n\n")
10962 f
.write("#include \"base/logging.h\"\n")
10963 f
.write("#include \"gpu/command_buffer/client/gles2_implementation.h\"\n")
10964 f
.write("#include \"ppapi/shared_impl/ppb_graphics_3d_shared.h\"\n")
10965 f
.write("#include \"ppapi/thunk/enter.h\"\n\n")
10967 f
.write("namespace ppapi {\n\n")
10968 f
.write("namespace {\n\n")
10970 f
.write("typedef thunk::EnterResource<thunk::PPB_Graphics3D_API>"
10973 f
.write("gpu::gles2::GLES2Implementation* ToGles2Impl(Enter3D*"
10975 f
.write(" DCHECK(enter);\n")
10976 f
.write(" DCHECK(enter->succeeded());\n")
10977 f
.write(" return static_cast<PPB_Graphics3D_Shared*>(enter->object())->"
10978 "gles2_impl();\n");
10981 for func
in self
.original_functions
:
10982 if not func
.InAnyPepperExtension():
10985 original_arg
= func
.MakeTypedPepperArgString("")
10986 context_arg
= "PP_Resource context_id"
10987 if len(original_arg
):
10988 arg
= context_arg
+ ", " + original_arg
10991 f
.write("%s %s(%s) {\n" %
10992 (func
.return_type
, func
.GetPepperName(), arg
))
10993 f
.write(" Enter3D enter(context_id, true);\n")
10994 f
.write(" if (enter.succeeded()) {\n")
10996 return_str
= "" if func
.return_type
== "void" else "return "
10997 f
.write(" %sToGles2Impl(&enter)->%s(%s);\n" %
10998 (return_str
, func
.original_name
,
10999 func
.MakeOriginalArgString("")))
11001 if func
.return_type
== "void":
11004 f
.write(" else {\n")
11005 f
.write(" return %s;\n" % func
.GetErrorReturnString())
11009 f
.write("} // namespace\n")
11011 for interface
in self
.pepper_interfaces
:
11012 f
.write("const %s* PPB_OpenGLES2_Shared::Get%sInterface() {\n" %
11013 (interface
.GetStructName(), interface
.GetName()))
11014 f
.write(" static const struct %s "
11015 "ppb_opengles2 = {\n" % interface
.GetStructName())
11017 f
.write(",\n &".join(
11018 f
.GetPepperName() for f
in self
.original_functions
11019 if f
.InPepperInterface(interface
)))
11023 f
.write(" return &ppb_opengles2;\n")
11026 f
.write("} // namespace ppapi\n")
11027 self
.generated_cpp_filenames
.append(filename
)
11029 def WriteGLES2ToPPAPIBridge(self
, filename
):
11030 """Connects GLES2 helper library to PPB_OpenGLES2 interface"""
11031 with
CWriter(filename
) as f
:
11032 f
.write("#ifndef GL_GLEXT_PROTOTYPES\n")
11033 f
.write("#define GL_GLEXT_PROTOTYPES\n")
11034 f
.write("#endif\n")
11035 f
.write("#include <GLES2/gl2.h>\n")
11036 f
.write("#include <GLES2/gl2ext.h>\n")
11037 f
.write("#include \"ppapi/lib/gl/gles2/gl2ext_ppapi.h\"\n\n")
11039 for func
in self
.original_functions
:
11040 if not func
.InAnyPepperExtension():
11043 interface
= self
.interface_info
[func
.GetInfo('pepper_interface') or '']
11045 f
.write("%s GL_APIENTRY gl%s(%s) {\n" %
11046 (func
.return_type
, func
.GetPepperName(),
11047 func
.MakeTypedPepperArgString("")))
11048 return_str
= "" if func
.return_type
== "void" else "return "
11049 interface_str
= "glGet%sInterfacePPAPI()" % interface
.GetName()
11050 original_arg
= func
.MakeOriginalArgString("")
11051 context_arg
= "glGetCurrentContextPPAPI()"
11052 if len(original_arg
):
11053 arg
= context_arg
+ ", " + original_arg
11056 if interface
.GetName():
11057 f
.write(" const struct %s* ext = %s;\n" %
11058 (interface
.GetStructName(), interface_str
))
11059 f
.write(" if (ext)\n")
11060 f
.write(" %sext->%s(%s);\n" %
11061 (return_str
, func
.GetPepperName(), arg
))
11063 f
.write(" %s0;\n" % return_str
)
11065 f
.write(" %s%s->%s(%s);\n" %
11066 (return_str
, interface_str
, func
.GetPepperName(), arg
))
11068 self
.generated_cpp_filenames
.append(filename
)
11070 def WriteMojoGLCallVisitor(self
, filename
):
11071 """Provides the GL implementation for mojo"""
11072 with
CWriter(filename
) as f
:
11073 for func
in self
.original_functions
:
11074 if not func
.IsCoreGLFunction():
11076 f
.write("VISIT_GL_CALL(%s, %s, (%s), (%s))\n" %
11077 (func
.name
, func
.return_type
,
11078 func
.MakeTypedOriginalArgString(""),
11079 func
.MakeOriginalArgString("")))
11080 self
.generated_cpp_filenames
.append(filename
)
11082 def WriteMojoGLCallVisitorForExtension(self
, filename
, extension
):
11083 """Provides the GL implementation for mojo for a particular extension"""
11084 with
CWriter(filename
) as f
:
11085 for func
in self
.original_functions
:
11086 if func
.GetInfo("extension") != extension
:
11088 f
.write("VISIT_GL_CALL(%s, %s, (%s), (%s))\n" %
11089 (func
.name
, func
.return_type
,
11090 func
.MakeTypedOriginalArgString(""),
11091 func
.MakeOriginalArgString("")))
11092 self
.generated_cpp_filenames
.append(filename
)
11094 def Format(generated_files
):
11095 formatter
= "clang-format"
11096 if platform
.system() == "Windows":
11097 formatter
+= ".bat"
11098 for filename
in generated_files
:
11099 call([formatter
, "-i", "-style=chromium", filename
])
11102 """This is the main function."""
11103 parser
= OptionParser()
11106 help="base directory for resulting files, under chrome/src. default is "
11107 "empty. Use this if you want the result stored under gen.")
11109 "-v", "--verbose", action
="store_true",
11110 help="prints more output.")
11112 (options
, args
) = parser
.parse_args(args
=argv
)
11114 # Add in states and capabilites to GLState
11115 gl_state_valid
= _NAMED_TYPE_INFO
['GLState']['valid']
11116 for state_name
in sorted(_STATES
.keys()):
11117 state
= _STATES
[state_name
]
11118 if 'extension_flag' in state
:
11120 if 'enum' in state
:
11121 if not state
['enum'] in gl_state_valid
:
11122 gl_state_valid
.append(state
['enum'])
11124 for item
in state
['states']:
11125 if 'extension_flag' in item
:
11127 if not item
['enum'] in gl_state_valid
:
11128 gl_state_valid
.append(item
['enum'])
11129 for capability
in _CAPABILITY_FLAGS
:
11130 valid_value
= "GL_%s" % capability
['name'].upper()
11131 if not valid_value
in gl_state_valid
:
11132 gl_state_valid
.append(valid_value
)
11134 # This script lives under gpu/command_buffer, cd to base directory.
11135 os
.chdir(os
.path
.dirname(__file__
) + "/../..")
11136 base_dir
= os
.getcwd()
11137 gen
= GLGenerator(options
.verbose
)
11138 gen
.ParseGLH("gpu/command_buffer/cmd_buffer_functions.txt")
11140 # Support generating files under gen/
11141 if options
.output_dir
!= None:
11142 os
.chdir(options
.output_dir
)
11144 gen
.WritePepperGLES2Interface("ppapi/api/ppb_opengles2.idl", False)
11145 gen
.WritePepperGLES2Interface("ppapi/api/dev/ppb_opengles2ext_dev.idl", True)
11146 gen
.WriteGLES2ToPPAPIBridge("ppapi/lib/gl/gles2/gles2.c")
11147 gen
.WritePepperGLES2Implementation(
11148 "ppapi/shared_impl/ppb_opengles2_shared.cc")
11150 gen
.WriteCommandIds("gpu/command_buffer/common/gles2_cmd_ids_autogen.h")
11151 gen
.WriteFormat("gpu/command_buffer/common/gles2_cmd_format_autogen.h")
11152 gen
.WriteFormatTest(
11153 "gpu/command_buffer/common/gles2_cmd_format_test_autogen.h")
11154 gen
.WriteGLES2InterfaceHeader(
11155 "gpu/command_buffer/client/gles2_interface_autogen.h")
11156 gen
.WriteMojoGLES2ImplHeader(
11157 "mojo/gpu/mojo_gles2_impl_autogen.h")
11158 gen
.WriteMojoGLES2Impl(
11159 "mojo/gpu/mojo_gles2_impl_autogen.cc")
11160 gen
.WriteGLES2InterfaceStub(
11161 "gpu/command_buffer/client/gles2_interface_stub_autogen.h")
11162 gen
.WriteGLES2InterfaceStubImpl(
11163 "gpu/command_buffer/client/gles2_interface_stub_impl_autogen.h")
11164 gen
.WriteGLES2ImplementationHeader(
11165 "gpu/command_buffer/client/gles2_implementation_autogen.h")
11166 gen
.WriteGLES2Implementation(
11167 "gpu/command_buffer/client/gles2_implementation_impl_autogen.h")
11168 gen
.WriteGLES2ImplementationUnitTests(
11169 "gpu/command_buffer/client/gles2_implementation_unittest_autogen.h")
11170 gen
.WriteGLES2TraceImplementationHeader(
11171 "gpu/command_buffer/client/gles2_trace_implementation_autogen.h")
11172 gen
.WriteGLES2TraceImplementation(
11173 "gpu/command_buffer/client/gles2_trace_implementation_impl_autogen.h")
11174 gen
.WriteGLES2CLibImplementation(
11175 "gpu/command_buffer/client/gles2_c_lib_autogen.h")
11176 gen
.WriteCmdHelperHeader(
11177 "gpu/command_buffer/client/gles2_cmd_helper_autogen.h")
11178 gen
.WriteServiceImplementation(
11179 "gpu/command_buffer/service/gles2_cmd_decoder_autogen.h")
11180 gen
.WriteServiceContextStateHeader(
11181 "gpu/command_buffer/service/context_state_autogen.h")
11182 gen
.WriteServiceContextStateImpl(
11183 "gpu/command_buffer/service/context_state_impl_autogen.h")
11184 gen
.WriteClientContextStateHeader(
11185 "gpu/command_buffer/client/client_context_state_autogen.h")
11186 gen
.WriteClientContextStateImpl(
11187 "gpu/command_buffer/client/client_context_state_impl_autogen.h")
11188 gen
.WriteServiceUnitTests(
11189 "gpu/command_buffer/service/gles2_cmd_decoder_unittest_%d_autogen.h")
11190 gen
.WriteServiceUnitTestsForExtensions(
11191 "gpu/command_buffer/service/"
11192 "gles2_cmd_decoder_unittest_extensions_autogen.h")
11193 gen
.WriteServiceUtilsHeader(
11194 "gpu/command_buffer/service/gles2_cmd_validation_autogen.h")
11195 gen
.WriteServiceUtilsImplementation(
11196 "gpu/command_buffer/service/"
11197 "gles2_cmd_validation_implementation_autogen.h")
11198 gen
.WriteCommonUtilsHeader(
11199 "gpu/command_buffer/common/gles2_cmd_utils_autogen.h")
11200 gen
.WriteCommonUtilsImpl(
11201 "gpu/command_buffer/common/gles2_cmd_utils_implementation_autogen.h")
11202 gen
.WriteGLES2Header("gpu/GLES2/gl2chromium_autogen.h")
11203 mojo_gles2_prefix
= ("third_party/mojo/src/mojo/public/c/gles2/"
11204 "gles2_call_visitor")
11205 gen
.WriteMojoGLCallVisitor(mojo_gles2_prefix
+ "_autogen.h")
11206 gen
.WriteMojoGLCallVisitorForExtension(
11207 mojo_gles2_prefix
+ "_chromium_texture_mailbox_autogen.h",
11208 "CHROMIUM_texture_mailbox")
11209 gen
.WriteMojoGLCallVisitorForExtension(
11210 mojo_gles2_prefix
+ "_chromium_sync_point_autogen.h",
11211 "CHROMIUM_sync_point")
11212 gen
.WriteMojoGLCallVisitorForExtension(
11213 mojo_gles2_prefix
+ "_chromium_sub_image_autogen.h",
11214 "CHROMIUM_sub_image")
11215 gen
.WriteMojoGLCallVisitorForExtension(
11216 mojo_gles2_prefix
+ "_chromium_miscellaneous_autogen.h",
11217 "CHROMIUM_miscellaneous")
11218 gen
.WriteMojoGLCallVisitorForExtension(
11219 mojo_gles2_prefix
+ "_occlusion_query_ext_autogen.h",
11220 "occlusion_query_EXT")
11221 gen
.WriteMojoGLCallVisitorForExtension(
11222 mojo_gles2_prefix
+ "_chromium_image_autogen.h",
11224 gen
.WriteMojoGLCallVisitorForExtension(
11225 mojo_gles2_prefix
+ "_chromium_copy_texture_autogen.h",
11226 "CHROMIUM_copy_texture")
11227 gen
.WriteMojoGLCallVisitorForExtension(
11228 mojo_gles2_prefix
+ "_chromium_pixel_transfer_buffer_object_autogen.h",
11229 "CHROMIUM_pixel_transfer_buffer_object")
11231 Format(gen
.generated_cpp_filenames
)
11234 print "%d errors" % gen
.errors
11239 if __name__
== '__main__':
11240 sys
.exit(main(sys
.argv
[1:]))