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',
815 'GL_GPU_DISJOINT_EXT',
817 'GL_MAX_3D_TEXTURE_SIZE',
818 'GL_MAX_ARRAY_TEXTURE_LAYERS',
819 'GL_MAX_COLOR_ATTACHMENTS',
820 'GL_MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS',
821 'GL_MAX_COMBINED_UNIFORM_BLOCKS',
822 'GL_MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS',
823 'GL_MAX_DRAW_BUFFERS',
824 'GL_MAX_ELEMENT_INDEX',
825 'GL_MAX_ELEMENTS_INDICES',
826 'GL_MAX_ELEMENTS_VERTICES',
827 'GL_MAX_FRAGMENT_INPUT_COMPONENTS',
828 'GL_MAX_FRAGMENT_UNIFORM_BLOCKS',
829 'GL_MAX_FRAGMENT_UNIFORM_COMPONENTS',
830 'GL_MAX_PROGRAM_TEXEL_OFFSET',
832 'GL_MAX_SERVER_WAIT_TIMEOUT',
833 'GL_MAX_TEXTURE_LOD_BIAS',
834 'GL_MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS',
835 'GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS',
836 'GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS',
837 'GL_MAX_UNIFORM_BLOCK_SIZE',
838 'GL_MAX_UNIFORM_BUFFER_BINDINGS',
839 'GL_MAX_VARYING_COMPONENTS',
840 'GL_MAX_VERTEX_OUTPUT_COMPONENTS',
841 'GL_MAX_VERTEX_UNIFORM_BLOCKS',
842 'GL_MAX_VERTEX_UNIFORM_COMPONENTS',
843 'GL_MIN_PROGRAM_TEXEL_OFFSET',
846 'GL_NUM_PROGRAM_BINARY_FORMATS',
847 'GL_PACK_ROW_LENGTH',
848 'GL_PACK_SKIP_PIXELS',
850 'GL_PIXEL_PACK_BUFFER_BINDING',
851 'GL_PIXEL_UNPACK_BUFFER_BINDING',
852 'GL_PROGRAM_BINARY_FORMATS',
854 'GL_READ_FRAMEBUFFER_BINDING',
855 'GL_SAMPLER_BINDING',
857 'GL_TEXTURE_BINDING_2D_ARRAY',
858 'GL_TEXTURE_BINDING_3D',
859 'GL_TRANSFORM_FEEDBACK_BINDING',
860 'GL_TRANSFORM_FEEDBACK_ACTIVE',
861 'GL_TRANSFORM_FEEDBACK_BUFFER_BINDING',
862 'GL_TRANSFORM_FEEDBACK_PAUSED',
863 'GL_TRANSFORM_FEEDBACK_BUFFER_SIZE',
864 'GL_TRANSFORM_FEEDBACK_BUFFER_START',
865 'GL_UNIFORM_BUFFER_BINDING',
866 'GL_UNIFORM_BUFFER_OFFSET_ALIGNMENT',
867 'GL_UNIFORM_BUFFER_SIZE',
868 'GL_UNIFORM_BUFFER_START',
869 'GL_UNPACK_IMAGE_HEIGHT',
870 'GL_UNPACK_ROW_LENGTH',
871 'GL_UNPACK_SKIP_IMAGES',
872 'GL_UNPACK_SKIP_PIXELS',
873 'GL_UNPACK_SKIP_ROWS',
874 # GL_VERTEX_ARRAY_BINDING is the same as GL_VERTEX_ARRAY_BINDING_OES
875 # 'GL_VERTEX_ARRAY_BINDING',
884 'GL_TRANSFORM_FEEDBACK_BUFFER_BINDING',
885 'GL_TRANSFORM_FEEDBACK_BUFFER_SIZE',
886 'GL_TRANSFORM_FEEDBACK_BUFFER_START',
887 'GL_UNIFORM_BUFFER_BINDING',
888 'GL_UNIFORM_BUFFER_SIZE',
889 'GL_UNIFORM_BUFFER_START',
895 'GetTexParamTarget': {
899 'GL_TEXTURE_CUBE_MAP',
902 'GL_TEXTURE_2D_ARRAY',
906 'GL_PROXY_TEXTURE_CUBE_MAP',
914 'GL_COLOR_ATTACHMENT0',
915 'GL_COLOR_ATTACHMENT1',
916 'GL_COLOR_ATTACHMENT2',
917 'GL_COLOR_ATTACHMENT3',
918 'GL_COLOR_ATTACHMENT4',
919 'GL_COLOR_ATTACHMENT5',
920 'GL_COLOR_ATTACHMENT6',
921 'GL_COLOR_ATTACHMENT7',
922 'GL_COLOR_ATTACHMENT8',
923 'GL_COLOR_ATTACHMENT9',
924 'GL_COLOR_ATTACHMENT10',
925 'GL_COLOR_ATTACHMENT11',
926 'GL_COLOR_ATTACHMENT12',
927 'GL_COLOR_ATTACHMENT13',
928 'GL_COLOR_ATTACHMENT14',
929 'GL_COLOR_ATTACHMENT15',
939 'GL_TEXTURE_CUBE_MAP_POSITIVE_X',
940 'GL_TEXTURE_CUBE_MAP_NEGATIVE_X',
941 'GL_TEXTURE_CUBE_MAP_POSITIVE_Y',
942 'GL_TEXTURE_CUBE_MAP_NEGATIVE_Y',
943 'GL_TEXTURE_CUBE_MAP_POSITIVE_Z',
944 'GL_TEXTURE_CUBE_MAP_NEGATIVE_Z',
947 'GL_PROXY_TEXTURE_CUBE_MAP',
954 'GL_TEXTURE_2D_ARRAY',
960 'TextureBindTarget': {
964 'GL_TEXTURE_CUBE_MAP',
968 'GL_TEXTURE_2D_ARRAY',
975 'TransformFeedbackBindTarget': {
978 'GL_TRANSFORM_FEEDBACK',
984 'TransformFeedbackPrimitiveMode': {
999 'GL_FRAGMENT_SHADER',
1002 'GL_GEOMETRY_SHADER',
1010 'GL_FRONT_AND_BACK',
1038 'GL_FUNC_REVERSE_SUBTRACT',
1054 'GL_ONE_MINUS_SRC_COLOR',
1056 'GL_ONE_MINUS_DST_COLOR',
1058 'GL_ONE_MINUS_SRC_ALPHA',
1060 'GL_ONE_MINUS_DST_ALPHA',
1061 'GL_CONSTANT_COLOR',
1062 'GL_ONE_MINUS_CONSTANT_COLOR',
1063 'GL_CONSTANT_ALPHA',
1064 'GL_ONE_MINUS_CONSTANT_ALPHA',
1065 'GL_SRC_ALPHA_SATURATE',
1074 'GL_ONE_MINUS_SRC_COLOR',
1076 'GL_ONE_MINUS_DST_COLOR',
1078 'GL_ONE_MINUS_SRC_ALPHA',
1080 'GL_ONE_MINUS_DST_ALPHA',
1081 'GL_CONSTANT_COLOR',
1082 'GL_ONE_MINUS_CONSTANT_COLOR',
1083 'GL_CONSTANT_ALPHA',
1084 'GL_ONE_MINUS_CONSTANT_ALPHA',
1089 'valid': ["GL_%s" % cap
['name'].upper() for cap
in _CAPABILITY_FLAGS
1090 if 'es3' not in cap
or cap
['es3'] != True],
1091 'valid_es3': ["GL_%s" % cap
['name'].upper() for cap
in _CAPABILITY_FLAGS
1092 if 'es3' in cap
and cap
['es3'] == True],
1105 'GL_TRIANGLE_STRIP',
1118 'GL_UNSIGNED_SHORT',
1127 'GetMaxIndexType': {
1131 'GL_UNSIGNED_SHORT',
1141 'GL_COLOR_ATTACHMENT0',
1142 'GL_DEPTH_ATTACHMENT',
1143 'GL_STENCIL_ATTACHMENT',
1146 'GL_DEPTH_STENCIL_ATTACHMENT',
1153 'BackbufferAttachment': {
1161 'BufferParameter': {
1168 'GL_BUFFER_ACCESS_FLAGS',
1172 'GL_PIXEL_PACK_BUFFER',
1175 'BufferParameter64': {
1179 'GL_BUFFER_MAP_LENGTH',
1180 'GL_BUFFER_MAP_OFFSET',
1183 'GL_PIXEL_PACK_BUFFER',
1189 'GL_INTERLEAVED_ATTRIBS',
1190 'GL_SEPARATE_ATTRIBS',
1193 'GL_PIXEL_PACK_BUFFER',
1196 'FrameBufferParameter': {
1199 'GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE',
1200 'GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME',
1201 'GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL',
1202 'GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE',
1205 'GL_FRAMEBUFFER_ATTACHMENT_RED_SIZE',
1206 'GL_FRAMEBUFFER_ATTACHMENT_GREEN_SIZE',
1207 'GL_FRAMEBUFFER_ATTACHMENT_BLUE_SIZE',
1208 'GL_FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE',
1209 'GL_FRAMEBUFFER_ATTACHMENT_DEPTH_SIZE',
1210 'GL_FRAMEBUFFER_ATTACHMENT_STENCIL_SIZE',
1211 'GL_FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE',
1212 'GL_FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING',
1213 'GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER',
1219 'GL_PATH_PROJECTION_CHROMIUM',
1220 'GL_PATH_MODELVIEW_CHROMIUM',
1223 'ProgramParameter': {
1228 'GL_VALIDATE_STATUS',
1229 'GL_INFO_LOG_LENGTH',
1230 'GL_ATTACHED_SHADERS',
1231 'GL_ACTIVE_ATTRIBUTES',
1232 'GL_ACTIVE_ATTRIBUTE_MAX_LENGTH',
1233 'GL_ACTIVE_UNIFORMS',
1234 'GL_ACTIVE_UNIFORM_MAX_LENGTH',
1237 'GL_ACTIVE_UNIFORM_BLOCKS',
1238 'GL_ACTIVE_UNIFORM_BLOCK_MAX_NAME_LENGTH',
1239 'GL_TRANSFORM_FEEDBACK_BUFFER_MODE',
1240 'GL_TRANSFORM_FEEDBACK_VARYINGS',
1241 'GL_TRANSFORM_FEEDBACK_VARYING_MAX_LENGTH',
1244 'GL_PROGRAM_BINARY_RETRIEVABLE_HINT', # not supported in Chromium.
1247 'QueryObjectParameter': {
1250 'GL_QUERY_RESULT_EXT',
1251 'GL_QUERY_RESULT_AVAILABLE_EXT',
1257 'GL_CURRENT_QUERY_EXT',
1263 'GL_ANY_SAMPLES_PASSED_EXT',
1264 'GL_ANY_SAMPLES_PASSED_CONSERVATIVE_EXT',
1265 'GL_COMMANDS_ISSUED_CHROMIUM',
1266 'GL_LATENCY_QUERY_CHROMIUM',
1267 'GL_ASYNC_PIXEL_PACK_COMPLETED_CHROMIUM',
1268 'GL_COMMANDS_COMPLETED_CHROMIUM',
1271 'RenderBufferParameter': {
1274 'GL_RENDERBUFFER_RED_SIZE',
1275 'GL_RENDERBUFFER_GREEN_SIZE',
1276 'GL_RENDERBUFFER_BLUE_SIZE',
1277 'GL_RENDERBUFFER_ALPHA_SIZE',
1278 'GL_RENDERBUFFER_DEPTH_SIZE',
1279 'GL_RENDERBUFFER_STENCIL_SIZE',
1280 'GL_RENDERBUFFER_WIDTH',
1281 'GL_RENDERBUFFER_HEIGHT',
1282 'GL_RENDERBUFFER_INTERNAL_FORMAT',
1285 'GL_RENDERBUFFER_SAMPLES',
1288 'InternalFormatParameter': {
1291 'GL_NUM_SAMPLE_COUNTS',
1295 'SamplerParameter': {
1298 'GL_TEXTURE_MAG_FILTER',
1299 'GL_TEXTURE_MIN_FILTER',
1300 'GL_TEXTURE_MIN_LOD',
1301 'GL_TEXTURE_MAX_LOD',
1302 'GL_TEXTURE_WRAP_S',
1303 'GL_TEXTURE_WRAP_T',
1304 'GL_TEXTURE_WRAP_R',
1305 'GL_TEXTURE_COMPARE_MODE',
1306 'GL_TEXTURE_COMPARE_FUNC',
1309 'GL_GENERATE_MIPMAP',
1312 'ShaderParameter': {
1317 'GL_COMPILE_STATUS',
1318 'GL_INFO_LOG_LENGTH',
1319 'GL_SHADER_SOURCE_LENGTH',
1320 'GL_TRANSLATED_SHADER_SOURCE_LENGTH_ANGLE',
1323 'ShaderPrecision': {
1340 'GL_SHADING_LANGUAGE_VERSION',
1344 'TextureParameter': {
1347 'GL_TEXTURE_MAG_FILTER',
1348 'GL_TEXTURE_MIN_FILTER',
1349 'GL_TEXTURE_POOL_CHROMIUM',
1350 'GL_TEXTURE_WRAP_S',
1351 'GL_TEXTURE_WRAP_T',
1354 'GL_TEXTURE_BASE_LEVEL',
1355 'GL_TEXTURE_COMPARE_FUNC',
1356 'GL_TEXTURE_COMPARE_MODE',
1357 'GL_TEXTURE_IMMUTABLE_FORMAT',
1358 'GL_TEXTURE_IMMUTABLE_LEVELS',
1359 'GL_TEXTURE_MAX_LEVEL',
1360 'GL_TEXTURE_MAX_LOD',
1361 'GL_TEXTURE_MIN_LOD',
1362 'GL_TEXTURE_WRAP_R',
1365 'GL_GENERATE_MIPMAP',
1371 'GL_TEXTURE_POOL_MANAGED_CHROMIUM',
1372 'GL_TEXTURE_POOL_UNMANAGED_CHROMIUM',
1375 'TextureWrapMode': {
1379 'GL_MIRRORED_REPEAT',
1383 'TextureMinFilterMode': {
1388 'GL_NEAREST_MIPMAP_NEAREST',
1389 'GL_LINEAR_MIPMAP_NEAREST',
1390 'GL_NEAREST_MIPMAP_LINEAR',
1391 'GL_LINEAR_MIPMAP_LINEAR',
1394 'TextureMagFilterMode': {
1401 'TextureCompareFunc': {
1414 'TextureCompareMode': {
1418 'GL_COMPARE_REF_TO_TEXTURE',
1425 'GL_FRAMEBUFFER_ATTACHMENT_ANGLE',
1428 'VertexAttribute': {
1431 # some enum that the decoder actually passes through to GL needs
1432 # to be the first listed here since it's used in unit tests.
1433 'GL_VERTEX_ATTRIB_ARRAY_NORMALIZED',
1434 'GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING',
1435 'GL_VERTEX_ATTRIB_ARRAY_ENABLED',
1436 'GL_VERTEX_ATTRIB_ARRAY_SIZE',
1437 'GL_VERTEX_ATTRIB_ARRAY_STRIDE',
1438 'GL_VERTEX_ATTRIB_ARRAY_TYPE',
1439 'GL_CURRENT_VERTEX_ATTRIB',
1442 'GL_VERTEX_ATTRIB_ARRAY_INTEGER',
1443 'GL_VERTEX_ATTRIB_ARRAY_DIVISOR',
1449 'GL_VERTEX_ATTRIB_ARRAY_POINTER',
1455 'GL_GENERATE_MIPMAP_HINT',
1458 'GL_FRAGMENT_SHADER_DERIVATIVE_HINT',
1461 'GL_PERSPECTIVE_CORRECTION_HINT',
1475 'GL_PACK_ALIGNMENT',
1476 'GL_UNPACK_ALIGNMENT',
1479 'GL_PACK_ROW_LENGTH',
1480 'GL_PACK_SKIP_PIXELS',
1481 'GL_PACK_SKIP_ROWS',
1482 'GL_UNPACK_ROW_LENGTH',
1483 'GL_UNPACK_IMAGE_HEIGHT',
1484 'GL_UNPACK_SKIP_PIXELS',
1485 'GL_UNPACK_SKIP_ROWS',
1486 'GL_UNPACK_SKIP_IMAGES',
1489 'GL_PACK_SWAP_BYTES',
1490 'GL_UNPACK_SWAP_BYTES',
1493 'PixelStoreAlignment': {
1506 'ReadPixelFormat': {
1526 'GL_UNSIGNED_SHORT_5_6_5',
1527 'GL_UNSIGNED_SHORT_4_4_4_4',
1528 'GL_UNSIGNED_SHORT_5_5_5_1',
1532 'GL_UNSIGNED_SHORT',
1538 'GL_UNSIGNED_INT_2_10_10_10_REV',
1539 'GL_UNSIGNED_INT_10F_11F_11F_REV',
1540 'GL_UNSIGNED_INT_5_9_9_9_REV',
1541 'GL_UNSIGNED_INT_24_8',
1542 'GL_FLOAT_32_UNSIGNED_INT_24_8_REV',
1545 'GL_UNSIGNED_BYTE_3_3_2',
1554 'GL_UNSIGNED_SHORT',
1561 'GL_CONVEX_HULL_CHROMIUM',
1562 'GL_BOUNDING_BOX_CHROMIUM',
1569 'GL_COUNT_UP_CHROMIUM',
1570 'GL_COUNT_DOWN_CHROMIUM',
1576 'GL_PATH_STROKE_WIDTH_CHROMIUM',
1577 'GL_PATH_END_CAPS_CHROMIUM',
1578 'GL_PATH_JOIN_STYLE_CHROMIUM',
1579 'GL_PATH_MITER_LIMIT_CHROMIUM',
1580 'GL_PATH_STROKE_BOUND_CHROMIUM',
1583 'PathParameterCapValues': {
1587 'GL_SQUARE_CHROMIUM',
1588 'GL_ROUND_CHROMIUM',
1591 'PathParameterJoinValues': {
1594 'GL_MITER_REVERT_CHROMIUM',
1595 'GL_BEVEL_CHROMIUM',
1596 'GL_ROUND_CHROMIUM',
1603 'GL_UNSIGNED_SHORT_5_6_5',
1604 'GL_UNSIGNED_SHORT_4_4_4_4',
1605 'GL_UNSIGNED_SHORT_5_5_5_1',
1609 'GL_UNSIGNED_SHORT',
1615 'GL_UNSIGNED_INT_2_10_10_10_REV',
1618 'RenderBufferFormat': {
1624 'GL_DEPTH_COMPONENT16',
1625 'GL_STENCIL_INDEX8',
1653 'GL_DEPTH_COMPONENT24',
1654 'GL_DEPTH_COMPONENT32F',
1655 'GL_DEPTH24_STENCIL8',
1656 'GL_DEPTH32F_STENCIL8',
1659 'ShaderBinaryFormat': {
1682 'GL_LUMINANCE_ALPHA',
1693 'GL_DEPTH_COMPONENT',
1701 'TextureInternalFormat': {
1706 'GL_LUMINANCE_ALPHA',
1735 'GL_R11F_G11F_B10F',
1760 # The DEPTH/STENCIL formats are not supported in CopyTexImage2D.
1761 # We will reject them dynamically in GPU command buffer.
1762 'GL_DEPTH_COMPONENT16',
1763 'GL_DEPTH_COMPONENT24',
1764 'GL_DEPTH_COMPONENT32F',
1765 'GL_DEPTH24_STENCIL8',
1766 'GL_DEPTH32F_STENCIL8',
1773 'TextureInternalFormatStorage': {
1780 'GL_LUMINANCE8_EXT',
1781 'GL_LUMINANCE8_ALPHA8_EXT',
1809 'GL_R11F_G11F_B10F',
1832 'GL_DEPTH_COMPONENT16',
1833 'GL_DEPTH_COMPONENT24',
1834 'GL_DEPTH_COMPONENT32F',
1835 'GL_DEPTH24_STENCIL8',
1836 'GL_DEPTH32F_STENCIL8',
1837 'GL_COMPRESSED_R11_EAC',
1838 'GL_COMPRESSED_SIGNED_R11_EAC',
1839 'GL_COMPRESSED_RG11_EAC',
1840 'GL_COMPRESSED_SIGNED_RG11_EAC',
1841 'GL_COMPRESSED_RGB8_ETC2',
1842 'GL_COMPRESSED_SRGB8_ETC2',
1843 'GL_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2',
1844 'GL_COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2',
1845 'GL_COMPRESSED_RGBA8_ETC2_EAC',
1846 'GL_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC',
1850 'GL_LUMINANCE8_EXT',
1851 'GL_LUMINANCE8_ALPHA8_EXT',
1853 'GL_LUMINANCE16F_EXT',
1854 'GL_LUMINANCE_ALPHA16F_EXT',
1856 'GL_LUMINANCE32F_EXT',
1857 'GL_LUMINANCE_ALPHA32F_EXT',
1860 'ImageInternalFormat': {
1864 'GL_RGB_YUV_420_CHROMIUM',
1865 'GL_RGB_YCBCR_422_CHROMIUM',
1873 'GL_SCANOUT_CHROMIUM'
1876 'ValueBufferTarget': {
1879 'GL_SUBSCRIBED_VALUES_BUFFER_CHROMIUM',
1882 'SubscriptionTarget': {
1885 'GL_MOUSE_POSITION_CHROMIUM',
1888 'UniformParameter': {
1893 'GL_UNIFORM_NAME_LENGTH',
1894 'GL_UNIFORM_BLOCK_INDEX',
1895 'GL_UNIFORM_OFFSET',
1896 'GL_UNIFORM_ARRAY_STRIDE',
1897 'GL_UNIFORM_MATRIX_STRIDE',
1898 'GL_UNIFORM_IS_ROW_MAJOR',
1901 'GL_UNIFORM_BLOCK_NAME_LENGTH',
1904 'UniformBlockParameter': {
1907 'GL_UNIFORM_BLOCK_BINDING',
1908 'GL_UNIFORM_BLOCK_DATA_SIZE',
1909 'GL_UNIFORM_BLOCK_NAME_LENGTH',
1910 'GL_UNIFORM_BLOCK_ACTIVE_UNIFORMS',
1911 'GL_UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES',
1912 'GL_UNIFORM_BLOCK_REFERENCED_BY_VERTEX_SHADER',
1913 'GL_UNIFORM_BLOCK_REFERENCED_BY_FRAGMENT_SHADER',
1919 'VertexAttribType': {
1925 'GL_UNSIGNED_SHORT',
1926 # 'GL_FIXED', // This is not available on Desktop GL.
1933 'GL_INT_2_10_10_10_REV',
1934 'GL_UNSIGNED_INT_2_10_10_10_REV',
1940 'VertexAttribIType': {
1946 'GL_UNSIGNED_SHORT',
1957 'is_complete': True,
1965 'VertexAttribSize': {
1980 'is_complete': True,
1989 'type': 'GLboolean',
1990 'is_complete': True,
2001 'GL_GUILTY_CONTEXT_RESET_ARB',
2002 'GL_INNOCENT_CONTEXT_RESET_ARB',
2003 'GL_UNKNOWN_CONTEXT_RESET_ARB',
2008 'is_complete': True,
2010 'GL_SYNC_GPU_COMMANDS_COMPLETE',
2017 'type': 'GLbitfield',
2018 'is_complete': True,
2027 'type': 'GLbitfield',
2029 'GL_SYNC_FLUSH_COMMANDS_BIT',
2039 'GL_SYNC_STATUS', # This needs to be the 1st; all others are cached.
2041 'GL_SYNC_CONDITION',
2050 # This table specifies the different pepper interfaces that are supported for
2051 # GL commands. 'dev' is true if it's a dev interface.
2052 _PEPPER_INTERFACES
= [
2053 {'name': '', 'dev': False},
2054 {'name': 'InstancedArrays', 'dev': False},
2055 {'name': 'FramebufferBlit', 'dev': False},
2056 {'name': 'FramebufferMultisample', 'dev': False},
2057 {'name': 'ChromiumEnableFeature', 'dev': False},
2058 {'name': 'ChromiumMapSub', 'dev': False},
2059 {'name': 'Query', 'dev': False},
2060 {'name': 'VertexArrayObject', 'dev': False},
2061 {'name': 'DrawBuffers', 'dev': True},
2064 # A function info object specifies the type and other special data for the
2065 # command that will be generated. A base function info object is generated by
2066 # parsing the "cmd_buffer_functions.txt", one for each function in the
2067 # file. These function info objects can be augmented and their values can be
2068 # overridden by adding an object to the table below.
2070 # Must match function names specified in "cmd_buffer_functions.txt".
2072 # cmd_comment: A comment added to the cmd format.
2073 # type: defines which handler will be used to generate code.
2074 # decoder_func: defines which function to call in the decoder to execute the
2075 # corresponding GL command. If not specified the GL command will
2076 # be called directly.
2077 # gl_test_func: GL function that is expected to be called when testing.
2078 # cmd_args: The arguments to use for the command. This overrides generating
2079 # them based on the GL function arguments.
2080 # gen_cmd: Whether or not this function geneates a command. Default = True.
2081 # data_transfer_methods: Array of methods that are used for transfering the
2082 # pointer data. Possible values: 'immediate', 'shm', 'bucket'.
2083 # The default is 'immediate' if the command has one pointer
2084 # argument, otherwise 'shm'. One command is generated for each
2085 # transfer method. Affects only commands which are not of type
2086 # 'HandWritten', 'GETn' or 'GLcharN'.
2087 # Note: the command arguments that affect this are the final args,
2088 # taking cmd_args override into consideration.
2089 # impl_func: Whether or not to generate the GLES2Implementation part of this
2091 # impl_decl: Whether or not to generate the GLES2Implementation declaration
2093 # needs_size: If True a data_size field is added to the command.
2094 # count: The number of units per element. For PUTn or PUT types.
2095 # use_count_func: If True the actual data count needs to be computed; the count
2096 # argument specifies the maximum count.
2097 # unit_test: If False no service side unit test will be generated.
2098 # client_test: If False no client side unit test will be generated.
2099 # expectation: If False the unit test will have no expected calls.
2100 # gen_func: Name of function that generates GL resource for corresponding
2102 # states: array of states that get set by this function corresponding to
2103 # the given arguments
2104 # state_flag: name of flag that is set to true when function is called.
2105 # no_gl: no GL function is called.
2106 # valid_args: A dictionary of argument indices to args to use in unit tests
2107 # when they can not be automatically determined.
2108 # pepper_interface: The pepper interface that is used for this extension
2109 # pepper_name: The name of the function as exposed to pepper.
2110 # pepper_args: A string representing the argument list (what would appear in
2111 # C/C++ between the parentheses for the function declaration)
2112 # that the Pepper API expects for this function. Use this only if
2113 # the stable Pepper API differs from the GLES2 argument list.
2114 # invalid_test: False if no invalid test needed.
2115 # shadowed: True = the value is shadowed so no glGetXXX call will be made.
2116 # first_element_only: For PUT types, True if only the first element of an
2117 # array is used and we end up calling the single value
2118 # corresponding function. eg. TexParameteriv -> TexParameteri
2119 # extension: Function is an extension to GL and should not be exposed to
2120 # pepper unless pepper_interface is defined.
2121 # extension_flag: Function is an extension and should be enabled only when
2122 # the corresponding feature info flag is enabled. Implies
2123 # 'extension': True.
2124 # not_shared: For GENn types, True if objects can't be shared between contexts
2125 # unsafe: True = no validation is implemented on the service side and the
2126 # command is only available with --enable-unsafe-es3-apis.
2127 # id_mapping: A list of resource type names whose client side IDs need to be
2128 # mapped to service side IDs. This is only used for unsafe APIs.
2132 'decoder_func': 'DoActiveTexture',
2135 'client_test': False,
2137 'ApplyScreenSpaceAntialiasingCHROMIUM': {
2138 'decoder_func': 'DoApplyScreenSpaceAntialiasingCHROMIUM',
2139 'extension_flag': 'chromium_screen_space_antialiasing',
2141 'client_test': False,
2143 'AttachShader': {'decoder_func': 'DoAttachShader'},
2144 'BindAttribLocation': {
2146 'data_transfer_methods': ['bucket'],
2151 'decoder_func': 'DoBindBuffer',
2152 'gen_func': 'GenBuffersARB',
2156 'decoder_func': 'DoBindBufferBase',
2157 'gen_func': 'GenBuffersARB',
2160 'BindBufferRange': {
2162 'decoder_func': 'DoBindBufferRange',
2163 'gen_func': 'GenBuffersARB',
2170 'BindFramebuffer': {
2172 'decoder_func': 'DoBindFramebuffer',
2173 'gl_test_func': 'glBindFramebufferEXT',
2174 'gen_func': 'GenFramebuffersEXT',
2177 'BindRenderbuffer': {
2179 'decoder_func': 'DoBindRenderbuffer',
2180 'gl_test_func': 'glBindRenderbufferEXT',
2181 'gen_func': 'GenRenderbuffersEXT',
2185 'id_mapping': [ 'Sampler' ],
2190 'decoder_func': 'DoBindTexture',
2191 'gen_func': 'GenTextures',
2192 # TODO(gman): remove this once client side caching works.
2193 'client_test': False,
2196 'BindTransformFeedback': {
2198 'id_mapping': [ 'TransformFeedback' ],
2201 'BlitFramebufferCHROMIUM': {
2202 'decoder_func': 'DoBlitFramebufferCHROMIUM',
2204 'extension': 'chromium_framebuffer_multisample',
2205 'extension_flag': 'chromium_framebuffer_multisample',
2206 'pepper_interface': 'FramebufferBlit',
2207 'pepper_name': 'BlitFramebufferEXT',
2208 'defer_reads': True,
2209 'defer_draws': True,
2214 'data_transfer_methods': ['shm'],
2215 'client_test': False,
2220 'client_test': False,
2221 'decoder_func': 'DoBufferSubData',
2222 'data_transfer_methods': ['shm'],
2225 'CheckFramebufferStatus': {
2227 'decoder_func': 'DoCheckFramebufferStatus',
2228 'gl_test_func': 'glCheckFramebufferStatusEXT',
2229 'error_value': 'GL_FRAMEBUFFER_UNSUPPORTED',
2230 'result': ['GLenum'],
2233 'decoder_func': 'DoClear',
2234 'defer_draws': True,
2239 'use_count_func': True,
2241 'decoder_func': 'DoClearBufferiv',
2249 'decoder_func': 'DoClearBufferuiv',
2256 'use_count_func': True,
2258 'decoder_func': 'DoClearBufferfv',
2265 'decoder_func': 'DoClearBufferfi',
2271 'state': 'ClearColor',
2275 'state': 'ClearDepthf',
2276 'decoder_func': 'glClearDepth',
2277 'gl_test_func': 'glClearDepth',
2284 'data_transfer_methods': ['shm'],
2285 'cmd_args': 'GLuint sync, GLbitfieldSyncFlushFlags flags, '
2286 'GLuint timeout_0, GLuint timeout_1, GLenum* result',
2288 'result': ['GLenum'],
2293 'state': 'ColorMask',
2295 'expectation': False,
2297 'ConsumeTextureCHROMIUM': {
2298 'decoder_func': 'DoConsumeTextureCHROMIUM',
2301 'count': 64, # GL_MAILBOX_SIZE_CHROMIUM
2303 'client_test': False,
2304 'extension': "CHROMIUM_texture_mailbox",
2308 'CopyBufferSubData': {
2311 'CreateAndConsumeTextureCHROMIUM': {
2312 'decoder_func': 'DoCreateAndConsumeTextureCHROMIUM',
2314 'type': 'HandWritten',
2315 'data_transfer_methods': ['immediate'],
2317 'client_test': False,
2318 'extension': "CHROMIUM_texture_mailbox",
2322 'GenValuebuffersCHROMIUM': {
2324 'gl_test_func': 'glGenValuebuffersCHROMIUM',
2325 'resource_type': 'Valuebuffer',
2326 'resource_types': 'Valuebuffers',
2331 'DeleteValuebuffersCHROMIUM': {
2333 'gl_test_func': 'glDeleteValuebuffersCHROMIUM',
2334 'resource_type': 'Valuebuffer',
2335 'resource_types': 'Valuebuffers',
2340 'IsValuebufferCHROMIUM': {
2342 'decoder_func': 'DoIsValuebufferCHROMIUM',
2343 'expectation': False,
2347 'BindValuebufferCHROMIUM': {
2349 'decoder_func': 'DoBindValueBufferCHROMIUM',
2350 'gen_func': 'GenValueBuffersCHROMIUM',
2355 'SubscribeValueCHROMIUM': {
2356 'decoder_func': 'DoSubscribeValueCHROMIUM',
2361 'PopulateSubscribedValuesCHROMIUM': {
2362 'decoder_func': 'DoPopulateSubscribedValuesCHROMIUM',
2367 'UniformValuebufferCHROMIUM': {
2368 'decoder_func': 'DoUniformValueBufferCHROMIUM',
2375 'state': 'ClearStencil',
2377 'EnableFeatureCHROMIUM': {
2379 'data_transfer_methods': ['shm'],
2380 'decoder_func': 'DoEnableFeatureCHROMIUM',
2381 'expectation': False,
2382 'cmd_args': 'GLuint bucket_id, GLint* result',
2383 'result': ['GLint'],
2386 'pepper_interface': 'ChromiumEnableFeature',
2388 'CompileShader': {'decoder_func': 'DoCompileShader', 'unit_test': False},
2389 'CompressedTexImage2D': {
2391 'data_transfer_methods': ['bucket', 'shm'],
2394 'CompressedTexSubImage2D': {
2396 'data_transfer_methods': ['bucket', 'shm'],
2397 'decoder_func': 'DoCompressedTexSubImage2D',
2401 'decoder_func': 'DoCopyTexImage2D',
2403 'defer_reads': True,
2406 'CopyTexSubImage2D': {
2407 'decoder_func': 'DoCopyTexSubImage2D',
2408 'defer_reads': True,
2411 'CompressedTexImage3D': {
2413 'data_transfer_methods': ['bucket', 'shm'],
2417 'CompressedTexSubImage3D': {
2419 'data_transfer_methods': ['bucket', 'shm'],
2420 'decoder_func': 'DoCompressedTexSubImage3D',
2424 'CopyTexSubImage3D': {
2425 'defer_reads': True,
2429 'CreateImageCHROMIUM': {
2432 'ClientBuffer buffer, GLsizei width, GLsizei height, '
2433 'GLenum internalformat',
2434 'result': ['GLuint'],
2435 'client_test': False,
2437 'expectation': False,
2438 'extension': "CHROMIUM_image",
2442 'DestroyImageCHROMIUM': {
2444 'client_test': False,
2446 'extension': "CHROMIUM_image",
2450 'CreateGpuMemoryBufferImageCHROMIUM': {
2453 'GLsizei width, GLsizei height, GLenum internalformat, GLenum usage',
2454 'result': ['GLuint'],
2455 'client_test': False,
2457 'expectation': False,
2458 'extension': "CHROMIUM_image",
2464 'client_test': False,
2468 'client_test': False,
2472 'state': 'BlendColor',
2475 'type': 'StateSetRGBAlpha',
2476 'state': 'BlendEquation',
2478 '0': 'GL_FUNC_SUBTRACT'
2481 'BlendEquationSeparate': {
2483 'state': 'BlendEquation',
2485 '0': 'GL_FUNC_SUBTRACT'
2489 'type': 'StateSetRGBAlpha',
2490 'state': 'BlendFunc',
2492 'BlendFuncSeparate': {
2494 'state': 'BlendFunc',
2496 'BlendBarrierKHR': {
2497 'gl_test_func': 'glBlendBarrierKHR',
2499 'extension_flag': 'blend_equation_advanced',
2500 'client_test': False,
2502 'SampleCoverage': {'decoder_func': 'DoSampleCoverage'},
2504 'type': 'StateSetFrontBack',
2505 'state': 'StencilFunc',
2507 'StencilFuncSeparate': {
2508 'type': 'StateSetFrontBackSeparate',
2509 'state': 'StencilFunc',
2512 'type': 'StateSetFrontBack',
2513 'state': 'StencilOp',
2518 'StencilOpSeparate': {
2519 'type': 'StateSetFrontBackSeparate',
2520 'state': 'StencilOp',
2526 'type': 'StateSetNamedParameter',
2529 'CullFace': {'type': 'StateSet', 'state': 'CullFace'},
2530 'FrontFace': {'type': 'StateSet', 'state': 'FrontFace'},
2531 'DepthFunc': {'type': 'StateSet', 'state': 'DepthFunc'},
2534 'state': 'LineWidth',
2541 'state': 'PolygonOffset',
2545 'gl_test_func': 'glDeleteBuffersARB',
2546 'resource_type': 'Buffer',
2547 'resource_types': 'Buffers',
2549 'DeleteFramebuffers': {
2551 'gl_test_func': 'glDeleteFramebuffersEXT',
2552 'resource_type': 'Framebuffer',
2553 'resource_types': 'Framebuffers',
2556 'DeleteProgram': { 'type': 'Delete' },
2557 'DeleteRenderbuffers': {
2559 'gl_test_func': 'glDeleteRenderbuffersEXT',
2560 'resource_type': 'Renderbuffer',
2561 'resource_types': 'Renderbuffers',
2566 'resource_type': 'Sampler',
2567 'resource_types': 'Samplers',
2570 'DeleteShader': { 'type': 'Delete' },
2573 'cmd_args': 'GLuint sync',
2574 'resource_type': 'Sync',
2579 'resource_type': 'Texture',
2580 'resource_types': 'Textures',
2582 'DeleteTransformFeedbacks': {
2584 'resource_type': 'TransformFeedback',
2585 'resource_types': 'TransformFeedbacks',
2589 'decoder_func': 'DoDepthRangef',
2590 'gl_test_func': 'glDepthRange',
2594 'state': 'DepthMask',
2596 'expectation': False,
2598 'DetachShader': {'decoder_func': 'DoDetachShader'},
2600 'decoder_func': 'DoDisable',
2602 'client_test': False,
2604 'DisableVertexAttribArray': {
2605 'decoder_func': 'DoDisableVertexAttribArray',
2610 'cmd_args': 'GLenumDrawMode mode, GLint first, GLsizei count',
2611 'defer_draws': True,
2616 'cmd_args': 'GLenumDrawMode mode, GLsizei count, '
2617 'GLenumIndexType type, GLuint index_offset',
2618 'client_test': False,
2619 'defer_draws': True,
2622 'DrawRangeElements': {
2628 'decoder_func': 'DoEnable',
2630 'client_test': False,
2632 'EnableVertexAttribArray': {
2633 'decoder_func': 'DoEnableVertexAttribArray',
2638 'client_test': False,
2644 'client_test': False,
2645 'decoder_func': 'DoFinish',
2646 'defer_reads': True,
2651 'decoder_func': 'DoFlush',
2654 'FramebufferRenderbuffer': {
2655 'decoder_func': 'DoFramebufferRenderbuffer',
2656 'gl_test_func': 'glFramebufferRenderbufferEXT',
2659 'FramebufferTexture2D': {
2660 'decoder_func': 'DoFramebufferTexture2D',
2661 'gl_test_func': 'glFramebufferTexture2DEXT',
2664 'FramebufferTexture2DMultisampleEXT': {
2665 'decoder_func': 'DoFramebufferTexture2DMultisample',
2666 'gl_test_func': 'glFramebufferTexture2DMultisampleEXT',
2667 'expectation': False,
2669 'extension_flag': 'multisampled_render_to_texture',
2672 'FramebufferTextureLayer': {
2673 'decoder_func': 'DoFramebufferTextureLayer',
2678 'decoder_func': 'DoGenerateMipmap',
2679 'gl_test_func': 'glGenerateMipmapEXT',
2684 'gl_test_func': 'glGenBuffersARB',
2685 'resource_type': 'Buffer',
2686 'resource_types': 'Buffers',
2688 'GenMailboxCHROMIUM': {
2689 'type': 'HandWritten',
2691 'extension': "CHROMIUM_texture_mailbox",
2694 'GenFramebuffers': {
2696 'gl_test_func': 'glGenFramebuffersEXT',
2697 'resource_type': 'Framebuffer',
2698 'resource_types': 'Framebuffers',
2700 'GenRenderbuffers': {
2701 'type': 'GENn', 'gl_test_func': 'glGenRenderbuffersEXT',
2702 'resource_type': 'Renderbuffer',
2703 'resource_types': 'Renderbuffers',
2707 'gl_test_func': 'glGenSamplers',
2708 'resource_type': 'Sampler',
2709 'resource_types': 'Samplers',
2714 'gl_test_func': 'glGenTextures',
2715 'resource_type': 'Texture',
2716 'resource_types': 'Textures',
2718 'GenTransformFeedbacks': {
2720 'gl_test_func': 'glGenTransformFeedbacks',
2721 'resource_type': 'TransformFeedback',
2722 'resource_types': 'TransformFeedbacks',
2725 'GetActiveAttrib': {
2727 'data_transfer_methods': ['shm'],
2729 'GLidProgram program, GLuint index, uint32_t name_bucket_id, '
2737 'GetActiveUniform': {
2739 'data_transfer_methods': ['shm'],
2741 'GLidProgram program, GLuint index, uint32_t name_bucket_id, '
2749 'GetActiveUniformBlockiv': {
2751 'data_transfer_methods': ['shm'],
2752 'result': ['SizedResult<GLint>'],
2755 'GetActiveUniformBlockName': {
2757 'data_transfer_methods': ['shm'],
2759 'GLidProgram program, GLuint index, uint32_t name_bucket_id, '
2761 'result': ['int32_t'],
2764 'GetActiveUniformsiv': {
2766 'data_transfer_methods': ['shm'],
2768 'GLidProgram program, uint32_t indices_bucket_id, GLenum pname, '
2770 'result': ['SizedResult<GLint>'],
2773 'GetAttachedShaders': {
2775 'data_transfer_methods': ['shm'],
2776 'cmd_args': 'GLidProgram program, void* result, uint32_t result_size',
2777 'result': ['SizedResult<GLuint>'],
2779 'GetAttribLocation': {
2781 'data_transfer_methods': ['shm'],
2783 'GLidProgram program, uint32_t name_bucket_id, GLint* location',
2784 'result': ['GLint'],
2787 'GetFragDataLocation': {
2789 'data_transfer_methods': ['shm'],
2791 'GLidProgram program, uint32_t name_bucket_id, GLint* location',
2792 'result': ['GLint'],
2798 'result': ['SizedResult<GLboolean>'],
2799 'decoder_func': 'DoGetBooleanv',
2800 'gl_test_func': 'glGetBooleanv',
2802 'GetBufferParameteri64v': {
2804 'result': ['SizedResult<GLint64>'],
2805 'decoder_func': 'DoGetBufferParameteri64v',
2806 'expectation': False,
2810 'GetBufferParameteriv': {
2812 'result': ['SizedResult<GLint>'],
2813 'decoder_func': 'DoGetBufferParameteriv',
2814 'expectation': False,
2819 'decoder_func': 'GetErrorState()->GetGLError',
2821 'result': ['GLenum'],
2822 'client_test': False,
2826 'result': ['SizedResult<GLfloat>'],
2827 'decoder_func': 'DoGetFloatv',
2828 'gl_test_func': 'glGetFloatv',
2830 'GetFramebufferAttachmentParameteriv': {
2832 'decoder_func': 'DoGetFramebufferAttachmentParameteriv',
2833 'gl_test_func': 'glGetFramebufferAttachmentParameterivEXT',
2834 'result': ['SizedResult<GLint>'],
2836 'GetGraphicsResetStatusKHR': {
2838 'client_test': False,
2844 'result': ['SizedResult<GLint64>'],
2845 'client_test': False,
2846 'decoder_func': 'DoGetInteger64v',
2851 'result': ['SizedResult<GLint>'],
2852 'decoder_func': 'DoGetIntegerv',
2853 'client_test': False,
2855 'GetInteger64i_v': {
2857 'result': ['SizedResult<GLint64>'],
2858 'client_test': False,
2863 'result': ['SizedResult<GLint>'],
2864 'client_test': False,
2867 'GetInternalformativ': {
2869 'data_transfer_methods': ['shm'],
2870 'result': ['SizedResult<GLint>'],
2872 'GLenumRenderBufferTarget target, GLenumRenderBufferFormat format, '
2873 'GLenumInternalFormatParameter pname, GLint* params',
2876 'GetMaxValueInBufferCHROMIUM': {
2878 'decoder_func': 'DoGetMaxValueInBufferCHROMIUM',
2879 'result': ['GLuint'],
2881 'client_test': False,
2888 'decoder_func': 'DoGetProgramiv',
2889 'result': ['SizedResult<GLint>'],
2890 'expectation': False,
2892 'GetProgramInfoCHROMIUM': {
2894 'expectation': False,
2898 'client_test': False,
2899 'cmd_args': 'GLidProgram program, uint32_t bucket_id',
2901 'uint32_t link_status',
2902 'uint32_t num_attribs',
2903 'uint32_t num_uniforms',
2906 'GetProgramInfoLog': {
2908 'expectation': False,
2910 'GetRenderbufferParameteriv': {
2912 'decoder_func': 'DoGetRenderbufferParameteriv',
2913 'gl_test_func': 'glGetRenderbufferParameterivEXT',
2914 'result': ['SizedResult<GLint>'],
2916 'GetSamplerParameterfv': {
2918 'result': ['SizedResult<GLfloat>'],
2919 'id_mapping': [ 'Sampler' ],
2922 'GetSamplerParameteriv': {
2924 'result': ['SizedResult<GLint>'],
2925 'id_mapping': [ 'Sampler' ],
2930 'decoder_func': 'DoGetShaderiv',
2931 'result': ['SizedResult<GLint>'],
2933 'GetShaderInfoLog': {
2935 'get_len_func': 'glGetShaderiv',
2936 'get_len_enum': 'GL_INFO_LOG_LENGTH',
2939 'GetShaderPrecisionFormat': {
2941 'data_transfer_methods': ['shm'],
2943 'GLenumShaderType shadertype, GLenumShaderPrecision precisiontype, '
2947 'int32_t min_range',
2948 'int32_t max_range',
2949 'int32_t precision',
2952 'GetShaderSource': {
2954 'get_len_func': 'DoGetShaderiv',
2955 'get_len_enum': 'GL_SHADER_SOURCE_LENGTH',
2957 'client_test': False,
2961 'client_test': False,
2962 'cmd_args': 'GLenumStringType name, uint32_t bucket_id',
2966 'cmd_args': 'GLuint sync, GLenumSyncParameter pname, void* values',
2967 'result': ['SizedResult<GLint>'],
2968 'id_mapping': ['Sync'],
2971 'GetTexParameterfv': {
2973 'decoder_func': 'DoGetTexParameterfv',
2974 'result': ['SizedResult<GLfloat>']
2976 'GetTexParameteriv': {
2978 'decoder_func': 'DoGetTexParameteriv',
2979 'result': ['SizedResult<GLint>']
2981 'GetTranslatedShaderSourceANGLE': {
2983 'get_len_func': 'DoGetShaderiv',
2984 'get_len_enum': 'GL_TRANSLATED_SHADER_SOURCE_LENGTH_ANGLE',
2988 'GetUniformBlockIndex': {
2990 'data_transfer_methods': ['shm'],
2992 'GLidProgram program, uint32_t name_bucket_id, GLuint* index',
2993 'result': ['GLuint'],
2994 'error_return': 'GL_INVALID_INDEX',
2997 'GetUniformBlocksCHROMIUM': {
2999 'expectation': False,
3003 'client_test': False,
3004 'cmd_args': 'GLidProgram program, uint32_t bucket_id',
3005 'result': ['uint32_t'],
3008 'GetUniformsES3CHROMIUM': {
3010 'expectation': False,
3014 'client_test': False,
3015 'cmd_args': 'GLidProgram program, uint32_t bucket_id',
3016 'result': ['uint32_t'],
3019 'GetTransformFeedbackVarying': {
3021 'data_transfer_methods': ['shm'],
3023 'GLidProgram program, GLuint index, uint32_t name_bucket_id, '
3032 'GetTransformFeedbackVaryingsCHROMIUM': {
3034 'expectation': False,
3038 'client_test': False,
3039 'cmd_args': 'GLidProgram program, uint32_t bucket_id',
3040 'result': ['uint32_t'],
3045 'data_transfer_methods': ['shm'],
3046 'result': ['SizedResult<GLfloat>'],
3050 'data_transfer_methods': ['shm'],
3051 'result': ['SizedResult<GLint>'],
3055 'data_transfer_methods': ['shm'],
3056 'result': ['SizedResult<GLuint>'],
3059 'GetUniformIndices': {
3061 'data_transfer_methods': ['shm'],
3062 'result': ['SizedResult<GLuint>'],
3063 'cmd_args': 'GLidProgram program, uint32_t names_bucket_id, '
3067 'GetUniformLocation': {
3069 'data_transfer_methods': ['shm'],
3071 'GLidProgram program, uint32_t name_bucket_id, GLint* location',
3072 'result': ['GLint'],
3073 'error_return': -1, # http://www.opengl.org/sdk/docs/man/xhtml/glGetUniformLocation.xml
3075 'GetVertexAttribfv': {
3077 'result': ['SizedResult<GLfloat>'],
3079 'decoder_func': 'DoGetVertexAttribfv',
3080 'expectation': False,
3081 'client_test': False,
3083 'GetVertexAttribiv': {
3085 'result': ['SizedResult<GLint>'],
3087 'decoder_func': 'DoGetVertexAttribiv',
3088 'expectation': False,
3089 'client_test': False,
3091 'GetVertexAttribIiv': {
3093 'result': ['SizedResult<GLint>'],
3095 'decoder_func': 'DoGetVertexAttribIiv',
3096 'expectation': False,
3097 'client_test': False,
3100 'GetVertexAttribIuiv': {
3102 'result': ['SizedResult<GLuint>'],
3104 'decoder_func': 'DoGetVertexAttribIuiv',
3105 'expectation': False,
3106 'client_test': False,
3109 'GetVertexAttribPointerv': {
3111 'data_transfer_methods': ['shm'],
3112 'result': ['SizedResult<GLuint>'],
3113 'client_test': False,
3115 'InvalidateFramebuffer': {
3118 'client_test': False,
3122 'InvalidateSubFramebuffer': {
3125 'client_test': False,
3131 'decoder_func': 'DoIsBuffer',
3132 'expectation': False,
3136 'decoder_func': 'DoIsEnabled',
3137 'client_test': False,
3139 'expectation': False,
3143 'decoder_func': 'DoIsFramebuffer',
3144 'expectation': False,
3148 'decoder_func': 'DoIsProgram',
3149 'expectation': False,
3153 'decoder_func': 'DoIsRenderbuffer',
3154 'expectation': False,
3158 'decoder_func': 'DoIsShader',
3159 'expectation': False,
3163 'id_mapping': [ 'Sampler' ],
3164 'expectation': False,
3169 'id_mapping': [ 'Sync' ],
3170 'cmd_args': 'GLuint sync',
3171 'expectation': False,
3176 'decoder_func': 'DoIsTexture',
3177 'expectation': False,
3179 'IsTransformFeedback': {
3181 'id_mapping': [ 'TransformFeedback' ],
3182 'expectation': False,
3186 'decoder_func': 'DoLinkProgram',
3190 'MapBufferCHROMIUM': {
3192 'extension': "CHROMIUM_pixel_transfer_buffer_object",
3194 'client_test': False,
3197 'MapBufferSubDataCHROMIUM': {
3201 'client_test': False,
3202 'pepper_interface': 'ChromiumMapSub',
3205 'MapTexSubImage2DCHROMIUM': {
3207 'extension': "CHROMIUM_sub_image",
3209 'client_test': False,
3210 'pepper_interface': 'ChromiumMapSub',
3215 'data_transfer_methods': ['shm'],
3216 'cmd_args': 'GLenumBufferTarget target, GLintptrNotNegative offset, '
3217 'GLsizeiptr size, GLbitfieldMapBufferAccess access, '
3218 'uint32_t data_shm_id, uint32_t data_shm_offset, '
3219 'uint32_t result_shm_id, uint32_t result_shm_offset',
3221 'result': ['uint32_t'],
3224 'PauseTransformFeedback': {
3227 'PixelStorei': {'type': 'Manual'},
3228 'PostSubBufferCHROMIUM': {
3232 'client_test': False,
3236 'ProduceTextureCHROMIUM': {
3237 'decoder_func': 'DoProduceTextureCHROMIUM',
3240 'count': 64, # GL_MAILBOX_SIZE_CHROMIUM
3242 'client_test': False,
3243 'extension': "CHROMIUM_texture_mailbox",
3247 'ProduceTextureDirectCHROMIUM': {
3248 'decoder_func': 'DoProduceTextureDirectCHROMIUM',
3251 'count': 64, # GL_MAILBOX_SIZE_CHROMIUM
3253 'client_test': False,
3254 'extension': "CHROMIUM_texture_mailbox",
3258 'RenderbufferStorage': {
3259 'decoder_func': 'DoRenderbufferStorage',
3260 'gl_test_func': 'glRenderbufferStorageEXT',
3261 'expectation': False,
3264 'RenderbufferStorageMultisampleCHROMIUM': {
3266 '// GL_CHROMIUM_framebuffer_multisample\n',
3267 'decoder_func': 'DoRenderbufferStorageMultisampleCHROMIUM',
3268 'gl_test_func': 'glRenderbufferStorageMultisampleCHROMIUM',
3269 'expectation': False,
3271 'extension': 'chromium_framebuffer_multisample',
3272 'extension_flag': 'chromium_framebuffer_multisample',
3273 'pepper_interface': 'FramebufferMultisample',
3274 'pepper_name': 'RenderbufferStorageMultisampleEXT',
3277 'RenderbufferStorageMultisampleEXT': {
3279 '// GL_EXT_multisampled_render_to_texture\n',
3280 'decoder_func': 'DoRenderbufferStorageMultisampleEXT',
3281 'gl_test_func': 'glRenderbufferStorageMultisampleEXT',
3282 'expectation': False,
3284 'extension_flag': 'multisampled_render_to_texture',
3289 'decoder_func': 'DoReadBuffer',
3294 '// ReadPixels has the result separated from the pixel buffer so that\n'
3295 '// it is easier to specify the result going to some specific place\n'
3296 '// that exactly fits the rectangle of pixels.\n',
3298 'data_transfer_methods': ['shm'],
3300 'client_test': False,
3302 'GLint x, GLint y, GLsizei width, GLsizei height, '
3303 'GLenumReadPixelFormat format, GLenumReadPixelType type, '
3304 'uint32_t pixels_shm_id, uint32_t pixels_shm_offset, '
3305 'uint32_t result_shm_id, uint32_t result_shm_offset, '
3307 'result': ['uint32_t'],
3308 'defer_reads': True,
3311 'ReleaseShaderCompiler': {
3312 'decoder_func': 'DoReleaseShaderCompiler',
3315 'ResumeTransformFeedback': {
3318 'SamplerParameterf': {
3322 'id_mapping': [ 'Sampler' ],
3325 'SamplerParameterfv': {
3327 'data_value': 'GL_NEAREST',
3329 'gl_test_func': 'glSamplerParameterf',
3330 'decoder_func': 'DoSamplerParameterfv',
3331 'first_element_only': True,
3332 'id_mapping': [ 'Sampler' ],
3335 'SamplerParameteri': {
3339 'id_mapping': [ 'Sampler' ],
3342 'SamplerParameteriv': {
3344 'data_value': 'GL_NEAREST',
3346 'gl_test_func': 'glSamplerParameteri',
3347 'decoder_func': 'DoSamplerParameteriv',
3348 'first_element_only': True,
3353 'client_test': False,
3357 'decoder_func': 'DoShaderSource',
3358 'expectation': False,
3359 'data_transfer_methods': ['bucket'],
3361 'GLuint shader, const char** str',
3363 'GLuint shader, GLsizei count, const char** str, const GLint* length',
3366 'type': 'StateSetFrontBack',
3367 'state': 'StencilMask',
3369 'expectation': False,
3371 'StencilMaskSeparate': {
3372 'type': 'StateSetFrontBackSeparate',
3373 'state': 'StencilMask',
3375 'expectation': False,
3379 'decoder_func': 'DoSwapBuffers',
3381 'client_test': False,
3387 'decoder_func': 'DoSwapInterval',
3389 'client_test': False,
3395 'data_transfer_methods': ['shm'],
3396 'client_test': False,
3401 'data_transfer_methods': ['shm'],
3402 'client_test': False,
3407 'decoder_func': 'DoTexParameterf',
3413 'decoder_func': 'DoTexParameteri',
3420 'data_value': 'GL_NEAREST',
3422 'decoder_func': 'DoTexParameterfv',
3423 'gl_test_func': 'glTexParameterf',
3424 'first_element_only': True,
3428 'data_value': 'GL_NEAREST',
3430 'decoder_func': 'DoTexParameteriv',
3431 'gl_test_func': 'glTexParameteri',
3432 'first_element_only': True,
3440 'data_transfer_methods': ['shm'],
3441 'client_test': False,
3443 'cmd_args': 'GLenumTextureTarget target, GLint level, '
3444 'GLint xoffset, GLint yoffset, '
3445 'GLsizei width, GLsizei height, '
3446 'GLenumTextureFormat format, GLenumPixelType type, '
3447 'const void* pixels, GLboolean internal'
3451 'data_transfer_methods': ['shm'],
3452 'client_test': False,
3454 'cmd_args': 'GLenumTextureTarget target, GLint level, '
3455 'GLint xoffset, GLint yoffset, GLint zoffset, '
3456 'GLsizei width, GLsizei height, GLsizei depth, '
3457 'GLenumTextureFormat format, GLenumPixelType type, '
3458 'const void* pixels, GLboolean internal',
3461 'TransformFeedbackVaryings': {
3463 'data_transfer_methods': ['bucket'],
3464 'decoder_func': 'DoTransformFeedbackVaryings',
3466 'GLuint program, const char** varyings, GLenum buffermode',
3467 'expectation': False,
3470 'Uniform1f': {'type': 'PUTXn', 'count': 1},
3474 'decoder_func': 'DoUniform1fv',
3476 'Uniform1i': {'decoder_func': 'DoUniform1i', 'unit_test': False},
3480 'decoder_func': 'DoUniform1iv',
3492 'decoder_func': 'DoUniform1uiv',
3496 'Uniform2i': {'type': 'PUTXn', 'count': 2},
3497 'Uniform2f': {'type': 'PUTXn', 'count': 2},
3501 'decoder_func': 'DoUniform2fv',
3506 'decoder_func': 'DoUniform2iv',
3517 'decoder_func': 'DoUniform2uiv',
3521 'Uniform3i': {'type': 'PUTXn', 'count': 3},
3522 'Uniform3f': {'type': 'PUTXn', 'count': 3},
3526 'decoder_func': 'DoUniform3fv',
3531 'decoder_func': 'DoUniform3iv',
3542 'decoder_func': 'DoUniform3uiv',
3546 'Uniform4i': {'type': 'PUTXn', 'count': 4},
3547 'Uniform4f': {'type': 'PUTXn', 'count': 4},
3551 'decoder_func': 'DoUniform4fv',
3556 'decoder_func': 'DoUniform4iv',
3567 'decoder_func': 'DoUniform4uiv',
3571 'UniformMatrix2fv': {
3574 'decoder_func': 'DoUniformMatrix2fv',
3576 'UniformMatrix2x3fv': {
3579 'decoder_func': 'DoUniformMatrix2x3fv',
3582 'UniformMatrix2x4fv': {
3585 'decoder_func': 'DoUniformMatrix2x4fv',
3588 'UniformMatrix3fv': {
3591 'decoder_func': 'DoUniformMatrix3fv',
3593 'UniformMatrix3x2fv': {
3596 'decoder_func': 'DoUniformMatrix3x2fv',
3599 'UniformMatrix3x4fv': {
3602 'decoder_func': 'DoUniformMatrix3x4fv',
3605 'UniformMatrix4fv': {
3608 'decoder_func': 'DoUniformMatrix4fv',
3610 'UniformMatrix4x2fv': {
3613 'decoder_func': 'DoUniformMatrix4x2fv',
3616 'UniformMatrix4x3fv': {
3619 'decoder_func': 'DoUniformMatrix4x3fv',
3622 'UniformBlockBinding': {
3627 'UnmapBufferCHROMIUM': {
3629 'extension': "CHROMIUM_pixel_transfer_buffer_object",
3631 'client_test': False,
3634 'UnmapBufferSubDataCHROMIUM': {
3638 'client_test': False,
3639 'pepper_interface': 'ChromiumMapSub',
3647 'UnmapTexSubImage2DCHROMIUM': {
3649 'extension': "CHROMIUM_sub_image",
3651 'client_test': False,
3652 'pepper_interface': 'ChromiumMapSub',
3657 'decoder_func': 'DoUseProgram',
3659 'ValidateProgram': {'decoder_func': 'DoValidateProgram'},
3660 'VertexAttrib1f': {'decoder_func': 'DoVertexAttrib1f'},
3661 'VertexAttrib1fv': {
3664 'decoder_func': 'DoVertexAttrib1fv',
3666 'VertexAttrib2f': {'decoder_func': 'DoVertexAttrib2f'},
3667 'VertexAttrib2fv': {
3670 'decoder_func': 'DoVertexAttrib2fv',
3672 'VertexAttrib3f': {'decoder_func': 'DoVertexAttrib3f'},
3673 'VertexAttrib3fv': {
3676 'decoder_func': 'DoVertexAttrib3fv',
3678 'VertexAttrib4f': {'decoder_func': 'DoVertexAttrib4f'},
3679 'VertexAttrib4fv': {
3682 'decoder_func': 'DoVertexAttrib4fv',
3684 'VertexAttribI4i': {
3686 'decoder_func': 'DoVertexAttribI4i',
3688 'VertexAttribI4iv': {
3692 'decoder_func': 'DoVertexAttribI4iv',
3694 'VertexAttribI4ui': {
3696 'decoder_func': 'DoVertexAttribI4ui',
3698 'VertexAttribI4uiv': {
3702 'decoder_func': 'DoVertexAttribI4uiv',
3704 'VertexAttribIPointer': {
3706 'cmd_args': 'GLuint indx, GLintVertexAttribSize size, '
3707 'GLenumVertexAttribIType type, GLsizei stride, '
3709 'client_test': False,
3712 'VertexAttribPointer': {
3714 'cmd_args': 'GLuint indx, GLintVertexAttribSize size, '
3715 'GLenumVertexAttribType type, GLboolean normalized, '
3716 'GLsizei stride, GLuint offset',
3717 'client_test': False,
3721 'cmd_args': 'GLuint sync, GLbitfieldSyncFlushFlags flags, '
3722 'GLuint timeout_0, GLuint timeout_1',
3724 'client_test': False,
3733 'decoder_func': 'DoViewport',
3743 'GetRequestableExtensionsCHROMIUM': {
3746 'cmd_args': 'uint32_t bucket_id',
3750 'RequestExtensionCHROMIUM': {
3753 'client_test': False,
3754 'cmd_args': 'uint32_t bucket_id',
3758 'RateLimitOffscreenContextCHROMIUM': {
3762 'client_test': False,
3764 'CreateStreamTextureCHROMIUM': {
3765 'type': 'HandWritten',
3772 'TexImageIOSurface2DCHROMIUM': {
3773 'decoder_func': 'DoTexImageIOSurface2DCHROMIUM',
3779 'CopyTextureCHROMIUM': {
3780 'decoder_func': 'DoCopyTextureCHROMIUM',
3782 'extension': "CHROMIUM_copy_texture",
3786 'CopySubTextureCHROMIUM': {
3787 'decoder_func': 'DoCopySubTextureCHROMIUM',
3789 'extension': "CHROMIUM_copy_texture",
3793 'CompressedCopyTextureCHROMIUM': {
3794 'decoder_func': 'DoCompressedCopyTextureCHROMIUM',
3799 'CompressedCopySubTextureCHROMIUM': {
3800 'decoder_func': 'DoCompressedCopySubTextureCHROMIUM',
3805 'TexStorage2DEXT': {
3808 'decoder_func': 'DoTexStorage2DEXT',
3811 'DrawArraysInstancedANGLE': {
3813 'cmd_args': 'GLenumDrawMode mode, GLint first, GLsizei count, '
3814 'GLsizei primcount',
3817 'pepper_interface': 'InstancedArrays',
3818 'defer_draws': True,
3823 'decoder_func': 'DoDrawBuffersEXT',
3825 'client_test': False,
3827 # could use 'extension_flag': 'ext_draw_buffers' but currently expected to
3830 'pepper_interface': 'DrawBuffers',
3833 'DrawElementsInstancedANGLE': {
3835 'cmd_args': 'GLenumDrawMode mode, GLsizei count, '
3836 'GLenumIndexType type, GLuint index_offset, GLsizei primcount',
3839 'client_test': False,
3840 'pepper_interface': 'InstancedArrays',
3841 'defer_draws': True,
3844 'VertexAttribDivisorANGLE': {
3846 'cmd_args': 'GLuint index, GLuint divisor',
3849 'pepper_interface': 'InstancedArrays',
3853 'gl_test_func': 'glGenQueriesARB',
3854 'resource_type': 'Query',
3855 'resource_types': 'Queries',
3857 'pepper_interface': 'Query',
3858 'not_shared': 'True',
3859 'extension': "occlusion_query_EXT",
3861 'DeleteQueriesEXT': {
3863 'gl_test_func': 'glDeleteQueriesARB',
3864 'resource_type': 'Query',
3865 'resource_types': 'Queries',
3867 'pepper_interface': 'Query',
3868 'extension': "occlusion_query_EXT",
3872 'client_test': False,
3873 'pepper_interface': 'Query',
3874 'extension': "occlusion_query_EXT",
3878 'cmd_args': 'GLenumQueryTarget target, GLidQuery id, void* sync_data',
3879 'data_transfer_methods': ['shm'],
3880 'gl_test_func': 'glBeginQuery',
3881 'pepper_interface': 'Query',
3882 'extension': "occlusion_query_EXT",
3884 'BeginTransformFeedback': {
3889 'cmd_args': 'GLenumQueryTarget target, GLuint submit_count',
3890 'gl_test_func': 'glEndnQuery',
3891 'client_test': False,
3892 'pepper_interface': 'Query',
3893 'extension': "occlusion_query_EXT",
3895 'EndTransformFeedback': {
3898 'FlushDriverCachesCHROMIUM': {
3899 'decoder_func': 'DoFlushDriverCachesCHROMIUM',
3907 'client_test': False,
3908 'gl_test_func': 'glGetQueryiv',
3909 'pepper_interface': 'Query',
3910 'extension': "occlusion_query_EXT",
3912 'QueryCounterEXT' : {
3914 'cmd_args': 'GLidQuery id, GLenumQueryTarget target, '
3915 'void* sync_data, GLuint submit_count',
3916 'data_transfer_methods': ['shm'],
3917 'gl_test_func': 'glQueryCounter',
3918 'extension': "disjoint_timer_query_EXT",
3920 'GetQueryObjectivEXT': {
3922 'client_test': False,
3923 'gl_test_func': 'glGetQueryObjectiv',
3924 'extension': "disjoint_timer_query_EXT",
3926 'GetQueryObjectuivEXT': {
3928 'client_test': False,
3929 'gl_test_func': 'glGetQueryObjectuiv',
3930 'pepper_interface': 'Query',
3931 'extension': "occlusion_query_EXT",
3933 'GetQueryObjecti64vEXT': {
3935 'client_test': False,
3936 'gl_test_func': 'glGetQueryObjecti64v',
3937 'extension': "disjoint_timer_query_EXT",
3939 'GetQueryObjectui64vEXT': {
3941 'client_test': False,
3942 'gl_test_func': 'glGetQueryObjectui64v',
3943 'extension': "disjoint_timer_query_EXT",
3945 'SetDisjointValueSyncCHROMIUM': {
3947 'data_transfer_methods': ['shm'],
3948 'client_test': False,
3949 'cmd_args': 'void* sync_data',
3953 'BindUniformLocationCHROMIUM': {
3956 'data_transfer_methods': ['bucket'],
3958 'gl_test_func': 'DoBindUniformLocationCHROMIUM',
3960 'InsertEventMarkerEXT': {
3962 'decoder_func': 'DoInsertEventMarkerEXT',
3963 'expectation': False,
3966 'PushGroupMarkerEXT': {
3968 'decoder_func': 'DoPushGroupMarkerEXT',
3969 'expectation': False,
3972 'PopGroupMarkerEXT': {
3973 'decoder_func': 'DoPopGroupMarkerEXT',
3974 'expectation': False,
3979 'GenVertexArraysOES': {
3982 'gl_test_func': 'glGenVertexArraysOES',
3983 'resource_type': 'VertexArray',
3984 'resource_types': 'VertexArrays',
3986 'pepper_interface': 'VertexArrayObject',
3988 'BindVertexArrayOES': {
3991 'gl_test_func': 'glBindVertexArrayOES',
3992 'decoder_func': 'DoBindVertexArrayOES',
3993 'gen_func': 'GenVertexArraysOES',
3995 'client_test': False,
3996 'pepper_interface': 'VertexArrayObject',
3998 'DeleteVertexArraysOES': {
4001 'gl_test_func': 'glDeleteVertexArraysOES',
4002 'resource_type': 'VertexArray',
4003 'resource_types': 'VertexArrays',
4005 'pepper_interface': 'VertexArrayObject',
4007 'IsVertexArrayOES': {
4010 'gl_test_func': 'glIsVertexArrayOES',
4011 'decoder_func': 'DoIsVertexArrayOES',
4012 'expectation': False,
4014 'pepper_interface': 'VertexArrayObject',
4016 'BindTexImage2DCHROMIUM': {
4017 'decoder_func': 'DoBindTexImage2DCHROMIUM',
4019 'extension': "CHROMIUM_image",
4022 'ReleaseTexImage2DCHROMIUM': {
4023 'decoder_func': 'DoReleaseTexImage2DCHROMIUM',
4025 'extension': "CHROMIUM_image",
4028 'ShallowFinishCHROMIUM': {
4033 'client_test': False,
4035 'ShallowFlushCHROMIUM': {
4038 'extension': "CHROMIUM_miscellaneous",
4040 'client_test': False,
4042 'OrderingBarrierCHROMIUM': {
4045 'extension': "CHROMIUM_miscellaneous",
4047 'client_test': False,
4049 'TraceBeginCHROMIUM': {
4052 'client_test': False,
4053 'cmd_args': 'GLuint category_bucket_id, GLuint name_bucket_id',
4057 'TraceEndCHROMIUM': {
4059 'client_test': False,
4060 'decoder_func': 'DoTraceEndCHROMIUM',
4065 'DiscardFramebufferEXT': {
4068 'decoder_func': 'DoDiscardFramebufferEXT',
4070 'client_test': False,
4071 'extension_flag': 'ext_discard_framebuffer',
4074 'LoseContextCHROMIUM': {
4075 'decoder_func': 'DoLoseContextCHROMIUM',
4081 'InsertSyncPointCHROMIUM': {
4082 'type': 'HandWritten',
4084 'extension': "CHROMIUM_sync_point",
4088 'WaitSyncPointCHROMIUM': {
4091 'extension': "CHROMIUM_sync_point",
4095 'DiscardBackbufferCHROMIUM': {
4102 'ScheduleOverlayPlaneCHROMIUM': {
4106 'client_test': False,
4110 'MatrixLoadfCHROMIUM': {
4113 'data_type': 'GLfloat',
4114 'decoder_func': 'DoMatrixLoadfCHROMIUM',
4115 'gl_test_func': 'glMatrixLoadfEXT',
4118 'extension_flag': 'chromium_path_rendering',
4120 'MatrixLoadIdentityCHROMIUM': {
4121 'decoder_func': 'DoMatrixLoadIdentityCHROMIUM',
4122 'gl_test_func': 'glMatrixLoadIdentityEXT',
4125 'extension_flag': 'chromium_path_rendering',
4127 'GenPathsCHROMIUM': {
4129 'cmd_args': 'GLuint first_client_id, GLsizei range',
4132 'extension_flag': 'chromium_path_rendering',
4134 'DeletePathsCHROMIUM': {
4136 'cmd_args': 'GLuint first_client_id, GLsizei range',
4141 'extension_flag': 'chromium_path_rendering',
4145 'decoder_func': 'DoIsPathCHROMIUM',
4146 'gl_test_func': 'glIsPathNV',
4149 'extension_flag': 'chromium_path_rendering',
4151 'PathCommandsCHROMIUM': {
4156 'extension_flag': 'chromium_path_rendering',
4158 'PathParameterfCHROMIUM': {
4162 'extension_flag': 'chromium_path_rendering',
4164 'PathParameteriCHROMIUM': {
4168 'extension_flag': 'chromium_path_rendering',
4170 'PathStencilFuncCHROMIUM': {
4172 'state': 'PathStencilFuncCHROMIUM',
4173 'decoder_func': 'glPathStencilFuncNV',
4176 'extension_flag': 'chromium_path_rendering',
4178 'StencilFillPathCHROMIUM': {
4182 'extension_flag': 'chromium_path_rendering',
4184 'StencilStrokePathCHROMIUM': {
4188 'extension_flag': 'chromium_path_rendering',
4190 'CoverFillPathCHROMIUM': {
4194 'extension_flag': 'chromium_path_rendering',
4196 'CoverStrokePathCHROMIUM': {
4200 'extension_flag': 'chromium_path_rendering',
4202 'StencilThenCoverFillPathCHROMIUM': {
4206 'extension_flag': 'chromium_path_rendering',
4208 'StencilThenCoverStrokePathCHROMIUM': {
4212 'extension_flag': 'chromium_path_rendering',
4218 def Grouper(n
, iterable
, fillvalue
=None):
4219 """Collect data into fixed-length chunks or blocks"""
4220 args
= [iter(iterable
)] * n
4221 return itertools
.izip_longest(fillvalue
=fillvalue
, *args
)
4224 def SplitWords(input_string
):
4225 """Split by '_' if found, otherwise split at uppercase/numeric chars.
4227 Will split "some_TEXT" into ["some", "TEXT"], "CamelCase" into ["Camel",
4228 "Case"], and "Vector3" into ["Vector", "3"].
4230 if input_string
.find('_') > -1:
4231 # 'some_TEXT_' -> 'some TEXT'
4232 return input_string
.replace('_', ' ').strip().split()
4234 if re
.search('[A-Z]', input_string
) and re
.search('[a-z]', input_string
):
4236 # look for capitalization to cut input_strings
4237 # 'SomeText' -> 'Some Text'
4238 input_string
= re
.sub('([A-Z])', r
' \1', input_string
).strip()
4239 # 'Vector3' -> 'Vector 3'
4240 input_string
= re
.sub('([^0-9])([0-9])', r
'\1 \2', input_string
)
4241 return input_string
.split()
4243 def ToUnderscore(input_string
):
4244 """converts CamelCase to camel_case."""
4245 words
= SplitWords(input_string
)
4246 return '_'.join([word
.lower() for word
in words
])
4248 def CachedStateName(item
):
4249 if item
.get('cached', False):
4250 return 'cached_' + item
['name']
4253 def ToGLExtensionString(extension_flag
):
4254 """Returns GL-type extension string of a extension flag."""
4255 if extension_flag
== "oes_compressed_etc1_rgb8_texture":
4256 return "OES_compressed_ETC1_RGB8_texture" # Fixup inconsitency with rgb8,
4258 uppercase_words
= [ 'img', 'ext', 'arb', 'chromium', 'oes', 'amd', 'bgra8888',
4259 'egl', 'atc', 'etc1', 'angle']
4260 parts
= extension_flag
.split('_')
4262 [part
.upper() if part
in uppercase_words
else part
for part
in parts
])
4264 def ToCamelCase(input_string
):
4265 """converts ABC_underscore_case to ABCUnderscoreCase."""
4266 return ''.join(w
[0].upper() + w
[1:] for w
in input_string
.split('_'))
4268 def GetGLGetTypeConversion(result_type
, value_type
, value
):
4269 """Makes a gl compatible type conversion string for accessing state variables.
4271 Useful when accessing state variables through glGetXXX calls.
4272 glGet documetation (for example, the manual pages):
4273 [...] If glGetIntegerv is called, [...] most floating-point values are
4274 rounded to the nearest integer value. [...]
4277 result_type: the gl type to be obtained
4278 value_type: the GL type of the state variable
4279 value: the name of the state variable
4282 String that converts the state variable to desired GL type according to GL
4286 if result_type
== 'GLint':
4287 if value_type
== 'GLfloat':
4288 return 'static_cast<GLint>(round(%s))' % value
4289 return 'static_cast<%s>(%s)' % (result_type
, value
)
4292 class CWriter(object):
4293 """Context manager that creates a C source file.
4295 To be used with the `with` statement. Returns a normal `file` type, open only
4296 for writing - any existing files with that name will be overwritten. It will
4297 automatically write the contents of `_LICENSE` and `_DO_NOT_EDIT_WARNING`
4301 with CWriter("file.cpp") as myfile:
4302 myfile.write("hello")
4303 # type(myfile) == file
4305 def __init__(self
, filename
):
4306 self
.filename
= filename
4307 self
._file
= open(filename
, 'w')
4308 self
._ENTER
_MSG
= _LICENSE
+ _DO_NOT_EDIT_WARNING
4311 def __enter__(self
):
4312 self
._file
.write(self
._ENTER
_MSG
)
4315 def __exit__(self
, exc_type
, exc_value
, traceback
):
4316 self
._file
.write(self
._EXIT
_MSG
)
4320 class CHeaderWriter(CWriter
):
4321 """Context manager that creates a C header file.
4323 Works the same way as CWriter, except it will also add the #ifdef guard
4324 around it. If `file_comment` is set, it will write that before the #ifdef
4327 def __init__(self
, filename
, file_comment
=None):
4328 super(CHeaderWriter
, self
).__init
__(filename
)
4329 guard
= self
._get
_guard
()
4330 if file_comment
is None:
4332 self
._ENTER
_MSG
= self
._ENTER
_MSG
+ file_comment \
4333 + "#ifndef %s\n#define %s\n\n" % (guard
, guard
)
4334 self
._EXIT
_MSG
= self
._EXIT
_MSG
+ "#endif // %s\n" % guard
4336 def _get_guard(self
):
4337 non_alnum_re
= re
.compile(r
'[^a-zA-Z0-9]')
4338 base
= os
.path
.abspath(self
.filename
)
4339 while os
.path
.basename(base
) != 'src':
4340 new_base
= os
.path
.dirname(base
)
4341 assert new_base
!= base
# Prevent infinite loop.
4343 hpath
= os
.path
.relpath(self
.filename
, base
)
4344 return non_alnum_re
.sub('_', hpath
).upper() + '_'
4347 class TypeHandler(object):
4348 """This class emits code for a particular type of function."""
4350 _remove_expected_call_re
= re
.compile(r
' EXPECT_CALL.*?;\n', re
.S
)
4352 def InitFunction(self
, func
):
4353 """Add or adjust anything type specific for this function."""
4354 if func
.GetInfo('needs_size') and not func
.name
.endswith('Bucket'):
4355 func
.AddCmdArg(DataSizeArgument('data_size'))
4357 def NeedsDataTransferFunction(self
, func
):
4358 """Overriden from TypeHandler."""
4359 return func
.num_pointer_args
>= 1
4361 def WriteStruct(self
, func
, f
):
4362 """Writes a structure that matches the arguments to a function."""
4363 comment
= func
.GetInfo('cmd_comment')
4364 if not comment
== None:
4366 f
.write("struct %s {\n" % func
.name
)
4367 f
.write(" typedef %s ValueType;\n" % func
.name
)
4368 f
.write(" static const CommandId kCmdId = k%s;\n" % func
.name
)
4369 func
.WriteCmdArgFlag(f
)
4370 func
.WriteCmdFlag(f
)
4372 result
= func
.GetInfo('result')
4373 if not result
== None:
4374 if len(result
) == 1:
4375 f
.write(" typedef %s Result;\n\n" % result
[0])
4377 f
.write(" struct Result {\n")
4379 f
.write(" %s;\n" % line
)
4382 func
.WriteCmdComputeSize(f
)
4383 func
.WriteCmdSetHeader(f
)
4384 func
.WriteCmdInit(f
)
4387 f
.write(" gpu::CommandHeader header;\n")
4388 args
= func
.GetCmdArgs()
4390 f
.write(" %s %s;\n" % (arg
.cmd_type
, arg
.name
))
4392 consts
= func
.GetCmdConstants()
4393 for const
in consts
:
4394 f
.write(" static const %s %s = %s;\n" %
4395 (const
.cmd_type
, const
.name
, const
.GetConstantValue()))
4400 size
= len(args
) * _SIZE_OF_UINT32
+ _SIZE_OF_COMMAND_HEADER
4401 f
.write("static_assert(sizeof(%s) == %d,\n" % (func
.name
, size
))
4402 f
.write(" \"size of %s should be %d\");\n" %
4404 f
.write("static_assert(offsetof(%s, header) == 0,\n" % func
.name
)
4405 f
.write(" \"offset of %s header should be 0\");\n" %
4407 offset
= _SIZE_OF_COMMAND_HEADER
4409 f
.write("static_assert(offsetof(%s, %s) == %d,\n" %
4410 (func
.name
, arg
.name
, offset
))
4411 f
.write(" \"offset of %s %s should be %d\");\n" %
4412 (func
.name
, arg
.name
, offset
))
4413 offset
+= _SIZE_OF_UINT32
4414 if not result
== None and len(result
) > 1:
4417 parts
= line
.split()
4420 static_assert(offsetof(%(cmd_name)s::Result, %(field_name)s) == %(offset)d,
4421 "offset of %(cmd_name)s Result %(field_name)s should be "
4424 f
.write((check
.strip() + "\n") % {
4425 'cmd_name': func
.name
,
4429 offset
+= _SIZE_OF_UINT32
4432 def WriteHandlerImplementation(self
, func
, f
):
4433 """Writes the handler implementation for this command."""
4434 if func
.IsUnsafe() and func
.GetInfo('id_mapping'):
4435 code_no_gen
= """ if (!group_->Get%(type)sServiceId(
4436 %(var)s, &%(service_var)s)) {
4437 LOCAL_SET_GL_ERROR(GL_INVALID_OPERATION, "%(func)s", "invalid %(var)s id");
4438 return error::kNoError;
4441 code_gen
= """ if (!group_->Get%(type)sServiceId(
4442 %(var)s, &%(service_var)s)) {
4443 if (!group_->bind_generates_resource()) {
4445 GL_INVALID_OPERATION, "%(func)s", "invalid %(var)s id");
4446 return error::kNoError;
4448 GLuint client_id = %(var)s;
4449 gl%(gen_func)s(1, &%(service_var)s);
4450 Create%(type)s(client_id, %(service_var)s);
4453 gen_func
= func
.GetInfo('gen_func')
4454 for id_type
in func
.GetInfo('id_mapping'):
4455 service_var
= id_type
.lower()
4456 if id_type
== 'Sync':
4457 service_var
= "service_%s" % service_var
4458 f
.write(" GLsync %s = 0;\n" % service_var
)
4459 if id_type
== 'Sampler' and func
.IsType('Bind'):
4460 # No error generated when binding a reserved zero sampler.
4461 args
= [arg
.name
for arg
in func
.GetOriginalArgs()]
4462 f
.write(""" if(%(var)s == 0) {
4464 return error::kNoError;
4465 }""" % { 'var': id_type
.lower(),
4466 'func': func
.GetGLFunctionName(),
4467 'args': ", ".join(args
) })
4468 if gen_func
and id_type
in gen_func
:
4469 f
.write(code_gen
% { 'type': id_type
,
4470 'var': id_type
.lower(),
4471 'service_var': service_var
,
4472 'func': func
.GetGLFunctionName(),
4473 'gen_func': gen_func
})
4475 f
.write(code_no_gen
% { 'type': id_type
,
4476 'var': id_type
.lower(),
4477 'service_var': service_var
,
4478 'func': func
.GetGLFunctionName() })
4480 for arg
in func
.GetOriginalArgs():
4481 if arg
.type == "GLsync":
4482 args
.append("service_%s" % arg
.name
)
4483 elif arg
.name
.endswith("size") and arg
.type == "GLsizei":
4484 args
.append("num_%s" % func
.GetLastOriginalArg().name
)
4485 elif arg
.name
== "length":
4486 args
.append("nullptr")
4488 args
.append(arg
.name
)
4489 f
.write(" %s(%s);\n" %
4490 (func
.GetGLFunctionName(), ", ".join(args
)))
4492 def WriteCmdSizeTest(self
, func
, f
):
4493 """Writes the size test for a command."""
4494 f
.write(" EXPECT_EQ(sizeof(cmd), cmd.header.size * 4u);\n")
4496 def WriteFormatTest(self
, func
, f
):
4497 """Writes a format test for a command."""
4498 f
.write("TEST_F(GLES2FormatTest, %s) {\n" % func
.name
)
4499 f
.write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
4500 (func
.name
, func
.name
))
4501 f
.write(" void* next_cmd = cmd.Set(\n")
4503 args
= func
.GetCmdArgs()
4504 for value
, arg
in enumerate(args
):
4505 f
.write(",\n static_cast<%s>(%d)" % (arg
.type, value
+ 11))
4507 f
.write(" EXPECT_EQ(static_cast<uint32_t>(cmds::%s::kCmdId),\n" %
4509 f
.write(" cmd.header.command);\n")
4510 func
.type_handler
.WriteCmdSizeTest(func
, f
)
4511 for value
, arg
in enumerate(args
):
4512 f
.write(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);\n" %
4513 (arg
.type, value
+ 11, arg
.name
))
4514 f
.write(" CheckBytesWrittenMatchesExpectedSize(\n")
4515 f
.write(" next_cmd, sizeof(cmd));\n")
4519 def WriteImmediateFormatTest(self
, func
, f
):
4520 """Writes a format test for an immediate version of a command."""
4523 def WriteGetDataSizeCode(self
, func
, f
):
4524 """Writes the code to set data_size used in validation"""
4527 def __WriteIdMapping(self
, func
, f
):
4528 """Writes client side / service side ID mapping."""
4529 if not func
.IsUnsafe() or not func
.GetInfo('id_mapping'):
4531 for id_type
in func
.GetInfo('id_mapping'):
4532 f
.write(" group_->Get%sServiceId(%s, &%s);\n" %
4533 (id_type
, id_type
.lower(), id_type
.lower()))
4535 def WriteImmediateHandlerImplementation (self
, func
, f
):
4536 """Writes the handler impl for the immediate version of a command."""
4537 self
.__WriteIdMapping
(func
, f
)
4538 f
.write(" %s(%s);\n" %
4539 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
4541 def WriteBucketHandlerImplementation (self
, func
, f
):
4542 """Writes the handler impl for the bucket version of a command."""
4543 self
.__WriteIdMapping
(func
, f
)
4544 f
.write(" %s(%s);\n" %
4545 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
4547 def WriteServiceHandlerFunctionHeader(self
, func
, f
):
4548 """Writes function header for service implementation handlers."""
4549 f
.write("""error::Error GLES2DecoderImpl::Handle%(name)s(
4550 uint32_t immediate_data_size, const void* cmd_data) {
4551 """ % {'name': func
.name
})
4553 f
.write("""if (!unsafe_es3_apis_enabled())
4554 return error::kUnknownCommand;
4556 f
.write("""const gles2::cmds::%(name)s& c =
4557 *static_cast<const gles2::cmds::%(name)s*>(cmd_data);
4559 """ % {'name': func
.name
})
4561 def WriteServiceImplementation(self
, func
, f
):
4562 """Writes the service implementation for a command."""
4563 self
.WriteServiceHandlerFunctionHeader(func
, f
)
4564 self
.WriteHandlerExtensionCheck(func
, f
)
4565 self
.WriteHandlerDeferReadWrite(func
, f
);
4566 if len(func
.GetOriginalArgs()) > 0:
4567 last_arg
= func
.GetLastOriginalArg()
4568 all_but_last_arg
= func
.GetOriginalArgs()[:-1]
4569 for arg
in all_but_last_arg
:
4571 self
.WriteGetDataSizeCode(func
, f
)
4572 last_arg
.WriteGetCode(f
)
4573 func
.WriteHandlerValidation(f
)
4574 func
.WriteHandlerImplementation(f
)
4575 f
.write(" return error::kNoError;\n")
4579 def WriteImmediateServiceImplementation(self
, func
, f
):
4580 """Writes the service implementation for an immediate version of command."""
4581 self
.WriteServiceHandlerFunctionHeader(func
, f
)
4582 self
.WriteHandlerExtensionCheck(func
, f
)
4583 self
.WriteHandlerDeferReadWrite(func
, f
);
4584 for arg
in func
.GetOriginalArgs():
4586 self
.WriteGetDataSizeCode(func
, f
)
4588 func
.WriteHandlerValidation(f
)
4589 func
.WriteHandlerImplementation(f
)
4590 f
.write(" return error::kNoError;\n")
4594 def WriteBucketServiceImplementation(self
, func
, f
):
4595 """Writes the service implementation for a bucket version of command."""
4596 self
.WriteServiceHandlerFunctionHeader(func
, f
)
4597 self
.WriteHandlerExtensionCheck(func
, f
)
4598 self
.WriteHandlerDeferReadWrite(func
, f
);
4599 for arg
in func
.GetCmdArgs():
4601 func
.WriteHandlerValidation(f
)
4602 func
.WriteHandlerImplementation(f
)
4603 f
.write(" return error::kNoError;\n")
4607 def WriteHandlerExtensionCheck(self
, func
, f
):
4608 if func
.GetInfo('extension_flag'):
4609 f
.write(" if (!features().%s) {\n" % func
.GetInfo('extension_flag'))
4610 f
.write(" LOCAL_SET_GL_ERROR(GL_INVALID_OPERATION, \"gl%s\","
4611 " \"function not available\");\n" % func
.original_name
)
4612 f
.write(" return error::kNoError;")
4615 def WriteHandlerDeferReadWrite(self
, func
, f
):
4616 """Writes the code to handle deferring reads or writes."""
4617 defer_draws
= func
.GetInfo('defer_draws')
4618 defer_reads
= func
.GetInfo('defer_reads')
4619 if defer_draws
or defer_reads
:
4620 f
.write(" error::Error error;\n")
4622 f
.write(" error = WillAccessBoundFramebufferForDraw();\n")
4623 f
.write(" if (error != error::kNoError)\n")
4624 f
.write(" return error;\n")
4626 f
.write(" error = WillAccessBoundFramebufferForRead();\n")
4627 f
.write(" if (error != error::kNoError)\n")
4628 f
.write(" return error;\n")
4630 def WriteValidUnitTest(self
, func
, f
, test
, *extras
):
4631 """Writes a valid unit test for the service implementation."""
4632 if func
.GetInfo('expectation') == False:
4633 test
= self
._remove
_expected
_call
_re
.sub('', test
)
4636 arg
.GetValidArg(func
) \
4637 for arg
in func
.GetOriginalArgs() if not arg
.IsConstant()
4640 arg
.GetValidGLArg(func
) \
4641 for arg
in func
.GetOriginalArgs()
4643 gl_func_name
= func
.GetGLTestFunctionName()
4646 'gl_func_name': gl_func_name
,
4647 'args': ", ".join(arg_strings
),
4648 'gl_args': ", ".join(gl_arg_strings
),
4650 for extra
in extras
:
4653 while (old_test
!= test
):
4656 f
.write(test
% vars)
4658 def WriteInvalidUnitTest(self
, func
, f
, test
, *extras
):
4659 """Writes an invalid unit test for the service implementation."""
4662 for invalid_arg_index
, invalid_arg
in enumerate(func
.GetOriginalArgs()):
4663 # Service implementation does not test constants, as they are not part of
4664 # the call in the service side.
4665 if invalid_arg
.IsConstant():
4668 num_invalid_values
= invalid_arg
.GetNumInvalidValues(func
)
4669 for value_index
in range(0, num_invalid_values
):
4671 parse_result
= "kNoError"
4673 for arg
in func
.GetOriginalArgs():
4674 if arg
.IsConstant():
4676 if invalid_arg
is arg
:
4677 (arg_string
, parse_result
, gl_error
) = arg
.GetInvalidArg(
4680 arg_string
= arg
.GetValidArg(func
)
4681 arg_strings
.append(arg_string
)
4683 for arg
in func
.GetOriginalArgs():
4684 gl_arg_strings
.append("_")
4685 gl_func_name
= func
.GetGLTestFunctionName()
4687 if not gl_error
== None:
4688 gl_error_test
= '\n EXPECT_EQ(%s, GetGLError());' % gl_error
4692 'arg_index': invalid_arg_index
,
4693 'value_index': value_index
,
4694 'gl_func_name': gl_func_name
,
4695 'args': ", ".join(arg_strings
),
4696 'all_but_last_args': ", ".join(arg_strings
[:-1]),
4697 'gl_args': ", ".join(gl_arg_strings
),
4698 'parse_result': parse_result
,
4699 'gl_error_test': gl_error_test
,
4701 for extra
in extras
:
4703 f
.write(test
% vars)
4705 def WriteServiceUnitTest(self
, func
, f
, *extras
):
4706 """Writes the service unit test for a command."""
4708 if func
.name
== 'Enable':
4710 TEST_P(%(test_name)s, %(name)sValidArgs) {
4711 SetupExpectationsForEnableDisable(%(gl_args)s, true);
4712 SpecializedSetup<cmds::%(name)s, 0>(true);
4714 cmd.Init(%(args)s);"""
4715 elif func
.name
== 'Disable':
4717 TEST_P(%(test_name)s, %(name)sValidArgs) {
4718 SetupExpectationsForEnableDisable(%(gl_args)s, false);
4719 SpecializedSetup<cmds::%(name)s, 0>(true);
4721 cmd.Init(%(args)s);"""
4724 TEST_P(%(test_name)s, %(name)sValidArgs) {
4725 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
4726 SpecializedSetup<cmds::%(name)s, 0>(true);
4728 cmd.Init(%(args)s);"""
4731 decoder_->set_unsafe_es3_apis_enabled(true);
4732 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4733 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4734 decoder_->set_unsafe_es3_apis_enabled(false);
4735 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));
4740 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4741 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4744 self
.WriteValidUnitTest(func
, f
, valid_test
, *extras
)
4746 if not func
.IsUnsafe():
4748 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
4749 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
4750 SpecializedSetup<cmds::%(name)s, 0>(false);
4753 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
4756 self
.WriteInvalidUnitTest(func
, f
, invalid_test
, *extras
)
4758 def WriteImmediateServiceUnitTest(self
, func
, f
, *extras
):
4759 """Writes the service unit test for an immediate command."""
4760 f
.write("// TODO(gman): %s\n" % func
.name
)
4762 def WriteImmediateValidationCode(self
, func
, f
):
4763 """Writes the validation code for an immediate version of a command."""
4766 def WriteBucketServiceUnitTest(self
, func
, f
, *extras
):
4767 """Writes the service unit test for a bucket command."""
4768 f
.write("// TODO(gman): %s\n" % func
.name
)
4770 def WriteGLES2ImplementationDeclaration(self
, func
, f
):
4771 """Writes the GLES2 Implemention declaration."""
4772 impl_decl
= func
.GetInfo('impl_decl')
4773 if impl_decl
== None or impl_decl
== True:
4774 f
.write("%s %s(%s) override;\n" %
4775 (func
.return_type
, func
.original_name
,
4776 func
.MakeTypedOriginalArgString("")))
4779 def WriteGLES2CLibImplementation(self
, func
, f
):
4780 f
.write("%s GL_APIENTRY GLES2%s(%s) {\n" %
4781 (func
.return_type
, func
.name
,
4782 func
.MakeTypedOriginalArgString("")))
4783 result_string
= "return "
4784 if func
.return_type
== "void":
4786 f
.write(" %sgles2::GetGLContext()->%s(%s);\n" %
4787 (result_string
, func
.original_name
,
4788 func
.MakeOriginalArgString("")))
4791 def WriteGLES2Header(self
, func
, f
):
4792 """Writes a re-write macro for GLES"""
4793 f
.write("#define gl%s GLES2_GET_FUN(%s)\n" %(func
.name
, func
.name
))
4795 def WriteClientGLCallLog(self
, func
, f
):
4796 """Writes a logging macro for the client side code."""
4798 if len(func
.GetOriginalArgs()):
4801 ' GPU_CLIENT_LOG("[" << GetLogPrefix() << "] gl%s("%s%s << ")");\n' %
4802 (func
.original_name
, comma
, func
.MakeLogArgString()))
4804 def WriteClientGLReturnLog(self
, func
, f
):
4805 """Writes the return value logging code."""
4806 if func
.return_type
!= "void":
4807 f
.write(' GPU_CLIENT_LOG("return:" << result)\n')
4809 def WriteGLES2ImplementationHeader(self
, func
, f
):
4810 """Writes the GLES2 Implemention."""
4811 self
.WriteGLES2ImplementationDeclaration(func
, f
)
4813 def WriteGLES2TraceImplementationHeader(self
, func
, f
):
4814 """Writes the GLES2 Trace Implemention header."""
4815 f
.write("%s %s(%s) override;\n" %
4816 (func
.return_type
, func
.original_name
,
4817 func
.MakeTypedOriginalArgString("")))
4819 def WriteGLES2TraceImplementation(self
, func
, f
):
4820 """Writes the GLES2 Trace Implemention."""
4821 f
.write("%s GLES2TraceImplementation::%s(%s) {\n" %
4822 (func
.return_type
, func
.original_name
,
4823 func
.MakeTypedOriginalArgString("")))
4824 result_string
= "return "
4825 if func
.return_type
== "void":
4827 f
.write(' TRACE_EVENT_BINARY_EFFICIENT0("gpu", "GLES2Trace::%s");\n' %
4829 f
.write(" %sgl_->%s(%s);\n" %
4830 (result_string
, func
.name
, func
.MakeOriginalArgString("")))
4834 def WriteGLES2Implementation(self
, func
, f
):
4835 """Writes the GLES2 Implemention."""
4836 impl_func
= func
.GetInfo('impl_func')
4837 impl_decl
= func
.GetInfo('impl_decl')
4838 gen_cmd
= func
.GetInfo('gen_cmd')
4839 if (func
.can_auto_generate
and
4840 (impl_func
== None or impl_func
== True) and
4841 (impl_decl
== None or impl_decl
== True) and
4842 (gen_cmd
== None or gen_cmd
== True)):
4843 f
.write("%s GLES2Implementation::%s(%s) {\n" %
4844 (func
.return_type
, func
.original_name
,
4845 func
.MakeTypedOriginalArgString("")))
4846 f
.write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
4847 self
.WriteClientGLCallLog(func
, f
)
4848 func
.WriteDestinationInitalizationValidation(f
)
4849 for arg
in func
.GetOriginalArgs():
4850 arg
.WriteClientSideValidationCode(f
, func
)
4851 f
.write(" helper_->%s(%s);\n" %
4852 (func
.name
, func
.MakeHelperArgString("")))
4853 f
.write(" CheckGLError();\n")
4854 self
.WriteClientGLReturnLog(func
, f
)
4858 def WriteGLES2InterfaceHeader(self
, func
, f
):
4859 """Writes the GLES2 Interface."""
4860 f
.write("virtual %s %s(%s) = 0;\n" %
4861 (func
.return_type
, func
.original_name
,
4862 func
.MakeTypedOriginalArgString("")))
4864 def WriteMojoGLES2ImplHeader(self
, func
, f
):
4865 """Writes the Mojo GLES2 implementation header."""
4866 f
.write("%s %s(%s) override;\n" %
4867 (func
.return_type
, func
.original_name
,
4868 func
.MakeTypedOriginalArgString("")))
4870 def WriteMojoGLES2Impl(self
, func
, f
):
4871 """Writes the Mojo GLES2 implementation."""
4872 f
.write("%s MojoGLES2Impl::%s(%s) {\n" %
4873 (func
.return_type
, func
.original_name
,
4874 func
.MakeTypedOriginalArgString("")))
4875 extensions
= ["CHROMIUM_sync_point", "CHROMIUM_texture_mailbox",
4876 "CHROMIUM_sub_image", "CHROMIUM_miscellaneous",
4877 "occlusion_query_EXT", "CHROMIUM_image",
4878 "CHROMIUM_copy_texture",
4879 "CHROMIUM_pixel_transfer_buffer_object",
4880 "chromium_framebuffer_multisample"]
4881 if func
.IsCoreGLFunction() or func
.GetInfo("extension") in extensions
:
4882 f
.write("MojoGLES2MakeCurrent(context_);");
4883 func_return
= "gl" + func
.original_name
+ "(" + \
4884 func
.MakeOriginalArgString("") + ");"
4885 if func
.return_type
== "void":
4886 f
.write(func_return
);
4888 f
.write("return " + func_return
);
4890 f
.write("NOTREACHED() << \"Unimplemented %s.\";\n" %
4891 func
.original_name
);
4892 if func
.return_type
!= "void":
4893 f
.write("return 0;")
4896 def WriteGLES2InterfaceStub(self
, func
, f
):
4897 """Writes the GLES2 Interface stub declaration."""
4898 f
.write("%s %s(%s) override;\n" %
4899 (func
.return_type
, func
.original_name
,
4900 func
.MakeTypedOriginalArgString("")))
4902 def WriteGLES2InterfaceStubImpl(self
, func
, f
):
4903 """Writes the GLES2 Interface stub declaration."""
4904 args
= func
.GetOriginalArgs()
4905 arg_string
= ", ".join(
4906 ["%s /* %s */" % (arg
.type, arg
.name
) for arg
in args
])
4907 f
.write("%s GLES2InterfaceStub::%s(%s) {\n" %
4908 (func
.return_type
, func
.original_name
, arg_string
))
4909 if func
.return_type
!= "void":
4910 f
.write(" return 0;\n")
4913 def WriteGLES2ImplementationUnitTest(self
, func
, f
):
4914 """Writes the GLES2 Implemention unit test."""
4915 client_test
= func
.GetInfo('client_test')
4916 if (func
.can_auto_generate
and
4917 (client_test
== None or client_test
== True)):
4919 TEST_F(GLES2ImplementationTest, %(name)s) {
4924 expected.cmd.Init(%(cmd_args)s);
4926 gl_->%(name)s(%(args)s);
4927 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
4931 arg
.GetValidClientSideCmdArg(func
) for arg
in func
.GetCmdArgs()
4935 arg
.GetValidClientSideArg(func
) for arg
in func
.GetOriginalArgs()
4940 'args': ", ".join(gl_arg_strings
),
4941 'cmd_args': ", ".join(cmd_arg_strings
),
4944 # Test constants for invalid values, as they are not tested by the
4946 constants
= [arg
for arg
in func
.GetOriginalArgs() if arg
.IsConstant()]
4949 TEST_F(GLES2ImplementationTest, %(name)sInvalidConstantArg%(invalid_index)d) {
4950 gl_->%(name)s(%(args)s);
4951 EXPECT_TRUE(NoCommandsWritten());
4952 EXPECT_EQ(%(gl_error)s, CheckError());
4955 for invalid_arg
in constants
:
4957 invalid
= invalid_arg
.GetInvalidArg(func
)
4958 for arg
in func
.GetOriginalArgs():
4959 if arg
is invalid_arg
:
4960 gl_arg_strings
.append(invalid
[0])
4962 gl_arg_strings
.append(arg
.GetValidClientSideArg(func
))
4966 'invalid_index': func
.GetOriginalArgs().index(invalid_arg
),
4967 'args': ", ".join(gl_arg_strings
),
4968 'gl_error': invalid
[2],
4971 if client_test
!= False:
4972 f
.write("// TODO(zmo): Implement unit test for %s\n" % func
.name
)
4974 def WriteDestinationInitalizationValidation(self
, func
, f
):
4975 """Writes the client side destintion initialization validation."""
4976 for arg
in func
.GetOriginalArgs():
4977 arg
.WriteDestinationInitalizationValidation(f
, func
)
4979 def WriteTraceEvent(self
, func
, f
):
4980 f
.write(' TRACE_EVENT0("gpu", "GLES2Implementation::%s");\n' %
4983 def WriteImmediateCmdComputeSize(self
, func
, f
):
4984 """Writes the size computation code for the immediate version of a cmd."""
4985 f
.write(" static uint32_t ComputeSize(uint32_t size_in_bytes) {\n")
4986 f
.write(" return static_cast<uint32_t>(\n")
4987 f
.write(" sizeof(ValueType) + // NOLINT\n")
4988 f
.write(" RoundSizeToMultipleOfEntries(size_in_bytes));\n")
4992 def WriteImmediateCmdSetHeader(self
, func
, f
):
4993 """Writes the SetHeader function for the immediate version of a cmd."""
4994 f
.write(" void SetHeader(uint32_t size_in_bytes) {\n")
4995 f
.write(" header.SetCmdByTotalSize<ValueType>(size_in_bytes);\n")
4999 def WriteImmediateCmdInit(self
, func
, f
):
5000 """Writes the Init function for the immediate version of a command."""
5001 raise NotImplementedError(func
.name
)
5003 def WriteImmediateCmdSet(self
, func
, f
):
5004 """Writes the Set function for the immediate version of a command."""
5005 raise NotImplementedError(func
.name
)
5007 def WriteCmdHelper(self
, func
, f
):
5008 """Writes the cmd helper definition for a cmd."""
5009 code
= """ void %(name)s(%(typed_args)s) {
5010 gles2::cmds::%(name)s* c = GetCmdSpace<gles2::cmds::%(name)s>();
5019 "typed_args": func
.MakeTypedCmdArgString(""),
5020 "args": func
.MakeCmdArgString(""),
5023 def WriteImmediateCmdHelper(self
, func
, f
):
5024 """Writes the cmd helper definition for the immediate version of a cmd."""
5025 code
= """ void %(name)s(%(typed_args)s) {
5026 const uint32_t s = 0; // TODO(gman): compute correct size
5027 gles2::cmds::%(name)s* c =
5028 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(s);
5037 "typed_args": func
.MakeTypedCmdArgString(""),
5038 "args": func
.MakeCmdArgString(""),
5042 class StateSetHandler(TypeHandler
):
5043 """Handler for commands that simply set state."""
5045 def WriteHandlerImplementation(self
, func
, f
):
5046 """Overrriden from TypeHandler."""
5047 state_name
= func
.GetInfo('state')
5048 state
= _STATES
[state_name
]
5049 states
= state
['states']
5050 args
= func
.GetOriginalArgs()
5051 for ndx
,item
in enumerate(states
):
5053 if 'range_checks' in item
:
5054 for range_check
in item
['range_checks']:
5055 code
.append("%s %s" % (args
[ndx
].name
, range_check
['check']))
5056 if 'nan_check' in item
:
5057 # Drivers might generate an INVALID_VALUE error when a value is set
5058 # to NaN. This is allowed behavior under GLES 3.0 section 2.1.1 or
5059 # OpenGL 4.5 section 2.3.4.1 - providing NaN allows undefined results.
5060 # Make this behavior consistent within Chromium, and avoid leaking GL
5061 # errors by generating the error in the command buffer instead of
5062 # letting the GL driver generate it.
5063 code
.append("std::isnan(%s)" % args
[ndx
].name
)
5065 f
.write(" if (%s) {\n" % " ||\n ".join(code
))
5067 ' LOCAL_SET_GL_ERROR(GL_INVALID_VALUE,'
5068 ' "%s", "%s out of range");\n' %
5069 (func
.name
, args
[ndx
].name
))
5070 f
.write(" return error::kNoError;\n")
5073 for ndx
,item
in enumerate(states
):
5074 code
.append("state_.%s != %s" % (item
['name'], args
[ndx
].name
))
5075 f
.write(" if (%s) {\n" % " ||\n ".join(code
))
5076 for ndx
,item
in enumerate(states
):
5077 f
.write(" state_.%s = %s;\n" % (item
['name'], args
[ndx
].name
))
5078 if 'state_flag' in state
:
5079 f
.write(" %s = true;\n" % state
['state_flag'])
5080 if not func
.GetInfo("no_gl"):
5081 for ndx
,item
in enumerate(states
):
5082 if item
.get('cached', False):
5083 f
.write(" state_.%s = %s;\n" %
5084 (CachedStateName(item
), args
[ndx
].name
))
5085 f
.write(" %s(%s);\n" %
5086 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
5089 def WriteServiceUnitTest(self
, func
, f
, *extras
):
5090 """Overrriden from TypeHandler."""
5091 TypeHandler
.WriteServiceUnitTest(self
, func
, f
, *extras
)
5092 state_name
= func
.GetInfo('state')
5093 state
= _STATES
[state_name
]
5094 states
= state
['states']
5095 for ndx
,item
in enumerate(states
):
5096 if 'range_checks' in item
:
5097 for check_ndx
, range_check
in enumerate(item
['range_checks']):
5099 TEST_P(%(test_name)s, %(name)sInvalidValue%(ndx)d_%(check_ndx)d) {
5100 SpecializedSetup<cmds::%(name)s, 0>(false);
5103 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5104 EXPECT_EQ(GL_INVALID_VALUE, GetGLError());
5109 arg
.GetValidArg(func
) \
5110 for arg
in func
.GetOriginalArgs() if not arg
.IsConstant()
5113 arg_strings
[ndx
] = range_check
['test_value']
5117 'check_ndx': check_ndx
,
5118 'args': ", ".join(arg_strings
),
5120 for extra
in extras
:
5122 f
.write(valid_test
% vars)
5123 if 'nan_check' in item
:
5125 TEST_P(%(test_name)s, %(name)sNaNValue%(ndx)d) {
5126 SpecializedSetup<cmds::%(name)s, 0>(false);
5129 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5130 EXPECT_EQ(GL_INVALID_VALUE, GetGLError());
5135 arg
.GetValidArg(func
) \
5136 for arg
in func
.GetOriginalArgs() if not arg
.IsConstant()
5139 arg_strings
[ndx
] = 'nanf("")'
5143 'args': ", ".join(arg_strings
),
5145 for extra
in extras
:
5147 f
.write(valid_test
% vars)
5150 class StateSetRGBAlphaHandler(TypeHandler
):
5151 """Handler for commands that simply set state that have rgb/alpha."""
5153 def WriteHandlerImplementation(self
, func
, f
):
5154 """Overrriden from TypeHandler."""
5155 state_name
= func
.GetInfo('state')
5156 state
= _STATES
[state_name
]
5157 states
= state
['states']
5158 args
= func
.GetOriginalArgs()
5159 num_args
= len(args
)
5161 for ndx
,item
in enumerate(states
):
5162 code
.append("state_.%s != %s" % (item
['name'], args
[ndx
% num_args
].name
))
5163 f
.write(" if (%s) {\n" % " ||\n ".join(code
))
5164 for ndx
, item
in enumerate(states
):
5165 f
.write(" state_.%s = %s;\n" %
5166 (item
['name'], args
[ndx
% num_args
].name
))
5167 if 'state_flag' in state
:
5168 f
.write(" %s = true;\n" % state
['state_flag'])
5169 if not func
.GetInfo("no_gl"):
5170 f
.write(" %s(%s);\n" %
5171 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
5175 class StateSetFrontBackSeparateHandler(TypeHandler
):
5176 """Handler for commands that simply set state that have front/back."""
5178 def WriteHandlerImplementation(self
, func
, f
):
5179 """Overrriden from TypeHandler."""
5180 state_name
= func
.GetInfo('state')
5181 state
= _STATES
[state_name
]
5182 states
= state
['states']
5183 args
= func
.GetOriginalArgs()
5185 num_args
= len(args
)
5186 f
.write(" bool changed = false;\n")
5187 for group_ndx
, group
in enumerate(Grouper(num_args
- 1, states
)):
5188 f
.write(" if (%s == %s || %s == GL_FRONT_AND_BACK) {\n" %
5189 (face
, ('GL_FRONT', 'GL_BACK')[group_ndx
], face
))
5191 for ndx
, item
in enumerate(group
):
5192 code
.append("state_.%s != %s" % (item
['name'], args
[ndx
+ 1].name
))
5193 f
.write(" changed |= %s;\n" % " ||\n ".join(code
))
5195 f
.write(" if (changed) {\n")
5196 for group_ndx
, group
in enumerate(Grouper(num_args
- 1, states
)):
5197 f
.write(" if (%s == %s || %s == GL_FRONT_AND_BACK) {\n" %
5198 (face
, ('GL_FRONT', 'GL_BACK')[group_ndx
], face
))
5199 for ndx
, item
in enumerate(group
):
5200 f
.write(" state_.%s = %s;\n" %
5201 (item
['name'], args
[ndx
+ 1].name
))
5203 if 'state_flag' in state
:
5204 f
.write(" %s = true;\n" % state
['state_flag'])
5205 if not func
.GetInfo("no_gl"):
5206 f
.write(" %s(%s);\n" %
5207 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
5211 class StateSetFrontBackHandler(TypeHandler
):
5212 """Handler for commands that simply set state that set both front/back."""
5214 def WriteHandlerImplementation(self
, func
, f
):
5215 """Overrriden from TypeHandler."""
5216 state_name
= func
.GetInfo('state')
5217 state
= _STATES
[state_name
]
5218 states
= state
['states']
5219 args
= func
.GetOriginalArgs()
5220 num_args
= len(args
)
5222 for group_ndx
, group
in enumerate(Grouper(num_args
, states
)):
5223 for ndx
, item
in enumerate(group
):
5224 code
.append("state_.%s != %s" % (item
['name'], args
[ndx
].name
))
5225 f
.write(" if (%s) {\n" % " ||\n ".join(code
))
5226 for group_ndx
, group
in enumerate(Grouper(num_args
, states
)):
5227 for ndx
, item
in enumerate(group
):
5228 f
.write(" state_.%s = %s;\n" % (item
['name'], args
[ndx
].name
))
5229 if 'state_flag' in state
:
5230 f
.write(" %s = true;\n" % state
['state_flag'])
5231 if not func
.GetInfo("no_gl"):
5232 f
.write(" %s(%s);\n" %
5233 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
5237 class StateSetNamedParameter(TypeHandler
):
5238 """Handler for commands that set a state chosen with an enum parameter."""
5240 def WriteHandlerImplementation(self
, func
, f
):
5241 """Overridden from TypeHandler."""
5242 state_name
= func
.GetInfo('state')
5243 state
= _STATES
[state_name
]
5244 states
= state
['states']
5245 args
= func
.GetOriginalArgs()
5246 num_args
= len(args
)
5247 assert num_args
== 2
5248 f
.write(" switch (%s) {\n" % args
[0].name
)
5249 for state
in states
:
5250 f
.write(" case %s:\n" % state
['enum'])
5251 f
.write(" if (state_.%s != %s) {\n" %
5252 (state
['name'], args
[1].name
))
5253 f
.write(" state_.%s = %s;\n" % (state
['name'], args
[1].name
))
5254 if not func
.GetInfo("no_gl"):
5255 f
.write(" %s(%s);\n" %
5256 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
5258 f
.write(" break;\n")
5259 f
.write(" default:\n")
5260 f
.write(" NOTREACHED();\n")
5264 class CustomHandler(TypeHandler
):
5265 """Handler for commands that are auto-generated but require minor tweaks."""
5267 def WriteServiceImplementation(self
, func
, f
):
5268 """Overrriden from TypeHandler."""
5271 def WriteImmediateServiceImplementation(self
, func
, f
):
5272 """Overrriden from TypeHandler."""
5275 def WriteBucketServiceImplementation(self
, func
, f
):
5276 """Overrriden from TypeHandler."""
5279 def WriteServiceUnitTest(self
, func
, f
, *extras
):
5280 """Overrriden from TypeHandler."""
5281 f
.write("// TODO(gman): %s\n\n" % func
.name
)
5283 def WriteImmediateServiceUnitTest(self
, func
, f
, *extras
):
5284 """Overrriden from TypeHandler."""
5285 f
.write("// TODO(gman): %s\n\n" % func
.name
)
5287 def WriteImmediateCmdGetTotalSize(self
, func
, f
):
5288 """Overrriden from TypeHandler."""
5290 " uint32_t total_size = 0; // TODO(gman): get correct size.\n")
5292 def WriteImmediateCmdInit(self
, func
, f
):
5293 """Overrriden from TypeHandler."""
5294 f
.write(" void Init(%s) {\n" % func
.MakeTypedCmdArgString("_"))
5295 self
.WriteImmediateCmdGetTotalSize(func
, f
)
5296 f
.write(" SetHeader(total_size);\n")
5297 args
= func
.GetCmdArgs()
5299 f
.write(" %s = _%s;\n" % (arg
.name
, arg
.name
))
5303 def WriteImmediateCmdSet(self
, func
, f
):
5304 """Overrriden from TypeHandler."""
5305 copy_args
= func
.MakeCmdArgString("_", False)
5306 f
.write(" void* Set(void* cmd%s) {\n" %
5307 func
.MakeTypedCmdArgString("_", True))
5308 self
.WriteImmediateCmdGetTotalSize(func
, f
)
5309 f
.write(" static_cast<ValueType*>(cmd)->Init(%s);\n" % copy_args
)
5310 f
.write(" return NextImmediateCmdAddressTotalSize<ValueType>("
5311 "cmd, total_size);\n")
5316 class HandWrittenHandler(CustomHandler
):
5317 """Handler for comands where everything must be written by hand."""
5319 def InitFunction(self
, func
):
5320 """Add or adjust anything type specific for this function."""
5321 CustomHandler
.InitFunction(self
, func
)
5322 func
.can_auto_generate
= False
5324 def NeedsDataTransferFunction(self
, func
):
5325 """Overriden from TypeHandler."""
5326 # If specified explicitly, force the data transfer method.
5327 if func
.GetInfo('data_transfer_methods'):
5331 def WriteStruct(self
, func
, f
):
5332 """Overrriden from TypeHandler."""
5335 def WriteDocs(self
, func
, f
):
5336 """Overrriden from TypeHandler."""
5339 def WriteServiceUnitTest(self
, func
, f
, *extras
):
5340 """Overrriden from TypeHandler."""
5341 f
.write("// TODO(gman): %s\n\n" % func
.name
)
5343 def WriteImmediateServiceUnitTest(self
, func
, f
, *extras
):
5344 """Overrriden from TypeHandler."""
5345 f
.write("// TODO(gman): %s\n\n" % func
.name
)
5347 def WriteBucketServiceUnitTest(self
, func
, f
, *extras
):
5348 """Overrriden from TypeHandler."""
5349 f
.write("// TODO(gman): %s\n\n" % func
.name
)
5351 def WriteServiceImplementation(self
, func
, f
):
5352 """Overrriden from TypeHandler."""
5355 def WriteImmediateServiceImplementation(self
, func
, f
):
5356 """Overrriden from TypeHandler."""
5359 def WriteBucketServiceImplementation(self
, func
, f
):
5360 """Overrriden from TypeHandler."""
5363 def WriteImmediateCmdHelper(self
, func
, f
):
5364 """Overrriden from TypeHandler."""
5367 def WriteCmdHelper(self
, func
, f
):
5368 """Overrriden from TypeHandler."""
5371 def WriteFormatTest(self
, func
, f
):
5372 """Overrriden from TypeHandler."""
5373 f
.write("// TODO(gman): Write test for %s\n" % func
.name
)
5375 def WriteImmediateFormatTest(self
, func
, f
):
5376 """Overrriden from TypeHandler."""
5377 f
.write("// TODO(gman): Write test for %s\n" % func
.name
)
5380 class ManualHandler(CustomHandler
):
5381 """Handler for commands who's handlers must be written by hand."""
5383 def InitFunction(self
, func
):
5384 """Overrriden from TypeHandler."""
5385 if (func
.name
== 'CompressedTexImage2DBucket' or
5386 func
.name
== 'CompressedTexImage3DBucket'):
5387 func
.cmd_args
= func
.cmd_args
[:-1]
5388 func
.AddCmdArg(Argument('bucket_id', 'GLuint'))
5390 CustomHandler
.InitFunction(self
, func
)
5392 def WriteServiceImplementation(self
, func
, f
):
5393 """Overrriden from TypeHandler."""
5396 def WriteBucketServiceImplementation(self
, func
, f
):
5397 """Overrriden from TypeHandler."""
5400 def WriteServiceUnitTest(self
, func
, f
, *extras
):
5401 """Overrriden from TypeHandler."""
5402 f
.write("// TODO(gman): %s\n\n" % func
.name
)
5404 def WriteImmediateServiceUnitTest(self
, func
, f
, *extras
):
5405 """Overrriden from TypeHandler."""
5406 f
.write("// TODO(gman): %s\n\n" % func
.name
)
5408 def WriteImmediateServiceImplementation(self
, func
, f
):
5409 """Overrriden from TypeHandler."""
5412 def WriteImmediateFormatTest(self
, func
, f
):
5413 """Overrriden from TypeHandler."""
5414 f
.write("// TODO(gman): Implement test for %s\n" % func
.name
)
5416 def WriteGLES2Implementation(self
, func
, f
):
5417 """Overrriden from TypeHandler."""
5418 if func
.GetInfo('impl_func'):
5419 super(ManualHandler
, self
).WriteGLES2Implementation(func
, f
)
5421 def WriteGLES2ImplementationHeader(self
, func
, f
):
5422 """Overrriden from TypeHandler."""
5423 f
.write("%s %s(%s) override;\n" %
5424 (func
.return_type
, func
.original_name
,
5425 func
.MakeTypedOriginalArgString("")))
5428 def WriteImmediateCmdGetTotalSize(self
, func
, f
):
5429 """Overrriden from TypeHandler."""
5430 # TODO(gman): Move this data to _FUNCTION_INFO?
5431 CustomHandler
.WriteImmediateCmdGetTotalSize(self
, func
, f
)
5434 class DataHandler(TypeHandler
):
5435 """Handler for glBufferData, glBufferSubData, glTexImage*D, glTexSubImage*D,
5436 glCompressedTexImage*D, glCompressedTexImageSub*D."""
5438 def InitFunction(self
, func
):
5439 """Overrriden from TypeHandler."""
5440 if (func
.name
== 'CompressedTexSubImage2DBucket' or
5441 func
.name
== 'CompressedTexSubImage3DBucket'):
5442 func
.cmd_args
= func
.cmd_args
[:-1]
5443 func
.AddCmdArg(Argument('bucket_id', 'GLuint'))
5445 def WriteGetDataSizeCode(self
, func
, f
):
5446 """Overrriden from TypeHandler."""
5447 # TODO(gman): Move this data to _FUNCTION_INFO?
5449 if name
.endswith("Immediate"):
5451 if name
== 'BufferData' or name
== 'BufferSubData':
5452 f
.write(" uint32_t data_size = size;\n")
5453 elif (name
== 'CompressedTexImage2D' or
5454 name
== 'CompressedTexSubImage2D' or
5455 name
== 'CompressedTexImage3D' or
5456 name
== 'CompressedTexSubImage3D'):
5457 f
.write(" uint32_t data_size = imageSize;\n")
5458 elif (name
== 'CompressedTexSubImage2DBucket' or
5459 name
== 'CompressedTexSubImage3DBucket'):
5460 f
.write(" Bucket* bucket = GetBucket(c.bucket_id);\n")
5461 f
.write(" uint32_t data_size = bucket->size();\n")
5462 f
.write(" GLsizei imageSize = data_size;\n")
5463 elif name
== 'TexImage2D' or name
== 'TexSubImage2D':
5464 code
= """ uint32_t data_size;
5465 if (!GLES2Util::ComputeImageDataSize(
5466 width, height, format, type, unpack_alignment_, &data_size)) {
5467 return error::kOutOfBounds;
5473 "// uint32_t data_size = 0; // TODO(gman): get correct size!\n")
5475 def WriteImmediateCmdGetTotalSize(self
, func
, f
):
5476 """Overrriden from TypeHandler."""
5479 def WriteImmediateCmdInit(self
, func
, f
):
5480 """Overrriden from TypeHandler."""
5481 f
.write(" void Init(%s) {\n" % func
.MakeTypedCmdArgString("_"))
5482 self
.WriteImmediateCmdGetTotalSize(func
, f
)
5483 f
.write(" SetHeader(total_size);\n")
5484 args
= func
.GetCmdArgs()
5486 f
.write(" %s = _%s;\n" % (arg
.name
, arg
.name
))
5490 def WriteImmediateCmdSet(self
, func
, f
):
5491 """Overrriden from TypeHandler."""
5492 copy_args
= func
.MakeCmdArgString("_", False)
5493 f
.write(" void* Set(void* cmd%s) {\n" %
5494 func
.MakeTypedCmdArgString("_", True))
5495 self
.WriteImmediateCmdGetTotalSize(func
, f
)
5496 f
.write(" static_cast<ValueType*>(cmd)->Init(%s);\n" % copy_args
)
5497 f
.write(" return NextImmediateCmdAddressTotalSize<ValueType>("
5498 "cmd, total_size);\n")
5502 def WriteImmediateFormatTest(self
, func
, f
):
5503 """Overrriden from TypeHandler."""
5504 # TODO(gman): Remove this exception.
5505 f
.write("// TODO(gman): Implement test for %s\n" % func
.name
)
5508 def WriteServiceUnitTest(self
, func
, f
, *extras
):
5509 """Overrriden from TypeHandler."""
5510 f
.write("// TODO(gman): %s\n\n" % func
.name
)
5512 def WriteImmediateServiceUnitTest(self
, func
, f
, *extras
):
5513 """Overrriden from TypeHandler."""
5514 f
.write("// TODO(gman): %s\n\n" % func
.name
)
5516 def WriteBucketServiceImplementation(self
, func
, f
):
5517 """Overrriden from TypeHandler."""
5518 if ((not func
.name
== 'CompressedTexSubImage2DBucket') and
5519 (not func
.name
== 'CompressedTexSubImage3DBucket')):
5520 TypeHandler
.WriteBucketServiceImplemenation(self
, func
, f
)
5523 class BindHandler(TypeHandler
):
5524 """Handler for glBind___ type functions."""
5526 def WriteServiceUnitTest(self
, func
, f
, *extras
):
5527 """Overrriden from TypeHandler."""
5529 if len(func
.GetOriginalArgs()) == 1:
5531 TEST_P(%(test_name)s, %(name)sValidArgs) {
5532 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
5533 SpecializedSetup<cmds::%(name)s, 0>(true);
5535 cmd.Init(%(args)s);"""
5538 decoder_->set_unsafe_es3_apis_enabled(true);
5539 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5540 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5541 decoder_->set_unsafe_es3_apis_enabled(false);
5542 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));
5547 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5548 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5551 if func
.GetInfo("gen_func"):
5553 TEST_P(%(test_name)s, %(name)sValidArgsNewId) {
5554 EXPECT_CALL(*gl_, %(gl_func_name)s(kNewServiceId));
5555 EXPECT_CALL(*gl_, %(gl_gen_func_name)s(1, _))
5556 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
5557 SpecializedSetup<cmds::%(name)s, 0>(true);
5559 cmd.Init(kNewClientId);
5560 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5561 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5562 EXPECT_TRUE(Get%(resource_type)s(kNewClientId) != NULL);
5565 self
.WriteValidUnitTest(func
, f
, valid_test
, {
5566 'resource_type': func
.GetOriginalArgs()[0].resource_type
,
5567 'gl_gen_func_name': func
.GetInfo("gen_func"),
5571 TEST_P(%(test_name)s, %(name)sValidArgs) {
5572 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
5573 SpecializedSetup<cmds::%(name)s, 0>(true);
5575 cmd.Init(%(args)s);"""
5578 decoder_->set_unsafe_es3_apis_enabled(true);
5579 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5580 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5581 decoder_->set_unsafe_es3_apis_enabled(false);
5582 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));
5587 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5588 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5591 if func
.GetInfo("gen_func"):
5593 TEST_P(%(test_name)s, %(name)sValidArgsNewId) {
5595 %(gl_func_name)s(%(gl_args_with_new_id)s));
5596 EXPECT_CALL(*gl_, %(gl_gen_func_name)s(1, _))
5597 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
5598 SpecializedSetup<cmds::%(name)s, 0>(true);
5600 cmd.Init(%(args_with_new_id)s);"""
5603 decoder_->set_unsafe_es3_apis_enabled(true);
5604 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5605 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5606 EXPECT_TRUE(Get%(resource_type)s(kNewClientId) != NULL);
5607 decoder_->set_unsafe_es3_apis_enabled(false);
5608 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));
5613 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5614 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5615 EXPECT_TRUE(Get%(resource_type)s(kNewClientId) != NULL);
5619 gl_args_with_new_id
= []
5620 args_with_new_id
= []
5621 for arg
in func
.GetOriginalArgs():
5622 if hasattr(arg
, 'resource_type'):
5623 gl_args_with_new_id
.append('kNewServiceId')
5624 args_with_new_id
.append('kNewClientId')
5626 gl_args_with_new_id
.append(arg
.GetValidGLArg(func
))
5627 args_with_new_id
.append(arg
.GetValidArg(func
))
5628 self
.WriteValidUnitTest(func
, f
, valid_test
, {
5629 'args_with_new_id': ", ".join(args_with_new_id
),
5630 'gl_args_with_new_id': ", ".join(gl_args_with_new_id
),
5631 'resource_type': func
.GetResourceIdArg().resource_type
,
5632 'gl_gen_func_name': func
.GetInfo("gen_func"),
5636 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
5637 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
5638 SpecializedSetup<cmds::%(name)s, 0>(false);
5641 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
5644 self
.WriteInvalidUnitTest(func
, f
, invalid_test
, *extras
)
5646 def WriteGLES2Implementation(self
, func
, f
):
5647 """Writes the GLES2 Implemention."""
5649 impl_func
= func
.GetInfo('impl_func')
5650 impl_decl
= func
.GetInfo('impl_decl')
5652 if (func
.can_auto_generate
and
5653 (impl_func
== None or impl_func
== True) and
5654 (impl_decl
== None or impl_decl
== True)):
5656 f
.write("%s GLES2Implementation::%s(%s) {\n" %
5657 (func
.return_type
, func
.original_name
,
5658 func
.MakeTypedOriginalArgString("")))
5659 f
.write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
5660 func
.WriteDestinationInitalizationValidation(f
)
5661 self
.WriteClientGLCallLog(func
, f
)
5662 for arg
in func
.GetOriginalArgs():
5663 arg
.WriteClientSideValidationCode(f
, func
)
5665 code
= """ if (Is%(type)sReservedId(%(id)s)) {
5666 SetGLError(GL_INVALID_OPERATION, "%(name)s\", \"%(id)s reserved id");
5669 %(name)sHelper(%(arg_string)s);
5674 name_arg
= func
.GetResourceIdArg()
5677 'arg_string': func
.MakeOriginalArgString(""),
5678 'id': name_arg
.name
,
5679 'type': name_arg
.resource_type
,
5680 'lc_type': name_arg
.resource_type
.lower(),
5683 def WriteGLES2ImplementationUnitTest(self
, func
, f
):
5684 """Overrriden from TypeHandler."""
5685 client_test
= func
.GetInfo('client_test')
5686 if client_test
== False:
5689 TEST_F(GLES2ImplementationTest, %(name)s) {
5694 expected.cmd.Init(%(cmd_args)s);
5696 gl_->%(name)s(%(args)s);
5697 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));"""
5698 if not func
.IsUnsafe():
5701 gl_->%(name)s(%(args)s);
5702 EXPECT_TRUE(NoCommandsWritten());"""
5707 arg
.GetValidClientSideCmdArg(func
) for arg
in func
.GetCmdArgs()
5710 arg
.GetValidClientSideArg(func
) for arg
in func
.GetOriginalArgs()
5715 'args': ", ".join(gl_arg_strings
),
5716 'cmd_args': ", ".join(cmd_arg_strings
),
5720 class GENnHandler(TypeHandler
):
5721 """Handler for glGen___ type functions."""
5723 def InitFunction(self
, func
):
5724 """Overrriden from TypeHandler."""
5727 def WriteGetDataSizeCode(self
, func
, f
):
5728 """Overrriden from TypeHandler."""
5729 code
= """ uint32_t data_size;
5730 if (!SafeMultiplyUint32(n, sizeof(GLuint), &data_size)) {
5731 return error::kOutOfBounds;
5736 def WriteHandlerImplementation (self
, func
, f
):
5737 """Overrriden from TypeHandler."""
5738 f
.write(" if (!%sHelper(n, %s)) {\n"
5739 " return error::kInvalidArguments;\n"
5741 (func
.name
, func
.GetLastOriginalArg().name
))
5743 def WriteImmediateHandlerImplementation(self
, func
, f
):
5744 """Overrriden from TypeHandler."""
5746 f
.write(""" for (GLsizei ii = 0; ii < n; ++ii) {
5747 if (group_->Get%(resource_name)sServiceId(%(last_arg_name)s[ii], NULL)) {
5748 return error::kInvalidArguments;
5751 scoped_ptr<GLuint[]> service_ids(new GLuint[n]);
5752 gl%(func_name)s(n, service_ids.get());
5753 for (GLsizei ii = 0; ii < n; ++ii) {
5754 group_->Add%(resource_name)sId(%(last_arg_name)s[ii], service_ids[ii]);
5756 """ % { 'func_name': func
.original_name
,
5757 'last_arg_name': func
.GetLastOriginalArg().name
,
5758 'resource_name': func
.GetInfo('resource_type') })
5760 f
.write(" if (!%sHelper(n, %s)) {\n"
5761 " return error::kInvalidArguments;\n"
5763 (func
.original_name
, func
.GetLastOriginalArg().name
))
5765 def WriteGLES2Implementation(self
, func
, f
):
5766 """Overrriden from TypeHandler."""
5767 log_code
= (""" GPU_CLIENT_LOG_CODE_BLOCK({
5768 for (GLsizei i = 0; i < n; ++i) {
5769 GPU_CLIENT_LOG(" " << i << ": " << %s[i]);
5771 });""" % func
.GetOriginalArgs()[1].name
)
5773 'log_code': log_code
,
5774 'return_type': func
.return_type
,
5775 'name': func
.original_name
,
5776 'typed_args': func
.MakeTypedOriginalArgString(""),
5777 'args': func
.MakeOriginalArgString(""),
5778 'resource_types': func
.GetInfo('resource_types'),
5779 'count_name': func
.GetOriginalArgs()[0].name
,
5782 "%(return_type)s GLES2Implementation::%(name)s(%(typed_args)s) {\n" %
5784 func
.WriteDestinationInitalizationValidation(f
)
5785 self
.WriteClientGLCallLog(func
, f
)
5786 for arg
in func
.GetOriginalArgs():
5787 arg
.WriteClientSideValidationCode(f
, func
)
5788 not_shared
= func
.GetInfo('not_shared')
5792 """ IdAllocator* id_allocator = GetIdAllocator(id_namespaces::k%s);
5793 for (GLsizei ii = 0; ii < n; ++ii)
5794 %s[ii] = id_allocator->AllocateID();""" %
5795 (func
.GetInfo('resource_types'), func
.GetOriginalArgs()[1].name
))
5797 alloc_code
= (""" GetIdHandler(id_namespaces::k%(resource_types)s)->
5798 MakeIds(this, 0, %(args)s);""" % args
)
5799 args
['alloc_code'] = alloc_code
5801 code
= """ GPU_CLIENT_SINGLE_THREAD_CHECK();
5803 %(name)sHelper(%(args)s);
5804 helper_->%(name)sImmediate(%(args)s);
5805 if (share_group_->bind_generates_resource())
5806 helper_->CommandBufferHelper::Flush();
5812 f
.write(code
% args
)
5814 def WriteGLES2ImplementationUnitTest(self
, func
, f
):
5815 """Overrriden from TypeHandler."""
5817 TEST_F(GLES2ImplementationTest, %(name)s) {
5818 GLuint ids[2] = { 0, };
5820 cmds::%(name)sImmediate gen;
5824 expected.gen.Init(arraysize(ids), &ids[0]);
5825 expected.data[0] = k%(types)sStartId;
5826 expected.data[1] = k%(types)sStartId + 1;
5827 gl_->%(name)s(arraysize(ids), &ids[0]);
5828 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
5829 EXPECT_EQ(k%(types)sStartId, ids[0]);
5830 EXPECT_EQ(k%(types)sStartId + 1, ids[1]);
5835 'types': func
.GetInfo('resource_types'),
5838 def WriteServiceUnitTest(self
, func
, f
, *extras
):
5839 """Overrriden from TypeHandler."""
5841 TEST_P(%(test_name)s, %(name)sValidArgs) {
5842 EXPECT_CALL(*gl_, %(gl_func_name)s(1, _))
5843 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
5844 GetSharedMemoryAs<GLuint*>()[0] = kNewClientId;
5845 SpecializedSetup<cmds::%(name)s, 0>(true);
5848 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5849 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
5853 EXPECT_TRUE(Get%(resource_name)sServiceId(kNewClientId, &service_id));
5854 EXPECT_EQ(kNewServiceId, service_id)
5859 EXPECT_TRUE(Get%(resource_name)s(kNewClientId, &service_id) != NULL);
5862 self
.WriteValidUnitTest(func
, f
, valid_test
, {
5863 'resource_name': func
.GetInfo('resource_type'),
5866 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
5867 EXPECT_CALL(*gl_, %(gl_func_name)s(_, _)).Times(0);
5868 GetSharedMemoryAs<GLuint*>()[0] = client_%(resource_name)s_id_;
5869 SpecializedSetup<cmds::%(name)s, 0>(false);
5872 EXPECT_EQ(error::kInvalidArguments, ExecuteCmd(cmd));
5875 self
.WriteValidUnitTest(func
, f
, invalid_test
, {
5876 'resource_name': func
.GetInfo('resource_type').lower(),
5879 def WriteImmediateServiceUnitTest(self
, func
, f
, *extras
):
5880 """Overrriden from TypeHandler."""
5882 TEST_P(%(test_name)s, %(name)sValidArgs) {
5883 EXPECT_CALL(*gl_, %(gl_func_name)s(1, _))
5884 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
5885 cmds::%(name)s* cmd = GetImmediateAs<cmds::%(name)s>();
5886 GLuint temp = kNewClientId;
5887 SpecializedSetup<cmds::%(name)s, 0>(true);"""
5890 decoder_->set_unsafe_es3_apis_enabled(true);"""
5892 cmd->Init(1, &temp);
5893 EXPECT_EQ(error::kNoError,
5894 ExecuteImmediateCmd(*cmd, sizeof(temp)));
5895 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
5899 EXPECT_TRUE(Get%(resource_name)sServiceId(kNewClientId, &service_id));
5900 EXPECT_EQ(kNewServiceId, service_id);
5901 decoder_->set_unsafe_es3_apis_enabled(false);
5902 EXPECT_EQ(error::kUnknownCommand,
5903 ExecuteImmediateCmd(*cmd, sizeof(temp)));
5908 EXPECT_TRUE(Get%(resource_name)s(kNewClientId) != NULL);
5911 self
.WriteValidUnitTest(func
, f
, valid_test
, {
5912 'resource_name': func
.GetInfo('resource_type'),
5915 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
5916 EXPECT_CALL(*gl_, %(gl_func_name)s(_, _)).Times(0);
5917 cmds::%(name)s* cmd = GetImmediateAs<cmds::%(name)s>();
5918 SpecializedSetup<cmds::%(name)s, 0>(false);
5919 cmd->Init(1, &client_%(resource_name)s_id_);"""
5922 decoder_->set_unsafe_es3_apis_enabled(true);
5923 EXPECT_EQ(error::kInvalidArguments,
5924 ExecuteImmediateCmd(*cmd, sizeof(&client_%(resource_name)s_id_)));
5925 decoder_->set_unsafe_es3_apis_enabled(false);
5930 EXPECT_EQ(error::kInvalidArguments,
5931 ExecuteImmediateCmd(*cmd, sizeof(&client_%(resource_name)s_id_)));
5934 self
.WriteValidUnitTest(func
, f
, invalid_test
, {
5935 'resource_name': func
.GetInfo('resource_type').lower(),
5938 def WriteImmediateCmdComputeSize(self
, func
, f
):
5939 """Overrriden from TypeHandler."""
5940 f
.write(" static uint32_t ComputeDataSize(GLsizei n) {\n")
5942 " return static_cast<uint32_t>(sizeof(GLuint) * n); // NOLINT\n")
5945 f
.write(" static uint32_t ComputeSize(GLsizei n) {\n")
5946 f
.write(" return static_cast<uint32_t>(\n")
5947 f
.write(" sizeof(ValueType) + ComputeDataSize(n)); // NOLINT\n")
5951 def WriteImmediateCmdSetHeader(self
, func
, f
):
5952 """Overrriden from TypeHandler."""
5953 f
.write(" void SetHeader(GLsizei n) {\n")
5954 f
.write(" header.SetCmdByTotalSize<ValueType>(ComputeSize(n));\n")
5958 def WriteImmediateCmdInit(self
, func
, f
):
5959 """Overrriden from TypeHandler."""
5960 last_arg
= func
.GetLastOriginalArg()
5961 f
.write(" void Init(%s, %s _%s) {\n" %
5962 (func
.MakeTypedCmdArgString("_"),
5963 last_arg
.type, last_arg
.name
))
5964 f
.write(" SetHeader(_n);\n")
5965 args
= func
.GetCmdArgs()
5967 f
.write(" %s = _%s;\n" % (arg
.name
, arg
.name
))
5968 f
.write(" memcpy(ImmediateDataAddress(this),\n")
5969 f
.write(" _%s, ComputeDataSize(_n));\n" % last_arg
.name
)
5973 def WriteImmediateCmdSet(self
, func
, f
):
5974 """Overrriden from TypeHandler."""
5975 last_arg
= func
.GetLastOriginalArg()
5976 copy_args
= func
.MakeCmdArgString("_", False)
5977 f
.write(" void* Set(void* cmd%s, %s _%s) {\n" %
5978 (func
.MakeTypedCmdArgString("_", True),
5979 last_arg
.type, last_arg
.name
))
5980 f
.write(" static_cast<ValueType*>(cmd)->Init(%s, _%s);\n" %
5981 (copy_args
, last_arg
.name
))
5982 f
.write(" const uint32_t size = ComputeSize(_n);\n")
5983 f
.write(" return NextImmediateCmdAddressTotalSize<ValueType>("
5988 def WriteImmediateCmdHelper(self
, func
, f
):
5989 """Overrriden from TypeHandler."""
5990 code
= """ void %(name)s(%(typed_args)s) {
5991 const uint32_t size = gles2::cmds::%(name)s::ComputeSize(n);
5992 gles2::cmds::%(name)s* c =
5993 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
6002 "typed_args": func
.MakeTypedOriginalArgString(""),
6003 "args": func
.MakeOriginalArgString(""),
6006 def WriteImmediateFormatTest(self
, func
, f
):
6007 """Overrriden from TypeHandler."""
6008 f
.write("TEST_F(GLES2FormatTest, %s) {\n" % func
.name
)
6009 f
.write(" static GLuint ids[] = { 12, 23, 34, };\n")
6010 f
.write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
6011 (func
.name
, func
.name
))
6012 f
.write(" void* next_cmd = cmd.Set(\n")
6013 f
.write(" &cmd, static_cast<GLsizei>(arraysize(ids)), ids);\n")
6014 f
.write(" EXPECT_EQ(static_cast<uint32_t>(cmds::%s::kCmdId),\n" %
6016 f
.write(" cmd.header.command);\n")
6017 f
.write(" EXPECT_EQ(sizeof(cmd) +\n")
6018 f
.write(" RoundSizeToMultipleOfEntries(cmd.n * 4u),\n")
6019 f
.write(" cmd.header.size * 4u);\n")
6020 f
.write(" EXPECT_EQ(static_cast<GLsizei>(arraysize(ids)), cmd.n);\n");
6021 f
.write(" CheckBytesWrittenMatchesExpectedSize(\n")
6022 f
.write(" next_cmd, sizeof(cmd) +\n")
6023 f
.write(" RoundSizeToMultipleOfEntries(arraysize(ids) * 4u));\n")
6024 f
.write(" // TODO(gman): Check that ids were inserted;\n")
6029 class CreateHandler(TypeHandler
):
6030 """Handler for glCreate___ type functions."""
6032 def InitFunction(self
, func
):
6033 """Overrriden from TypeHandler."""
6034 func
.AddCmdArg(Argument("client_id", 'uint32_t'))
6036 def __GetResourceType(self
, func
):
6037 if func
.return_type
== "GLsync":
6040 return func
.name
[6:] # Create*
6042 def WriteServiceUnitTest(self
, func
, f
, *extras
):
6043 """Overrriden from TypeHandler."""
6045 TEST_P(%(test_name)s, %(name)sValidArgs) {
6046 %(id_type_cast)sEXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s))
6047 .WillOnce(Return(%(const_service_id)s));
6048 SpecializedSetup<cmds::%(name)s, 0>(true);
6050 cmd.Init(%(args)s%(comma)skNewClientId);"""
6053 decoder_->set_unsafe_es3_apis_enabled(true);"""
6055 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
6056 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
6059 %(return_type)s service_id = 0;
6060 EXPECT_TRUE(Get%(resource_type)sServiceId(kNewClientId, &service_id));
6061 EXPECT_EQ(%(const_service_id)s, service_id);
6062 decoder_->set_unsafe_es3_apis_enabled(false);
6063 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));
6068 EXPECT_TRUE(Get%(resource_type)s(kNewClientId));
6073 for arg
in func
.GetOriginalArgs():
6074 if not arg
.IsConstant():
6078 if func
.return_type
== 'GLsync':
6079 id_type_cast
= ("const GLsync kNewServiceIdGLuint = reinterpret_cast"
6080 "<GLsync>(kNewServiceId);\n ")
6081 const_service_id
= "kNewServiceIdGLuint"
6084 const_service_id
= "kNewServiceId"
6085 self
.WriteValidUnitTest(func
, f
, valid_test
, {
6087 'resource_type': self
.__GetResourceType
(func
),
6088 'return_type': func
.return_type
,
6089 'id_type_cast': id_type_cast
,
6090 'const_service_id': const_service_id
,
6093 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
6094 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
6095 SpecializedSetup<cmds::%(name)s, 0>(false);
6097 cmd.Init(%(args)s%(comma)skNewClientId);
6098 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));%(gl_error_test)s
6101 self
.WriteInvalidUnitTest(func
, f
, invalid_test
, {
6105 def WriteHandlerImplementation (self
, func
, f
):
6106 """Overrriden from TypeHandler."""
6108 code
= """ uint32_t client_id = c.client_id;
6109 %(return_type)s service_id = 0;
6110 if (group_->Get%(resource_name)sServiceId(client_id, &service_id)) {
6111 return error::kInvalidArguments;
6113 service_id = %(gl_func_name)s(%(gl_args)s);
6115 group_->Add%(resource_name)sId(client_id, service_id);
6119 code
= """ uint32_t client_id = c.client_id;
6120 if (Get%(resource_name)s(client_id)) {
6121 return error::kInvalidArguments;
6123 %(return_type)s service_id = %(gl_func_name)s(%(gl_args)s);
6125 Create%(resource_name)s(client_id, service_id%(gl_args_with_comma)s);
6129 'resource_name': self
.__GetResourceType
(func
),
6130 'return_type': func
.return_type
,
6131 'gl_func_name': func
.GetGLFunctionName(),
6132 'gl_args': func
.MakeOriginalArgString(""),
6133 'gl_args_with_comma': func
.MakeOriginalArgString("", True) })
6135 def WriteGLES2Implementation(self
, func
, f
):
6136 """Overrriden from TypeHandler."""
6137 f
.write("%s GLES2Implementation::%s(%s) {\n" %
6138 (func
.return_type
, func
.original_name
,
6139 func
.MakeTypedOriginalArgString("")))
6140 f
.write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
6141 func
.WriteDestinationInitalizationValidation(f
)
6142 self
.WriteClientGLCallLog(func
, f
)
6143 for arg
in func
.GetOriginalArgs():
6144 arg
.WriteClientSideValidationCode(f
, func
)
6145 f
.write(" GLuint client_id;\n")
6146 if func
.return_type
== "GLsync":
6148 " GetIdHandler(id_namespaces::kSyncs)->\n")
6151 " GetIdHandler(id_namespaces::kProgramsAndShaders)->\n")
6152 f
.write(" MakeIds(this, 0, 1, &client_id);\n")
6153 f
.write(" helper_->%s(%s);\n" %
6154 (func
.name
, func
.MakeCmdArgString("")))
6155 f
.write(' GPU_CLIENT_LOG("returned " << client_id);\n')
6156 f
.write(" CheckGLError();\n")
6157 if func
.return_type
== "GLsync":
6158 f
.write(" return reinterpret_cast<GLsync>(client_id);\n")
6160 f
.write(" return client_id;\n")
6165 class DeleteHandler(TypeHandler
):
6166 """Handler for glDelete___ single resource type functions."""
6168 def WriteServiceImplementation(self
, func
, f
):
6169 """Overrriden from TypeHandler."""
6171 TypeHandler
.WriteServiceImplementation(self
, func
, f
)
6172 # HandleDeleteShader and HandleDeleteProgram are manually written.
6175 def WriteGLES2Implementation(self
, func
, f
):
6176 """Overrriden from TypeHandler."""
6177 f
.write("%s GLES2Implementation::%s(%s) {\n" %
6178 (func
.return_type
, func
.original_name
,
6179 func
.MakeTypedOriginalArgString("")))
6180 f
.write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
6181 func
.WriteDestinationInitalizationValidation(f
)
6182 self
.WriteClientGLCallLog(func
, f
)
6183 for arg
in func
.GetOriginalArgs():
6184 arg
.WriteClientSideValidationCode(f
, func
)
6186 " GPU_CLIENT_DCHECK(%s != 0);\n" % func
.GetOriginalArgs()[-1].name
)
6187 f
.write(" %sHelper(%s);\n" %
6188 (func
.original_name
, func
.GetOriginalArgs()[-1].name
))
6189 f
.write(" CheckGLError();\n")
6193 def WriteHandlerImplementation (self
, func
, f
):
6194 """Overrriden from TypeHandler."""
6195 assert len(func
.GetOriginalArgs()) == 1
6196 arg
= func
.GetOriginalArgs()[0]
6198 f
.write(""" %(arg_type)s service_id = 0;
6199 if (group_->Get%(resource_type)sServiceId(%(arg_name)s, &service_id)) {
6200 glDelete%(resource_type)s(service_id);
6201 group_->Remove%(resource_type)sId(%(arg_name)s);
6204 GL_INVALID_VALUE, "gl%(func_name)s", "unknown %(arg_name)s");
6206 """ % { 'resource_type': func
.GetInfo('resource_type'),
6207 'arg_name': arg
.name
,
6208 'arg_type': arg
.type,
6209 'func_name': func
.original_name
})
6211 f
.write(" %sHelper(%s);\n" % (func
.original_name
, arg
.name
))
6213 class DELnHandler(TypeHandler
):
6214 """Handler for glDelete___ type functions."""
6216 def WriteGetDataSizeCode(self
, func
, f
):
6217 """Overrriden from TypeHandler."""
6218 code
= """ uint32_t data_size;
6219 if (!SafeMultiplyUint32(n, sizeof(GLuint), &data_size)) {
6220 return error::kOutOfBounds;
6225 def WriteGLES2ImplementationUnitTest(self
, func
, f
):
6226 """Overrriden from TypeHandler."""
6228 TEST_F(GLES2ImplementationTest, %(name)s) {
6229 GLuint ids[2] = { k%(types)sStartId, k%(types)sStartId + 1 };
6231 cmds::%(name)sImmediate del;
6235 expected.del.Init(arraysize(ids), &ids[0]);
6236 expected.data[0] = k%(types)sStartId;
6237 expected.data[1] = k%(types)sStartId + 1;
6238 gl_->%(name)s(arraysize(ids), &ids[0]);
6239 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
6244 'types': func
.GetInfo('resource_types'),
6247 def WriteServiceUnitTest(self
, func
, f
, *extras
):
6248 """Overrriden from TypeHandler."""
6250 TEST_P(%(test_name)s, %(name)sValidArgs) {
6253 %(gl_func_name)s(1, Pointee(kService%(upper_resource_name)sId)))
6255 GetSharedMemoryAs<GLuint*>()[0] = client_%(resource_name)s_id_;
6256 SpecializedSetup<cmds::%(name)s, 0>(true);
6259 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
6260 EXPECT_EQ(GL_NO_ERROR, GetGLError());
6262 Get%(upper_resource_name)s(client_%(resource_name)s_id_) == NULL);
6265 self
.WriteValidUnitTest(func
, f
, valid_test
, {
6266 'resource_name': func
.GetInfo('resource_type').lower(),
6267 'upper_resource_name': func
.GetInfo('resource_type'),
6270 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
6271 GetSharedMemoryAs<GLuint*>()[0] = kInvalidClientId;
6272 SpecializedSetup<cmds::%(name)s, 0>(false);
6275 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
6278 self
.WriteValidUnitTest(func
, f
, invalid_test
, *extras
)
6280 def WriteImmediateServiceUnitTest(self
, func
, f
, *extras
):
6281 """Overrriden from TypeHandler."""
6283 TEST_P(%(test_name)s, %(name)sValidArgs) {
6286 %(gl_func_name)s(1, Pointee(kService%(upper_resource_name)sId)))
6288 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
6289 SpecializedSetup<cmds::%(name)s, 0>(true);
6290 cmd.Init(1, &client_%(resource_name)s_id_);"""
6293 decoder_->set_unsafe_es3_apis_enabled(true);"""
6295 EXPECT_EQ(error::kNoError,
6296 ExecuteImmediateCmd(cmd, sizeof(client_%(resource_name)s_id_)));
6297 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
6300 EXPECT_FALSE(Get%(upper_resource_name)sServiceId(
6301 client_%(resource_name)s_id_, NULL));
6302 decoder_->set_unsafe_es3_apis_enabled(false);
6303 EXPECT_EQ(error::kUnknownCommand,
6304 ExecuteImmediateCmd(cmd, sizeof(client_%(resource_name)s_id_)));
6310 Get%(upper_resource_name)s(client_%(resource_name)s_id_) == NULL);
6313 self
.WriteValidUnitTest(func
, f
, valid_test
, {
6314 'resource_name': func
.GetInfo('resource_type').lower(),
6315 'upper_resource_name': func
.GetInfo('resource_type'),
6318 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
6319 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
6320 SpecializedSetup<cmds::%(name)s, 0>(false);
6321 GLuint temp = kInvalidClientId;
6322 cmd.Init(1, &temp);"""
6325 decoder_->set_unsafe_es3_apis_enabled(true);
6326 EXPECT_EQ(error::kNoError,
6327 ExecuteImmediateCmd(cmd, sizeof(temp)));
6328 decoder_->set_unsafe_es3_apis_enabled(false);
6329 EXPECT_EQ(error::kUnknownCommand,
6330 ExecuteImmediateCmd(cmd, sizeof(temp)));
6335 EXPECT_EQ(error::kNoError,
6336 ExecuteImmediateCmd(cmd, sizeof(temp)));
6339 self
.WriteValidUnitTest(func
, f
, invalid_test
, *extras
)
6341 def WriteHandlerImplementation (self
, func
, f
):
6342 """Overrriden from TypeHandler."""
6343 f
.write(" %sHelper(n, %s);\n" %
6344 (func
.name
, func
.GetLastOriginalArg().name
))
6346 def WriteImmediateHandlerImplementation (self
, func
, f
):
6347 """Overrriden from TypeHandler."""
6349 f
.write(""" for (GLsizei ii = 0; ii < n; ++ii) {
6350 GLuint service_id = 0;
6351 if (group_->Get%(resource_type)sServiceId(
6352 %(last_arg_name)s[ii], &service_id)) {
6353 glDelete%(resource_type)ss(1, &service_id);
6354 group_->Remove%(resource_type)sId(%(last_arg_name)s[ii]);
6357 """ % { 'resource_type': func
.GetInfo('resource_type'),
6358 'last_arg_name': func
.GetLastOriginalArg().name
})
6360 f
.write(" %sHelper(n, %s);\n" %
6361 (func
.original_name
, func
.GetLastOriginalArg().name
))
6363 def WriteGLES2Implementation(self
, func
, f
):
6364 """Overrriden from TypeHandler."""
6365 impl_decl
= func
.GetInfo('impl_decl')
6366 if impl_decl
== None or impl_decl
== True:
6368 'return_type': func
.return_type
,
6369 'name': func
.original_name
,
6370 'typed_args': func
.MakeTypedOriginalArgString(""),
6371 'args': func
.MakeOriginalArgString(""),
6372 'resource_type': func
.GetInfo('resource_type').lower(),
6373 'count_name': func
.GetOriginalArgs()[0].name
,
6376 "%(return_type)s GLES2Implementation::%(name)s(%(typed_args)s) {\n" %
6378 f
.write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
6379 func
.WriteDestinationInitalizationValidation(f
)
6380 self
.WriteClientGLCallLog(func
, f
)
6381 f
.write(""" GPU_CLIENT_LOG_CODE_BLOCK({
6382 for (GLsizei i = 0; i < n; ++i) {
6383 GPU_CLIENT_LOG(" " << i << ": " << %s[i]);
6386 """ % func
.GetOriginalArgs()[1].name
)
6387 f
.write(""" GPU_CLIENT_DCHECK_CODE_BLOCK({
6388 for (GLsizei i = 0; i < n; ++i) {
6392 """ % func
.GetOriginalArgs()[1].name
)
6393 for arg
in func
.GetOriginalArgs():
6394 arg
.WriteClientSideValidationCode(f
, func
)
6395 code
= """ %(name)sHelper(%(args)s);
6400 f
.write(code
% args
)
6402 def WriteImmediateCmdComputeSize(self
, func
, f
):
6403 """Overrriden from TypeHandler."""
6404 f
.write(" static uint32_t ComputeDataSize(GLsizei n) {\n")
6406 " return static_cast<uint32_t>(sizeof(GLuint) * n); // NOLINT\n")
6409 f
.write(" static uint32_t ComputeSize(GLsizei n) {\n")
6410 f
.write(" return static_cast<uint32_t>(\n")
6411 f
.write(" sizeof(ValueType) + ComputeDataSize(n)); // NOLINT\n")
6415 def WriteImmediateCmdSetHeader(self
, func
, f
):
6416 """Overrriden from TypeHandler."""
6417 f
.write(" void SetHeader(GLsizei n) {\n")
6418 f
.write(" header.SetCmdByTotalSize<ValueType>(ComputeSize(n));\n")
6422 def WriteImmediateCmdInit(self
, func
, f
):
6423 """Overrriden from TypeHandler."""
6424 last_arg
= func
.GetLastOriginalArg()
6425 f
.write(" void Init(%s, %s _%s) {\n" %
6426 (func
.MakeTypedCmdArgString("_"),
6427 last_arg
.type, last_arg
.name
))
6428 f
.write(" SetHeader(_n);\n")
6429 args
= func
.GetCmdArgs()
6431 f
.write(" %s = _%s;\n" % (arg
.name
, arg
.name
))
6432 f
.write(" memcpy(ImmediateDataAddress(this),\n")
6433 f
.write(" _%s, ComputeDataSize(_n));\n" % last_arg
.name
)
6437 def WriteImmediateCmdSet(self
, func
, f
):
6438 """Overrriden from TypeHandler."""
6439 last_arg
= func
.GetLastOriginalArg()
6440 copy_args
= func
.MakeCmdArgString("_", False)
6441 f
.write(" void* Set(void* cmd%s, %s _%s) {\n" %
6442 (func
.MakeTypedCmdArgString("_", True),
6443 last_arg
.type, last_arg
.name
))
6444 f
.write(" static_cast<ValueType*>(cmd)->Init(%s, _%s);\n" %
6445 (copy_args
, last_arg
.name
))
6446 f
.write(" const uint32_t size = ComputeSize(_n);\n")
6447 f
.write(" return NextImmediateCmdAddressTotalSize<ValueType>("
6452 def WriteImmediateCmdHelper(self
, func
, f
):
6453 """Overrriden from TypeHandler."""
6454 code
= """ void %(name)s(%(typed_args)s) {
6455 const uint32_t size = gles2::cmds::%(name)s::ComputeSize(n);
6456 gles2::cmds::%(name)s* c =
6457 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
6466 "typed_args": func
.MakeTypedOriginalArgString(""),
6467 "args": func
.MakeOriginalArgString(""),
6470 def WriteImmediateFormatTest(self
, func
, f
):
6471 """Overrriden from TypeHandler."""
6472 f
.write("TEST_F(GLES2FormatTest, %s) {\n" % func
.name
)
6473 f
.write(" static GLuint ids[] = { 12, 23, 34, };\n")
6474 f
.write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
6475 (func
.name
, func
.name
))
6476 f
.write(" void* next_cmd = cmd.Set(\n")
6477 f
.write(" &cmd, static_cast<GLsizei>(arraysize(ids)), ids);\n")
6478 f
.write(" EXPECT_EQ(static_cast<uint32_t>(cmds::%s::kCmdId),\n" %
6480 f
.write(" cmd.header.command);\n")
6481 f
.write(" EXPECT_EQ(sizeof(cmd) +\n")
6482 f
.write(" RoundSizeToMultipleOfEntries(cmd.n * 4u),\n")
6483 f
.write(" cmd.header.size * 4u);\n")
6484 f
.write(" EXPECT_EQ(static_cast<GLsizei>(arraysize(ids)), cmd.n);\n");
6485 f
.write(" CheckBytesWrittenMatchesExpectedSize(\n")
6486 f
.write(" next_cmd, sizeof(cmd) +\n")
6487 f
.write(" RoundSizeToMultipleOfEntries(arraysize(ids) * 4u));\n")
6488 f
.write(" // TODO(gman): Check that ids were inserted;\n")
6493 class GETnHandler(TypeHandler
):
6494 """Handler for GETn for glGetBooleanv, glGetFloatv, ... type functions."""
6496 def NeedsDataTransferFunction(self
, func
):
6497 """Overriden from TypeHandler."""
6500 def WriteServiceImplementation(self
, func
, f
):
6501 """Overrriden from TypeHandler."""
6502 self
.WriteServiceHandlerFunctionHeader(func
, f
)
6503 last_arg
= func
.GetLastOriginalArg()
6504 # All except shm_id and shm_offset.
6505 all_but_last_args
= func
.GetCmdArgs()[:-2]
6506 for arg
in all_but_last_args
:
6509 code
= """ typedef cmds::%(func_name)s::Result Result;
6510 GLsizei num_values = 0;
6511 GetNumValuesReturnedForGLGet(pname, &num_values);
6512 Result* result = GetSharedMemoryAs<Result*>(
6513 c.%(last_arg_name)s_shm_id, c.%(last_arg_name)s_shm_offset,
6514 Result::ComputeSize(num_values));
6515 %(last_arg_type)s %(last_arg_name)s = result ? result->GetData() : NULL;
6518 'last_arg_type': last_arg
.type,
6519 'last_arg_name': last_arg
.name
,
6520 'func_name': func
.name
,
6522 func
.WriteHandlerValidation(f
)
6523 code
= """ // Check that the client initialized the result.
6524 if (result->size != 0) {
6525 return error::kInvalidArguments;
6528 shadowed
= func
.GetInfo('shadowed')
6530 f
.write(' LOCAL_COPY_REAL_GL_ERRORS_TO_WRAPPER("%s");\n' % func
.name
)
6532 func
.WriteHandlerImplementation(f
)
6534 code
= """ result->SetNumResults(num_values);
6535 return error::kNoError;
6539 code
= """ GLenum error = LOCAL_PEEK_GL_ERROR("%(func_name)s");
6540 if (error == GL_NO_ERROR) {
6541 result->SetNumResults(num_values);
6543 return error::kNoError;
6547 f
.write(code
% {'func_name': func
.name
})
6549 def WriteGLES2Implementation(self
, func
, f
):
6550 """Overrriden from TypeHandler."""
6551 impl_decl
= func
.GetInfo('impl_decl')
6552 if impl_decl
== None or impl_decl
== True:
6553 f
.write("%s GLES2Implementation::%s(%s) {\n" %
6554 (func
.return_type
, func
.original_name
,
6555 func
.MakeTypedOriginalArgString("")))
6556 f
.write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
6557 func
.WriteDestinationInitalizationValidation(f
)
6558 self
.WriteClientGLCallLog(func
, f
)
6559 for arg
in func
.GetOriginalArgs():
6560 arg
.WriteClientSideValidationCode(f
, func
)
6561 all_but_last_args
= func
.GetOriginalArgs()[:-1]
6563 has_length_arg
= False
6564 for arg
in all_but_last_args
:
6565 if arg
.type == 'GLsync':
6566 args
.append('ToGLuint(%s)' % arg
.name
)
6567 elif arg
.name
.endswith('size') and arg
.type == 'GLsizei':
6569 elif arg
.name
== 'length':
6570 has_length_arg
= True
6573 args
.append(arg
.name
)
6574 arg_string
= ", ".join(args
)
6578 for arg
in func
.GetOriginalArgs() if not arg
.IsConstant()]))
6579 self
.WriteTraceEvent(func
, f
)
6580 code
= """ if (%(func_name)sHelper(%(all_arg_string)s)) {
6583 typedef cmds::%(func_name)s::Result Result;
6584 Result* result = GetResultAs<Result*>();
6588 result->SetNumResults(0);
6589 helper_->%(func_name)s(%(arg_string)s,
6590 GetResultShmId(), GetResultShmOffset());
6592 result->CopyResult(%(last_arg_name)s);
6593 GPU_CLIENT_LOG_CODE_BLOCK({
6594 for (int32_t i = 0; i < result->GetNumResults(); ++i) {
6595 GPU_CLIENT_LOG(" " << i << ": " << result->GetData()[i]);
6601 *length = result->GetNumResults();
6608 'func_name': func
.name
,
6609 'arg_string': arg_string
,
6610 'all_arg_string': all_arg_string
,
6611 'last_arg_name': func
.GetLastOriginalArg().name
,
6614 def WriteGLES2ImplementationUnitTest(self
, func
, f
):
6615 """Writes the GLES2 Implemention unit test."""
6617 TEST_F(GLES2ImplementationTest, %(name)s) {
6621 typedef cmds::%(name)s::Result::Type ResultType;
6622 ResultType result = 0;
6624 ExpectedMemoryInfo result1 = GetExpectedResultMemory(
6625 sizeof(uint32_t) + sizeof(ResultType));
6626 expected.cmd.Init(%(cmd_args)s, result1.id, result1.offset);
6627 EXPECT_CALL(*command_buffer(), OnFlush())
6628 .WillOnce(SetMemory(result1.ptr, SizedResultHelper<ResultType>(1)))
6629 .RetiresOnSaturation();
6630 gl_->%(name)s(%(args)s, &result);
6631 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
6632 EXPECT_EQ(static_cast<ResultType>(1), result);
6635 first_cmd_arg
= func
.GetCmdArgs()[0].GetValidNonCachedClientSideCmdArg(func
)
6636 if not first_cmd_arg
:
6639 first_gl_arg
= func
.GetOriginalArgs()[0].GetValidNonCachedClientSideArg(
6642 cmd_arg_strings
= [first_cmd_arg
]
6643 for arg
in func
.GetCmdArgs()[1:-2]:
6644 cmd_arg_strings
.append(arg
.GetValidClientSideCmdArg(func
))
6645 gl_arg_strings
= [first_gl_arg
]
6646 for arg
in func
.GetOriginalArgs()[1:-1]:
6647 gl_arg_strings
.append(arg
.GetValidClientSideArg(func
))
6651 'args': ", ".join(gl_arg_strings
),
6652 'cmd_args': ", ".join(cmd_arg_strings
),
6655 def WriteServiceUnitTest(self
, func
, f
, *extras
):
6656 """Overrriden from TypeHandler."""
6658 TEST_P(%(test_name)s, %(name)sValidArgs) {
6659 EXPECT_CALL(*gl_, GetError())
6660 .WillRepeatedly(Return(GL_NO_ERROR));
6661 SpecializedSetup<cmds::%(name)s, 0>(true);
6662 typedef cmds::%(name)s::Result Result;
6663 Result* result = static_cast<Result*>(shared_memory_address_);
6664 EXPECT_CALL(*gl_, %(gl_func_name)s(%(local_gl_args)s));
6667 cmd.Init(%(cmd_args)s);"""
6670 decoder_->set_unsafe_es3_apis_enabled(true);"""
6672 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
6673 EXPECT_EQ(decoder_->GetGLES2Util()->GLGetNumValuesReturned(
6675 result->GetNumResults());
6676 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
6679 decoder_->set_unsafe_es3_apis_enabled(false);
6680 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));"""
6685 cmd_arg_strings
= []
6687 for arg
in func
.GetOriginalArgs()[:-1]:
6688 if arg
.name
== 'length':
6689 gl_arg_value
= 'nullptr'
6690 elif arg
.name
.endswith('size'):
6691 gl_arg_value
= ("decoder_->GetGLES2Util()->GLGetNumValuesReturned(%s)" %
6693 elif arg
.type == 'GLsync':
6694 gl_arg_value
= 'reinterpret_cast<GLsync>(kServiceSyncId)'
6696 gl_arg_value
= arg
.GetValidGLArg(func
)
6697 gl_arg_strings
.append(gl_arg_value
)
6698 if arg
.name
== 'pname':
6699 valid_pname
= gl_arg_value
6700 if arg
.name
.endswith('size') or arg
.name
== 'length':
6702 if arg
.type == 'GLsync':
6703 arg_value
= 'client_sync_id_'
6705 arg_value
= arg
.GetValidArg(func
)
6706 cmd_arg_strings
.append(arg_value
)
6707 if func
.GetInfo('gl_test_func') == 'glGetIntegerv':
6708 gl_arg_strings
.append("_")
6710 gl_arg_strings
.append("result->GetData()")
6711 cmd_arg_strings
.append("shared_memory_id_")
6712 cmd_arg_strings
.append("shared_memory_offset_")
6714 self
.WriteValidUnitTest(func
, f
, valid_test
, {
6715 'local_gl_args': ", ".join(gl_arg_strings
),
6716 'cmd_args': ", ".join(cmd_arg_strings
),
6717 'valid_pname': valid_pname
,
6720 if not func
.IsUnsafe():
6722 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
6723 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
6724 SpecializedSetup<cmds::%(name)s, 0>(false);
6725 cmds::%(name)s::Result* result =
6726 static_cast<cmds::%(name)s::Result*>(shared_memory_address_);
6730 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));
6731 EXPECT_EQ(0u, result->size);%(gl_error_test)s
6734 self
.WriteInvalidUnitTest(func
, f
, invalid_test
, *extras
)
6736 class ArrayArgTypeHandler(TypeHandler
):
6737 """Base class for type handlers that handle args that are arrays"""
6739 def GetArrayType(self
, func
):
6740 """Returns the type of the element in the element array being PUT to."""
6741 for arg
in func
.GetOriginalArgs():
6743 element_type
= arg
.GetPointedType()
6746 # Special case: array type handler is used for a function that is forwarded
6747 # to the actual array type implementation
6748 element_type
= func
.GetOriginalArgs()[-1].type
6749 assert all(arg
.type == element_type \
6750 for arg
in func
.GetOriginalArgs()[-self
.GetArrayCount(func
):])
6753 def GetArrayCount(self
, func
):
6754 """Returns the count of the elements in the array being PUT to."""
6755 return func
.GetInfo('count')
6757 class PUTHandler(ArrayArgTypeHandler
):
6758 """Handler for glTexParameter_v, glVertexAttrib_v functions."""
6760 def WriteServiceUnitTest(self
, func
, f
, *extras
):
6761 """Writes the service unit test for a command."""
6762 expected_call
= "EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));"
6763 if func
.GetInfo("first_element_only"):
6765 arg
.GetValidGLArg(func
) for arg
in func
.GetOriginalArgs()
6767 gl_arg_strings
[-1] = "*" + gl_arg_strings
[-1]
6768 expected_call
= ("EXPECT_CALL(*gl_, %%(gl_func_name)s(%s));" %
6769 ", ".join(gl_arg_strings
))
6771 TEST_P(%(test_name)s, %(name)sValidArgs) {
6772 SpecializedSetup<cmds::%(name)s, 0>(true);
6775 GetSharedMemoryAs<%(data_type)s*>()[0] = %(data_value)s;
6777 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
6778 EXPECT_EQ(GL_NO_ERROR, GetGLError());
6782 'data_type': self
.GetArrayType(func
),
6783 'data_value': func
.GetInfo('data_value') or '0',
6784 'expected_call': expected_call
,
6786 self
.WriteValidUnitTest(func
, f
, valid_test
, extra
, *extras
)
6789 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
6790 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
6791 SpecializedSetup<cmds::%(name)s, 0>(false);
6794 GetSharedMemoryAs<%(data_type)s*>()[0] = %(data_value)s;
6795 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
6798 self
.WriteInvalidUnitTest(func
, f
, invalid_test
, extra
, *extras
)
6800 def WriteImmediateServiceUnitTest(self
, func
, f
, *extras
):
6801 """Writes the service unit test for a command."""
6803 TEST_P(%(test_name)s, %(name)sValidArgs) {
6804 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
6805 SpecializedSetup<cmds::%(name)s, 0>(true);
6806 %(data_type)s temp[%(data_count)s] = { %(data_value)s, };
6807 cmd.Init(%(gl_args)s, &temp[0]);
6810 %(gl_func_name)s(%(gl_args)s, %(data_ref)sreinterpret_cast<
6811 %(data_type)s*>(ImmediateDataAddress(&cmd))));"""
6814 decoder_->set_unsafe_es3_apis_enabled(true);"""
6816 EXPECT_EQ(error::kNoError,
6817 ExecuteImmediateCmd(cmd, sizeof(temp)));
6818 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
6821 decoder_->set_unsafe_es3_apis_enabled(false);
6822 EXPECT_EQ(error::kUnknownCommand,
6823 ExecuteImmediateCmd(cmd, sizeof(temp)));"""
6828 arg
.GetValidGLArg(func
) for arg
in func
.GetOriginalArgs()[0:-1]
6830 gl_any_strings
= ["_"] * len(gl_arg_strings
)
6833 'data_ref': ("*" if func
.GetInfo('first_element_only') else ""),
6834 'data_type': self
.GetArrayType(func
),
6835 'data_count': self
.GetArrayCount(func
),
6836 'data_value': func
.GetInfo('data_value') or '0',
6837 'gl_args': ", ".join(gl_arg_strings
),
6838 'gl_any_args': ", ".join(gl_any_strings
),
6840 self
.WriteValidUnitTest(func
, f
, valid_test
, extra
, *extras
)
6843 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
6844 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();"""
6847 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_any_args)s, _)).Times(1);
6851 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_any_args)s, _)).Times(0);
6854 SpecializedSetup<cmds::%(name)s, 0>(false);
6855 %(data_type)s temp[%(data_count)s] = { %(data_value)s, };
6856 cmd.Init(%(all_but_last_args)s, &temp[0]);"""
6859 decoder_->set_unsafe_es3_apis_enabled(true);
6860 EXPECT_EQ(error::%(parse_result)s,
6861 ExecuteImmediateCmd(cmd, sizeof(temp)));
6862 decoder_->set_unsafe_es3_apis_enabled(false);
6867 EXPECT_EQ(error::%(parse_result)s,
6868 ExecuteImmediateCmd(cmd, sizeof(temp)));
6872 self
.WriteInvalidUnitTest(func
, f
, invalid_test
, extra
, *extras
)
6874 def WriteGetDataSizeCode(self
, func
, f
):
6875 """Overrriden from TypeHandler."""
6876 code
= """ uint32_t data_size;
6877 if (!ComputeDataSize(1, sizeof(%s), %d, &data_size)) {
6878 return error::kOutOfBounds;
6881 f
.write(code
% (self
.GetArrayType(func
), self
.GetArrayCount(func
)))
6882 if func
.IsImmediate():
6883 f
.write(" if (data_size > immediate_data_size) {\n")
6884 f
.write(" return error::kOutOfBounds;\n")
6887 def __NeedsToCalcDataCount(self
, func
):
6888 use_count_func
= func
.GetInfo('use_count_func')
6889 return use_count_func
!= None and use_count_func
!= False
6891 def WriteGLES2Implementation(self
, func
, f
):
6892 """Overrriden from TypeHandler."""
6893 impl_func
= func
.GetInfo('impl_func')
6894 if (impl_func
!= None and impl_func
!= True):
6896 f
.write("%s GLES2Implementation::%s(%s) {\n" %
6897 (func
.return_type
, func
.original_name
,
6898 func
.MakeTypedOriginalArgString("")))
6899 f
.write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
6900 func
.WriteDestinationInitalizationValidation(f
)
6901 self
.WriteClientGLCallLog(func
, f
)
6903 if self
.__NeedsToCalcDataCount
(func
):
6904 f
.write(" size_t count = GLES2Util::Calc%sDataCount(%s);\n" %
6905 (func
.name
, func
.GetOriginalArgs()[0].name
))
6906 f
.write(" DCHECK_LE(count, %du);\n" % self
.GetArrayCount(func
))
6908 f
.write(" size_t count = %d;" % self
.GetArrayCount(func
))
6909 f
.write(" for (size_t ii = 0; ii < count; ++ii)\n")
6910 f
.write(' GPU_CLIENT_LOG("value[" << ii << "]: " << %s[ii]);\n' %
6911 func
.GetLastOriginalArg().name
)
6912 for arg
in func
.GetOriginalArgs():
6913 arg
.WriteClientSideValidationCode(f
, func
)
6914 f
.write(" helper_->%sImmediate(%s);\n" %
6915 (func
.name
, func
.MakeOriginalArgString("")))
6916 f
.write(" CheckGLError();\n")
6920 def WriteGLES2ImplementationUnitTest(self
, func
, f
):
6921 """Writes the GLES2 Implemention unit test."""
6922 client_test
= func
.GetInfo('client_test')
6923 if (client_test
!= None and client_test
!= True):
6926 TEST_F(GLES2ImplementationTest, %(name)s) {
6927 %(type)s data[%(count)d] = {0};
6929 cmds::%(name)sImmediate cmd;
6930 %(type)s data[%(count)d];
6933 for (int jj = 0; jj < %(count)d; ++jj) {
6934 data[jj] = static_cast<%(type)s>(jj);
6937 expected.cmd.Init(%(cmd_args)s, &data[0]);
6938 gl_->%(name)s(%(args)s, &data[0]);
6939 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
6943 arg
.GetValidClientSideCmdArg(func
) for arg
in func
.GetCmdArgs()[0:-2]
6946 arg
.GetValidClientSideArg(func
) for arg
in func
.GetOriginalArgs()[0:-1]
6951 'type': self
.GetArrayType(func
),
6952 'count': self
.GetArrayCount(func
),
6953 'args': ", ".join(gl_arg_strings
),
6954 'cmd_args': ", ".join(cmd_arg_strings
),
6957 def WriteImmediateCmdComputeSize(self
, func
, f
):
6958 """Overrriden from TypeHandler."""
6959 f
.write(" static uint32_t ComputeDataSize() {\n")
6960 f
.write(" return static_cast<uint32_t>(\n")
6961 f
.write(" sizeof(%s) * %d);\n" %
6962 (self
.GetArrayType(func
), self
.GetArrayCount(func
)))
6965 if self
.__NeedsToCalcDataCount
(func
):
6966 f
.write(" static uint32_t ComputeEffectiveDataSize(%s %s) {\n" %
6967 (func
.GetOriginalArgs()[0].type,
6968 func
.GetOriginalArgs()[0].name
))
6969 f
.write(" return static_cast<uint32_t>(\n")
6970 f
.write(" sizeof(%s) * GLES2Util::Calc%sDataCount(%s));\n" %
6971 (self
.GetArrayType(func
), func
.original_name
,
6972 func
.GetOriginalArgs()[0].name
))
6975 f
.write(" static uint32_t ComputeSize() {\n")
6976 f
.write(" return static_cast<uint32_t>(\n")
6978 " sizeof(ValueType) + ComputeDataSize());\n")
6982 def WriteImmediateCmdSetHeader(self
, func
, f
):
6983 """Overrriden from TypeHandler."""
6984 f
.write(" void SetHeader() {\n")
6986 " header.SetCmdByTotalSize<ValueType>(ComputeSize());\n")
6990 def WriteImmediateCmdInit(self
, func
, f
):
6991 """Overrriden from TypeHandler."""
6992 last_arg
= func
.GetLastOriginalArg()
6993 f
.write(" void Init(%s, %s _%s) {\n" %
6994 (func
.MakeTypedCmdArgString("_"),
6995 last_arg
.type, last_arg
.name
))
6996 f
.write(" SetHeader();\n")
6997 args
= func
.GetCmdArgs()
6999 f
.write(" %s = _%s;\n" % (arg
.name
, arg
.name
))
7000 f
.write(" memcpy(ImmediateDataAddress(this),\n")
7001 if self
.__NeedsToCalcDataCount
(func
):
7002 f
.write(" _%s, ComputeEffectiveDataSize(%s));" %
7003 (last_arg
.name
, func
.GetOriginalArgs()[0].name
))
7005 DCHECK_GE(ComputeDataSize(), ComputeEffectiveDataSize(%(arg)s));
7006 char* pointer = reinterpret_cast<char*>(ImmediateDataAddress(this)) +
7007 ComputeEffectiveDataSize(%(arg)s);
7008 memset(pointer, 0, ComputeDataSize() - ComputeEffectiveDataSize(%(arg)s));
7009 """ % { 'arg': func
.GetOriginalArgs()[0].name
, })
7011 f
.write(" _%s, ComputeDataSize());\n" % last_arg
.name
)
7015 def WriteImmediateCmdSet(self
, func
, f
):
7016 """Overrriden from TypeHandler."""
7017 last_arg
= func
.GetLastOriginalArg()
7018 copy_args
= func
.MakeCmdArgString("_", False)
7019 f
.write(" void* Set(void* cmd%s, %s _%s) {\n" %
7020 (func
.MakeTypedCmdArgString("_", True),
7021 last_arg
.type, last_arg
.name
))
7022 f
.write(" static_cast<ValueType*>(cmd)->Init(%s, _%s);\n" %
7023 (copy_args
, last_arg
.name
))
7024 f
.write(" const uint32_t size = ComputeSize();\n")
7025 f
.write(" return NextImmediateCmdAddressTotalSize<ValueType>("
7030 def WriteImmediateCmdHelper(self
, func
, f
):
7031 """Overrriden from TypeHandler."""
7032 code
= """ void %(name)s(%(typed_args)s) {
7033 const uint32_t size = gles2::cmds::%(name)s::ComputeSize();
7034 gles2::cmds::%(name)s* c =
7035 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
7044 "typed_args": func
.MakeTypedOriginalArgString(""),
7045 "args": func
.MakeOriginalArgString(""),
7048 def WriteImmediateFormatTest(self
, func
, f
):
7049 """Overrriden from TypeHandler."""
7050 f
.write("TEST_F(GLES2FormatTest, %s) {\n" % func
.name
)
7051 f
.write(" const int kSomeBaseValueToTestWith = 51;\n")
7052 f
.write(" static %s data[] = {\n" % self
.GetArrayType(func
))
7053 for v
in range(0, self
.GetArrayCount(func
)):
7054 f
.write(" static_cast<%s>(kSomeBaseValueToTestWith + %d),\n" %
7055 (self
.GetArrayType(func
), v
))
7057 f
.write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
7058 (func
.name
, func
.name
))
7059 f
.write(" void* next_cmd = cmd.Set(\n")
7061 args
= func
.GetCmdArgs()
7062 for value
, arg
in enumerate(args
):
7063 f
.write(",\n static_cast<%s>(%d)" % (arg
.type, value
+ 11))
7064 f
.write(",\n data);\n")
7065 args
= func
.GetCmdArgs()
7066 f
.write(" EXPECT_EQ(static_cast<uint32_t>(cmds::%s::kCmdId),\n"
7068 f
.write(" cmd.header.command);\n")
7069 f
.write(" EXPECT_EQ(sizeof(cmd) +\n")
7070 f
.write(" RoundSizeToMultipleOfEntries(sizeof(data)),\n")
7071 f
.write(" cmd.header.size * 4u);\n")
7072 for value
, arg
in enumerate(args
):
7073 f
.write(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);\n" %
7074 (arg
.type, value
+ 11, arg
.name
))
7075 f
.write(" CheckBytesWrittenMatchesExpectedSize(\n")
7076 f
.write(" next_cmd, sizeof(cmd) +\n")
7077 f
.write(" RoundSizeToMultipleOfEntries(sizeof(data)));\n")
7078 f
.write(" // TODO(gman): Check that data was inserted;\n")
7083 class PUTnHandler(ArrayArgTypeHandler
):
7084 """Handler for PUTn 'glUniform__v' type functions."""
7086 def WriteServiceUnitTest(self
, func
, f
, *extras
):
7087 """Overridden from TypeHandler."""
7088 ArrayArgTypeHandler
.WriteServiceUnitTest(self
, func
, f
, *extras
)
7091 TEST_P(%(test_name)s, %(name)sValidArgsCountTooLarge) {
7092 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
7093 SpecializedSetup<cmds::%(name)s, 0>(true);
7096 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
7097 EXPECT_EQ(GL_NO_ERROR, GetGLError());
7102 for count
, arg
in enumerate(func
.GetOriginalArgs()):
7103 # hardcoded to match unit tests.
7105 # the location of the second element of the 2nd uniform.
7106 # defined in GLES2DecoderBase::SetupShaderForUniform
7107 gl_arg_strings
.append("3")
7108 arg_strings
.append("ProgramManager::MakeFakeLocation(1, 1)")
7110 # the number of elements that gl will be called with.
7111 gl_arg_strings
.append("3")
7112 # the number of elements requested in the command.
7113 arg_strings
.append("5")
7115 gl_arg_strings
.append(arg
.GetValidGLArg(func
))
7116 if not arg
.IsConstant():
7117 arg_strings
.append(arg
.GetValidArg(func
))
7119 'gl_args': ", ".join(gl_arg_strings
),
7120 'args': ", ".join(arg_strings
),
7122 self
.WriteValidUnitTest(func
, f
, valid_test
, extra
, *extras
)
7124 def WriteImmediateServiceUnitTest(self
, func
, f
, *extras
):
7125 """Overridden from TypeHandler."""
7127 TEST_P(%(test_name)s, %(name)sValidArgs) {
7128 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
7131 %(gl_func_name)s(%(gl_args)s,
7132 reinterpret_cast<%(data_type)s*>(ImmediateDataAddress(&cmd))));
7133 SpecializedSetup<cmds::%(name)s, 0>(true);
7134 %(data_type)s temp[%(data_count)s * 2] = { 0, };
7135 cmd.Init(%(args)s, &temp[0]);"""
7138 decoder_->set_unsafe_es3_apis_enabled(true);"""
7140 EXPECT_EQ(error::kNoError,
7141 ExecuteImmediateCmd(cmd, sizeof(temp)));
7142 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
7145 decoder_->set_unsafe_es3_apis_enabled(false);
7146 EXPECT_EQ(error::kUnknownCommand,
7147 ExecuteImmediateCmd(cmd, sizeof(temp)));"""
7154 for arg
in func
.GetOriginalArgs()[0:-1]:
7155 gl_arg_strings
.append(arg
.GetValidGLArg(func
))
7156 gl_any_strings
.append("_")
7157 if not arg
.IsConstant():
7158 arg_strings
.append(arg
.GetValidArg(func
))
7160 'data_type': self
.GetArrayType(func
),
7161 'data_count': self
.GetArrayCount(func
),
7162 'args': ", ".join(arg_strings
),
7163 'gl_args': ", ".join(gl_arg_strings
),
7164 'gl_any_args': ", ".join(gl_any_strings
),
7166 self
.WriteValidUnitTest(func
, f
, valid_test
, extra
, *extras
)
7169 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
7170 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
7171 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_any_args)s, _)).Times(0);
7172 SpecializedSetup<cmds::%(name)s, 0>(false);
7173 %(data_type)s temp[%(data_count)s * 2] = { 0, };
7174 cmd.Init(%(all_but_last_args)s, &temp[0]);
7175 EXPECT_EQ(error::%(parse_result)s,
7176 ExecuteImmediateCmd(cmd, sizeof(temp)));%(gl_error_test)s
7179 self
.WriteInvalidUnitTest(func
, f
, invalid_test
, extra
, *extras
)
7181 def WriteGetDataSizeCode(self
, func
, f
):
7182 """Overrriden from TypeHandler."""
7183 code
= """ uint32_t data_size;
7184 if (!ComputeDataSize(count, sizeof(%s), %d, &data_size)) {
7185 return error::kOutOfBounds;
7188 f
.write(code
% (self
.GetArrayType(func
), self
.GetArrayCount(func
)))
7189 if func
.IsImmediate():
7190 f
.write(" if (data_size > immediate_data_size) {\n")
7191 f
.write(" return error::kOutOfBounds;\n")
7194 def WriteGLES2Implementation(self
, func
, f
):
7195 """Overrriden from TypeHandler."""
7196 f
.write("%s GLES2Implementation::%s(%s) {\n" %
7197 (func
.return_type
, func
.original_name
,
7198 func
.MakeTypedOriginalArgString("")))
7199 f
.write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
7200 func
.WriteDestinationInitalizationValidation(f
)
7201 self
.WriteClientGLCallLog(func
, f
)
7202 last_pointer_name
= func
.GetLastOriginalPointerArg().name
7203 f
.write(""" GPU_CLIENT_LOG_CODE_BLOCK({
7204 for (GLsizei i = 0; i < count; ++i) {
7206 values_str
= ' << ", " << '.join(
7207 ["%s[%d + i * %d]" % (
7208 last_pointer_name
, ndx
, self
.GetArrayCount(func
)) for ndx
in range(
7209 0, self
.GetArrayCount(func
))])
7210 f
.write(' GPU_CLIENT_LOG(" " << i << ": " << %s);\n' % values_str
)
7211 f
.write(" }\n });\n")
7212 for arg
in func
.GetOriginalArgs():
7213 arg
.WriteClientSideValidationCode(f
, func
)
7214 f
.write(" helper_->%sImmediate(%s);\n" %
7215 (func
.name
, func
.MakeInitString("")))
7216 f
.write(" CheckGLError();\n")
7220 def WriteGLES2ImplementationUnitTest(self
, func
, f
):
7221 """Writes the GLES2 Implemention unit test."""
7223 TEST_F(GLES2ImplementationTest, %(name)s) {
7224 %(type)s data[%(count_param)d][%(count)d] = {{0}};
7226 cmds::%(name)sImmediate cmd;
7227 %(type)s data[%(count_param)d][%(count)d];
7231 for (int ii = 0; ii < %(count_param)d; ++ii) {
7232 for (int jj = 0; jj < %(count)d; ++jj) {
7233 data[ii][jj] = static_cast<%(type)s>(ii * %(count)d + jj);
7236 expected.cmd.Init(%(cmd_args)s);
7237 gl_->%(name)s(%(args)s);
7238 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
7241 cmd_arg_strings
= []
7242 for arg
in func
.GetCmdArgs():
7243 if arg
.name
.endswith("_shm_id"):
7244 cmd_arg_strings
.append("&data[0][0]")
7245 elif arg
.name
.endswith("_shm_offset"):
7248 cmd_arg_strings
.append(arg
.GetValidClientSideCmdArg(func
))
7251 for arg
in func
.GetOriginalArgs():
7253 valid_value
= "&data[0][0]"
7255 valid_value
= arg
.GetValidClientSideArg(func
)
7256 gl_arg_strings
.append(valid_value
)
7257 if arg
.name
== "count":
7258 count_param
= int(valid_value
)
7261 'type': self
.GetArrayType(func
),
7262 'count': self
.GetArrayCount(func
),
7263 'args': ", ".join(gl_arg_strings
),
7264 'cmd_args': ", ".join(cmd_arg_strings
),
7265 'count_param': count_param
,
7268 # Test constants for invalid values, as they are not tested by the
7271 arg
for arg
in func
.GetOriginalArgs()[0:-1] if arg
.IsConstant()
7277 TEST_F(GLES2ImplementationTest, %(name)sInvalidConstantArg%(invalid_index)d) {
7278 %(type)s data[%(count_param)d][%(count)d] = {{0}};
7279 for (int ii = 0; ii < %(count_param)d; ++ii) {
7280 for (int jj = 0; jj < %(count)d; ++jj) {
7281 data[ii][jj] = static_cast<%(type)s>(ii * %(count)d + jj);
7284 gl_->%(name)s(%(args)s);
7285 EXPECT_TRUE(NoCommandsWritten());
7286 EXPECT_EQ(%(gl_error)s, CheckError());
7289 for invalid_arg
in constants
:
7291 invalid
= invalid_arg
.GetInvalidArg(func
)
7292 for arg
in func
.GetOriginalArgs():
7293 if arg
is invalid_arg
:
7294 gl_arg_strings
.append(invalid
[0])
7295 elif arg
.IsPointer():
7296 gl_arg_strings
.append("&data[0][0]")
7298 valid_value
= arg
.GetValidClientSideArg(func
)
7299 gl_arg_strings
.append(valid_value
)
7300 if arg
.name
== "count":
7301 count_param
= int(valid_value
)
7305 'invalid_index': func
.GetOriginalArgs().index(invalid_arg
),
7306 'type': self
.GetArrayType(func
),
7307 'count': self
.GetArrayCount(func
),
7308 'args': ", ".join(gl_arg_strings
),
7309 'gl_error': invalid
[2],
7310 'count_param': count_param
,
7314 def WriteImmediateCmdComputeSize(self
, func
, f
):
7315 """Overrriden from TypeHandler."""
7316 f
.write(" static uint32_t ComputeDataSize(GLsizei count) {\n")
7317 f
.write(" return static_cast<uint32_t>(\n")
7318 f
.write(" sizeof(%s) * %d * count); // NOLINT\n" %
7319 (self
.GetArrayType(func
), self
.GetArrayCount(func
)))
7322 f
.write(" static uint32_t ComputeSize(GLsizei count) {\n")
7323 f
.write(" return static_cast<uint32_t>(\n")
7325 " sizeof(ValueType) + ComputeDataSize(count)); // NOLINT\n")
7329 def WriteImmediateCmdSetHeader(self
, func
, f
):
7330 """Overrriden from TypeHandler."""
7331 f
.write(" void SetHeader(GLsizei count) {\n")
7333 " header.SetCmdByTotalSize<ValueType>(ComputeSize(count));\n")
7337 def WriteImmediateCmdInit(self
, func
, f
):
7338 """Overrriden from TypeHandler."""
7339 f
.write(" void Init(%s) {\n" %
7340 func
.MakeTypedInitString("_"))
7341 f
.write(" SetHeader(_count);\n")
7342 args
= func
.GetCmdArgs()
7344 f
.write(" %s = _%s;\n" % (arg
.name
, arg
.name
))
7345 f
.write(" memcpy(ImmediateDataAddress(this),\n")
7346 pointer_arg
= func
.GetLastOriginalPointerArg()
7347 f
.write(" _%s, ComputeDataSize(_count));\n" % pointer_arg
.name
)
7351 def WriteImmediateCmdSet(self
, func
, f
):
7352 """Overrriden from TypeHandler."""
7353 f
.write(" void* Set(void* cmd%s) {\n" %
7354 func
.MakeTypedInitString("_", True))
7355 f
.write(" static_cast<ValueType*>(cmd)->Init(%s);\n" %
7356 func
.MakeInitString("_"))
7357 f
.write(" const uint32_t size = ComputeSize(_count);\n")
7358 f
.write(" return NextImmediateCmdAddressTotalSize<ValueType>("
7363 def WriteImmediateCmdHelper(self
, func
, f
):
7364 """Overrriden from TypeHandler."""
7365 code
= """ void %(name)s(%(typed_args)s) {
7366 const uint32_t size = gles2::cmds::%(name)s::ComputeSize(count);
7367 gles2::cmds::%(name)s* c =
7368 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
7377 "typed_args": func
.MakeTypedInitString(""),
7378 "args": func
.MakeInitString("")
7381 def WriteImmediateFormatTest(self
, func
, f
):
7382 """Overrriden from TypeHandler."""
7383 args
= func
.GetOriginalArgs()
7386 if arg
.name
== "count":
7387 count_param
= int(arg
.GetValidClientSideCmdArg(func
))
7388 f
.write("TEST_F(GLES2FormatTest, %s) {\n" % func
.name
)
7389 f
.write(" const int kSomeBaseValueToTestWith = 51;\n")
7390 f
.write(" static %s data[] = {\n" % self
.GetArrayType(func
))
7391 for v
in range(0, self
.GetArrayCount(func
) * count_param
):
7392 f
.write(" static_cast<%s>(kSomeBaseValueToTestWith + %d),\n" %
7393 (self
.GetArrayType(func
), v
))
7395 f
.write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
7396 (func
.name
, func
.name
))
7397 f
.write(" const GLsizei kNumElements = %d;\n" % count_param
)
7398 f
.write(" const size_t kExpectedCmdSize =\n")
7399 f
.write(" sizeof(cmd) + kNumElements * sizeof(%s) * %d;\n" %
7400 (self
.GetArrayType(func
), self
.GetArrayCount(func
)))
7401 f
.write(" void* next_cmd = cmd.Set(\n")
7403 for value
, arg
in enumerate(args
):
7406 elif arg
.IsConstant():
7409 f
.write(",\n static_cast<%s>(%d)" % (arg
.type, value
+ 1))
7411 f
.write(" EXPECT_EQ(static_cast<uint32_t>(cmds::%s::kCmdId),\n" %
7413 f
.write(" cmd.header.command);\n")
7414 f
.write(" EXPECT_EQ(kExpectedCmdSize, cmd.header.size * 4u);\n")
7415 for value
, arg
in enumerate(args
):
7416 if arg
.IsPointer() or arg
.IsConstant():
7418 f
.write(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);\n" %
7419 (arg
.type, value
+ 1, arg
.name
))
7420 f
.write(" CheckBytesWrittenMatchesExpectedSize(\n")
7421 f
.write(" next_cmd, sizeof(cmd) +\n")
7422 f
.write(" RoundSizeToMultipleOfEntries(sizeof(data)));\n")
7423 f
.write(" // TODO(gman): Check that data was inserted;\n")
7427 class PUTSTRHandler(ArrayArgTypeHandler
):
7428 """Handler for functions that pass a string array."""
7430 def __GetDataArg(self
, func
):
7431 """Return the argument that points to the 2D char arrays"""
7432 for arg
in func
.GetOriginalArgs():
7433 if arg
.IsPointer2D():
7437 def __GetLengthArg(self
, func
):
7438 """Return the argument that holds length for each char array"""
7439 for arg
in func
.GetOriginalArgs():
7440 if arg
.IsPointer() and not arg
.IsPointer2D():
7444 def WriteGLES2Implementation(self
, func
, f
):
7445 """Overrriden from TypeHandler."""
7446 f
.write("%s GLES2Implementation::%s(%s) {\n" %
7447 (func
.return_type
, func
.original_name
,
7448 func
.MakeTypedOriginalArgString("")))
7449 f
.write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
7450 func
.WriteDestinationInitalizationValidation(f
)
7451 self
.WriteClientGLCallLog(func
, f
)
7452 data_arg
= self
.__GetDataArg
(func
)
7453 length_arg
= self
.__GetLengthArg
(func
)
7454 log_code_block
= """ GPU_CLIENT_LOG_CODE_BLOCK({
7455 for (GLsizei ii = 0; ii < count; ++ii) {
7456 if (%(data)s[ii]) {"""
7457 if length_arg
== None:
7458 log_code_block
+= """
7459 GPU_CLIENT_LOG(" " << ii << ": ---\\n" << %(data)s[ii] << "\\n---");"""
7461 log_code_block
+= """
7462 if (%(length)s && %(length)s[ii] >= 0) {
7463 const std::string my_str(%(data)s[ii], %(length)s[ii]);
7464 GPU_CLIENT_LOG(" " << ii << ": ---\\n" << my_str << "\\n---");
7466 GPU_CLIENT_LOG(" " << ii << ": ---\\n" << %(data)s[ii] << "\\n---");
7468 log_code_block
+= """
7470 GPU_CLIENT_LOG(" " << ii << ": NULL");
7475 f
.write(log_code_block
% {
7476 'data': data_arg
.name
,
7477 'length': length_arg
.name
if not length_arg
== None else ''
7479 for arg
in func
.GetOriginalArgs():
7480 arg
.WriteClientSideValidationCode(f
, func
)
7483 for arg
in func
.GetOriginalArgs():
7484 if arg
.name
== 'count' or arg
== self
.__GetLengthArg
(func
):
7486 if arg
== self
.__GetDataArg
(func
):
7487 bucket_args
.append('kResultBucketId')
7489 bucket_args
.append(arg
.name
)
7491 if (!PackStringsToBucket(count, %(data)s, %(length)s, "gl%(func_name)s")) {
7494 helper_->%(func_name)sBucket(%(bucket_args)s);
7495 helper_->SetBucketSize(kResultBucketId, 0);
7500 f
.write(code_block
% {
7501 'data': data_arg
.name
,
7502 'length': length_arg
.name
if not length_arg
== None else 'NULL',
7503 'func_name': func
.name
,
7504 'bucket_args': ', '.join(bucket_args
),
7507 def WriteGLES2ImplementationUnitTest(self
, func
, f
):
7508 """Overrriden from TypeHandler."""
7510 TEST_F(GLES2ImplementationTest, %(name)s) {
7511 const uint32 kBucketId = GLES2Implementation::kResultBucketId;
7512 const char* kString1 = "happy";
7513 const char* kString2 = "ending";
7514 const size_t kString1Size = ::strlen(kString1) + 1;
7515 const size_t kString2Size = ::strlen(kString2) + 1;
7516 const size_t kHeaderSize = sizeof(GLint) * 3;
7517 const size_t kSourceSize = kHeaderSize + kString1Size + kString2Size;
7518 const size_t kPaddedHeaderSize =
7519 transfer_buffer_->RoundToAlignment(kHeaderSize);
7520 const size_t kPaddedString1Size =
7521 transfer_buffer_->RoundToAlignment(kString1Size);
7522 const size_t kPaddedString2Size =
7523 transfer_buffer_->RoundToAlignment(kString2Size);
7525 cmd::SetBucketSize set_bucket_size;
7526 cmd::SetBucketData set_bucket_header;
7527 cmd::SetToken set_token1;
7528 cmd::SetBucketData set_bucket_data1;
7529 cmd::SetToken set_token2;
7530 cmd::SetBucketData set_bucket_data2;
7531 cmd::SetToken set_token3;
7532 cmds::%(name)sBucket cmd_bucket;
7533 cmd::SetBucketSize clear_bucket_size;
7536 ExpectedMemoryInfo mem0 = GetExpectedMemory(kPaddedHeaderSize);
7537 ExpectedMemoryInfo mem1 = GetExpectedMemory(kPaddedString1Size);
7538 ExpectedMemoryInfo mem2 = GetExpectedMemory(kPaddedString2Size);
7541 expected.set_bucket_size.Init(kBucketId, kSourceSize);
7542 expected.set_bucket_header.Init(
7543 kBucketId, 0, kHeaderSize, mem0.id, mem0.offset);
7544 expected.set_token1.Init(GetNextToken());
7545 expected.set_bucket_data1.Init(
7546 kBucketId, kHeaderSize, kString1Size, mem1.id, mem1.offset);
7547 expected.set_token2.Init(GetNextToken());
7548 expected.set_bucket_data2.Init(
7549 kBucketId, kHeaderSize + kString1Size, kString2Size, mem2.id,
7551 expected.set_token3.Init(GetNextToken());
7552 expected.cmd_bucket.Init(%(bucket_args)s);
7553 expected.clear_bucket_size.Init(kBucketId, 0);
7554 const char* kStrings[] = { kString1, kString2 };
7555 gl_->%(name)s(%(gl_args)s);
7556 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
7561 for arg
in func
.GetOriginalArgs():
7562 if arg
== self
.__GetDataArg
(func
):
7563 gl_args
.append('kStrings')
7564 bucket_args
.append('kBucketId')
7565 elif arg
== self
.__GetLengthArg
(func
):
7566 gl_args
.append('NULL')
7567 elif arg
.name
== 'count':
7570 gl_args
.append(arg
.GetValidClientSideArg(func
))
7571 bucket_args
.append(arg
.GetValidClientSideArg(func
))
7574 'gl_args': ", ".join(gl_args
),
7575 'bucket_args': ", ".join(bucket_args
),
7578 if self
.__GetLengthArg
(func
) == None:
7581 TEST_F(GLES2ImplementationTest, %(name)sWithLength) {
7582 const uint32 kBucketId = GLES2Implementation::kResultBucketId;
7583 const char* kString = "foobar******";
7584 const size_t kStringSize = 6; // We only need "foobar".
7585 const size_t kHeaderSize = sizeof(GLint) * 2;
7586 const size_t kSourceSize = kHeaderSize + kStringSize + 1;
7587 const size_t kPaddedHeaderSize =
7588 transfer_buffer_->RoundToAlignment(kHeaderSize);
7589 const size_t kPaddedStringSize =
7590 transfer_buffer_->RoundToAlignment(kStringSize + 1);
7592 cmd::SetBucketSize set_bucket_size;
7593 cmd::SetBucketData set_bucket_header;
7594 cmd::SetToken set_token1;
7595 cmd::SetBucketData set_bucket_data;
7596 cmd::SetToken set_token2;
7597 cmds::ShaderSourceBucket shader_source_bucket;
7598 cmd::SetBucketSize clear_bucket_size;
7601 ExpectedMemoryInfo mem0 = GetExpectedMemory(kPaddedHeaderSize);
7602 ExpectedMemoryInfo mem1 = GetExpectedMemory(kPaddedStringSize);
7605 expected.set_bucket_size.Init(kBucketId, kSourceSize);
7606 expected.set_bucket_header.Init(
7607 kBucketId, 0, kHeaderSize, mem0.id, mem0.offset);
7608 expected.set_token1.Init(GetNextToken());
7609 expected.set_bucket_data.Init(
7610 kBucketId, kHeaderSize, kStringSize + 1, mem1.id, mem1.offset);
7611 expected.set_token2.Init(GetNextToken());
7612 expected.shader_source_bucket.Init(%(bucket_args)s);
7613 expected.clear_bucket_size.Init(kBucketId, 0);
7614 const char* kStrings[] = { kString };
7615 const GLint kLength[] = { kStringSize };
7616 gl_->%(name)s(%(gl_args)s);
7617 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
7621 for arg
in func
.GetOriginalArgs():
7622 if arg
== self
.__GetDataArg
(func
):
7623 gl_args
.append('kStrings')
7624 elif arg
== self
.__GetLengthArg
(func
):
7625 gl_args
.append('kLength')
7626 elif arg
.name
== 'count':
7629 gl_args
.append(arg
.GetValidClientSideArg(func
))
7632 'gl_args': ", ".join(gl_args
),
7633 'bucket_args': ", ".join(bucket_args
),
7636 def WriteBucketServiceUnitTest(self
, func
, f
, *extras
):
7637 """Overrriden from TypeHandler."""
7639 cmd_args_with_invalid_id
= []
7641 for index
, arg
in enumerate(func
.GetOriginalArgs()):
7642 if arg
== self
.__GetLengthArg
(func
):
7644 elif arg
.name
== 'count':
7646 elif arg
== self
.__GetDataArg
(func
):
7647 cmd_args
.append('kBucketId')
7648 cmd_args_with_invalid_id
.append('kBucketId')
7650 elif index
== 0: # Resource ID arg
7651 cmd_args
.append(arg
.GetValidArg(func
))
7652 cmd_args_with_invalid_id
.append('kInvalidClientId')
7653 gl_args
.append(arg
.GetValidGLArg(func
))
7655 cmd_args
.append(arg
.GetValidArg(func
))
7656 cmd_args_with_invalid_id
.append(arg
.GetValidArg(func
))
7657 gl_args
.append(arg
.GetValidGLArg(func
))
7660 TEST_P(%(test_name)s, %(name)sValidArgs) {
7661 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
7662 const uint32 kBucketId = 123;
7663 const char kSource0[] = "hello";
7664 const char* kSource[] = { kSource0 };
7665 const char kValidStrEnd = 0;
7666 SetBucketAsCStrings(kBucketId, 1, kSource, 1, kValidStrEnd);
7668 cmd.Init(%(cmd_args)s);
7669 decoder_->set_unsafe_es3_apis_enabled(true);
7670 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));"""
7673 decoder_->set_unsafe_es3_apis_enabled(false);
7674 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));
7679 self
.WriteValidUnitTest(func
, f
, test
, {
7680 'cmd_args': ", ".join(cmd_args
),
7681 'gl_args': ", ".join(gl_args
),
7685 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
7686 const uint32 kBucketId = 123;
7687 const char kSource0[] = "hello";
7688 const char* kSource[] = { kSource0 };
7689 const char kValidStrEnd = 0;
7690 decoder_->set_unsafe_es3_apis_enabled(true);
7693 cmd.Init(%(cmd_args)s);
7694 EXPECT_NE(error::kNoError, ExecuteCmd(cmd));
7695 // Test invalid client.
7696 SetBucketAsCStrings(kBucketId, 1, kSource, 1, kValidStrEnd);
7697 cmd.Init(%(cmd_args_with_invalid_id)s);
7698 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
7699 EXPECT_EQ(GL_INVALID_VALUE, GetGLError());
7702 self
.WriteValidUnitTest(func
, f
, test
, {
7703 'cmd_args': ", ".join(cmd_args
),
7704 'cmd_args_with_invalid_id': ", ".join(cmd_args_with_invalid_id
),
7708 TEST_P(%(test_name)s, %(name)sInvalidHeader) {
7709 const uint32 kBucketId = 123;
7710 const char kSource0[] = "hello";
7711 const char* kSource[] = { kSource0 };
7712 const char kValidStrEnd = 0;
7713 const GLsizei kCount = static_cast<GLsizei>(arraysize(kSource));
7714 const GLsizei kTests[] = {
7717 std::numeric_limits<GLsizei>::max(),
7720 decoder_->set_unsafe_es3_apis_enabled(true);
7721 for (size_t ii = 0; ii < arraysize(kTests); ++ii) {
7722 SetBucketAsCStrings(kBucketId, 1, kSource, kTests[ii], kValidStrEnd);
7724 cmd.Init(%(cmd_args)s);
7725 EXPECT_EQ(error::kInvalidArguments, ExecuteCmd(cmd));
7729 self
.WriteValidUnitTest(func
, f
, test
, {
7730 'cmd_args': ", ".join(cmd_args
),
7734 TEST_P(%(test_name)s, %(name)sInvalidStringEnding) {
7735 const uint32 kBucketId = 123;
7736 const char kSource0[] = "hello";
7737 const char* kSource[] = { kSource0 };
7738 const char kInvalidStrEnd = '*';
7739 SetBucketAsCStrings(kBucketId, 1, kSource, 1, kInvalidStrEnd);
7741 cmd.Init(%(cmd_args)s);
7742 decoder_->set_unsafe_es3_apis_enabled(true);
7743 EXPECT_EQ(error::kInvalidArguments, ExecuteCmd(cmd));
7746 self
.WriteValidUnitTest(func
, f
, test
, {
7747 'cmd_args': ", ".join(cmd_args
),
7751 class PUTXnHandler(ArrayArgTypeHandler
):
7752 """Handler for glUniform?f functions."""
7754 def WriteHandlerImplementation(self
, func
, f
):
7755 """Overrriden from TypeHandler."""
7756 code
= """ %(type)s temp[%(count)s] = { %(values)s};
7757 Do%(name)sv(%(location)s, 1, &temp[0]);
7760 args
= func
.GetOriginalArgs()
7761 count
= int(self
.GetArrayCount(func
))
7762 num_args
= len(args
)
7763 for ii
in range(count
):
7764 values
+= "%s, " % args
[len(args
) - count
+ ii
].name
7768 'count': self
.GetArrayCount(func
),
7769 'type': self
.GetArrayType(func
),
7770 'location': args
[0].name
,
7771 'args': func
.MakeOriginalArgString(""),
7775 def WriteServiceUnitTest(self
, func
, f
, *extras
):
7776 """Overrriden from TypeHandler."""
7778 TEST_P(%(test_name)s, %(name)sValidArgs) {
7779 EXPECT_CALL(*gl_, %(name)sv(%(local_args)s));
7780 SpecializedSetup<cmds::%(name)s, 0>(true);
7782 cmd.Init(%(args)s);"""
7785 decoder_->set_unsafe_es3_apis_enabled(true);"""
7787 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
7788 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
7791 decoder_->set_unsafe_es3_apis_enabled(false);
7792 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));"""
7796 args
= func
.GetOriginalArgs()
7797 local_args
= "%s, 1, _" % args
[0].GetValidGLArg(func
)
7798 self
.WriteValidUnitTest(func
, f
, valid_test
, {
7800 'count': self
.GetArrayCount(func
),
7801 'local_args': local_args
,
7805 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
7806 EXPECT_CALL(*gl_, %(name)sv(_, _, _).Times(0);
7807 SpecializedSetup<cmds::%(name)s, 0>(false);
7810 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
7813 self
.WriteInvalidUnitTest(func
, f
, invalid_test
, {
7814 'name': func
.GetInfo('name'),
7815 'count': self
.GetArrayCount(func
),
7819 class GLcharHandler(CustomHandler
):
7820 """Handler for functions that pass a single string ."""
7822 def WriteImmediateCmdComputeSize(self
, func
, f
):
7823 """Overrriden from TypeHandler."""
7824 f
.write(" static uint32_t ComputeSize(uint32_t data_size) {\n")
7825 f
.write(" return static_cast<uint32_t>(\n")
7826 f
.write(" sizeof(ValueType) + data_size); // NOLINT\n")
7829 def WriteImmediateCmdSetHeader(self
, func
, f
):
7830 """Overrriden from TypeHandler."""
7832 void SetHeader(uint32_t data_size) {
7833 header.SetCmdBySize<ValueType>(data_size);
7838 def WriteImmediateCmdInit(self
, func
, f
):
7839 """Overrriden from TypeHandler."""
7840 last_arg
= func
.GetLastOriginalArg()
7841 args
= func
.GetCmdArgs()
7844 set_code
.append(" %s = _%s;" % (arg
.name
, arg
.name
))
7846 void Init(%(typed_args)s, uint32_t _data_size) {
7847 SetHeader(_data_size);
7849 memcpy(ImmediateDataAddress(this), _%(last_arg)s, _data_size);
7854 "typed_args": func
.MakeTypedArgString("_"),
7855 "set_code": "\n".join(set_code
),
7856 "last_arg": last_arg
.name
7859 def WriteImmediateCmdSet(self
, func
, f
):
7860 """Overrriden from TypeHandler."""
7861 last_arg
= func
.GetLastOriginalArg()
7862 f
.write(" void* Set(void* cmd%s, uint32_t _data_size) {\n" %
7863 func
.MakeTypedCmdArgString("_", True))
7864 f
.write(" static_cast<ValueType*>(cmd)->Init(%s, _data_size);\n" %
7865 func
.MakeCmdArgString("_"))
7866 f
.write(" return NextImmediateCmdAddress<ValueType>("
7867 "cmd, _data_size);\n")
7871 def WriteImmediateCmdHelper(self
, func
, f
):
7872 """Overrriden from TypeHandler."""
7873 code
= """ void %(name)s(%(typed_args)s) {
7874 const uint32_t data_size = strlen(name);
7875 gles2::cmds::%(name)s* c =
7876 GetImmediateCmdSpace<gles2::cmds::%(name)s>(data_size);
7878 c->Init(%(args)s, data_size);
7885 "typed_args": func
.MakeTypedOriginalArgString(""),
7886 "args": func
.MakeOriginalArgString(""),
7890 def WriteImmediateFormatTest(self
, func
, f
):
7891 """Overrriden from TypeHandler."""
7894 all_but_last_arg
= func
.GetCmdArgs()[:-1]
7895 for value
, arg
in enumerate(all_but_last_arg
):
7896 init_code
.append(" static_cast<%s>(%d)," % (arg
.type, value
+ 11))
7897 for value
, arg
in enumerate(all_but_last_arg
):
7898 check_code
.append(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);" %
7899 (arg
.type, value
+ 11, arg
.name
))
7901 TEST_F(GLES2FormatTest, %(func_name)s) {
7902 cmds::%(func_name)s& cmd = *GetBufferAs<cmds::%(func_name)s>();
7903 static const char* const test_str = \"test string\";
7904 void* next_cmd = cmd.Set(
7909 EXPECT_EQ(static_cast<uint32_t>(cmds::%(func_name)s::kCmdId),
7910 cmd.header.command);
7911 EXPECT_EQ(sizeof(cmd) +
7912 RoundSizeToMultipleOfEntries(strlen(test_str)),
7913 cmd.header.size * 4u);
7914 EXPECT_EQ(static_cast<char*>(next_cmd),
7915 reinterpret_cast<char*>(&cmd) + sizeof(cmd) +
7916 RoundSizeToMultipleOfEntries(strlen(test_str)));
7918 EXPECT_EQ(static_cast<uint32_t>(strlen(test_str)), cmd.data_size);
7919 EXPECT_EQ(0, memcmp(test_str, ImmediateDataAddress(&cmd), strlen(test_str)));
7922 sizeof(cmd) + RoundSizeToMultipleOfEntries(strlen(test_str)),
7923 sizeof(cmd) + strlen(test_str));
7928 'func_name': func
.name
,
7929 'init_code': "\n".join(init_code
),
7930 'check_code': "\n".join(check_code
),
7934 class GLcharNHandler(CustomHandler
):
7935 """Handler for functions that pass a single string with an optional len."""
7937 def InitFunction(self
, func
):
7938 """Overrriden from TypeHandler."""
7940 func
.AddCmdArg(Argument('bucket_id', 'GLuint'))
7942 def NeedsDataTransferFunction(self
, func
):
7943 """Overriden from TypeHandler."""
7946 def WriteServiceImplementation(self
, func
, f
):
7947 """Overrriden from TypeHandler."""
7948 self
.WriteServiceHandlerFunctionHeader(func
, f
)
7950 GLuint bucket_id = static_cast<GLuint>(c.%(bucket_id)s);
7951 Bucket* bucket = GetBucket(bucket_id);
7952 if (!bucket || bucket->size() == 0) {
7953 return error::kInvalidArguments;
7956 if (!bucket->GetAsString(&str)) {
7957 return error::kInvalidArguments;
7959 %(gl_func_name)s(0, str.c_str());
7960 return error::kNoError;
7965 'gl_func_name': func
.GetGLFunctionName(),
7966 'bucket_id': func
.cmd_args
[0].name
,
7970 class IsHandler(TypeHandler
):
7971 """Handler for glIs____ type and glGetError functions."""
7973 def InitFunction(self
, func
):
7974 """Overrriden from TypeHandler."""
7975 func
.AddCmdArg(Argument("result_shm_id", 'uint32_t'))
7976 func
.AddCmdArg(Argument("result_shm_offset", 'uint32_t'))
7977 if func
.GetInfo('result') == None:
7978 func
.AddInfo('result', ['uint32_t'])
7980 def WriteServiceUnitTest(self
, func
, f
, *extras
):
7981 """Overrriden from TypeHandler."""
7983 TEST_P(%(test_name)s, %(name)sValidArgs) {
7984 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
7985 SpecializedSetup<cmds::%(name)s, 0>(true);
7987 cmd.Init(%(args)s%(comma)sshared_memory_id_, shared_memory_offset_);"""
7990 decoder_->set_unsafe_es3_apis_enabled(true);"""
7992 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
7993 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
7996 decoder_->set_unsafe_es3_apis_enabled(false);
7997 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));"""
8002 if len(func
.GetOriginalArgs()):
8004 self
.WriteValidUnitTest(func
, f
, valid_test
, {
8009 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
8010 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
8011 SpecializedSetup<cmds::%(name)s, 0>(false);
8013 cmd.Init(%(args)s%(comma)sshared_memory_id_, shared_memory_offset_);
8014 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
8017 self
.WriteInvalidUnitTest(func
, f
, invalid_test
, {
8022 TEST_P(%(test_name)s, %(name)sInvalidArgsBadSharedMemoryId) {
8023 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
8024 SpecializedSetup<cmds::%(name)s, 0>(false);"""
8027 decoder_->set_unsafe_es3_apis_enabled(true);"""
8030 cmd.Init(%(args)s%(comma)skInvalidSharedMemoryId, shared_memory_offset_);
8031 EXPECT_EQ(error::kOutOfBounds, ExecuteCmd(cmd));
8032 cmd.Init(%(args)s%(comma)sshared_memory_id_, kInvalidSharedMemoryOffset);
8033 EXPECT_EQ(error::kOutOfBounds, ExecuteCmd(cmd));"""
8036 decoder_->set_unsafe_es3_apis_enabled(true);"""
8040 self
.WriteValidUnitTest(func
, f
, invalid_test
, {
8044 def WriteServiceImplementation(self
, func
, f
):
8045 """Overrriden from TypeHandler."""
8046 self
.WriteServiceHandlerFunctionHeader(func
, f
)
8047 self
.WriteHandlerExtensionCheck(func
, f
)
8048 args
= func
.GetOriginalArgs()
8052 code
= """ typedef cmds::%(func_name)s::Result Result;
8053 Result* result_dst = GetSharedMemoryAs<Result*>(
8054 c.result_shm_id, c.result_shm_offset, sizeof(*result_dst));
8056 return error::kOutOfBounds;
8059 f
.write(code
% {'func_name': func
.name
})
8060 func
.WriteHandlerValidation(f
)
8062 assert func
.GetInfo('id_mapping')
8063 assert len(func
.GetInfo('id_mapping')) == 1
8064 assert len(args
) == 1
8065 id_type
= func
.GetInfo('id_mapping')[0]
8066 f
.write(" %s service_%s = 0;\n" % (args
[0].type, id_type
.lower()))
8067 f
.write(" *result_dst = group_->Get%sServiceId(%s, &service_%s);\n" %
8068 (id_type
, id_type
.lower(), id_type
.lower()))
8070 f
.write(" *result_dst = %s(%s);\n" %
8071 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
8072 f
.write(" return error::kNoError;\n")
8076 def WriteGLES2Implementation(self
, func
, f
):
8077 """Overrriden from TypeHandler."""
8078 impl_func
= func
.GetInfo('impl_func')
8079 if impl_func
== None or impl_func
== True:
8080 error_value
= func
.GetInfo("error_value") or "GL_FALSE"
8081 f
.write("%s GLES2Implementation::%s(%s) {\n" %
8082 (func
.return_type
, func
.original_name
,
8083 func
.MakeTypedOriginalArgString("")))
8084 f
.write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
8085 self
.WriteTraceEvent(func
, f
)
8086 func
.WriteDestinationInitalizationValidation(f
)
8087 self
.WriteClientGLCallLog(func
, f
)
8088 f
.write(" typedef cmds::%s::Result Result;\n" % func
.name
)
8089 f
.write(" Result* result = GetResultAs<Result*>();\n")
8090 f
.write(" if (!result) {\n")
8091 f
.write(" return %s;\n" % error_value
)
8093 f
.write(" *result = 0;\n")
8094 assert len(func
.GetOriginalArgs()) == 1
8095 id_arg
= func
.GetOriginalArgs()[0]
8096 if id_arg
.type == 'GLsync':
8097 arg_string
= "ToGLuint(%s)" % func
.MakeOriginalArgString("")
8099 arg_string
= func
.MakeOriginalArgString("")
8101 " helper_->%s(%s, GetResultShmId(), GetResultShmOffset());\n" %
8102 (func
.name
, arg_string
))
8103 f
.write(" WaitForCmd();\n")
8104 f
.write(" %s result_value = *result" % func
.return_type
)
8105 if func
.return_type
== "GLboolean":
8107 f
.write(';\n GPU_CLIENT_LOG("returned " << result_value);\n')
8108 f
.write(" CheckGLError();\n")
8109 f
.write(" return result_value;\n")
8113 def WriteGLES2ImplementationUnitTest(self
, func
, f
):
8114 """Overrriden from TypeHandler."""
8115 client_test
= func
.GetInfo('client_test')
8116 if client_test
== None or client_test
== True:
8118 TEST_F(GLES2ImplementationTest, %(name)s) {
8124 ExpectedMemoryInfo result1 =
8125 GetExpectedResultMemory(sizeof(cmds::%(name)s::Result));
8126 expected.cmd.Init(%(cmd_id_value)s, result1.id, result1.offset);
8128 EXPECT_CALL(*command_buffer(), OnFlush())
8129 .WillOnce(SetMemory(result1.ptr, uint32_t(GL_TRUE)))
8130 .RetiresOnSaturation();
8132 GLboolean result = gl_->%(name)s(%(gl_id_value)s);
8133 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
8134 EXPECT_TRUE(result);
8137 args
= func
.GetOriginalArgs()
8138 assert len(args
) == 1
8141 'cmd_id_value': args
[0].GetValidClientSideCmdArg(func
),
8142 'gl_id_value': args
[0].GetValidClientSideArg(func
) })
8145 class STRnHandler(TypeHandler
):
8146 """Handler for GetProgramInfoLog, GetShaderInfoLog, GetShaderSource, and
8147 GetTranslatedShaderSourceANGLE."""
8149 def InitFunction(self
, func
):
8150 """Overrriden from TypeHandler."""
8151 # remove all but the first cmd args.
8152 cmd_args
= func
.GetCmdArgs()
8154 func
.AddCmdArg(cmd_args
[0])
8155 # add on a bucket id.
8156 func
.AddCmdArg(Argument('bucket_id', 'uint32_t'))
8158 def WriteGLES2Implementation(self
, func
, f
):
8159 """Overrriden from TypeHandler."""
8160 code_1
= """%(return_type)s GLES2Implementation::%(func_name)s(%(args)s) {
8161 GPU_CLIENT_SINGLE_THREAD_CHECK();
8163 code_2
= """ GPU_CLIENT_LOG("[" << GetLogPrefix()
8164 << "] gl%(func_name)s" << "("
8167 << static_cast<void*>(%(arg2)s) << ", "
8168 << static_cast<void*>(%(arg3)s) << ")");
8169 helper_->SetBucketSize(kResultBucketId, 0);
8170 helper_->%(func_name)s(%(id_name)s, kResultBucketId);
8172 GLsizei max_size = 0;
8173 if (GetBucketAsString(kResultBucketId, &str)) {
8176 std::min(static_cast<size_t>(%(bufsize_name)s) - 1, str.size());
8177 memcpy(%(dest_name)s, str.c_str(), max_size);
8178 %(dest_name)s[max_size] = '\\0';
8179 GPU_CLIENT_LOG("------\\n" << %(dest_name)s << "\\n------");
8182 if (%(length_name)s != NULL) {
8183 *%(length_name)s = max_size;
8188 args
= func
.GetOriginalArgs()
8190 'return_type': func
.return_type
,
8191 'func_name': func
.original_name
,
8192 'args': func
.MakeTypedOriginalArgString(""),
8193 'id_name': args
[0].name
,
8194 'bufsize_name': args
[1].name
,
8195 'length_name': args
[2].name
,
8196 'dest_name': args
[3].name
,
8197 'arg0': args
[0].name
,
8198 'arg1': args
[1].name
,
8199 'arg2': args
[2].name
,
8200 'arg3': args
[3].name
,
8202 f
.write(code_1
% str_args
)
8203 func
.WriteDestinationInitalizationValidation(f
)
8204 f
.write(code_2
% str_args
)
8206 def WriteServiceUnitTest(self
, func
, f
, *extras
):
8207 """Overrriden from TypeHandler."""
8209 TEST_P(%(test_name)s, %(name)sValidArgs) {
8210 const char* kInfo = "hello";
8211 const uint32_t kBucketId = 123;
8212 SpecializedSetup<cmds::%(name)s, 0>(true);
8214 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s))
8215 .WillOnce(DoAll(SetArgumentPointee<2>(strlen(kInfo)),
8216 SetArrayArgument<3>(kInfo, kInfo + strlen(kInfo) + 1)));
8219 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
8220 CommonDecoder::Bucket* bucket = decoder_->GetBucket(kBucketId);
8221 ASSERT_TRUE(bucket != NULL);
8222 EXPECT_EQ(strlen(kInfo) + 1, bucket->size());
8223 EXPECT_EQ(0, memcmp(bucket->GetData(0, bucket->size()), kInfo,
8225 EXPECT_EQ(GL_NO_ERROR, GetGLError());
8228 args
= func
.GetOriginalArgs()
8229 id_name
= args
[0].GetValidGLArg(func
)
8230 get_len_func
= func
.GetInfo('get_len_func')
8231 get_len_enum
= func
.GetInfo('get_len_enum')
8234 'get_len_func': get_len_func
,
8235 'get_len_enum': get_len_enum
,
8236 'gl_args': '%s, strlen(kInfo) + 1, _, _' %
8237 args
[0].GetValidGLArg(func
),
8238 'args': '%s, kBucketId' % args
[0].GetValidArg(func
),
8239 'expect_len_code': '',
8241 if get_len_func
and get_len_func
[0:2] == 'gl':
8242 sub
['expect_len_code'] = (
8243 " EXPECT_CALL(*gl_, %s(%s, %s, _))\n"
8244 " .WillOnce(SetArgumentPointee<2>(strlen(kInfo) + 1));") % (
8245 get_len_func
[2:], id_name
, get_len_enum
)
8246 self
.WriteValidUnitTest(func
, f
, valid_test
, sub
, *extras
)
8249 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
8250 const uint32_t kBucketId = 123;
8251 EXPECT_CALL(*gl_, %(gl_func_name)s(_, _, _, _))
8254 cmd.Init(kInvalidClientId, kBucketId);
8255 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
8256 EXPECT_EQ(GL_INVALID_VALUE, GetGLError());
8259 self
.WriteValidUnitTest(func
, f
, invalid_test
, *extras
)
8261 def WriteServiceImplementation(self
, func
, f
):
8262 """Overrriden from TypeHandler."""
8265 class NamedType(object):
8266 """A class that represents a type of an argument in a client function.
8268 A type of an argument that is to be passed through in the command buffer
8269 command. Currently used only for the arguments that are specificly named in
8270 the 'cmd_buffer_functions.txt' f, mostly enums.
8273 def __init__(self
, info
):
8274 assert not 'is_complete' in info
or info
['is_complete'] == True
8276 self
.valid
= info
['valid']
8277 if 'invalid' in info
:
8278 self
.invalid
= info
['invalid']
8281 if 'valid_es3' in info
:
8282 self
.valid_es3
= info
['valid_es3']
8285 if 'deprecated_es3' in info
:
8286 self
.deprecated_es3
= info
['deprecated_es3']
8288 self
.deprecated_es3
= []
8291 return self
.info
['type']
8293 def GetInvalidValues(self
):
8296 def GetValidValues(self
):
8299 def GetValidValuesES3(self
):
8300 return self
.valid_es3
8302 def GetDeprecatedValuesES3(self
):
8303 return self
.deprecated_es3
8305 def IsConstant(self
):
8306 if not 'is_complete' in self
.info
:
8309 return len(self
.GetValidValues()) == 1
8311 def GetConstantValue(self
):
8312 return self
.GetValidValues()[0]
8314 class Argument(object):
8315 """A class that represents a function argument."""
8318 'GLenum': 'uint32_t',
8320 'GLintptr': 'int32_t',
8321 'GLsizei': 'int32_t',
8322 'GLsizeiptr': 'int32_t',
8324 'GLclampf': 'float',
8326 need_validation_
= ['GLsizei*', 'GLboolean*', 'GLenum*', 'GLint*']
8328 def __init__(self
, name
, type):
8330 self
.optional
= type.endswith("Optional*")
8332 type = type[:-9] + "*"
8335 if type in self
.cmd_type_map_
:
8336 self
.cmd_type
= self
.cmd_type_map_
[type]
8338 self
.cmd_type
= 'uint32_t'
8340 def IsPointer(self
):
8341 """Returns true if argument is a pointer."""
8344 def IsPointer2D(self
):
8345 """Returns true if argument is a 2D pointer."""
8348 def IsConstant(self
):
8349 """Returns true if the argument has only one valid value."""
8352 def AddCmdArgs(self
, args
):
8353 """Adds command arguments for this argument to the given list."""
8354 if not self
.IsConstant():
8355 return args
.append(self
)
8357 def AddInitArgs(self
, args
):
8358 """Adds init arguments for this argument to the given list."""
8359 if not self
.IsConstant():
8360 return args
.append(self
)
8362 def GetValidArg(self
, func
):
8363 """Gets a valid value for this argument."""
8364 valid_arg
= func
.GetValidArg(self
)
8365 if valid_arg
!= None:
8368 index
= func
.GetOriginalArgs().index(self
)
8369 return str(index
+ 1)
8371 def GetValidClientSideArg(self
, func
):
8372 """Gets a valid value for this argument."""
8373 valid_arg
= func
.GetValidArg(self
)
8374 if valid_arg
!= None:
8377 if self
.IsPointer():
8379 index
= func
.GetOriginalArgs().index(self
)
8380 if self
.type == 'GLsync':
8381 return ("reinterpret_cast<GLsync>(%d)" % (index
+ 1))
8382 return str(index
+ 1)
8384 def GetValidClientSideCmdArg(self
, func
):
8385 """Gets a valid value for this argument."""
8386 valid_arg
= func
.GetValidArg(self
)
8387 if valid_arg
!= None:
8390 index
= func
.GetOriginalArgs().index(self
)
8391 return str(index
+ 1)
8394 index
= func
.GetCmdArgs().index(self
)
8395 return str(index
+ 1)
8397 def GetValidGLArg(self
, func
):
8398 """Gets a valid GL value for this argument."""
8399 value
= self
.GetValidArg(func
)
8400 if self
.type == 'GLsync':
8401 return ("reinterpret_cast<GLsync>(%s)" % value
)
8404 def GetValidNonCachedClientSideArg(self
, func
):
8405 """Returns a valid value for this argument in a GL call.
8406 Using the value will produce a command buffer service invocation.
8407 Returns None if there is no such value."""
8409 if self
.type == 'GLsync':
8410 return ("reinterpret_cast<GLsync>(%s)" % value
)
8413 def GetValidNonCachedClientSideCmdArg(self
, func
):
8414 """Returns a valid value for this argument in a command buffer command.
8415 Calling the GL function with the value returned by
8416 GetValidNonCachedClientSideArg will result in a command buffer command
8417 that contains the value returned by this function. """
8420 def GetNumInvalidValues(self
, func
):
8421 """returns the number of invalid values to be tested."""
8424 def GetInvalidArg(self
, index
):
8425 """returns an invalid value and expected parse result by index."""
8426 return ("---ERROR0---", "---ERROR2---", None)
8428 def GetLogArg(self
):
8429 """Get argument appropriate for LOG macro."""
8430 if self
.type == 'GLboolean':
8431 return 'GLES2Util::GetStringBool(%s)' % self
.name
8432 if self
.type == 'GLenum':
8433 return 'GLES2Util::GetStringEnum(%s)' % self
.name
8436 def WriteGetCode(self
, f
):
8437 """Writes the code to get an argument from a command structure."""
8438 if self
.type == 'GLsync':
8442 f
.write(" %s %s = static_cast<%s>(c.%s);\n" %
8443 (my_type
, self
.name
, my_type
, self
.name
))
8445 def WriteValidationCode(self
, f
, func
):
8446 """Writes the validation code for an argument."""
8449 def WriteClientSideValidationCode(self
, f
, func
):
8450 """Writes the validation code for an argument."""
8453 def WriteDestinationInitalizationValidation(self
, f
, func
):
8454 """Writes the client side destintion initialization validation."""
8457 def WriteDestinationInitalizationValidatationIfNeeded(self
, f
, func
):
8458 """Writes the client side destintion initialization validation if needed."""
8459 parts
= self
.type.split(" ")
8462 if parts
[0] in self
.need_validation_
:
8464 " GPU_CLIENT_VALIDATE_DESTINATION_%sINITALIZATION(%s, %s);\n" %
8465 ("OPTIONAL_" if self
.optional
else "", self
.type[:-1], self
.name
))
8467 def GetImmediateVersion(self
):
8468 """Gets the immediate version of this argument."""
8471 def GetBucketVersion(self
):
8472 """Gets the bucket version of this argument."""
8476 class BoolArgument(Argument
):
8477 """class for GLboolean"""
8479 def __init__(self
, name
, type):
8480 Argument
.__init
__(self
, name
, 'GLboolean')
8482 def GetValidArg(self
, func
):
8483 """Gets a valid value for this argument."""
8486 def GetValidClientSideArg(self
, func
):
8487 """Gets a valid value for this argument."""
8490 def GetValidClientSideCmdArg(self
, func
):
8491 """Gets a valid value for this argument."""
8494 def GetValidGLArg(self
, func
):
8495 """Gets a valid GL value for this argument."""
8499 class UniformLocationArgument(Argument
):
8500 """class for uniform locations."""
8502 def __init__(self
, name
):
8503 Argument
.__init
__(self
, name
, "GLint")
8505 def WriteGetCode(self
, f
):
8506 """Writes the code to get an argument from a command structure."""
8507 code
= """ %s %s = static_cast<%s>(c.%s);
8509 f
.write(code
% (self
.type, self
.name
, self
.type, self
.name
))
8511 class DataSizeArgument(Argument
):
8512 """class for data_size which Bucket commands do not need."""
8514 def __init__(self
, name
):
8515 Argument
.__init
__(self
, name
, "uint32_t")
8517 def GetBucketVersion(self
):
8521 class SizeArgument(Argument
):
8522 """class for GLsizei and GLsizeiptr."""
8524 def GetNumInvalidValues(self
, func
):
8525 """overridden from Argument."""
8526 if func
.IsImmediate():
8530 def GetInvalidArg(self
, index
):
8531 """overridden from Argument."""
8532 return ("-1", "kNoError", "GL_INVALID_VALUE")
8534 def WriteValidationCode(self
, f
, func
):
8535 """overridden from Argument."""
8538 code
= """ if (%(var_name)s < 0) {
8539 LOCAL_SET_GL_ERROR(GL_INVALID_VALUE, "gl%(func_name)s", "%(var_name)s < 0");
8540 return error::kNoError;
8544 "var_name": self
.name
,
8545 "func_name": func
.original_name
,
8548 def WriteClientSideValidationCode(self
, f
, func
):
8549 """overridden from Argument."""
8550 code
= """ if (%(var_name)s < 0) {
8551 SetGLError(GL_INVALID_VALUE, "gl%(func_name)s", "%(var_name)s < 0");
8556 "var_name": self
.name
,
8557 "func_name": func
.original_name
,
8561 class SizeNotNegativeArgument(SizeArgument
):
8562 """class for GLsizeiNotNegative. It's NEVER allowed to be negative"""
8564 def __init__(self
, name
, type, gl_type
):
8565 SizeArgument
.__init
__(self
, name
, gl_type
)
8567 def GetInvalidArg(self
, index
):
8568 """overridden from SizeArgument."""
8569 return ("-1", "kOutOfBounds", "GL_NO_ERROR")
8571 def WriteValidationCode(self
, f
, func
):
8572 """overridden from SizeArgument."""
8576 class EnumBaseArgument(Argument
):
8577 """Base class for EnumArgument, IntArgument, BitfieldArgument, and
8578 ValidatedBoolArgument."""
8580 def __init__(self
, name
, gl_type
, type, gl_error
):
8581 Argument
.__init
__(self
, name
, gl_type
)
8583 self
.gl_error
= gl_error
8584 name
= type[len(gl_type
):]
8585 self
.type_name
= name
8586 self
.named_type
= NamedType(_NAMED_TYPE_INFO
[name
])
8588 def IsConstant(self
):
8589 return self
.named_type
.IsConstant()
8591 def GetConstantValue(self
):
8592 return self
.named_type
.GetConstantValue()
8594 def WriteValidationCode(self
, f
, func
):
8597 if self
.named_type
.IsConstant():
8599 f
.write(" if (!validators_->%s.IsValid(%s)) {\n" %
8600 (ToUnderscore(self
.type_name
), self
.name
))
8601 if self
.gl_error
== "GL_INVALID_ENUM":
8603 " LOCAL_SET_GL_ERROR_INVALID_ENUM(\"gl%s\", %s, \"%s\");\n" %
8604 (func
.original_name
, self
.name
, self
.name
))
8607 " LOCAL_SET_GL_ERROR(%s, \"gl%s\", \"%s %s\");\n" %
8608 (self
.gl_error
, func
.original_name
, self
.name
, self
.gl_error
))
8609 f
.write(" return error::kNoError;\n")
8612 def WriteClientSideValidationCode(self
, f
, func
):
8613 if not self
.named_type
.IsConstant():
8615 f
.write(" if (%s != %s) {" % (self
.name
,
8616 self
.GetConstantValue()))
8618 " SetGLError(%s, \"gl%s\", \"%s %s\");\n" %
8619 (self
.gl_error
, func
.original_name
, self
.name
, self
.gl_error
))
8620 if func
.return_type
== "void":
8621 f
.write(" return;\n")
8623 f
.write(" return %s;\n" % func
.GetErrorReturnString())
8626 def GetValidArg(self
, func
):
8627 valid_arg
= func
.GetValidArg(self
)
8628 if valid_arg
!= None:
8630 valid
= self
.named_type
.GetValidValues()
8634 index
= func
.GetOriginalArgs().index(self
)
8635 return str(index
+ 1)
8637 def GetValidClientSideArg(self
, func
):
8638 """Gets a valid value for this argument."""
8639 return self
.GetValidArg(func
)
8641 def GetValidClientSideCmdArg(self
, func
):
8642 """Gets a valid value for this argument."""
8643 valid_arg
= func
.GetValidArg(self
)
8644 if valid_arg
!= None:
8647 valid
= self
.named_type
.GetValidValues()
8652 index
= func
.GetOriginalArgs().index(self
)
8653 return str(index
+ 1)
8656 index
= func
.GetCmdArgs().index(self
)
8657 return str(index
+ 1)
8659 def GetValidGLArg(self
, func
):
8660 """Gets a valid value for this argument."""
8661 return self
.GetValidArg(func
)
8663 def GetNumInvalidValues(self
, func
):
8664 """returns the number of invalid values to be tested."""
8665 return len(self
.named_type
.GetInvalidValues())
8667 def GetInvalidArg(self
, index
):
8668 """returns an invalid value by index."""
8669 invalid
= self
.named_type
.GetInvalidValues()
8671 num_invalid
= len(invalid
)
8672 if index
>= num_invalid
:
8673 index
= num_invalid
- 1
8674 return (invalid
[index
], "kNoError", self
.gl_error
)
8675 return ("---ERROR1---", "kNoError", self
.gl_error
)
8678 class EnumArgument(EnumBaseArgument
):
8679 """A class that represents a GLenum argument"""
8681 def __init__(self
, name
, type):
8682 EnumBaseArgument
.__init
__(self
, name
, "GLenum", type, "GL_INVALID_ENUM")
8684 def GetLogArg(self
):
8685 """Overridden from Argument."""
8686 return ("GLES2Util::GetString%s(%s)" %
8687 (self
.type_name
, self
.name
))
8690 class IntArgument(EnumBaseArgument
):
8691 """A class for a GLint argument that can only accept specific values.
8693 For example glTexImage2D takes a GLint for its internalformat
8694 argument instead of a GLenum.
8697 def __init__(self
, name
, type):
8698 EnumBaseArgument
.__init
__(self
, name
, "GLint", type, "GL_INVALID_VALUE")
8701 class ValidatedBoolArgument(EnumBaseArgument
):
8702 """A class for a GLboolean argument that can only accept specific values.
8704 For example glUniformMatrix takes a GLboolean for it's transpose but it
8708 def __init__(self
, name
, type):
8709 EnumBaseArgument
.__init
__(self
, name
, "GLboolean", type, "GL_INVALID_VALUE")
8711 def GetLogArg(self
):
8712 """Overridden from Argument."""
8713 return 'GLES2Util::GetStringBool(%s)' % self
.name
8716 class BitFieldArgument(EnumBaseArgument
):
8717 """A class for a GLbitfield argument that can only accept specific values.
8719 For example glFenceSync takes a GLbitfield for its flags argument bit it
8723 def __init__(self
, name
, type):
8724 EnumBaseArgument
.__init
__(self
, name
, "GLbitfield", type,
8728 class ImmediatePointerArgument(Argument
):
8729 """A class that represents an immediate argument to a function.
8731 An immediate argument is one where the data follows the command.
8734 def IsPointer(self
):
8737 def GetPointedType(self
):
8738 match
= re
.match('(const\s+)?(?P<element_type>[\w]+)\s*\*', self
.type)
8740 return match
.groupdict()['element_type']
8742 def AddCmdArgs(self
, args
):
8743 """Overridden from Argument."""
8746 def WriteGetCode(self
, f
):
8747 """Overridden from Argument."""
8749 " %s %s = GetImmediateDataAs<%s>(\n" %
8750 (self
.type, self
.name
, self
.type))
8751 f
.write(" c, data_size, immediate_data_size);\n")
8753 def WriteValidationCode(self
, f
, func
):
8754 """Overridden from Argument."""
8757 f
.write(" if (%s == NULL) {\n" % self
.name
)
8758 f
.write(" return error::kOutOfBounds;\n")
8761 def GetImmediateVersion(self
):
8762 """Overridden from Argument."""
8765 def WriteDestinationInitalizationValidation(self
, f
, func
):
8766 """Overridden from Argument."""
8767 self
.WriteDestinationInitalizationValidatationIfNeeded(f
, func
)
8769 def GetLogArg(self
):
8770 """Overridden from Argument."""
8771 return "static_cast<const void*>(%s)" % self
.name
8774 class PointerArgument(Argument
):
8775 """A class that represents a pointer argument to a function."""
8777 def IsPointer(self
):
8778 """Overridden from Argument."""
8781 def IsPointer2D(self
):
8782 """Overridden from Argument."""
8783 return self
.type.count('*') == 2
8785 def GetPointedType(self
):
8786 match
= re
.match('(const\s+)?(?P<element_type>[\w]+)\s*\*', self
.type)
8788 return match
.groupdict()['element_type']
8790 def GetValidArg(self
, func
):
8791 """Overridden from Argument."""
8792 return "shared_memory_id_, shared_memory_offset_"
8794 def GetValidGLArg(self
, func
):
8795 """Overridden from Argument."""
8796 return "reinterpret_cast<%s>(shared_memory_address_)" % self
.type
8798 def GetNumInvalidValues(self
, func
):
8799 """Overridden from Argument."""
8802 def GetInvalidArg(self
, index
):
8803 """Overridden from Argument."""
8805 return ("kInvalidSharedMemoryId, 0", "kOutOfBounds", None)
8807 return ("shared_memory_id_, kInvalidSharedMemoryOffset",
8808 "kOutOfBounds", None)
8810 def GetLogArg(self
):
8811 """Overridden from Argument."""
8812 return "static_cast<const void*>(%s)" % self
.name
8814 def AddCmdArgs(self
, args
):
8815 """Overridden from Argument."""
8816 args
.append(Argument("%s_shm_id" % self
.name
, 'uint32_t'))
8817 args
.append(Argument("%s_shm_offset" % self
.name
, 'uint32_t'))
8819 def WriteGetCode(self
, f
):
8820 """Overridden from Argument."""
8822 " %s %s = GetSharedMemoryAs<%s>(\n" %
8823 (self
.type, self
.name
, self
.type))
8825 " c.%s_shm_id, c.%s_shm_offset, data_size);\n" %
8826 (self
.name
, self
.name
))
8828 def WriteValidationCode(self
, f
, func
):
8829 """Overridden from Argument."""
8832 f
.write(" if (%s == NULL) {\n" % self
.name
)
8833 f
.write(" return error::kOutOfBounds;\n")
8836 def GetImmediateVersion(self
):
8837 """Overridden from Argument."""
8838 return ImmediatePointerArgument(self
.name
, self
.type)
8840 def GetBucketVersion(self
):
8841 """Overridden from Argument."""
8842 if self
.type.find('char') >= 0:
8843 if self
.IsPointer2D():
8844 return InputStringArrayBucketArgument(self
.name
, self
.type)
8845 return InputStringBucketArgument(self
.name
, self
.type)
8846 return BucketPointerArgument(self
.name
, self
.type)
8848 def WriteDestinationInitalizationValidation(self
, f
, func
):
8849 """Overridden from Argument."""
8850 self
.WriteDestinationInitalizationValidatationIfNeeded(f
, func
)
8853 class BucketPointerArgument(PointerArgument
):
8854 """A class that represents an bucket argument to a function."""
8856 def AddCmdArgs(self
, args
):
8857 """Overridden from Argument."""
8860 def WriteGetCode(self
, f
):
8861 """Overridden from Argument."""
8863 " %s %s = bucket->GetData(0, data_size);\n" %
8864 (self
.type, self
.name
))
8866 def WriteValidationCode(self
, f
, func
):
8867 """Overridden from Argument."""
8870 def GetImmediateVersion(self
):
8871 """Overridden from Argument."""
8874 def WriteDestinationInitalizationValidation(self
, f
, func
):
8875 """Overridden from Argument."""
8876 self
.WriteDestinationInitalizationValidatationIfNeeded(f
, func
)
8878 def GetLogArg(self
):
8879 """Overridden from Argument."""
8880 return "static_cast<const void*>(%s)" % self
.name
8883 class InputStringBucketArgument(Argument
):
8884 """A string input argument where the string is passed in a bucket."""
8886 def __init__(self
, name
, type):
8887 Argument
.__init
__(self
, name
+ "_bucket_id", "uint32_t")
8889 def IsPointer(self
):
8890 """Overridden from Argument."""
8893 def IsPointer2D(self
):
8894 """Overridden from Argument."""
8898 class InputStringArrayBucketArgument(Argument
):
8899 """A string array input argument where the strings are passed in a bucket."""
8901 def __init__(self
, name
, type):
8902 Argument
.__init
__(self
, name
+ "_bucket_id", "uint32_t")
8903 self
._original
_name
= name
8905 def WriteGetCode(self
, f
):
8906 """Overridden from Argument."""
8908 Bucket* bucket = GetBucket(c.%(name)s);
8910 return error::kInvalidArguments;
8913 std::vector<char*> strs;
8914 std::vector<GLint> len;
8915 if (!bucket->GetAsStrings(&count, &strs, &len)) {
8916 return error::kInvalidArguments;
8918 const char** %(original_name)s =
8919 strs.size() > 0 ? const_cast<const char**>(&strs[0]) : NULL;
8920 const GLint* length =
8921 len.size() > 0 ? const_cast<const GLint*>(&len[0]) : NULL;
8926 'original_name': self
._original
_name
,
8929 def GetValidArg(self
, func
):
8930 return "kNameBucketId"
8932 def GetValidGLArg(self
, func
):
8935 def IsPointer(self
):
8936 """Overridden from Argument."""
8939 def IsPointer2D(self
):
8940 """Overridden from Argument."""
8944 class ResourceIdArgument(Argument
):
8945 """A class that represents a resource id argument to a function."""
8947 def __init__(self
, name
, type):
8948 match
= re
.match("(GLid\w+)", type)
8949 self
.resource_type
= match
.group(1)[4:]
8950 if self
.resource_type
== "Sync":
8951 type = type.replace(match
.group(1), "GLsync")
8953 type = type.replace(match
.group(1), "GLuint")
8954 Argument
.__init
__(self
, name
, type)
8956 def WriteGetCode(self
, f
):
8957 """Overridden from Argument."""
8958 if self
.type == "GLsync":
8962 f
.write(" %s %s = c.%s;\n" % (my_type
, self
.name
, self
.name
))
8964 def GetValidArg(self
, func
):
8965 return "client_%s_id_" % self
.resource_type
.lower()
8967 def GetValidGLArg(self
, func
):
8968 if self
.resource_type
== "Sync":
8969 return "reinterpret_cast<GLsync>(kService%sId)" % self
.resource_type
8970 return "kService%sId" % self
.resource_type
8973 class ResourceIdBindArgument(Argument
):
8974 """Represents a resource id argument to a bind function."""
8976 def __init__(self
, name
, type):
8977 match
= re
.match("(GLidBind\w+)", type)
8978 self
.resource_type
= match
.group(1)[8:]
8979 type = type.replace(match
.group(1), "GLuint")
8980 Argument
.__init
__(self
, name
, type)
8982 def WriteGetCode(self
, f
):
8983 """Overridden from Argument."""
8984 code
= """ %(type)s %(name)s = c.%(name)s;
8986 f
.write(code
% {'type': self
.type, 'name': self
.name
})
8988 def GetValidArg(self
, func
):
8989 return "client_%s_id_" % self
.resource_type
.lower()
8991 def GetValidGLArg(self
, func
):
8992 return "kService%sId" % self
.resource_type
8995 class ResourceIdZeroArgument(Argument
):
8996 """Represents a resource id argument to a function that can be zero."""
8998 def __init__(self
, name
, type):
8999 match
= re
.match("(GLidZero\w+)", type)
9000 self
.resource_type
= match
.group(1)[8:]
9001 type = type.replace(match
.group(1), "GLuint")
9002 Argument
.__init
__(self
, name
, type)
9004 def WriteGetCode(self
, f
):
9005 """Overridden from Argument."""
9006 f
.write(" %s %s = c.%s;\n" % (self
.type, self
.name
, self
.name
))
9008 def GetValidArg(self
, func
):
9009 return "client_%s_id_" % self
.resource_type
.lower()
9011 def GetValidGLArg(self
, func
):
9012 return "kService%sId" % self
.resource_type
9014 def GetNumInvalidValues(self
, func
):
9015 """returns the number of invalid values to be tested."""
9018 def GetInvalidArg(self
, index
):
9019 """returns an invalid value by index."""
9020 return ("kInvalidClientId", "kNoError", "GL_INVALID_VALUE")
9023 class Function(object):
9024 """A class that represents a function."""
9028 'Bind': BindHandler(),
9029 'Create': CreateHandler(),
9030 'Custom': CustomHandler(),
9031 'Data': DataHandler(),
9032 'Delete': DeleteHandler(),
9033 'DELn': DELnHandler(),
9034 'GENn': GENnHandler(),
9035 'GETn': GETnHandler(),
9036 'GLchar': GLcharHandler(),
9037 'GLcharN': GLcharNHandler(),
9038 'HandWritten': HandWrittenHandler(),
9040 'Manual': ManualHandler(),
9041 'PUT': PUTHandler(),
9042 'PUTn': PUTnHandler(),
9043 'PUTSTR': PUTSTRHandler(),
9044 'PUTXn': PUTXnHandler(),
9045 'StateSet': StateSetHandler(),
9046 'StateSetRGBAlpha': StateSetRGBAlphaHandler(),
9047 'StateSetFrontBack': StateSetFrontBackHandler(),
9048 'StateSetFrontBackSeparate': StateSetFrontBackSeparateHandler(),
9049 'StateSetNamedParameter': StateSetNamedParameter(),
9050 'STRn': STRnHandler(),
9053 def __init__(self
, name
, info
):
9055 self
.original_name
= info
['original_name']
9057 self
.original_args
= self
.ParseArgs(info
['original_args'])
9059 if 'cmd_args' in info
:
9060 self
.args_for_cmds
= self
.ParseArgs(info
['cmd_args'])
9062 self
.args_for_cmds
= self
.original_args
[:]
9064 self
.return_type
= info
['return_type']
9065 if self
.return_type
!= 'void':
9066 self
.return_arg
= CreateArg(info
['return_type'] + " result")
9068 self
.return_arg
= None
9070 self
.num_pointer_args
= sum(
9071 [1 for arg
in self
.args_for_cmds
if arg
.IsPointer()])
9072 if self
.num_pointer_args
> 0:
9073 for arg
in reversed(self
.original_args
):
9075 self
.last_original_pointer_arg
= arg
9078 self
.last_original_pointer_arg
= None
9080 self
.type_handler
= self
.type_handlers
[info
['type']]
9081 self
.can_auto_generate
= (self
.num_pointer_args
== 0 and
9082 info
['return_type'] == "void")
9085 def ParseArgs(self
, arg_string
):
9086 """Parses a function arg string."""
9088 parts
= arg_string
.split(',')
9089 for arg_string
in parts
:
9090 arg
= CreateArg(arg_string
)
9095 def IsType(self
, type_name
):
9096 """Returns true if function is a certain type."""
9097 return self
.info
['type'] == type_name
9099 def InitFunction(self
):
9100 """Creates command args and calls the init function for the type handler.
9102 Creates argument lists for command buffer commands, eg. self.cmd_args and
9104 Calls the type function initialization.
9105 Override to create different kind of command buffer command argument lists.
9108 for arg
in self
.args_for_cmds
:
9109 arg
.AddCmdArgs(self
.cmd_args
)
9112 for arg
in self
.args_for_cmds
:
9113 arg
.AddInitArgs(self
.init_args
)
9116 self
.init_args
.append(self
.return_arg
)
9118 self
.type_handler
.InitFunction(self
)
9120 def IsImmediate(self
):
9121 """Returns whether the function is immediate data function or not."""
9125 """Returns whether the function has service side validation or not."""
9126 return self
.GetInfo('unsafe', False)
9128 def GetInfo(self
, name
, default
= None):
9129 """Returns a value from the function info for this function."""
9130 if name
in self
.info
:
9131 return self
.info
[name
]
9134 def GetValidArg(self
, arg
):
9135 """Gets a valid argument value for the parameter arg from the function info
9138 index
= self
.GetOriginalArgs().index(arg
)
9142 valid_args
= self
.GetInfo('valid_args')
9143 if valid_args
and str(index
) in valid_args
:
9144 return valid_args
[str(index
)]
9147 def AddInfo(self
, name
, value
):
9149 self
.info
[name
] = value
9151 def IsExtension(self
):
9152 return self
.GetInfo('extension') or self
.GetInfo('extension_flag')
9154 def IsCoreGLFunction(self
):
9155 return (not self
.IsExtension() and
9156 not self
.GetInfo('pepper_interface') and
9157 not self
.IsUnsafe())
9159 def InPepperInterface(self
, interface
):
9160 ext
= self
.GetInfo('pepper_interface')
9161 if not interface
.GetName():
9162 return self
.IsCoreGLFunction()
9163 return ext
== interface
.GetName()
9165 def InAnyPepperExtension(self
):
9166 return self
.IsCoreGLFunction() or self
.GetInfo('pepper_interface')
9168 def GetErrorReturnString(self
):
9169 if self
.GetInfo("error_return"):
9170 return self
.GetInfo("error_return")
9171 elif self
.return_type
== "GLboolean":
9173 elif "*" in self
.return_type
:
9177 def GetGLFunctionName(self
):
9178 """Gets the function to call to execute GL for this command."""
9179 if self
.GetInfo('decoder_func'):
9180 return self
.GetInfo('decoder_func')
9181 return "gl%s" % self
.original_name
9183 def GetGLTestFunctionName(self
):
9184 gl_func_name
= self
.GetInfo('gl_test_func')
9185 if gl_func_name
== None:
9186 gl_func_name
= self
.GetGLFunctionName()
9187 if gl_func_name
.startswith("gl"):
9188 gl_func_name
= gl_func_name
[2:]
9190 gl_func_name
= self
.original_name
9193 def GetDataTransferMethods(self
):
9194 return self
.GetInfo('data_transfer_methods',
9195 ['immediate' if self
.num_pointer_args
== 1 else 'shm'])
9197 def AddCmdArg(self
, arg
):
9198 """Adds a cmd argument to this function."""
9199 self
.cmd_args
.append(arg
)
9201 def GetCmdArgs(self
):
9202 """Gets the command args for this function."""
9203 return self
.cmd_args
9205 def ClearCmdArgs(self
):
9206 """Clears the command args for this function."""
9209 def GetCmdConstants(self
):
9210 """Gets the constants for this function."""
9211 return [arg
for arg
in self
.args_for_cmds
if arg
.IsConstant()]
9213 def GetInitArgs(self
):
9214 """Gets the init args for this function."""
9215 return self
.init_args
9217 def GetOriginalArgs(self
):
9218 """Gets the original arguments to this function."""
9219 return self
.original_args
9221 def GetLastOriginalArg(self
):
9222 """Gets the last original argument to this function."""
9223 return self
.original_args
[len(self
.original_args
) - 1]
9225 def GetLastOriginalPointerArg(self
):
9226 return self
.last_original_pointer_arg
9228 def GetResourceIdArg(self
):
9229 for arg
in self
.original_args
:
9230 if hasattr(arg
, 'resource_type'):
9234 def _MaybePrependComma(self
, arg_string
, add_comma
):
9235 """Adds a comma if arg_string is not empty and add_comma is true."""
9237 if add_comma
and len(arg_string
):
9239 return "%s%s" % (comma
, arg_string
)
9241 def MakeTypedOriginalArgString(self
, prefix
, add_comma
= False):
9242 """Gets a list of arguments as they are in GL."""
9243 args
= self
.GetOriginalArgs()
9244 arg_string
= ", ".join(
9245 ["%s %s%s" % (arg
.type, prefix
, arg
.name
) for arg
in args
])
9246 return self
._MaybePrependComma
(arg_string
, add_comma
)
9248 def MakeOriginalArgString(self
, prefix
, add_comma
= False, separator
= ", "):
9249 """Gets the list of arguments as they are in GL."""
9250 args
= self
.GetOriginalArgs()
9251 arg_string
= separator
.join(
9252 ["%s%s" % (prefix
, arg
.name
) for arg
in args
])
9253 return self
._MaybePrependComma
(arg_string
, add_comma
)
9255 def MakeHelperArgString(self
, prefix
, add_comma
= False, separator
= ", "):
9256 """Gets a list of GL arguments after removing unneeded arguments."""
9257 args
= self
.GetOriginalArgs()
9258 arg_string
= separator
.join(
9259 ["%s%s" % (prefix
, arg
.name
)
9260 for arg
in args
if not arg
.IsConstant()])
9261 return self
._MaybePrependComma
(arg_string
, add_comma
)
9263 def MakeTypedPepperArgString(self
, prefix
):
9264 """Gets a list of arguments as they need to be for Pepper."""
9265 if self
.GetInfo("pepper_args"):
9266 return self
.GetInfo("pepper_args")
9268 return self
.MakeTypedOriginalArgString(prefix
, False)
9270 def MapCTypeToPepperIdlType(self
, ctype
, is_for_return_type
=False):
9271 """Converts a C type name to the corresponding Pepper IDL type."""
9273 'char*': '[out] str_t',
9274 'const GLchar* const*': '[out] cstr_t',
9275 'const char*': 'cstr_t',
9276 'const void*': 'mem_t',
9277 'void*': '[out] mem_t',
9278 'void**': '[out] mem_ptr_t',
9280 # We use "GLxxx_ptr_t" for "GLxxx*".
9281 matched
= re
.match(r
'(const )?(GL\w+)\*$', ctype
)
9283 idltype
= matched
.group(2) + '_ptr_t'
9284 if not matched
.group(1):
9285 idltype
= '[out] ' + idltype
9286 # If an in/out specifier is not specified yet, prepend [in].
9287 if idltype
[0] != '[':
9288 idltype
= '[in] ' + idltype
9289 # Strip the in/out specifier for a return type.
9290 if is_for_return_type
:
9291 idltype
= re
.sub(r
'\[\w+\] ', '', idltype
)
9294 def MakeTypedPepperIdlArgStrings(self
):
9295 """Gets a list of arguments as they need to be for Pepper IDL."""
9296 args
= self
.GetOriginalArgs()
9297 return ["%s %s" % (self
.MapCTypeToPepperIdlType(arg
.type), arg
.name
)
9300 def GetPepperName(self
):
9301 if self
.GetInfo("pepper_name"):
9302 return self
.GetInfo("pepper_name")
9305 def MakeTypedCmdArgString(self
, prefix
, add_comma
= False):
9306 """Gets a typed list of arguments as they need to be for command buffers."""
9307 args
= self
.GetCmdArgs()
9308 arg_string
= ", ".join(
9309 ["%s %s%s" % (arg
.type, prefix
, arg
.name
) for arg
in args
])
9310 return self
._MaybePrependComma
(arg_string
, add_comma
)
9312 def MakeCmdArgString(self
, prefix
, add_comma
= False):
9313 """Gets the list of arguments as they need to be for command buffers."""
9314 args
= self
.GetCmdArgs()
9315 arg_string
= ", ".join(
9316 ["%s%s" % (prefix
, arg
.name
) for arg
in args
])
9317 return self
._MaybePrependComma
(arg_string
, add_comma
)
9319 def MakeTypedInitString(self
, prefix
, add_comma
= False):
9320 """Gets a typed list of arguments as they need to be for cmd Init/Set."""
9321 args
= self
.GetInitArgs()
9322 arg_string
= ", ".join(
9323 ["%s %s%s" % (arg
.type, prefix
, arg
.name
) for arg
in args
])
9324 return self
._MaybePrependComma
(arg_string
, add_comma
)
9326 def MakeInitString(self
, prefix
, add_comma
= False):
9327 """Gets the list of arguments as they need to be for cmd Init/Set."""
9328 args
= self
.GetInitArgs()
9329 arg_string
= ", ".join(
9330 ["%s%s" % (prefix
, arg
.name
) for arg
in args
])
9331 return self
._MaybePrependComma
(arg_string
, add_comma
)
9333 def MakeLogArgString(self
):
9334 """Makes a string of the arguments for the LOG macros"""
9335 args
= self
.GetOriginalArgs()
9336 return ' << ", " << '.join([arg
.GetLogArg() for arg
in args
])
9338 def WriteHandlerValidation(self
, f
):
9339 """Writes validation code for the function."""
9340 for arg
in self
.GetOriginalArgs():
9341 arg
.WriteValidationCode(f
, self
)
9342 self
.WriteValidationCode(f
)
9344 def WriteHandlerImplementation(self
, f
):
9345 """Writes the handler implementation for this command."""
9346 self
.type_handler
.WriteHandlerImplementation(self
, f
)
9348 def WriteValidationCode(self
, f
):
9349 """Writes the validation code for a command."""
9352 def WriteCmdFlag(self
, f
):
9353 """Writes the cmd cmd_flags constant."""
9355 # By default trace only at the highest level 3.
9356 trace_level
= int(self
.GetInfo('trace_level', default
= 3))
9357 if trace_level
not in xrange(0, 4):
9358 raise KeyError("Unhandled trace_level: %d" % trace_level
)
9360 flags
.append('CMD_FLAG_SET_TRACE_LEVEL(%d)' % trace_level
)
9363 cmd_flags
= ' | '.join(flags
)
9367 f
.write(" static const uint8 cmd_flags = %s;\n" % cmd_flags
)
9370 def WriteCmdArgFlag(self
, f
):
9371 """Writes the cmd kArgFlags constant."""
9372 f
.write(" static const cmd::ArgFlags kArgFlags = cmd::kFixed;\n")
9374 def WriteCmdComputeSize(self
, f
):
9375 """Writes the ComputeSize function for the command."""
9376 f
.write(" static uint32_t ComputeSize() {\n")
9378 " return static_cast<uint32_t>(sizeof(ValueType)); // NOLINT\n")
9382 def WriteCmdSetHeader(self
, f
):
9383 """Writes the cmd's SetHeader function."""
9384 f
.write(" void SetHeader() {\n")
9385 f
.write(" header.SetCmd<ValueType>();\n")
9389 def WriteCmdInit(self
, f
):
9390 """Writes the cmd's Init function."""
9391 f
.write(" void Init(%s) {\n" % self
.MakeTypedCmdArgString("_"))
9392 f
.write(" SetHeader();\n")
9393 args
= self
.GetCmdArgs()
9395 f
.write(" %s = _%s;\n" % (arg
.name
, arg
.name
))
9399 def WriteCmdSet(self
, f
):
9400 """Writes the cmd's Set function."""
9401 copy_args
= self
.MakeCmdArgString("_", False)
9402 f
.write(" void* Set(void* cmd%s) {\n" %
9403 self
.MakeTypedCmdArgString("_", True))
9404 f
.write(" static_cast<ValueType*>(cmd)->Init(%s);\n" % copy_args
)
9405 f
.write(" return NextCmdAddress<ValueType>(cmd);\n")
9409 def WriteStruct(self
, f
):
9410 self
.type_handler
.WriteStruct(self
, f
)
9412 def WriteDocs(self
, f
):
9413 self
.type_handler
.WriteDocs(self
, f
)
9415 def WriteCmdHelper(self
, f
):
9416 """Writes the cmd's helper."""
9417 self
.type_handler
.WriteCmdHelper(self
, f
)
9419 def WriteServiceImplementation(self
, f
):
9420 """Writes the service implementation for a command."""
9421 self
.type_handler
.WriteServiceImplementation(self
, f
)
9423 def WriteServiceUnitTest(self
, f
, *extras
):
9424 """Writes the service implementation for a command."""
9425 self
.type_handler
.WriteServiceUnitTest(self
, f
, *extras
)
9427 def WriteGLES2CLibImplementation(self
, f
):
9428 """Writes the GLES2 C Lib Implemention."""
9429 self
.type_handler
.WriteGLES2CLibImplementation(self
, f
)
9431 def WriteGLES2InterfaceHeader(self
, f
):
9432 """Writes the GLES2 Interface declaration."""
9433 self
.type_handler
.WriteGLES2InterfaceHeader(self
, f
)
9435 def WriteMojoGLES2ImplHeader(self
, f
):
9436 """Writes the Mojo GLES2 implementation header declaration."""
9437 self
.type_handler
.WriteMojoGLES2ImplHeader(self
, f
)
9439 def WriteMojoGLES2Impl(self
, f
):
9440 """Writes the Mojo GLES2 implementation declaration."""
9441 self
.type_handler
.WriteMojoGLES2Impl(self
, f
)
9443 def WriteGLES2InterfaceStub(self
, f
):
9444 """Writes the GLES2 Interface Stub declaration."""
9445 self
.type_handler
.WriteGLES2InterfaceStub(self
, f
)
9447 def WriteGLES2InterfaceStubImpl(self
, f
):
9448 """Writes the GLES2 Interface Stub declaration."""
9449 self
.type_handler
.WriteGLES2InterfaceStubImpl(self
, f
)
9451 def WriteGLES2ImplementationHeader(self
, f
):
9452 """Writes the GLES2 Implemention declaration."""
9453 self
.type_handler
.WriteGLES2ImplementationHeader(self
, f
)
9455 def WriteGLES2Implementation(self
, f
):
9456 """Writes the GLES2 Implemention definition."""
9457 self
.type_handler
.WriteGLES2Implementation(self
, f
)
9459 def WriteGLES2TraceImplementationHeader(self
, f
):
9460 """Writes the GLES2 Trace Implemention declaration."""
9461 self
.type_handler
.WriteGLES2TraceImplementationHeader(self
, f
)
9463 def WriteGLES2TraceImplementation(self
, f
):
9464 """Writes the GLES2 Trace Implemention definition."""
9465 self
.type_handler
.WriteGLES2TraceImplementation(self
, f
)
9467 def WriteGLES2Header(self
, f
):
9468 """Writes the GLES2 Implemention unit test."""
9469 self
.type_handler
.WriteGLES2Header(self
, f
)
9471 def WriteGLES2ImplementationUnitTest(self
, f
):
9472 """Writes the GLES2 Implemention unit test."""
9473 self
.type_handler
.WriteGLES2ImplementationUnitTest(self
, f
)
9475 def WriteDestinationInitalizationValidation(self
, f
):
9476 """Writes the client side destintion initialization validation."""
9477 self
.type_handler
.WriteDestinationInitalizationValidation(self
, f
)
9479 def WriteFormatTest(self
, f
):
9480 """Writes the cmd's format test."""
9481 self
.type_handler
.WriteFormatTest(self
, f
)
9484 class PepperInterface(object):
9485 """A class that represents a function."""
9487 def __init__(self
, info
):
9488 self
.name
= info
["name"]
9489 self
.dev
= info
["dev"]
9494 def GetInterfaceName(self
):
9498 upperint
= "_" + self
.name
.upper()
9501 return "PPB_OPENGLES2%s%s_INTERFACE" % (upperint
, dev
)
9503 def GetStructName(self
):
9507 return "PPB_OpenGLES2%s%s" % (self
.name
, dev
)
9510 class ImmediateFunction(Function
):
9511 """A class that represnets an immediate function command."""
9513 def __init__(self
, func
):
9516 "%sImmediate" % func
.name
,
9519 def InitFunction(self
):
9520 # Override args in original_args and args_for_cmds with immediate versions
9523 new_original_args
= []
9524 for arg
in self
.original_args
:
9525 new_arg
= arg
.GetImmediateVersion()
9527 new_original_args
.append(new_arg
)
9528 self
.original_args
= new_original_args
9530 new_args_for_cmds
= []
9531 for arg
in self
.args_for_cmds
:
9532 new_arg
= arg
.GetImmediateVersion()
9534 new_args_for_cmds
.append(new_arg
)
9536 self
.args_for_cmds
= new_args_for_cmds
9538 Function
.InitFunction(self
)
9540 def IsImmediate(self
):
9543 def WriteServiceImplementation(self
, f
):
9544 """Overridden from Function"""
9545 self
.type_handler
.WriteImmediateServiceImplementation(self
, f
)
9547 def WriteHandlerImplementation(self
, f
):
9548 """Overridden from Function"""
9549 self
.type_handler
.WriteImmediateHandlerImplementation(self
, f
)
9551 def WriteServiceUnitTest(self
, f
, *extras
):
9552 """Writes the service implementation for a command."""
9553 self
.type_handler
.WriteImmediateServiceUnitTest(self
, f
, *extras
)
9555 def WriteValidationCode(self
, f
):
9556 """Overridden from Function"""
9557 self
.type_handler
.WriteImmediateValidationCode(self
, f
)
9559 def WriteCmdArgFlag(self
, f
):
9560 """Overridden from Function"""
9561 f
.write(" static const cmd::ArgFlags kArgFlags = cmd::kAtLeastN;\n")
9563 def WriteCmdComputeSize(self
, f
):
9564 """Overridden from Function"""
9565 self
.type_handler
.WriteImmediateCmdComputeSize(self
, f
)
9567 def WriteCmdSetHeader(self
, f
):
9568 """Overridden from Function"""
9569 self
.type_handler
.WriteImmediateCmdSetHeader(self
, f
)
9571 def WriteCmdInit(self
, f
):
9572 """Overridden from Function"""
9573 self
.type_handler
.WriteImmediateCmdInit(self
, f
)
9575 def WriteCmdSet(self
, f
):
9576 """Overridden from Function"""
9577 self
.type_handler
.WriteImmediateCmdSet(self
, f
)
9579 def WriteCmdHelper(self
, f
):
9580 """Overridden from Function"""
9581 self
.type_handler
.WriteImmediateCmdHelper(self
, f
)
9583 def WriteFormatTest(self
, f
):
9584 """Overridden from Function"""
9585 self
.type_handler
.WriteImmediateFormatTest(self
, f
)
9588 class BucketFunction(Function
):
9589 """A class that represnets a bucket version of a function command."""
9591 def __init__(self
, func
):
9594 "%sBucket" % func
.name
,
9597 def InitFunction(self
):
9598 # Override args in original_args and args_for_cmds with bucket versions
9601 new_original_args
= []
9602 for arg
in self
.original_args
:
9603 new_arg
= arg
.GetBucketVersion()
9605 new_original_args
.append(new_arg
)
9606 self
.original_args
= new_original_args
9608 new_args_for_cmds
= []
9609 for arg
in self
.args_for_cmds
:
9610 new_arg
= arg
.GetBucketVersion()
9612 new_args_for_cmds
.append(new_arg
)
9614 self
.args_for_cmds
= new_args_for_cmds
9616 Function
.InitFunction(self
)
9618 def WriteServiceImplementation(self
, f
):
9619 """Overridden from Function"""
9620 self
.type_handler
.WriteBucketServiceImplementation(self
, f
)
9622 def WriteHandlerImplementation(self
, f
):
9623 """Overridden from Function"""
9624 self
.type_handler
.WriteBucketHandlerImplementation(self
, f
)
9626 def WriteServiceUnitTest(self
, f
, *extras
):
9627 """Overridden from Function"""
9628 self
.type_handler
.WriteBucketServiceUnitTest(self
, f
, *extras
)
9630 def MakeOriginalArgString(self
, prefix
, add_comma
= False, separator
= ", "):
9631 """Overridden from Function"""
9632 args
= self
.GetOriginalArgs()
9633 arg_string
= separator
.join(
9634 ["%s%s" % (prefix
, arg
.name
[0:-10] if arg
.name
.endswith("_bucket_id")
9635 else arg
.name
) for arg
in args
])
9636 return super(BucketFunction
, self
)._MaybePrependComma
(arg_string
, add_comma
)
9639 def CreateArg(arg_string
):
9640 """Creates an Argument."""
9641 arg_parts
= arg_string
.split()
9642 if len(arg_parts
) == 1 and arg_parts
[0] == 'void':
9644 # Is this a pointer argument?
9645 elif arg_string
.find('*') >= 0:
9646 return PointerArgument(
9648 " ".join(arg_parts
[0:-1]))
9649 # Is this a resource argument? Must come after pointer check.
9650 elif arg_parts
[0].startswith('GLidBind'):
9651 return ResourceIdBindArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
9652 elif arg_parts
[0].startswith('GLidZero'):
9653 return ResourceIdZeroArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
9654 elif arg_parts
[0].startswith('GLid'):
9655 return ResourceIdArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
9656 elif arg_parts
[0].startswith('GLenum') and len(arg_parts
[0]) > 6:
9657 return EnumArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
9658 elif arg_parts
[0].startswith('GLbitfield') and len(arg_parts
[0]) > 10:
9659 return BitFieldArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
9660 elif arg_parts
[0].startswith('GLboolean') and len(arg_parts
[0]) > 9:
9661 return ValidatedBoolArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
9662 elif arg_parts
[0].startswith('GLboolean'):
9663 return BoolArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
9664 elif arg_parts
[0].startswith('GLintUniformLocation'):
9665 return UniformLocationArgument(arg_parts
[-1])
9666 elif (arg_parts
[0].startswith('GLint') and len(arg_parts
[0]) > 5 and
9667 not arg_parts
[0].startswith('GLintptr')):
9668 return IntArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
9669 elif (arg_parts
[0].startswith('GLsizeiNotNegative') or
9670 arg_parts
[0].startswith('GLintptrNotNegative')):
9671 return SizeNotNegativeArgument(arg_parts
[-1],
9672 " ".join(arg_parts
[0:-1]),
9673 arg_parts
[0][0:-11])
9674 elif arg_parts
[0].startswith('GLsize'):
9675 return SizeArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
9677 return Argument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
9680 class GLGenerator(object):
9681 """A class to generate GL command buffers."""
9683 _function_re
= re
.compile(r
'GL_APICALL(.*?)GL_APIENTRY (.*?) \((.*?)\);')
9685 def __init__(self
, verbose
):
9686 self
.original_functions
= []
9688 self
.verbose
= verbose
9690 self
.pepper_interfaces
= []
9691 self
.interface_info
= {}
9692 self
.generated_cpp_filenames
= []
9694 for interface
in _PEPPER_INTERFACES
:
9695 interface
= PepperInterface(interface
)
9696 self
.pepper_interfaces
.append(interface
)
9697 self
.interface_info
[interface
.GetName()] = interface
9699 def AddFunction(self
, func
):
9700 """Adds a function."""
9701 self
.functions
.append(func
)
9703 def GetFunctionInfo(self
, name
):
9704 """Gets a type info for the given function name."""
9705 if name
in _FUNCTION_INFO
:
9706 func_info
= _FUNCTION_INFO
[name
].copy()
9710 if not 'type' in func_info
:
9711 func_info
['type'] = ''
9716 """Prints something if verbose is true."""
9720 def Error(self
, msg
):
9721 """Prints an error."""
9722 print "Error: %s" % msg
9725 def ParseGLH(self
, filename
):
9726 """Parses the cmd_buffer_functions.txt file and extracts the functions"""
9727 with
open(filename
, "r") as f
:
9728 functions
= f
.read()
9729 for line
in functions
.splitlines():
9730 match
= self
._function
_re
.match(line
)
9732 func_name
= match
.group(2)[2:]
9733 func_info
= self
.GetFunctionInfo(func_name
)
9734 if func_info
['type'] == 'Noop':
9737 parsed_func_info
= {
9738 'original_name': func_name
,
9739 'original_args': match
.group(3),
9740 'return_type': match
.group(1).strip(),
9743 for k
in parsed_func_info
.keys():
9744 if not k
in func_info
:
9745 func_info
[k
] = parsed_func_info
[k
]
9747 f
= Function(func_name
, func_info
)
9748 self
.original_functions
.append(f
)
9750 #for arg in f.GetOriginalArgs():
9751 # if not isinstance(arg, EnumArgument) and arg.type == 'GLenum':
9752 # self.Log("%s uses bare GLenum %s." % (func_name, arg.name))
9754 gen_cmd
= f
.GetInfo('gen_cmd')
9755 if gen_cmd
== True or gen_cmd
== None:
9756 if f
.type_handler
.NeedsDataTransferFunction(f
):
9757 methods
= f
.GetDataTransferMethods()
9758 if 'immediate' in methods
:
9759 self
.AddFunction(ImmediateFunction(f
))
9760 if 'bucket' in methods
:
9761 self
.AddFunction(BucketFunction(f
))
9762 if 'shm' in methods
:
9767 self
.Log("Auto Generated Functions : %d" %
9768 len([f
for f
in self
.functions
if f
.can_auto_generate
or
9769 (not f
.IsType('') and not f
.IsType('Custom') and
9770 not f
.IsType('Todo'))]))
9772 funcs
= [f
for f
in self
.functions
if not f
.can_auto_generate
and
9773 (f
.IsType('') or f
.IsType('Custom') or f
.IsType('Todo'))]
9774 self
.Log("Non Auto Generated Functions: %d" % len(funcs
))
9777 self
.Log(" %-10s %-20s gl%s" % (f
.info
['type'], f
.return_type
, f
.name
))
9779 def WriteCommandIds(self
, filename
):
9780 """Writes the command buffer format"""
9781 with
CHeaderWriter(filename
) as f
:
9782 f
.write("#define GLES2_COMMAND_LIST(OP) \\\n")
9784 for func
in self
.functions
:
9785 f
.write(" %-60s /* %d */ \\\n" %
9786 ("OP(%s)" % func
.name
, id))
9790 f
.write("enum CommandId {\n")
9791 f
.write(" kStartPoint = cmd::kLastCommonId, "
9792 "// All GLES2 commands start after this.\n")
9793 f
.write("#define GLES2_CMD_OP(name) k ## name,\n")
9794 f
.write(" GLES2_COMMAND_LIST(GLES2_CMD_OP)\n")
9795 f
.write("#undef GLES2_CMD_OP\n")
9796 f
.write(" kNumCommands\n")
9799 self
.generated_cpp_filenames
.append(filename
)
9801 def WriteFormat(self
, filename
):
9802 """Writes the command buffer format"""
9803 with
CHeaderWriter(filename
) as f
:
9804 # Forward declaration of a few enums used in constant argument
9805 # to avoid including GL header files.
9807 'GL_SYNC_GPU_COMMANDS_COMPLETE': '0x9117',
9808 'GL_SYNC_FLUSH_COMMANDS_BIT': '0x00000001',
9811 for enum
in enum_defines
:
9812 f
.write("#define %s %s\n" % (enum
, enum_defines
[enum
]))
9814 for func
in self
.functions
:
9816 #gen_cmd = func.GetInfo('gen_cmd')
9817 #if gen_cmd == True or gen_cmd == None:
9820 self
.generated_cpp_filenames
.append(filename
)
9822 def WriteDocs(self
, filename
):
9823 """Writes the command buffer doc version of the commands"""
9824 with
CHeaderWriter(filename
) as f
:
9825 for func
in self
.functions
:
9827 #gen_cmd = func.GetInfo('gen_cmd')
9828 #if gen_cmd == True or gen_cmd == None:
9831 self
.generated_cpp_filenames
.append(filename
)
9833 def WriteFormatTest(self
, filename
):
9834 """Writes the command buffer format test."""
9835 comment
= ("// This file contains unit tests for gles2 commmands\n"
9836 "// It is included by gles2_cmd_format_test.cc\n\n")
9837 with
CHeaderWriter(filename
, comment
) as f
:
9838 for func
in self
.functions
:
9840 #gen_cmd = func.GetInfo('gen_cmd')
9841 #if gen_cmd == True or gen_cmd == None:
9842 func
.WriteFormatTest(f
)
9843 self
.generated_cpp_filenames
.append(filename
)
9845 def WriteCmdHelperHeader(self
, filename
):
9846 """Writes the gles2 command helper."""
9847 with
CHeaderWriter(filename
) as f
:
9848 for func
in self
.functions
:
9850 #gen_cmd = func.GetInfo('gen_cmd')
9851 #if gen_cmd == True or gen_cmd == None:
9852 func
.WriteCmdHelper(f
)
9853 self
.generated_cpp_filenames
.append(filename
)
9855 def WriteServiceContextStateHeader(self
, filename
):
9856 """Writes the service context state header."""
9857 comment
= "// It is included by context_state.h\n"
9858 with
CHeaderWriter(filename
, comment
) as f
:
9859 f
.write("struct EnableFlags {\n")
9860 f
.write(" EnableFlags();\n")
9861 for capability
in _CAPABILITY_FLAGS
:
9862 f
.write(" bool %s;\n" % capability
['name'])
9863 f
.write(" bool cached_%s;\n" % capability
['name'])
9866 for state_name
in sorted(_STATES
.keys()):
9867 state
= _STATES
[state_name
]
9868 for item
in state
['states']:
9869 if isinstance(item
['default'], list):
9870 f
.write("%s %s[%d];\n" % (item
['type'], item
['name'],
9871 len(item
['default'])))
9873 f
.write("%s %s;\n" % (item
['type'], item
['name']))
9875 if item
.get('cached', False):
9876 if isinstance(item
['default'], list):
9877 f
.write("%s cached_%s[%d];\n" % (item
['type'], item
['name'],
9878 len(item
['default'])))
9880 f
.write("%s cached_%s;\n" % (item
['type'], item
['name']))
9884 inline void SetDeviceCapabilityState(GLenum cap, bool enable) {
9887 for capability
in _CAPABILITY_FLAGS
:
9890 """ % capability
['name'].upper())
9892 if (enable_flags.cached_%(name)s == enable &&
9893 !ignore_cached_state)
9895 enable_flags.cached_%(name)s = enable;
9910 self
.generated_cpp_filenames
.append(filename
)
9912 def WriteClientContextStateHeader(self
, filename
):
9913 """Writes the client context state header."""
9914 comment
= "// It is included by client_context_state.h\n"
9915 with
CHeaderWriter(filename
, comment
) as f
:
9916 f
.write("struct EnableFlags {\n")
9917 f
.write(" EnableFlags();\n")
9918 for capability
in _CAPABILITY_FLAGS
:
9919 f
.write(" bool %s;\n" % capability
['name'])
9921 self
.generated_cpp_filenames
.append(filename
)
9923 def WriteContextStateGetters(self
, f
, class_name
):
9924 """Writes the state getters."""
9925 for gl_type
in ["GLint", "GLfloat"]:
9927 bool %s::GetStateAs%s(
9928 GLenum pname, %s* params, GLsizei* num_written) const {
9930 """ % (class_name
, gl_type
, gl_type
))
9931 for state_name
in sorted(_STATES
.keys()):
9932 state
= _STATES
[state_name
]
9934 f
.write(" case %s:\n" % state
['enum'])
9935 f
.write(" *num_written = %d;\n" % len(state
['states']))
9936 f
.write(" if (params) {\n")
9937 for ndx
,item
in enumerate(state
['states']):
9938 f
.write(" params[%d] = static_cast<%s>(%s);\n" %
9939 (ndx
, gl_type
, item
['name']))
9941 f
.write(" return true;\n")
9943 for item
in state
['states']:
9944 f
.write(" case %s:\n" % item
['enum'])
9945 if isinstance(item
['default'], list):
9946 item_len
= len(item
['default'])
9947 f
.write(" *num_written = %d;\n" % item_len
)
9948 f
.write(" if (params) {\n")
9949 if item
['type'] == gl_type
:
9950 f
.write(" memcpy(params, %s, sizeof(%s) * %d);\n" %
9951 (item
['name'], item
['type'], item_len
))
9953 f
.write(" for (size_t i = 0; i < %s; ++i) {\n" %
9955 f
.write(" params[i] = %s;\n" %
9956 (GetGLGetTypeConversion(gl_type
, item
['type'],
9957 "%s[i]" % item
['name'])))
9960 f
.write(" *num_written = 1;\n")
9961 f
.write(" if (params) {\n")
9962 f
.write(" params[0] = %s;\n" %
9963 (GetGLGetTypeConversion(gl_type
, item
['type'],
9966 f
.write(" return true;\n")
9967 for capability
in _CAPABILITY_FLAGS
:
9968 f
.write(" case GL_%s:\n" % capability
['name'].upper())
9969 f
.write(" *num_written = 1;\n")
9970 f
.write(" if (params) {\n")
9972 " params[0] = static_cast<%s>(enable_flags.%s);\n" %
9973 (gl_type
, capability
['name']))
9975 f
.write(" return true;\n")
9976 f
.write(""" default:
9982 def WriteServiceContextStateImpl(self
, filename
):
9983 """Writes the context state service implementation."""
9984 comment
= "// It is included by context_state.cc\n"
9985 with
CHeaderWriter(filename
, comment
) as f
:
9987 for capability
in _CAPABILITY_FLAGS
:
9988 code
.append("%s(%s)" %
9989 (capability
['name'],
9990 ('false', 'true')['default' in capability
]))
9991 code
.append("cached_%s(%s)" %
9992 (capability
['name'],
9993 ('false', 'true')['default' in capability
]))
9994 f
.write("ContextState::EnableFlags::EnableFlags()\n : %s {\n}\n" %
9998 f
.write("void ContextState::Initialize() {\n")
9999 for state_name
in sorted(_STATES
.keys()):
10000 state
= _STATES
[state_name
]
10001 for item
in state
['states']:
10002 if isinstance(item
['default'], list):
10003 for ndx
, value
in enumerate(item
['default']):
10004 f
.write(" %s[%d] = %s;\n" % (item
['name'], ndx
, value
))
10006 f
.write(" %s = %s;\n" % (item
['name'], item
['default']))
10007 if item
.get('cached', False):
10008 if isinstance(item
['default'], list):
10009 for ndx
, value
in enumerate(item
['default']):
10010 f
.write(" cached_%s[%d] = %s;\n" % (item
['name'], ndx
, value
))
10012 f
.write(" cached_%s = %s;\n" % (item
['name'], item
['default']))
10016 void ContextState::InitCapabilities(const ContextState* prev_state) const {
10018 def WriteCapabilities(test_prev
, es3_caps
):
10019 for capability
in _CAPABILITY_FLAGS
:
10020 capability_name
= capability
['name']
10021 capability_es3
= 'es3' in capability
and capability
['es3'] == True
10022 if capability_es3
and not es3_caps
or not capability_es3
and es3_caps
:
10025 f
.write(""" if (prev_state->enable_flags.cached_%s !=
10026 enable_flags.cached_%s) {\n""" %
10027 (capability_name
, capability_name
))
10028 f
.write(" EnableDisable(GL_%s, enable_flags.cached_%s);\n" %
10029 (capability_name
.upper(), capability_name
))
10033 f
.write(" if (prev_state) {")
10034 WriteCapabilities(True, False)
10035 f
.write(" if (feature_info_->IsES3Capable()) {\n")
10036 WriteCapabilities(True, True)
10038 f
.write(" } else {")
10039 WriteCapabilities(False, False)
10040 f
.write(" if (feature_info_->IsES3Capable()) {\n")
10041 WriteCapabilities(False, True)
10046 void ContextState::InitState(const ContextState *prev_state) const {
10049 def WriteStates(test_prev
):
10050 # We need to sort the keys so the expectations match
10051 for state_name
in sorted(_STATES
.keys()):
10052 state
= _STATES
[state_name
]
10053 if state
['type'] == 'FrontBack':
10054 num_states
= len(state
['states'])
10055 for ndx
, group
in enumerate(Grouper(num_states
/ 2,
10060 for place
, item
in enumerate(group
):
10061 item_name
= CachedStateName(item
)
10062 args
.append('%s' % item_name
)
10066 f
.write("(%s != prev_state->%s)" % (item_name
, item_name
))
10070 " gl%s(%s, %s);\n" %
10071 (state
['func'], ('GL_FRONT', 'GL_BACK')[ndx
],
10073 elif state
['type'] == 'NamedParameter':
10074 for item
in state
['states']:
10075 item_name
= CachedStateName(item
)
10077 if 'extension_flag' in item
:
10078 f
.write(" if (feature_info_->feature_flags().%s) {\n " %
10079 item
['extension_flag'])
10081 if isinstance(item
['default'], list):
10082 f
.write(" if (memcmp(prev_state->%s, %s, "
10083 "sizeof(%s) * %d)) {\n" %
10084 (item_name
, item_name
, item
['type'],
10085 len(item
['default'])))
10087 f
.write(" if (prev_state->%s != %s) {\n " %
10088 (item_name
, item_name
))
10089 if 'gl_version_flag' in item
:
10090 item_name
= item
['gl_version_flag']
10092 if item_name
[0] == '!':
10094 item_name
= item_name
[1:]
10095 f
.write(" if (%sfeature_info_->gl_version_info().%s) {\n" %
10096 (inverted
, item_name
))
10097 f
.write(" gl%s(%s, %s);\n" %
10100 if 'enum_set' in item
else item
['enum']),
10102 if 'gl_version_flag' in item
:
10105 if 'extension_flag' in item
:
10108 if 'extension_flag' in item
:
10111 if 'extension_flag' in state
:
10112 f
.write(" if (feature_info_->feature_flags().%s)\n " %
10113 state
['extension_flag'])
10117 for place
, item
in enumerate(state
['states']):
10118 item_name
= CachedStateName(item
)
10119 args
.append('%s' % item_name
)
10123 f
.write("(%s != prev_state->%s)" %
10124 (item_name
, item_name
))
10127 f
.write(" gl%s(%s);\n" % (state
['func'], ", ".join(args
)))
10129 f
.write(" if (prev_state) {")
10131 f
.write(" } else {")
10136 f
.write("""bool ContextState::GetEnabled(GLenum cap) const {
10139 for capability
in _CAPABILITY_FLAGS
:
10140 f
.write(" case GL_%s:\n" % capability
['name'].upper())
10141 f
.write(" return enable_flags.%s;\n" % capability
['name'])
10142 f
.write(""" default:
10148 self
.WriteContextStateGetters(f
, "ContextState")
10149 self
.generated_cpp_filenames
.append(filename
)
10151 def WriteClientContextStateImpl(self
, filename
):
10152 """Writes the context state client side implementation."""
10153 comment
= "// It is included by client_context_state.cc\n"
10154 with
CHeaderWriter(filename
, comment
) as f
:
10156 for capability
in _CAPABILITY_FLAGS
:
10157 code
.append("%s(%s)" %
10158 (capability
['name'],
10159 ('false', 'true')['default' in capability
]))
10161 "ClientContextState::EnableFlags::EnableFlags()\n : %s {\n}\n" %
10166 bool ClientContextState::SetCapabilityState(
10167 GLenum cap, bool enabled, bool* changed) {
10171 for capability
in _CAPABILITY_FLAGS
:
10172 f
.write(" case GL_%s:\n" % capability
['name'].upper())
10173 f
.write(""" if (enable_flags.%(name)s != enabled) {
10175 enable_flags.%(name)s = enabled;
10179 f
.write(""" default:
10184 f
.write("""bool ClientContextState::GetEnabled(
10185 GLenum cap, bool* enabled) const {
10188 for capability
in _CAPABILITY_FLAGS
:
10189 f
.write(" case GL_%s:\n" % capability
['name'].upper())
10190 f
.write(" *enabled = enable_flags.%s;\n" % capability
['name'])
10191 f
.write(" return true;\n")
10192 f
.write(""" default:
10197 self
.generated_cpp_filenames
.append(filename
)
10199 def WriteServiceImplementation(self
, filename
):
10200 """Writes the service decorder implementation."""
10201 comment
= "// It is included by gles2_cmd_decoder.cc\n"
10202 with
CHeaderWriter(filename
, comment
) as f
:
10203 for func
in self
.functions
:
10205 #gen_cmd = func.GetInfo('gen_cmd')
10206 #if gen_cmd == True or gen_cmd == None:
10207 func
.WriteServiceImplementation(f
)
10210 bool GLES2DecoderImpl::SetCapabilityState(GLenum cap, bool enabled) {
10213 for capability
in _CAPABILITY_FLAGS
:
10214 f
.write(" case GL_%s:\n" % capability
['name'].upper())
10215 if 'state_flag' in capability
:
10218 state_.enable_flags.%(name)s = enabled;
10219 if (state_.enable_flags.cached_%(name)s != enabled
10220 || state_.ignore_cached_state) {
10221 %(state_flag)s = true;
10227 state_.enable_flags.%(name)s = enabled;
10228 if (state_.enable_flags.cached_%(name)s != enabled
10229 || state_.ignore_cached_state) {
10230 state_.enable_flags.cached_%(name)s = enabled;
10235 f
.write(""" default:
10241 self
.generated_cpp_filenames
.append(filename
)
10243 def WriteServiceUnitTests(self
, filename_pattern
):
10244 """Writes the service decorder unit tests."""
10245 num_tests
= len(self
.functions
)
10246 FUNCTIONS_PER_FILE
= 98 # hard code this so it doesn't change.
10248 for test_num
in range(0, num_tests
, FUNCTIONS_PER_FILE
):
10250 filename
= filename_pattern
% count
10251 comment
= "// It is included by gles2_cmd_decoder_unittest_%d.cc\n" \
10253 with
CHeaderWriter(filename
, comment
) as f
:
10254 test_name
= 'GLES2DecoderTest%d' % count
10255 end
= test_num
+ FUNCTIONS_PER_FILE
10256 if end
> num_tests
:
10258 for idx
in range(test_num
, end
):
10259 func
= self
.functions
[idx
]
10261 # Do any filtering of the functions here, so that the functions
10262 # will not move between the numbered files if filtering properties
10264 if func
.GetInfo('extension_flag'):
10268 #gen_cmd = func.GetInfo('gen_cmd')
10269 #if gen_cmd == True or gen_cmd == None:
10270 if func
.GetInfo('unit_test') == False:
10271 f
.write("// TODO(gman): %s\n" % func
.name
)
10273 func
.WriteServiceUnitTest(f
, {
10274 'test_name': test_name
10276 self
.generated_cpp_filenames
.append(filename
)
10278 comment
= "// It is included by gles2_cmd_decoder_unittest_base.cc\n"
10279 filename
= filename_pattern
% 0
10280 with
CHeaderWriter(filename
, comment
) as f
:
10282 """void GLES2DecoderTestBase::SetupInitCapabilitiesExpectations(
10283 bool es3_capable) {""")
10284 for capability
in _CAPABILITY_FLAGS
:
10285 capability_es3
= 'es3' in capability
and capability
['es3'] == True
10286 if not capability_es3
:
10287 f
.write(" ExpectEnableDisable(GL_%s, %s);\n" %
10288 (capability
['name'].upper(),
10289 ('false', 'true')['default' in capability
]))
10291 f
.write(" if (es3_capable) {")
10292 for capability
in _CAPABILITY_FLAGS
:
10293 capability_es3
= 'es3' in capability
and capability
['es3'] == True
10295 f
.write(" ExpectEnableDisable(GL_%s, %s);\n" %
10296 (capability
['name'].upper(),
10297 ('false', 'true')['default' in capability
]))
10301 void GLES2DecoderTestBase::SetupInitStateExpectations() {
10303 # We need to sort the keys so the expectations match
10304 for state_name
in sorted(_STATES
.keys()):
10305 state
= _STATES
[state_name
]
10306 if state
['type'] == 'FrontBack':
10307 num_states
= len(state
['states'])
10308 for ndx
, group
in enumerate(Grouper(num_states
/ 2, state
['states'])):
10311 if 'expected' in item
:
10312 args
.append(item
['expected'])
10314 args
.append(item
['default'])
10316 " EXPECT_CALL(*gl_, %s(%s, %s))\n" %
10317 (state
['func'], ('GL_FRONT', 'GL_BACK')[ndx
], ", ".join(args
)))
10318 f
.write(" .Times(1)\n")
10319 f
.write(" .RetiresOnSaturation();\n")
10320 elif state
['type'] == 'NamedParameter':
10321 for item
in state
['states']:
10322 if 'extension_flag' in item
:
10323 f
.write(" if (group_->feature_info()->feature_flags().%s) {\n" %
10324 item
['extension_flag'])
10326 expect_value
= item
['default']
10327 if isinstance(expect_value
, list):
10328 # TODO: Currently we do not check array values.
10332 " EXPECT_CALL(*gl_, %s(%s, %s))\n" %
10335 if 'enum_set' in item
else item
['enum']),
10337 f
.write(" .Times(1)\n")
10338 f
.write(" .RetiresOnSaturation();\n")
10339 if 'extension_flag' in item
:
10342 if 'extension_flag' in state
:
10343 f
.write(" if (group_->feature_info()->feature_flags().%s) {\n" %
10344 state
['extension_flag'])
10347 for item
in state
['states']:
10348 if 'expected' in item
:
10349 args
.append(item
['expected'])
10351 args
.append(item
['default'])
10352 # TODO: Currently we do not check array values.
10353 args
= ["_" if isinstance(arg
, list) else arg
for arg
in args
]
10354 f
.write(" EXPECT_CALL(*gl_, %s(%s))\n" %
10355 (state
['func'], ", ".join(args
)))
10356 f
.write(" .Times(1)\n")
10357 f
.write(" .RetiresOnSaturation();\n")
10358 if 'extension_flag' in state
:
10361 self
.generated_cpp_filenames
.append(filename
)
10363 def WriteServiceUnitTestsForExtensions(self
, filename
):
10364 """Writes the service decorder unit tests for functions with extension_flag.
10366 The functions are special in that they need a specific unit test
10367 baseclass to turn on the extension.
10369 functions
= [f
for f
in self
.functions
if f
.GetInfo('extension_flag')]
10370 comment
= "// It is included by gles2_cmd_decoder_unittest_extensions.cc\n"
10371 with
CHeaderWriter(filename
, comment
) as f
:
10372 for func
in functions
:
10374 if func
.GetInfo('unit_test') == False:
10375 f
.write("// TODO(gman): %s\n" % func
.name
)
10377 extension
= ToCamelCase(
10378 ToGLExtensionString(func
.GetInfo('extension_flag')))
10379 func
.WriteServiceUnitTest(f
, {
10380 'test_name': 'GLES2DecoderTestWith%s' % extension
10382 self
.generated_cpp_filenames
.append(filename
)
10384 def WriteGLES2Header(self
, filename
):
10385 """Writes the GLES2 header."""
10386 comment
= "// This file contains Chromium-specific GLES2 declarations.\n\n"
10387 with
CHeaderWriter(filename
, comment
) as f
:
10388 for func
in self
.original_functions
:
10389 func
.WriteGLES2Header(f
)
10391 self
.generated_cpp_filenames
.append(filename
)
10393 def WriteGLES2CLibImplementation(self
, filename
):
10394 """Writes the GLES2 c lib implementation."""
10395 comment
= "// These functions emulate GLES2 over command buffers.\n"
10396 with
CHeaderWriter(filename
, comment
) as f
:
10397 for func
in self
.original_functions
:
10398 func
.WriteGLES2CLibImplementation(f
)
10402 extern const NameToFunc g_gles2_function_table[] = {
10404 for func
in self
.original_functions
:
10406 ' { "gl%s", reinterpret_cast<GLES2FunctionPointer>(gl%s), },\n' %
10407 (func
.name
, func
.name
))
10408 f
.write(""" { NULL, NULL, },
10411 } // namespace gles2
10413 self
.generated_cpp_filenames
.append(filename
)
10415 def WriteGLES2InterfaceHeader(self
, filename
):
10416 """Writes the GLES2 interface header."""
10417 comment
= ("// This file is included by gles2_interface.h to declare the\n"
10418 "// GL api functions.\n")
10419 with
CHeaderWriter(filename
, comment
) as f
:
10420 for func
in self
.original_functions
:
10421 func
.WriteGLES2InterfaceHeader(f
)
10422 self
.generated_cpp_filenames
.append(filename
)
10424 def WriteMojoGLES2ImplHeader(self
, filename
):
10425 """Writes the Mojo GLES2 implementation header."""
10426 comment
= ("// This file is included by gles2_interface.h to declare the\n"
10427 "// GL api functions.\n")
10429 #include "gpu/command_buffer/client/gles2_interface.h"
10430 #include "third_party/mojo/src/mojo/public/c/gles2/gles2.h"
10434 class MojoGLES2Impl : public gpu::gles2::GLES2Interface {
10436 explicit MojoGLES2Impl(MojoGLES2Context context) {
10437 context_ = context;
10439 ~MojoGLES2Impl() override {}
10441 with
CHeaderWriter(filename
, comment
) as f
:
10443 for func
in self
.original_functions
:
10444 func
.WriteMojoGLES2ImplHeader(f
)
10447 MojoGLES2Context context_;
10450 } // namespace mojo
10453 self
.generated_cpp_filenames
.append(filename
)
10455 def WriteMojoGLES2Impl(self
, filename
):
10456 """Writes the Mojo GLES2 implementation."""
10458 #include "mojo/gpu/mojo_gles2_impl_autogen.h"
10460 #include "base/logging.h"
10461 #include "third_party/mojo/src/mojo/public/c/gles2/chromium_copy_texture.h"
10462 #include "third_party/mojo/src/mojo/public/c/gles2/chromium_framebuffer_multisample.h"
10463 #include "third_party/mojo/src/mojo/public/c/gles2/chromium_image.h"
10464 #include "third_party/mojo/src/mojo/public/c/gles2/chromium_miscellaneous.h"
10465 #include "third_party/mojo/src/mojo/public/c/gles2/chromium_pixel_transfer_buffer_object.h"
10466 #include "third_party/mojo/src/mojo/public/c/gles2/chromium_sub_image.h"
10467 #include "third_party/mojo/src/mojo/public/c/gles2/chromium_sync_point.h"
10468 #include "third_party/mojo/src/mojo/public/c/gles2/chromium_texture_mailbox.h"
10469 #include "third_party/mojo/src/mojo/public/c/gles2/gles2.h"
10470 #include "third_party/mojo/src/mojo/public/c/gles2/occlusion_query_ext.h"
10475 with
CWriter(filename
) as f
:
10477 for func
in self
.original_functions
:
10478 func
.WriteMojoGLES2Impl(f
)
10481 } // namespace mojo
10484 self
.generated_cpp_filenames
.append(filename
)
10486 def WriteGLES2InterfaceStub(self
, filename
):
10487 """Writes the GLES2 interface stub header."""
10488 comment
= "// This file is included by gles2_interface_stub.h.\n"
10489 with
CHeaderWriter(filename
, comment
) as f
:
10490 for func
in self
.original_functions
:
10491 func
.WriteGLES2InterfaceStub(f
)
10492 self
.generated_cpp_filenames
.append(filename
)
10494 def WriteGLES2InterfaceStubImpl(self
, filename
):
10495 """Writes the GLES2 interface header."""
10496 comment
= "// This file is included by gles2_interface_stub.cc.\n"
10497 with
CHeaderWriter(filename
, comment
) as f
:
10498 for func
in self
.original_functions
:
10499 func
.WriteGLES2InterfaceStubImpl(f
)
10500 self
.generated_cpp_filenames
.append(filename
)
10502 def WriteGLES2ImplementationHeader(self
, filename
):
10503 """Writes the GLES2 Implementation header."""
10505 ("// This file is included by gles2_implementation.h to declare the\n"
10506 "// GL api functions.\n")
10507 with
CHeaderWriter(filename
, comment
) as f
:
10508 for func
in self
.original_functions
:
10509 func
.WriteGLES2ImplementationHeader(f
)
10510 self
.generated_cpp_filenames
.append(filename
)
10512 def WriteGLES2Implementation(self
, filename
):
10513 """Writes the GLES2 Implementation."""
10515 ("// This file is included by gles2_implementation.cc to define the\n"
10516 "// GL api functions.\n")
10517 with
CHeaderWriter(filename
, comment
) as f
:
10518 for func
in self
.original_functions
:
10519 func
.WriteGLES2Implementation(f
)
10520 self
.generated_cpp_filenames
.append(filename
)
10522 def WriteGLES2TraceImplementationHeader(self
, filename
):
10523 """Writes the GLES2 Trace Implementation header."""
10524 comment
= "// This file is included by gles2_trace_implementation.h\n"
10525 with
CHeaderWriter(filename
, comment
) as f
:
10526 for func
in self
.original_functions
:
10527 func
.WriteGLES2TraceImplementationHeader(f
)
10528 self
.generated_cpp_filenames
.append(filename
)
10530 def WriteGLES2TraceImplementation(self
, filename
):
10531 """Writes the GLES2 Trace Implementation."""
10532 comment
= "// This file is included by gles2_trace_implementation.cc\n"
10533 with
CHeaderWriter(filename
, comment
) as f
:
10534 for func
in self
.original_functions
:
10535 func
.WriteGLES2TraceImplementation(f
)
10536 self
.generated_cpp_filenames
.append(filename
)
10538 def WriteGLES2ImplementationUnitTests(self
, filename
):
10539 """Writes the GLES2 helper header."""
10541 ("// This file is included by gles2_implementation.h to declare the\n"
10542 "// GL api functions.\n")
10543 with
CHeaderWriter(filename
, comment
) as f
:
10544 for func
in self
.original_functions
:
10545 func
.WriteGLES2ImplementationUnitTest(f
)
10546 self
.generated_cpp_filenames
.append(filename
)
10548 def WriteServiceUtilsHeader(self
, filename
):
10549 """Writes the gles2 auto generated utility header."""
10550 with
CHeaderWriter(filename
) as f
:
10551 for name
in sorted(_NAMED_TYPE_INFO
.keys()):
10552 named_type
= NamedType(_NAMED_TYPE_INFO
[name
])
10553 if named_type
.IsConstant():
10555 f
.write("ValueValidator<%s> %s;\n" %
10556 (named_type
.GetType(), ToUnderscore(name
)))
10558 self
.generated_cpp_filenames
.append(filename
)
10560 def WriteServiceUtilsImplementation(self
, filename
):
10561 """Writes the gles2 auto generated utility implementation."""
10562 with
CHeaderWriter(filename
) as f
:
10563 names
= sorted(_NAMED_TYPE_INFO
.keys())
10565 named_type
= NamedType(_NAMED_TYPE_INFO
[name
])
10566 if named_type
.IsConstant():
10568 if named_type
.GetValidValues():
10569 f
.write("static const %s valid_%s_table[] = {\n" %
10570 (named_type
.GetType(), ToUnderscore(name
)))
10571 for value
in named_type
.GetValidValues():
10572 f
.write(" %s,\n" % value
)
10575 if named_type
.GetValidValuesES3():
10576 f
.write("static const %s valid_%s_table_es3[] = {\n" %
10577 (named_type
.GetType(), ToUnderscore(name
)))
10578 for value
in named_type
.GetValidValuesES3():
10579 f
.write(" %s,\n" % value
)
10582 if named_type
.GetDeprecatedValuesES3():
10583 f
.write("static const %s deprecated_%s_table_es3[] = {\n" %
10584 (named_type
.GetType(), ToUnderscore(name
)))
10585 for value
in named_type
.GetDeprecatedValuesES3():
10586 f
.write(" %s,\n" % value
)
10589 f
.write("Validators::Validators()")
10591 for count
, name
in enumerate(names
):
10592 named_type
= NamedType(_NAMED_TYPE_INFO
[name
])
10593 if named_type
.IsConstant():
10595 if named_type
.GetValidValues():
10596 code
= """%(pre)s%(name)s(
10597 valid_%(name)s_table, arraysize(valid_%(name)s_table))"""
10599 code
= "%(pre)s%(name)s()"
10601 'name': ToUnderscore(name
),
10608 f
.write("void Validators::UpdateValuesES3() {\n")
10610 named_type
= NamedType(_NAMED_TYPE_INFO
[name
])
10611 if named_type
.GetDeprecatedValuesES3():
10612 code
= """ %(name)s.RemoveValues(
10613 deprecated_%(name)s_table_es3, arraysize(deprecated_%(name)s_table_es3));
10616 'name': ToUnderscore(name
),
10618 if named_type
.GetValidValuesES3():
10619 code
= """ %(name)s.AddValues(
10620 valid_%(name)s_table_es3, arraysize(valid_%(name)s_table_es3));
10623 'name': ToUnderscore(name
),
10626 self
.generated_cpp_filenames
.append(filename
)
10628 def WriteCommonUtilsHeader(self
, filename
):
10629 """Writes the gles2 common utility header."""
10630 with
CHeaderWriter(filename
) as f
:
10631 type_infos
= sorted(_NAMED_TYPE_INFO
.keys())
10632 for type_info
in type_infos
:
10633 if _NAMED_TYPE_INFO
[type_info
]['type'] == 'GLenum':
10634 f
.write("static std::string GetString%s(uint32_t value);\n" %
10637 self
.generated_cpp_filenames
.append(filename
)
10639 def WriteCommonUtilsImpl(self
, filename
):
10640 """Writes the gles2 common utility header."""
10641 enum_re
= re
.compile(r
'\#define\s+(GL_[a-zA-Z0-9_]+)\s+([0-9A-Fa-fx]+)')
10643 for fname
in ['third_party/khronos/GLES2/gl2.h',
10644 'third_party/khronos/GLES2/gl2ext.h',
10645 'third_party/khronos/GLES3/gl3.h',
10646 'gpu/GLES2/gl2chromium.h',
10647 'gpu/GLES2/gl2extchromium.h']:
10648 lines
= open(fname
).readlines()
10650 m
= enum_re
.match(line
)
10654 if len(value
) <= 10:
10655 if not value
in dict:
10657 # check our own _CHROMIUM macro conflicts with khronos GL headers.
10658 elif dict[value
] != name
and (name
.endswith('_CHROMIUM') or
10659 dict[value
].endswith('_CHROMIUM')):
10660 self
.Error("code collision: %s and %s have the same code %s" %
10661 (dict[value
], name
, value
))
10663 with
CHeaderWriter(filename
) as f
:
10664 f
.write("static const GLES2Util::EnumToString "
10665 "enum_to_string_table[] = {\n")
10667 f
.write(' { %s, "%s", },\n' % (value
, dict[value
]))
10670 const GLES2Util::EnumToString* const GLES2Util::enum_to_string_table_ =
10671 enum_to_string_table;
10672 const size_t GLES2Util::enum_to_string_table_len_ =
10673 sizeof(enum_to_string_table) / sizeof(enum_to_string_table[0]);
10677 enums
= sorted(_NAMED_TYPE_INFO
.keys())
10679 if _NAMED_TYPE_INFO
[enum
]['type'] == 'GLenum':
10680 f
.write("std::string GLES2Util::GetString%s(uint32_t value) {\n" %
10682 valid_list
= _NAMED_TYPE_INFO
[enum
]['valid']
10683 if 'valid_es3' in _NAMED_TYPE_INFO
[enum
]:
10684 valid_list
= valid_list
+ _NAMED_TYPE_INFO
[enum
]['valid_es3']
10685 assert len(valid_list
) == len(set(valid_list
))
10686 if len(valid_list
) > 0:
10687 f
.write(" static const EnumToString string_table[] = {\n")
10688 for value
in valid_list
:
10689 f
.write(' { %s, "%s" },\n' % (value
, value
))
10691 return GLES2Util::GetQualifiedEnumString(
10692 string_table, arraysize(string_table), value);
10697 f
.write(""" return GLES2Util::GetQualifiedEnumString(
10702 self
.generated_cpp_filenames
.append(filename
)
10704 def WritePepperGLES2Interface(self
, filename
, dev
):
10705 """Writes the Pepper OpenGLES interface definition."""
10706 with
CWriter(filename
) as f
:
10707 f
.write("label Chrome {\n")
10708 f
.write(" M39 = 1.0\n")
10712 # Declare GL types.
10713 f
.write("[version=1.0]\n")
10714 f
.write("describe {\n")
10715 for gltype
in ['GLbitfield', 'GLboolean', 'GLbyte', 'GLclampf',
10716 'GLclampx', 'GLenum', 'GLfixed', 'GLfloat', 'GLint',
10717 'GLintptr', 'GLshort', 'GLsizei', 'GLsizeiptr',
10718 'GLubyte', 'GLuint', 'GLushort']:
10719 f
.write(" %s;\n" % gltype
)
10720 f
.write(" %s_ptr_t;\n" % gltype
)
10723 # C level typedefs.
10724 f
.write("#inline c\n")
10725 f
.write("#include \"ppapi/c/pp_resource.h\"\n")
10727 f
.write("#include \"ppapi/c/ppb_opengles2.h\"\n\n")
10729 f
.write("\n#ifndef __gl2_h_\n")
10730 for (k
, v
) in _GL_TYPES
.iteritems():
10731 f
.write("typedef %s %s;\n" % (v
, k
))
10732 f
.write("#ifdef _WIN64\n")
10733 for (k
, v
) in _GL_TYPES_64
.iteritems():
10734 f
.write("typedef %s %s;\n" % (v
, k
))
10736 for (k
, v
) in _GL_TYPES_32
.iteritems():
10737 f
.write("typedef %s %s;\n" % (v
, k
))
10738 f
.write("#endif // _WIN64\n")
10739 f
.write("#endif // __gl2_h_\n\n")
10740 f
.write("#endinl\n")
10742 for interface
in self
.pepper_interfaces
:
10743 if interface
.dev
!= dev
:
10745 # Historically, we provide OpenGLES2 interfaces with struct
10746 # namespace. Not to break code which uses the interface as
10747 # "struct OpenGLES2", we put it in struct namespace.
10748 f
.write('\n[macro="%s", force_struct_namespace]\n' %
10749 interface
.GetInterfaceName())
10750 f
.write("interface %s {\n" % interface
.GetStructName())
10751 for func
in self
.original_functions
:
10752 if not func
.InPepperInterface(interface
):
10755 ret_type
= func
.MapCTypeToPepperIdlType(func
.return_type
,
10756 is_for_return_type
=True)
10757 func_prefix
= " %s %s(" % (ret_type
, func
.GetPepperName())
10758 f
.write(func_prefix
)
10759 f
.write("[in] PP_Resource context")
10760 for arg
in func
.MakeTypedPepperIdlArgStrings():
10761 f
.write(",\n" + " " * len(func_prefix
) + arg
)
10765 def WritePepperGLES2Implementation(self
, filename
):
10766 """Writes the Pepper OpenGLES interface implementation."""
10767 with
CWriter(filename
) as f
:
10768 f
.write("#include \"ppapi/shared_impl/ppb_opengles2_shared.h\"\n\n")
10769 f
.write("#include \"base/logging.h\"\n")
10770 f
.write("#include \"gpu/command_buffer/client/gles2_implementation.h\"\n")
10771 f
.write("#include \"ppapi/shared_impl/ppb_graphics_3d_shared.h\"\n")
10772 f
.write("#include \"ppapi/thunk/enter.h\"\n\n")
10774 f
.write("namespace ppapi {\n\n")
10775 f
.write("namespace {\n\n")
10777 f
.write("typedef thunk::EnterResource<thunk::PPB_Graphics3D_API>"
10780 f
.write("gpu::gles2::GLES2Implementation* ToGles2Impl(Enter3D*"
10782 f
.write(" DCHECK(enter);\n")
10783 f
.write(" DCHECK(enter->succeeded());\n")
10784 f
.write(" return static_cast<PPB_Graphics3D_Shared*>(enter->object())->"
10785 "gles2_impl();\n");
10788 for func
in self
.original_functions
:
10789 if not func
.InAnyPepperExtension():
10792 original_arg
= func
.MakeTypedPepperArgString("")
10793 context_arg
= "PP_Resource context_id"
10794 if len(original_arg
):
10795 arg
= context_arg
+ ", " + original_arg
10798 f
.write("%s %s(%s) {\n" %
10799 (func
.return_type
, func
.GetPepperName(), arg
))
10800 f
.write(" Enter3D enter(context_id, true);\n")
10801 f
.write(" if (enter.succeeded()) {\n")
10803 return_str
= "" if func
.return_type
== "void" else "return "
10804 f
.write(" %sToGles2Impl(&enter)->%s(%s);\n" %
10805 (return_str
, func
.original_name
,
10806 func
.MakeOriginalArgString("")))
10808 if func
.return_type
== "void":
10811 f
.write(" else {\n")
10812 f
.write(" return %s;\n" % func
.GetErrorReturnString())
10816 f
.write("} // namespace\n")
10818 for interface
in self
.pepper_interfaces
:
10819 f
.write("const %s* PPB_OpenGLES2_Shared::Get%sInterface() {\n" %
10820 (interface
.GetStructName(), interface
.GetName()))
10821 f
.write(" static const struct %s "
10822 "ppb_opengles2 = {\n" % interface
.GetStructName())
10824 f
.write(",\n &".join(
10825 f
.GetPepperName() for f
in self
.original_functions
10826 if f
.InPepperInterface(interface
)))
10830 f
.write(" return &ppb_opengles2;\n")
10833 f
.write("} // namespace ppapi\n")
10834 self
.generated_cpp_filenames
.append(filename
)
10836 def WriteGLES2ToPPAPIBridge(self
, filename
):
10837 """Connects GLES2 helper library to PPB_OpenGLES2 interface"""
10838 with
CWriter(filename
) as f
:
10839 f
.write("#ifndef GL_GLEXT_PROTOTYPES\n")
10840 f
.write("#define GL_GLEXT_PROTOTYPES\n")
10841 f
.write("#endif\n")
10842 f
.write("#include <GLES2/gl2.h>\n")
10843 f
.write("#include <GLES2/gl2ext.h>\n")
10844 f
.write("#include \"ppapi/lib/gl/gles2/gl2ext_ppapi.h\"\n\n")
10846 for func
in self
.original_functions
:
10847 if not func
.InAnyPepperExtension():
10850 interface
= self
.interface_info
[func
.GetInfo('pepper_interface') or '']
10852 f
.write("%s GL_APIENTRY gl%s(%s) {\n" %
10853 (func
.return_type
, func
.GetPepperName(),
10854 func
.MakeTypedPepperArgString("")))
10855 return_str
= "" if func
.return_type
== "void" else "return "
10856 interface_str
= "glGet%sInterfacePPAPI()" % interface
.GetName()
10857 original_arg
= func
.MakeOriginalArgString("")
10858 context_arg
= "glGetCurrentContextPPAPI()"
10859 if len(original_arg
):
10860 arg
= context_arg
+ ", " + original_arg
10863 if interface
.GetName():
10864 f
.write(" const struct %s* ext = %s;\n" %
10865 (interface
.GetStructName(), interface_str
))
10866 f
.write(" if (ext)\n")
10867 f
.write(" %sext->%s(%s);\n" %
10868 (return_str
, func
.GetPepperName(), arg
))
10870 f
.write(" %s0;\n" % return_str
)
10872 f
.write(" %s%s->%s(%s);\n" %
10873 (return_str
, interface_str
, func
.GetPepperName(), arg
))
10875 self
.generated_cpp_filenames
.append(filename
)
10877 def WriteMojoGLCallVisitor(self
, filename
):
10878 """Provides the GL implementation for mojo"""
10879 with
CWriter(filename
) as f
:
10880 for func
in self
.original_functions
:
10881 if not func
.IsCoreGLFunction():
10883 f
.write("VISIT_GL_CALL(%s, %s, (%s), (%s))\n" %
10884 (func
.name
, func
.return_type
,
10885 func
.MakeTypedOriginalArgString(""),
10886 func
.MakeOriginalArgString("")))
10887 self
.generated_cpp_filenames
.append(filename
)
10889 def WriteMojoGLCallVisitorForExtension(self
, filename
, extension
):
10890 """Provides the GL implementation for mojo for a particular extension"""
10891 with
CWriter(filename
) as f
:
10892 for func
in self
.original_functions
:
10893 if func
.GetInfo("extension") != extension
:
10895 f
.write("VISIT_GL_CALL(%s, %s, (%s), (%s))\n" %
10896 (func
.name
, func
.return_type
,
10897 func
.MakeTypedOriginalArgString(""),
10898 func
.MakeOriginalArgString("")))
10899 self
.generated_cpp_filenames
.append(filename
)
10901 def Format(generated_files
):
10902 formatter
= "clang-format"
10903 if platform
.system() == "Windows":
10904 formatter
+= ".bat"
10905 for filename
in generated_files
:
10906 call([formatter
, "-i", "-style=chromium", filename
])
10909 """This is the main function."""
10910 parser
= OptionParser()
10913 help="base directory for resulting files, under chrome/src. default is "
10914 "empty. Use this if you want the result stored under gen.")
10916 "-v", "--verbose", action
="store_true",
10917 help="prints more output.")
10919 (options
, args
) = parser
.parse_args(args
=argv
)
10921 # Add in states and capabilites to GLState
10922 gl_state_valid
= _NAMED_TYPE_INFO
['GLState']['valid']
10923 for state_name
in sorted(_STATES
.keys()):
10924 state
= _STATES
[state_name
]
10925 if 'extension_flag' in state
:
10927 if 'enum' in state
:
10928 if not state
['enum'] in gl_state_valid
:
10929 gl_state_valid
.append(state
['enum'])
10931 for item
in state
['states']:
10932 if 'extension_flag' in item
:
10934 if not item
['enum'] in gl_state_valid
:
10935 gl_state_valid
.append(item
['enum'])
10936 for capability
in _CAPABILITY_FLAGS
:
10937 valid_value
= "GL_%s" % capability
['name'].upper()
10938 if not valid_value
in gl_state_valid
:
10939 gl_state_valid
.append(valid_value
)
10941 # This script lives under gpu/command_buffer, cd to base directory.
10942 os
.chdir(os
.path
.dirname(__file__
) + "/../..")
10943 base_dir
= os
.getcwd()
10944 gen
= GLGenerator(options
.verbose
)
10945 gen
.ParseGLH("gpu/command_buffer/cmd_buffer_functions.txt")
10947 # Support generating files under gen/
10948 if options
.output_dir
!= None:
10949 os
.chdir(options
.output_dir
)
10951 gen
.WritePepperGLES2Interface("ppapi/api/ppb_opengles2.idl", False)
10952 gen
.WritePepperGLES2Interface("ppapi/api/dev/ppb_opengles2ext_dev.idl", True)
10953 gen
.WriteGLES2ToPPAPIBridge("ppapi/lib/gl/gles2/gles2.c")
10954 gen
.WritePepperGLES2Implementation(
10955 "ppapi/shared_impl/ppb_opengles2_shared.cc")
10957 gen
.WriteCommandIds("gpu/command_buffer/common/gles2_cmd_ids_autogen.h")
10958 gen
.WriteFormat("gpu/command_buffer/common/gles2_cmd_format_autogen.h")
10959 gen
.WriteFormatTest(
10960 "gpu/command_buffer/common/gles2_cmd_format_test_autogen.h")
10961 gen
.WriteGLES2InterfaceHeader(
10962 "gpu/command_buffer/client/gles2_interface_autogen.h")
10963 gen
.WriteMojoGLES2ImplHeader(
10964 "mojo/gpu/mojo_gles2_impl_autogen.h")
10965 gen
.WriteMojoGLES2Impl(
10966 "mojo/gpu/mojo_gles2_impl_autogen.cc")
10967 gen
.WriteGLES2InterfaceStub(
10968 "gpu/command_buffer/client/gles2_interface_stub_autogen.h")
10969 gen
.WriteGLES2InterfaceStubImpl(
10970 "gpu/command_buffer/client/gles2_interface_stub_impl_autogen.h")
10971 gen
.WriteGLES2ImplementationHeader(
10972 "gpu/command_buffer/client/gles2_implementation_autogen.h")
10973 gen
.WriteGLES2Implementation(
10974 "gpu/command_buffer/client/gles2_implementation_impl_autogen.h")
10975 gen
.WriteGLES2ImplementationUnitTests(
10976 "gpu/command_buffer/client/gles2_implementation_unittest_autogen.h")
10977 gen
.WriteGLES2TraceImplementationHeader(
10978 "gpu/command_buffer/client/gles2_trace_implementation_autogen.h")
10979 gen
.WriteGLES2TraceImplementation(
10980 "gpu/command_buffer/client/gles2_trace_implementation_impl_autogen.h")
10981 gen
.WriteGLES2CLibImplementation(
10982 "gpu/command_buffer/client/gles2_c_lib_autogen.h")
10983 gen
.WriteCmdHelperHeader(
10984 "gpu/command_buffer/client/gles2_cmd_helper_autogen.h")
10985 gen
.WriteServiceImplementation(
10986 "gpu/command_buffer/service/gles2_cmd_decoder_autogen.h")
10987 gen
.WriteServiceContextStateHeader(
10988 "gpu/command_buffer/service/context_state_autogen.h")
10989 gen
.WriteServiceContextStateImpl(
10990 "gpu/command_buffer/service/context_state_impl_autogen.h")
10991 gen
.WriteClientContextStateHeader(
10992 "gpu/command_buffer/client/client_context_state_autogen.h")
10993 gen
.WriteClientContextStateImpl(
10994 "gpu/command_buffer/client/client_context_state_impl_autogen.h")
10995 gen
.WriteServiceUnitTests(
10996 "gpu/command_buffer/service/gles2_cmd_decoder_unittest_%d_autogen.h")
10997 gen
.WriteServiceUnitTestsForExtensions(
10998 "gpu/command_buffer/service/"
10999 "gles2_cmd_decoder_unittest_extensions_autogen.h")
11000 gen
.WriteServiceUtilsHeader(
11001 "gpu/command_buffer/service/gles2_cmd_validation_autogen.h")
11002 gen
.WriteServiceUtilsImplementation(
11003 "gpu/command_buffer/service/"
11004 "gles2_cmd_validation_implementation_autogen.h")
11005 gen
.WriteCommonUtilsHeader(
11006 "gpu/command_buffer/common/gles2_cmd_utils_autogen.h")
11007 gen
.WriteCommonUtilsImpl(
11008 "gpu/command_buffer/common/gles2_cmd_utils_implementation_autogen.h")
11009 gen
.WriteGLES2Header("gpu/GLES2/gl2chromium_autogen.h")
11010 mojo_gles2_prefix
= ("third_party/mojo/src/mojo/public/c/gles2/"
11011 "gles2_call_visitor")
11012 gen
.WriteMojoGLCallVisitor(mojo_gles2_prefix
+ "_autogen.h")
11013 gen
.WriteMojoGLCallVisitorForExtension(
11014 mojo_gles2_prefix
+ "_chromium_texture_mailbox_autogen.h",
11015 "CHROMIUM_texture_mailbox")
11016 gen
.WriteMojoGLCallVisitorForExtension(
11017 mojo_gles2_prefix
+ "_chromium_sync_point_autogen.h",
11018 "CHROMIUM_sync_point")
11019 gen
.WriteMojoGLCallVisitorForExtension(
11020 mojo_gles2_prefix
+ "_chromium_sub_image_autogen.h",
11021 "CHROMIUM_sub_image")
11022 gen
.WriteMojoGLCallVisitorForExtension(
11023 mojo_gles2_prefix
+ "_chromium_miscellaneous_autogen.h",
11024 "CHROMIUM_miscellaneous")
11025 gen
.WriteMojoGLCallVisitorForExtension(
11026 mojo_gles2_prefix
+ "_occlusion_query_ext_autogen.h",
11027 "occlusion_query_EXT")
11028 gen
.WriteMojoGLCallVisitorForExtension(
11029 mojo_gles2_prefix
+ "_chromium_image_autogen.h",
11031 gen
.WriteMojoGLCallVisitorForExtension(
11032 mojo_gles2_prefix
+ "_chromium_copy_texture_autogen.h",
11033 "CHROMIUM_copy_texture")
11034 gen
.WriteMojoGLCallVisitorForExtension(
11035 mojo_gles2_prefix
+ "_chromium_pixel_transfer_buffer_object_autogen.h",
11036 "CHROMIUM_pixel_transfer_buffer_object")
11037 gen
.WriteMojoGLCallVisitorForExtension(
11038 mojo_gles2_prefix
+ "_chromium_framebuffer_multisample_autogen.h",
11039 "chromium_framebuffer_multisample")
11041 Format(gen
.generated_cpp_filenames
)
11044 print "%d errors" % gen
.errors
11049 if __name__
== '__main__':
11050 sys
.exit(main(sys
.argv
[1:]))