2 # Copyright (c) 2012 The Chromium Authors. All rights reserved.
3 # Use of this source code is governed by a BSD-style license that can be
4 # found in the LICENSE file.
6 """code generator for GLES2 command buffers."""
14 from optparse
import OptionParser
15 from subprocess
import call
18 _SIZE_OF_COMMAND_HEADER
= 4
19 _FIRST_SPECIFIC_COMMAND_ID
= 256
21 _LICENSE
= """// Copyright 2014 The Chromium Authors. All rights reserved.
22 // Use of this source code is governed by a BSD-style license that can be
23 // found in the LICENSE file.
27 _DO_NOT_EDIT_WARNING
= """// This file is auto-generated from
28 // gpu/command_buffer/build_gles2_cmd_buffer.py
29 // It's formatted by clang-format using chromium coding style:
30 // clang-format -i -style=chromium filename
35 # This string is copied directly out of the gl2.h file from GLES2.0
39 # *) Any argument that is a resourceID has been changed to GLid<Type>.
40 # (not pointer arguments) and if it's allowed to be zero it's GLidZero<Type>
41 # If it's allowed to not exist it's GLidBind<Type>
43 # *) All GLenums have been changed to GLenumTypeOfEnum
46 'GLenum': 'unsigned int',
47 'GLboolean': 'unsigned char',
48 'GLbitfield': 'unsigned int',
49 'GLbyte': 'signed char',
53 'GLubyte': 'unsigned char',
54 'GLushort': 'unsigned short',
55 'GLuint': 'unsigned int',
64 'GLintptr': 'long int',
65 'GLsizeiptr': 'long int'
69 'GLintptr': 'long long int',
70 'GLsizeiptr': 'long long int'
73 # Capabilites selected with glEnable
76 {'name': 'cull_face'},
77 {'name': 'depth_test', 'state_flag': 'framebuffer_state_.clear_state_dirty'},
78 {'name': 'dither', 'default': True},
79 {'name': 'polygon_offset_fill'},
80 {'name': 'sample_alpha_to_coverage'},
81 {'name': 'sample_coverage'},
82 {'name': 'scissor_test'},
83 {'name': 'stencil_test',
84 'state_flag': 'framebuffer_state_.clear_state_dirty'},
85 {'name': 'rasterizer_discard', 'es3': True},
86 {'name': 'primitive_restart_fixed_index', 'es3': True},
93 'enum': 'GL_COLOR_CLEAR_VALUE',
95 {'name': 'color_clear_red', 'type': 'GLfloat', 'default': '0.0f'},
96 {'name': 'color_clear_green', 'type': 'GLfloat', 'default': '0.0f'},
97 {'name': 'color_clear_blue', 'type': 'GLfloat', 'default': '0.0f'},
98 {'name': 'color_clear_alpha', 'type': 'GLfloat', 'default': '0.0f'},
103 'func': 'ClearDepth',
104 'enum': 'GL_DEPTH_CLEAR_VALUE',
106 {'name': 'depth_clear', 'type': 'GLclampf', 'default': '1.0f'},
112 'enum': 'GL_COLOR_WRITEMASK',
115 'name': 'color_mask_red',
121 'name': 'color_mask_green',
127 'name': 'color_mask_blue',
133 'name': 'color_mask_alpha',
139 'state_flag': 'framebuffer_state_.clear_state_dirty',
143 'func': 'ClearStencil',
144 'enum': 'GL_STENCIL_CLEAR_VALUE',
146 {'name': 'stencil_clear', 'type': 'GLint', 'default': '0'},
151 'func': 'BlendColor',
152 'enum': 'GL_BLEND_COLOR',
154 {'name': 'blend_color_red', 'type': 'GLfloat', 'default': '0.0f'},
155 {'name': 'blend_color_green', 'type': 'GLfloat', 'default': '0.0f'},
156 {'name': 'blend_color_blue', 'type': 'GLfloat', 'default': '0.0f'},
157 {'name': 'blend_color_alpha', 'type': 'GLfloat', 'default': '0.0f'},
162 'func': 'BlendEquationSeparate',
165 'name': 'blend_equation_rgb',
167 'enum': 'GL_BLEND_EQUATION_RGB',
168 'default': 'GL_FUNC_ADD',
171 'name': 'blend_equation_alpha',
173 'enum': 'GL_BLEND_EQUATION_ALPHA',
174 'default': 'GL_FUNC_ADD',
180 'func': 'BlendFuncSeparate',
183 'name': 'blend_source_rgb',
185 'enum': 'GL_BLEND_SRC_RGB',
189 'name': 'blend_dest_rgb',
191 'enum': 'GL_BLEND_DST_RGB',
192 'default': 'GL_ZERO',
195 'name': 'blend_source_alpha',
197 'enum': 'GL_BLEND_SRC_ALPHA',
201 'name': 'blend_dest_alpha',
203 'enum': 'GL_BLEND_DST_ALPHA',
204 'default': 'GL_ZERO',
210 'func': 'PolygonOffset',
213 'name': 'polygon_offset_factor',
215 'enum': 'GL_POLYGON_OFFSET_FACTOR',
219 'name': 'polygon_offset_units',
221 'enum': 'GL_POLYGON_OFFSET_UNITS',
229 'enum': 'GL_CULL_FACE_MODE',
234 'default': 'GL_BACK',
241 'enum': 'GL_FRONT_FACE',
242 'states': [{'name': 'front_face', 'type': 'GLenum', 'default': 'GL_CCW'}],
247 'enum': 'GL_DEPTH_FUNC',
248 'states': [{'name': 'depth_func', 'type': 'GLenum', 'default': 'GL_LESS'}],
252 'func': 'DepthRange',
253 'enum': 'GL_DEPTH_RANGE',
255 {'name': 'z_near', 'type': 'GLclampf', 'default': '0.0f'},
256 {'name': 'z_far', 'type': 'GLclampf', 'default': '1.0f'},
261 'func': 'SampleCoverage',
264 'name': 'sample_coverage_value',
266 'enum': 'GL_SAMPLE_COVERAGE_VALUE',
270 'name': 'sample_coverage_invert',
272 'enum': 'GL_SAMPLE_COVERAGE_INVERT',
279 'func': 'StencilMaskSeparate',
280 'state_flag': 'framebuffer_state_.clear_state_dirty',
283 'name': 'stencil_front_writemask',
285 'enum': 'GL_STENCIL_WRITEMASK',
286 'default': '0xFFFFFFFFU',
290 'name': 'stencil_back_writemask',
292 'enum': 'GL_STENCIL_BACK_WRITEMASK',
293 'default': '0xFFFFFFFFU',
300 'func': 'StencilOpSeparate',
303 'name': 'stencil_front_fail_op',
305 'enum': 'GL_STENCIL_FAIL',
306 'default': 'GL_KEEP',
309 'name': 'stencil_front_z_fail_op',
311 'enum': 'GL_STENCIL_PASS_DEPTH_FAIL',
312 'default': 'GL_KEEP',
315 'name': 'stencil_front_z_pass_op',
317 'enum': 'GL_STENCIL_PASS_DEPTH_PASS',
318 'default': 'GL_KEEP',
321 'name': 'stencil_back_fail_op',
323 'enum': 'GL_STENCIL_BACK_FAIL',
324 'default': 'GL_KEEP',
327 'name': 'stencil_back_z_fail_op',
329 'enum': 'GL_STENCIL_BACK_PASS_DEPTH_FAIL',
330 'default': 'GL_KEEP',
333 'name': 'stencil_back_z_pass_op',
335 'enum': 'GL_STENCIL_BACK_PASS_DEPTH_PASS',
336 'default': 'GL_KEEP',
342 'func': 'StencilFuncSeparate',
345 'name': 'stencil_front_func',
347 'enum': 'GL_STENCIL_FUNC',
348 'default': 'GL_ALWAYS',
351 'name': 'stencil_front_ref',
353 'enum': 'GL_STENCIL_REF',
357 'name': 'stencil_front_mask',
359 'enum': 'GL_STENCIL_VALUE_MASK',
360 'default': '0xFFFFFFFFU',
363 'name': 'stencil_back_func',
365 'enum': 'GL_STENCIL_BACK_FUNC',
366 'default': 'GL_ALWAYS',
369 'name': 'stencil_back_ref',
371 'enum': 'GL_STENCIL_BACK_REF',
375 'name': 'stencil_back_mask',
377 'enum': 'GL_STENCIL_BACK_VALUE_MASK',
378 'default': '0xFFFFFFFFU',
383 'type': 'NamedParameter',
387 'name': 'hint_generate_mipmap',
389 'enum': 'GL_GENERATE_MIPMAP_HINT',
390 'default': 'GL_DONT_CARE',
391 'gl_version_flag': '!is_desktop_core_profile'
394 'name': 'hint_fragment_shader_derivative',
396 'enum': 'GL_FRAGMENT_SHADER_DERIVATIVE_HINT_OES',
397 'default': 'GL_DONT_CARE',
398 'extension_flag': 'oes_standard_derivatives'
403 'type': 'NamedParameter',
404 'func': 'PixelStorei',
407 'name': 'pack_alignment',
409 'enum': 'GL_PACK_ALIGNMENT',
413 'name': 'unpack_alignment',
415 'enum': 'GL_UNPACK_ALIGNMENT',
420 # TODO: Consider implemenenting these states
425 'enum': 'GL_LINE_WIDTH',
428 'name': 'line_width',
431 'range_checks': [{'check': "<= 0.0f", 'test_value': "0.0f"}],
438 'enum': 'GL_DEPTH_WRITEMASK',
441 'name': 'depth_mask',
447 'state_flag': 'framebuffer_state_.clear_state_dirty',
452 'enum': 'GL_SCISSOR_BOX',
454 # NOTE: These defaults reset at GLES2DecoderImpl::Initialization.
459 'expected': 'kViewportX',
465 'expected': 'kViewportY',
468 'name': 'scissor_width',
471 'expected': 'kViewportWidth',
474 'name': 'scissor_height',
477 'expected': 'kViewportHeight',
484 'enum': 'GL_VIEWPORT',
486 # NOTE: These defaults reset at GLES2DecoderImpl::Initialization.
488 'name': 'viewport_x',
491 'expected': 'kViewportX',
494 'name': 'viewport_y',
497 'expected': 'kViewportY',
500 'name': 'viewport_width',
503 'expected': 'kViewportWidth',
506 'name': 'viewport_height',
509 'expected': 'kViewportHeight',
513 'MatrixValuesCHROMIUM': {
514 'type': 'NamedParameter',
515 'func': 'MatrixLoadfEXT',
517 { 'enum': 'GL_PATH_MODELVIEW_MATRIX_CHROMIUM',
518 'enum_set': 'GL_PATH_MODELVIEW_CHROMIUM',
519 'name': 'modelview_matrix',
522 '1.0f', '0.0f','0.0f','0.0f',
523 '0.0f', '1.0f','0.0f','0.0f',
524 '0.0f', '0.0f','1.0f','0.0f',
525 '0.0f', '0.0f','0.0f','1.0f',
527 'extension_flag': 'chromium_path_rendering',
529 { 'enum': 'GL_PATH_PROJECTION_MATRIX_CHROMIUM',
530 'enum_set': 'GL_PATH_PROJECTION_CHROMIUM',
531 'name': 'projection_matrix',
534 '1.0f', '0.0f','0.0f','0.0f',
535 '0.0f', '1.0f','0.0f','0.0f',
536 '0.0f', '0.0f','1.0f','0.0f',
537 '0.0f', '0.0f','0.0f','1.0f',
539 'extension_flag': 'chromium_path_rendering',
545 # Named type info object represents a named type that is used in OpenGL call
546 # arguments. Each named type defines a set of valid OpenGL call arguments. The
547 # named types are used in 'cmd_buffer_functions.txt'.
548 # type: The actual GL type of the named type.
549 # valid: The list of values that are valid for both the client and the service.
550 # valid_es3: The list of values that are valid in OpenGL ES 3, but not ES 2.
551 # invalid: Examples of invalid values for the type. At least these values
552 # should be tested to be invalid.
553 # deprecated_es3: The list of values that are valid in OpenGL ES 2, but
554 # deprecated in ES 3.
555 # is_complete: The list of valid values of type are final and will not be
556 # modified during runtime.
565 'GL_LINEAR_MIPMAP_LINEAR',
568 'FrameBufferTarget': {
574 'GL_DRAW_FRAMEBUFFER' ,
575 'GL_READ_FRAMEBUFFER' ,
581 'InvalidateFrameBufferTarget': {
587 'GL_DRAW_FRAMEBUFFER' ,
588 'GL_READ_FRAMEBUFFER' ,
591 'RenderBufferTarget': {
604 'GL_ELEMENT_ARRAY_BUFFER',
607 'GL_COPY_READ_BUFFER',
608 'GL_COPY_WRITE_BUFFER',
609 'GL_PIXEL_PACK_BUFFER',
610 'GL_PIXEL_UNPACK_BUFFER',
611 'GL_TRANSFORM_FEEDBACK_BUFFER',
618 'IndexedBufferTarget': {
621 'GL_TRANSFORM_FEEDBACK_BUFFER',
633 'GL_MAP_INVALIDATE_RANGE_BIT',
634 'GL_MAP_INVALIDATE_BUFFER_BIT',
635 'GL_MAP_FLUSH_EXPLICIT_BIT',
636 'GL_MAP_UNSYNCHRONIZED_BIT',
639 'GL_SYNC_FLUSH_COMMANDS_BIT',
699 'CompressedTextureFormat': {
704 'GL_COMPRESSED_R11_EAC',
705 'GL_COMPRESSED_SIGNED_R11_EAC',
706 'GL_COMPRESSED_RG11_EAC',
707 'GL_COMPRESSED_SIGNED_RG11_EAC',
708 'GL_COMPRESSED_RGB8_ETC2',
709 'GL_COMPRESSED_SRGB8_ETC2',
710 'GL_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2',
711 'GL_COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2',
712 'GL_COMPRESSED_RGBA8_ETC2_EAC',
713 'GL_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC',
719 # NOTE: State an Capability entries added later.
721 'GL_ALIASED_LINE_WIDTH_RANGE',
722 'GL_ALIASED_POINT_SIZE_RANGE',
724 'GL_ARRAY_BUFFER_BINDING',
726 'GL_COMPRESSED_TEXTURE_FORMATS',
727 'GL_CURRENT_PROGRAM',
730 'GL_ELEMENT_ARRAY_BUFFER_BINDING',
731 'GL_FRAMEBUFFER_BINDING',
732 'GL_GENERATE_MIPMAP_HINT',
734 'GL_IMPLEMENTATION_COLOR_READ_FORMAT',
735 'GL_IMPLEMENTATION_COLOR_READ_TYPE',
736 'GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS',
737 'GL_MAX_CUBE_MAP_TEXTURE_SIZE',
738 'GL_MAX_FRAGMENT_UNIFORM_VECTORS',
739 'GL_MAX_RENDERBUFFER_SIZE',
740 'GL_MAX_TEXTURE_IMAGE_UNITS',
741 'GL_MAX_TEXTURE_SIZE',
742 'GL_MAX_VARYING_VECTORS',
743 'GL_MAX_VERTEX_ATTRIBS',
744 'GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS',
745 'GL_MAX_VERTEX_UNIFORM_VECTORS',
746 'GL_MAX_VIEWPORT_DIMS',
747 'GL_NUM_COMPRESSED_TEXTURE_FORMATS',
748 'GL_NUM_SHADER_BINARY_FORMATS',
751 'GL_RENDERBUFFER_BINDING',
753 'GL_SAMPLE_COVERAGE_INVERT',
754 'GL_SAMPLE_COVERAGE_VALUE',
757 'GL_SHADER_BINARY_FORMATS',
758 'GL_SHADER_COMPILER',
761 'GL_TEXTURE_BINDING_2D',
762 'GL_TEXTURE_BINDING_CUBE_MAP',
763 'GL_UNPACK_ALIGNMENT',
764 'GL_UNPACK_FLIP_Y_CHROMIUM',
765 'GL_UNPACK_PREMULTIPLY_ALPHA_CHROMIUM',
766 'GL_UNPACK_UNPREMULTIPLY_ALPHA_CHROMIUM',
767 'GL_BIND_GENERATES_RESOURCE_CHROMIUM',
768 # we can add this because we emulate it if the driver does not support it.
769 'GL_VERTEX_ARRAY_BINDING_OES',
773 'GL_COPY_READ_BUFFER_BINDING',
774 'GL_COPY_WRITE_BUFFER_BINDING',
791 'GL_DRAW_FRAMEBUFFER_BINDING',
792 'GL_FRAGMENT_SHADER_DERIVATIVE_HINT',
794 'GL_MAX_3D_TEXTURE_SIZE',
795 'GL_MAX_ARRAY_TEXTURE_LAYERS',
796 'GL_MAX_COLOR_ATTACHMENTS',
797 'GL_MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS',
798 'GL_MAX_COMBINED_UNIFORM_BLOCKS',
799 'GL_MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS',
800 'GL_MAX_DRAW_BUFFERS',
801 'GL_MAX_ELEMENT_INDEX',
802 'GL_MAX_ELEMENTS_INDICES',
803 'GL_MAX_ELEMENTS_VERTICES',
804 'GL_MAX_FRAGMENT_INPUT_COMPONENTS',
805 'GL_MAX_FRAGMENT_UNIFORM_BLOCKS',
806 'GL_MAX_FRAGMENT_UNIFORM_COMPONENTS',
807 'GL_MAX_PROGRAM_TEXEL_OFFSET',
809 'GL_MAX_SERVER_WAIT_TIMEOUT',
810 'GL_MAX_TEXTURE_LOD_BIAS',
811 'GL_MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS',
812 'GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS',
813 'GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS',
814 'GL_MAX_UNIFORM_BLOCK_SIZE',
815 'GL_MAX_UNIFORM_BUFFER_BINDINGS',
816 'GL_MAX_VARYING_COMPONENTS',
817 'GL_MAX_VERTEX_OUTPUT_COMPONENTS',
818 'GL_MAX_VERTEX_UNIFORM_BLOCKS',
819 'GL_MAX_VERTEX_UNIFORM_COMPONENTS',
820 'GL_MIN_PROGRAM_TEXEL_OFFSET',
823 'GL_NUM_PROGRAM_BINARY_FORMATS',
824 'GL_PACK_ROW_LENGTH',
825 'GL_PACK_SKIP_PIXELS',
827 'GL_PIXEL_PACK_BUFFER_BINDING',
828 'GL_PIXEL_UNPACK_BUFFER_BINDING',
829 'GL_PROGRAM_BINARY_FORMATS',
831 'GL_READ_FRAMEBUFFER_BINDING',
832 'GL_SAMPLER_BINDING',
833 'GL_TEXTURE_BINDING_2D_ARRAY',
834 'GL_TEXTURE_BINDING_3D',
835 'GL_TRANSFORM_FEEDBACK_BINDING',
836 'GL_TRANSFORM_FEEDBACK_ACTIVE',
837 'GL_TRANSFORM_FEEDBACK_BUFFER_BINDING',
838 'GL_TRANSFORM_FEEDBACK_PAUSED',
839 'GL_TRANSFORM_FEEDBACK_BUFFER_SIZE',
840 'GL_TRANSFORM_FEEDBACK_BUFFER_START',
841 'GL_UNIFORM_BUFFER_BINDING',
842 'GL_UNIFORM_BUFFER_OFFSET_ALIGNMENT',
843 'GL_UNIFORM_BUFFER_SIZE',
844 'GL_UNIFORM_BUFFER_START',
845 'GL_UNPACK_IMAGE_HEIGHT',
846 'GL_UNPACK_ROW_LENGTH',
847 'GL_UNPACK_SKIP_IMAGES',
848 'GL_UNPACK_SKIP_PIXELS',
849 'GL_UNPACK_SKIP_ROWS',
850 # GL_VERTEX_ARRAY_BINDING is the same as GL_VERTEX_ARRAY_BINDING_OES
851 # 'GL_VERTEX_ARRAY_BINDING',
860 'GL_TRANSFORM_FEEDBACK_BUFFER_BINDING',
861 'GL_TRANSFORM_FEEDBACK_BUFFER_SIZE',
862 'GL_TRANSFORM_FEEDBACK_BUFFER_START',
863 'GL_UNIFORM_BUFFER_BINDING',
864 'GL_UNIFORM_BUFFER_SIZE',
865 'GL_UNIFORM_BUFFER_START',
871 'GetTexParamTarget': {
875 'GL_TEXTURE_CUBE_MAP',
878 'GL_TEXTURE_2D_ARRAY',
882 'GL_PROXY_TEXTURE_CUBE_MAP',
889 'GL_TEXTURE_CUBE_MAP_POSITIVE_X',
890 'GL_TEXTURE_CUBE_MAP_NEGATIVE_X',
891 'GL_TEXTURE_CUBE_MAP_POSITIVE_Y',
892 'GL_TEXTURE_CUBE_MAP_NEGATIVE_Y',
893 'GL_TEXTURE_CUBE_MAP_POSITIVE_Z',
894 'GL_TEXTURE_CUBE_MAP_NEGATIVE_Z',
897 'GL_PROXY_TEXTURE_CUBE_MAP',
904 'GL_TEXTURE_2D_ARRAY',
910 'TextureBindTarget': {
914 'GL_TEXTURE_CUBE_MAP',
918 'GL_TEXTURE_2D_ARRAY',
925 'TransformFeedbackBindTarget': {
928 'GL_TRANSFORM_FEEDBACK',
934 'TransformFeedbackPrimitiveMode': {
949 'GL_FRAGMENT_SHADER',
952 'GL_GEOMETRY_SHADER',
988 'GL_FUNC_REVERSE_SUBTRACT',
1004 'GL_ONE_MINUS_SRC_COLOR',
1006 'GL_ONE_MINUS_DST_COLOR',
1008 'GL_ONE_MINUS_SRC_ALPHA',
1010 'GL_ONE_MINUS_DST_ALPHA',
1011 'GL_CONSTANT_COLOR',
1012 'GL_ONE_MINUS_CONSTANT_COLOR',
1013 'GL_CONSTANT_ALPHA',
1014 'GL_ONE_MINUS_CONSTANT_ALPHA',
1015 'GL_SRC_ALPHA_SATURATE',
1024 'GL_ONE_MINUS_SRC_COLOR',
1026 'GL_ONE_MINUS_DST_COLOR',
1028 'GL_ONE_MINUS_SRC_ALPHA',
1030 'GL_ONE_MINUS_DST_ALPHA',
1031 'GL_CONSTANT_COLOR',
1032 'GL_ONE_MINUS_CONSTANT_COLOR',
1033 'GL_CONSTANT_ALPHA',
1034 'GL_ONE_MINUS_CONSTANT_ALPHA',
1039 'valid': ["GL_%s" % cap
['name'].upper() for cap
in _CAPABILITY_FLAGS
1040 if 'es3' not in cap
or cap
['es3'] != True],
1041 'valid_es3': ["GL_%s" % cap
['name'].upper() for cap
in _CAPABILITY_FLAGS
1042 if 'es3' in cap
and cap
['es3'] == True],
1055 'GL_TRIANGLE_STRIP',
1068 'GL_UNSIGNED_SHORT',
1077 'GetMaxIndexType': {
1081 'GL_UNSIGNED_SHORT',
1091 'GL_COLOR_ATTACHMENT0',
1092 'GL_DEPTH_ATTACHMENT',
1093 'GL_STENCIL_ATTACHMENT',
1096 'GL_DEPTH_STENCIL_ATTACHMENT',
1099 'BackbufferAttachment': {
1107 'BufferParameter': {
1114 'GL_BUFFER_ACCESS_FLAGS',
1116 'GL_BUFFER_MAP_LENGTH',
1117 'GL_BUFFER_MAP_OFFSET',
1120 'GL_PIXEL_PACK_BUFFER',
1126 'GL_INTERLEAVED_ATTRIBS',
1127 'GL_SEPARATE_ATTRIBS',
1130 'GL_PIXEL_PACK_BUFFER',
1133 'FrameBufferParameter': {
1136 'GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE',
1137 'GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME',
1138 'GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL',
1139 'GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE',
1142 'GL_FRAMEBUFFER_ATTACHMENT_RED_SIZE',
1143 'GL_FRAMEBUFFER_ATTACHMENT_GREEN_SIZE',
1144 'GL_FRAMEBUFFER_ATTACHMENT_BLUE_SIZE',
1145 'GL_FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE',
1146 'GL_FRAMEBUFFER_ATTACHMENT_DEPTH_SIZE',
1147 'GL_FRAMEBUFFER_ATTACHMENT_STENCIL_SIZE',
1148 'GL_FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE',
1149 'GL_FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING',
1150 'GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER',
1156 'GL_PATH_PROJECTION_CHROMIUM',
1157 'GL_PATH_MODELVIEW_CHROMIUM',
1160 'ProgramParameter': {
1165 'GL_VALIDATE_STATUS',
1166 'GL_INFO_LOG_LENGTH',
1167 'GL_ATTACHED_SHADERS',
1168 'GL_ACTIVE_ATTRIBUTES',
1169 'GL_ACTIVE_ATTRIBUTE_MAX_LENGTH',
1170 'GL_ACTIVE_UNIFORMS',
1171 'GL_ACTIVE_UNIFORM_MAX_LENGTH',
1174 'GL_ACTIVE_UNIFORM_BLOCKS',
1175 'GL_ACTIVE_UNIFORM_BLOCK_MAX_NAME_LENGTH',
1176 'GL_TRANSFORM_FEEDBACK_BUFFER_MODE',
1177 'GL_TRANSFORM_FEEDBACK_VARYINGS',
1178 'GL_TRANSFORM_FEEDBACK_VARYING_MAX_LENGTH',
1181 'GL_PROGRAM_BINARY_RETRIEVABLE_HINT', # not supported in Chromium.
1184 'QueryObjectParameter': {
1187 'GL_QUERY_RESULT_EXT',
1188 'GL_QUERY_RESULT_AVAILABLE_EXT',
1194 'GL_CURRENT_QUERY_EXT',
1200 'GL_ANY_SAMPLES_PASSED_EXT',
1201 'GL_ANY_SAMPLES_PASSED_CONSERVATIVE_EXT',
1202 'GL_COMMANDS_ISSUED_CHROMIUM',
1203 'GL_LATENCY_QUERY_CHROMIUM',
1204 'GL_ASYNC_PIXEL_UNPACK_COMPLETED_CHROMIUM',
1205 'GL_ASYNC_PIXEL_PACK_COMPLETED_CHROMIUM',
1206 'GL_COMMANDS_COMPLETED_CHROMIUM',
1209 'RenderBufferParameter': {
1212 'GL_RENDERBUFFER_RED_SIZE',
1213 'GL_RENDERBUFFER_GREEN_SIZE',
1214 'GL_RENDERBUFFER_BLUE_SIZE',
1215 'GL_RENDERBUFFER_ALPHA_SIZE',
1216 'GL_RENDERBUFFER_DEPTH_SIZE',
1217 'GL_RENDERBUFFER_STENCIL_SIZE',
1218 'GL_RENDERBUFFER_WIDTH',
1219 'GL_RENDERBUFFER_HEIGHT',
1220 'GL_RENDERBUFFER_INTERNAL_FORMAT',
1223 'GL_RENDERBUFFER_SAMPLES',
1226 'InternalFormatParameter': {
1229 'GL_NUM_SAMPLE_COUNTS',
1233 'SamplerParameter': {
1236 'GL_TEXTURE_MAG_FILTER',
1237 'GL_TEXTURE_MIN_FILTER',
1238 'GL_TEXTURE_MIN_LOD',
1239 'GL_TEXTURE_MAX_LOD',
1240 'GL_TEXTURE_WRAP_S',
1241 'GL_TEXTURE_WRAP_T',
1242 'GL_TEXTURE_WRAP_R',
1243 'GL_TEXTURE_COMPARE_MODE',
1244 'GL_TEXTURE_COMPARE_FUNC',
1247 'GL_GENERATE_MIPMAP',
1250 'ShaderParameter': {
1255 'GL_COMPILE_STATUS',
1256 'GL_INFO_LOG_LENGTH',
1257 'GL_SHADER_SOURCE_LENGTH',
1258 'GL_TRANSLATED_SHADER_SOURCE_LENGTH_ANGLE',
1261 'ShaderPrecision': {
1278 'GL_SHADING_LANGUAGE_VERSION',
1282 'TextureParameter': {
1285 'GL_TEXTURE_MAG_FILTER',
1286 'GL_TEXTURE_MIN_FILTER',
1287 'GL_TEXTURE_POOL_CHROMIUM',
1288 'GL_TEXTURE_WRAP_S',
1289 'GL_TEXTURE_WRAP_T',
1292 'GL_TEXTURE_BASE_LEVEL',
1293 'GL_TEXTURE_COMPARE_FUNC',
1294 'GL_TEXTURE_COMPARE_MODE',
1295 'GL_TEXTURE_IMMUTABLE_FORMAT',
1296 'GL_TEXTURE_IMMUTABLE_LEVELS',
1297 'GL_TEXTURE_MAX_LEVEL',
1298 'GL_TEXTURE_MAX_LOD',
1299 'GL_TEXTURE_MIN_LOD',
1300 'GL_TEXTURE_WRAP_R',
1303 'GL_GENERATE_MIPMAP',
1309 'GL_TEXTURE_POOL_MANAGED_CHROMIUM',
1310 'GL_TEXTURE_POOL_UNMANAGED_CHROMIUM',
1313 'TextureWrapMode': {
1317 'GL_MIRRORED_REPEAT',
1321 'TextureMinFilterMode': {
1326 'GL_NEAREST_MIPMAP_NEAREST',
1327 'GL_LINEAR_MIPMAP_NEAREST',
1328 'GL_NEAREST_MIPMAP_LINEAR',
1329 'GL_LINEAR_MIPMAP_LINEAR',
1332 'TextureMagFilterMode': {
1339 'TextureCompareFunc': {
1352 'TextureCompareMode': {
1356 'GL_COMPARE_REF_TO_TEXTURE',
1363 'GL_FRAMEBUFFER_ATTACHMENT_ANGLE',
1366 'VertexAttribute': {
1369 # some enum that the decoder actually passes through to GL needs
1370 # to be the first listed here since it's used in unit tests.
1371 'GL_VERTEX_ATTRIB_ARRAY_NORMALIZED',
1372 'GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING',
1373 'GL_VERTEX_ATTRIB_ARRAY_ENABLED',
1374 'GL_VERTEX_ATTRIB_ARRAY_SIZE',
1375 'GL_VERTEX_ATTRIB_ARRAY_STRIDE',
1376 'GL_VERTEX_ATTRIB_ARRAY_TYPE',
1377 'GL_CURRENT_VERTEX_ATTRIB',
1380 'GL_VERTEX_ATTRIB_ARRAY_INTEGER',
1381 'GL_VERTEX_ATTRIB_ARRAY_DIVISOR',
1387 'GL_VERTEX_ATTRIB_ARRAY_POINTER',
1393 'GL_GENERATE_MIPMAP_HINT',
1396 'GL_FRAGMENT_SHADER_DERIVATIVE_HINT',
1399 'GL_PERSPECTIVE_CORRECTION_HINT',
1413 'GL_PACK_ALIGNMENT',
1414 'GL_UNPACK_ALIGNMENT',
1415 'GL_UNPACK_FLIP_Y_CHROMIUM',
1416 'GL_UNPACK_PREMULTIPLY_ALPHA_CHROMIUM',
1417 'GL_UNPACK_UNPREMULTIPLY_ALPHA_CHROMIUM',
1420 'GL_PACK_ROW_LENGTH',
1421 'GL_PACK_SKIP_PIXELS',
1422 'GL_PACK_SKIP_ROWS',
1423 'GL_UNPACK_ROW_LENGTH',
1424 'GL_UNPACK_IMAGE_HEIGHT',
1425 'GL_UNPACK_SKIP_PIXELS',
1426 'GL_UNPACK_SKIP_ROWS',
1427 'GL_UNPACK_SKIP_IMAGES',
1430 'GL_PACK_SWAP_BYTES',
1431 'GL_UNPACK_SWAP_BYTES',
1434 'PixelStoreAlignment': {
1447 'ReadPixelFormat': {
1466 'GL_UNSIGNED_SHORT_5_6_5',
1467 'GL_UNSIGNED_SHORT_4_4_4_4',
1468 'GL_UNSIGNED_SHORT_5_5_5_1',
1472 'GL_UNSIGNED_SHORT',
1478 'GL_UNSIGNED_INT_2_10_10_10_REV',
1479 'GL_UNSIGNED_INT_10F_11F_11F_REV',
1480 'GL_UNSIGNED_INT_5_9_9_9_REV',
1481 'GL_UNSIGNED_INT_24_8',
1482 'GL_FLOAT_32_UNSIGNED_INT_24_8_REV',
1485 'GL_UNSIGNED_BYTE_3_3_2',
1492 'GL_UNSIGNED_SHORT_5_6_5',
1493 'GL_UNSIGNED_SHORT_4_4_4_4',
1494 'GL_UNSIGNED_SHORT_5_5_5_1',
1505 'GL_UNSIGNED_SHORT_5_6_5',
1506 'GL_UNSIGNED_SHORT_4_4_4_4',
1507 'GL_UNSIGNED_SHORT_5_5_5_1',
1510 'RenderBufferFormat': {
1516 'GL_DEPTH_COMPONENT16',
1517 'GL_STENCIL_INDEX8',
1545 'GL_DEPTH_COMPONENT24',
1546 'GL_DEPTH_COMPONENT32F',
1547 'GL_DEPTH24_STENCIL8',
1548 'GL_DEPTH32F_STENCIL8',
1551 'ShaderBinaryFormat': {
1574 'GL_LUMINANCE_ALPHA',
1585 'GL_DEPTH_COMPONENT',
1593 'TextureInternalFormat': {
1598 'GL_LUMINANCE_ALPHA',
1627 'GL_R11F_G11F_B10F',
1652 # The DEPTH/STENCIL formats are not supported in CopyTexImage2D.
1653 # We will reject them dynamically in GPU command buffer.
1654 'GL_DEPTH_COMPONENT16',
1655 'GL_DEPTH_COMPONENT24',
1656 'GL_DEPTH_COMPONENT32F',
1657 'GL_DEPTH24_STENCIL8',
1658 'GL_DEPTH32F_STENCIL8',
1665 'TextureInternalFormatStorage': {
1672 'GL_LUMINANCE8_EXT',
1673 'GL_LUMINANCE8_ALPHA8_EXT',
1700 'GL_R11F_G11F_B10F',
1722 'GL_DEPTH_COMPONENT16',
1723 'GL_DEPTH_COMPONENT24',
1724 'GL_DEPTH_COMPONENT32F',
1725 'GL_DEPTH24_STENCIL8',
1726 'GL_DEPTH32F_STENCIL8',
1727 'GL_COMPRESSED_R11_EAC',
1728 'GL_COMPRESSED_SIGNED_R11_EAC',
1729 'GL_COMPRESSED_RG11_EAC',
1730 'GL_COMPRESSED_SIGNED_RG11_EAC',
1731 'GL_COMPRESSED_RGB8_ETC2',
1732 'GL_COMPRESSED_SRGB8_ETC2',
1733 'GL_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2',
1734 'GL_COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2',
1735 'GL_COMPRESSED_RGBA8_ETC2_EAC',
1736 'GL_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC',
1740 'GL_LUMINANCE8_EXT',
1741 'GL_LUMINANCE8_ALPHA8_EXT',
1743 'GL_LUMINANCE16F_EXT',
1744 'GL_LUMINANCE_ALPHA16F_EXT',
1746 'GL_LUMINANCE32F_EXT',
1747 'GL_LUMINANCE_ALPHA32F_EXT',
1750 'ImageInternalFormat': {
1754 'GL_RGB_YUV_420_CHROMIUM',
1762 'GL_SCANOUT_CHROMIUM'
1765 'ValueBufferTarget': {
1768 'GL_SUBSCRIBED_VALUES_BUFFER_CHROMIUM',
1771 'SubscriptionTarget': {
1774 'GL_MOUSE_POSITION_CHROMIUM',
1777 'UniformParameter': {
1782 'GL_UNIFORM_NAME_LENGTH',
1783 'GL_UNIFORM_BLOCK_INDEX',
1784 'GL_UNIFORM_OFFSET',
1785 'GL_UNIFORM_ARRAY_STRIDE',
1786 'GL_UNIFORM_MATRIX_STRIDE',
1787 'GL_UNIFORM_IS_ROW_MAJOR',
1790 'GL_UNIFORM_BLOCK_NAME_LENGTH',
1793 'UniformBlockParameter': {
1796 'GL_UNIFORM_BLOCK_BINDING',
1797 'GL_UNIFORM_BLOCK_DATA_SIZE',
1798 'GL_UNIFORM_BLOCK_NAME_LENGTH',
1799 'GL_UNIFORM_BLOCK_ACTIVE_UNIFORMS',
1800 'GL_UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES',
1801 'GL_UNIFORM_BLOCK_REFERENCED_BY_VERTEX_SHADER',
1802 'GL_UNIFORM_BLOCK_REFERENCED_BY_FRAGMENT_SHADER',
1808 'VertexAttribType': {
1814 'GL_UNSIGNED_SHORT',
1815 # 'GL_FIXED', // This is not available on Desktop GL.
1822 'GL_INT_2_10_10_10_REV',
1823 'GL_UNSIGNED_INT_2_10_10_10_REV',
1829 'VertexAttribIType': {
1835 'GL_UNSIGNED_SHORT',
1846 'is_complete': True,
1854 'VertexAttribSize': {
1869 'is_complete': True,
1878 'type': 'GLboolean',
1879 'is_complete': True,
1890 'GL_GUILTY_CONTEXT_RESET_ARB',
1891 'GL_INNOCENT_CONTEXT_RESET_ARB',
1892 'GL_UNKNOWN_CONTEXT_RESET_ARB',
1897 'is_complete': True,
1899 'GL_SYNC_GPU_COMMANDS_COMPLETE',
1906 'type': 'GLbitfield',
1907 'is_complete': True,
1916 'type': 'GLbitfield',
1918 'GL_SYNC_FLUSH_COMMANDS_BIT',
1928 'GL_SYNC_STATUS', # This needs to be the 1st; all others are cached.
1930 'GL_SYNC_CONDITION',
1939 # This table specifies the different pepper interfaces that are supported for
1940 # GL commands. 'dev' is true if it's a dev interface.
1941 _PEPPER_INTERFACES
= [
1942 {'name': '', 'dev': False},
1943 {'name': 'InstancedArrays', 'dev': False},
1944 {'name': 'FramebufferBlit', 'dev': False},
1945 {'name': 'FramebufferMultisample', 'dev': False},
1946 {'name': 'ChromiumEnableFeature', 'dev': False},
1947 {'name': 'ChromiumMapSub', 'dev': False},
1948 {'name': 'Query', 'dev': False},
1949 {'name': 'VertexArrayObject', 'dev': False},
1950 {'name': 'DrawBuffers', 'dev': True},
1953 # A function info object specifies the type and other special data for the
1954 # command that will be generated. A base function info object is generated by
1955 # parsing the "cmd_buffer_functions.txt", one for each function in the
1956 # file. These function info objects can be augmented and their values can be
1957 # overridden by adding an object to the table below.
1959 # Must match function names specified in "cmd_buffer_functions.txt".
1961 # cmd_comment: A comment added to the cmd format.
1962 # type: defines which handler will be used to generate code.
1963 # decoder_func: defines which function to call in the decoder to execute the
1964 # corresponding GL command. If not specified the GL command will
1965 # be called directly.
1966 # gl_test_func: GL function that is expected to be called when testing.
1967 # cmd_args: The arguments to use for the command. This overrides generating
1968 # them based on the GL function arguments.
1969 # gen_cmd: Whether or not this function geneates a command. Default = True.
1970 # data_transfer_methods: Array of methods that are used for transfering the
1971 # pointer data. Possible values: 'immediate', 'shm', 'bucket'.
1972 # The default is 'immediate' if the command has one pointer
1973 # argument, otherwise 'shm'. One command is generated for each
1974 # transfer method. Affects only commands which are not of type
1975 # 'HandWritten', 'GETn' or 'GLcharN'.
1976 # Note: the command arguments that affect this are the final args,
1977 # taking cmd_args override into consideration.
1978 # impl_func: Whether or not to generate the GLES2Implementation part of this
1980 # impl_decl: Whether or not to generate the GLES2Implementation declaration
1982 # needs_size: If True a data_size field is added to the command.
1983 # count: The number of units per element. For PUTn or PUT types.
1984 # use_count_func: If True the actual data count needs to be computed; the count
1985 # argument specifies the maximum count.
1986 # unit_test: If False no service side unit test will be generated.
1987 # client_test: If False no client side unit test will be generated.
1988 # expectation: If False the unit test will have no expected calls.
1989 # gen_func: Name of function that generates GL resource for corresponding
1991 # states: array of states that get set by this function corresponding to
1992 # the given arguments
1993 # state_flag: name of flag that is set to true when function is called.
1994 # no_gl: no GL function is called.
1995 # valid_args: A dictionary of argument indices to args to use in unit tests
1996 # when they can not be automatically determined.
1997 # pepper_interface: The pepper interface that is used for this extension
1998 # pepper_name: The name of the function as exposed to pepper.
1999 # pepper_args: A string representing the argument list (what would appear in
2000 # C/C++ between the parentheses for the function declaration)
2001 # that the Pepper API expects for this function. Use this only if
2002 # the stable Pepper API differs from the GLES2 argument list.
2003 # invalid_test: False if no invalid test needed.
2004 # shadowed: True = the value is shadowed so no glGetXXX call will be made.
2005 # first_element_only: For PUT types, True if only the first element of an
2006 # array is used and we end up calling the single value
2007 # corresponding function. eg. TexParameteriv -> TexParameteri
2008 # extension: Function is an extension to GL and should not be exposed to
2009 # pepper unless pepper_interface is defined.
2010 # extension_flag: Function is an extension and should be enabled only when
2011 # the corresponding feature info flag is enabled. Implies
2012 # 'extension': True.
2013 # not_shared: For GENn types, True if objects can't be shared between contexts
2014 # unsafe: True = no validation is implemented on the service side and the
2015 # command is only available with --enable-unsafe-es3-apis.
2016 # id_mapping: A list of resource type names whose client side IDs need to be
2017 # mapped to service side IDs. This is only used for unsafe APIs.
2021 'decoder_func': 'DoActiveTexture',
2024 'client_test': False,
2026 'AttachShader': {'decoder_func': 'DoAttachShader'},
2027 'BindAttribLocation': {
2029 'data_transfer_methods': ['bucket'],
2034 'decoder_func': 'DoBindBuffer',
2035 'gen_func': 'GenBuffersARB',
2039 'id_mapping': [ 'Buffer' ],
2040 'gen_func': 'GenBuffersARB',
2043 'BindBufferRange': {
2045 'id_mapping': [ 'Buffer' ],
2046 'gen_func': 'GenBuffersARB',
2053 'BindFramebuffer': {
2055 'decoder_func': 'DoBindFramebuffer',
2056 'gl_test_func': 'glBindFramebufferEXT',
2057 'gen_func': 'GenFramebuffersEXT',
2060 'BindRenderbuffer': {
2062 'decoder_func': 'DoBindRenderbuffer',
2063 'gl_test_func': 'glBindRenderbufferEXT',
2064 'gen_func': 'GenRenderbuffersEXT',
2068 'id_mapping': [ 'Sampler' ],
2073 'decoder_func': 'DoBindTexture',
2074 'gen_func': 'GenTextures',
2075 # TODO(gman): remove this once client side caching works.
2076 'client_test': False,
2079 'BindTransformFeedback': {
2081 'id_mapping': [ 'TransformFeedback' ],
2084 'BlitFramebufferCHROMIUM': {
2085 'decoder_func': 'DoBlitFramebufferCHROMIUM',
2087 'extension_flag': 'chromium_framebuffer_multisample',
2088 'pepper_interface': 'FramebufferBlit',
2089 'pepper_name': 'BlitFramebufferEXT',
2090 'defer_reads': True,
2091 'defer_draws': True,
2096 'data_transfer_methods': ['shm'],
2097 'client_test': False,
2101 'client_test': False,
2102 'decoder_func': 'DoBufferSubData',
2103 'data_transfer_methods': ['shm'],
2105 'CheckFramebufferStatus': {
2107 'decoder_func': 'DoCheckFramebufferStatus',
2108 'gl_test_func': 'glCheckFramebufferStatusEXT',
2109 'error_value': 'GL_FRAMEBUFFER_UNSUPPORTED',
2110 'result': ['GLenum'],
2113 'decoder_func': 'DoClear',
2114 'defer_draws': True,
2119 'use_count_func': True,
2130 'use_count_func': True,
2139 'state': 'ClearColor',
2143 'state': 'ClearDepthf',
2144 'decoder_func': 'glClearDepth',
2145 'gl_test_func': 'glClearDepth',
2152 'data_transfer_methods': ['shm'],
2153 'cmd_args': 'GLuint sync, GLbitfieldSyncFlushFlags flags, '
2154 'GLuint timeout_0, GLuint timeout_1, GLenum* result',
2156 'result': ['GLenum'],
2160 'state': 'ColorMask',
2162 'expectation': False,
2164 'ConsumeTextureCHROMIUM': {
2165 'decoder_func': 'DoConsumeTextureCHROMIUM',
2168 'count': 64, # GL_MAILBOX_SIZE_CHROMIUM
2170 'client_test': False,
2171 'extension': "CHROMIUM_texture_mailbox",
2175 'CopyBufferSubData': {
2178 'CreateAndConsumeTextureCHROMIUM': {
2179 'decoder_func': 'DoCreateAndConsumeTextureCHROMIUM',
2181 'type': 'HandWritten',
2182 'data_transfer_methods': ['immediate'],
2184 'client_test': False,
2185 'extension': "CHROMIUM_texture_mailbox",
2188 'GenValuebuffersCHROMIUM': {
2190 'gl_test_func': 'glGenValuebuffersCHROMIUM',
2191 'resource_type': 'Valuebuffer',
2192 'resource_types': 'Valuebuffers',
2197 'DeleteValuebuffersCHROMIUM': {
2199 'gl_test_func': 'glDeleteValuebuffersCHROMIUM',
2200 'resource_type': 'Valuebuffer',
2201 'resource_types': 'Valuebuffers',
2206 'IsValuebufferCHROMIUM': {
2208 'decoder_func': 'DoIsValuebufferCHROMIUM',
2209 'expectation': False,
2213 'BindValuebufferCHROMIUM': {
2215 'decoder_func': 'DoBindValueBufferCHROMIUM',
2216 'gen_func': 'GenValueBuffersCHROMIUM',
2221 'SubscribeValueCHROMIUM': {
2222 'decoder_func': 'DoSubscribeValueCHROMIUM',
2227 'PopulateSubscribedValuesCHROMIUM': {
2228 'decoder_func': 'DoPopulateSubscribedValuesCHROMIUM',
2233 'UniformValuebufferCHROMIUM': {
2234 'decoder_func': 'DoUniformValueBufferCHROMIUM',
2241 'state': 'ClearStencil',
2243 'EnableFeatureCHROMIUM': {
2245 'data_transfer_methods': ['shm'],
2246 'decoder_func': 'DoEnableFeatureCHROMIUM',
2247 'expectation': False,
2248 'cmd_args': 'GLuint bucket_id, GLint* result',
2249 'result': ['GLint'],
2252 'pepper_interface': 'ChromiumEnableFeature',
2254 'CompileShader': {'decoder_func': 'DoCompileShader', 'unit_test': False},
2255 'CompressedTexImage2D': {
2257 'data_transfer_methods': ['bucket', 'shm'],
2259 'CompressedTexSubImage2D': {
2261 'data_transfer_methods': ['bucket', 'shm'],
2262 'decoder_func': 'DoCompressedTexSubImage2D',
2265 'decoder_func': 'DoCopyTexImage2D',
2267 'defer_reads': True,
2269 'CopyTexSubImage2D': {
2270 'decoder_func': 'DoCopyTexSubImage2D',
2271 'defer_reads': True,
2273 'CompressedTexImage3D': {
2275 'data_transfer_methods': ['bucket', 'shm'],
2278 'CompressedTexSubImage3D': {
2280 'data_transfer_methods': ['bucket', 'shm'],
2281 'decoder_func': 'DoCompressedTexSubImage3D',
2284 'CopyTexSubImage3D': {
2285 'defer_reads': True,
2288 'CreateImageCHROMIUM': {
2291 'ClientBuffer buffer, GLsizei width, GLsizei height, '
2292 'GLenum internalformat',
2293 'result': ['GLuint'],
2294 'client_test': False,
2296 'expectation': False,
2300 'DestroyImageCHROMIUM': {
2302 'client_test': False,
2307 'CreateGpuMemoryBufferImageCHROMIUM': {
2310 'GLsizei width, GLsizei height, GLenum internalformat, GLenum usage',
2311 'result': ['GLuint'],
2312 'client_test': False,
2314 'expectation': False,
2320 'client_test': False,
2324 'client_test': False,
2328 'state': 'BlendColor',
2331 'type': 'StateSetRGBAlpha',
2332 'state': 'BlendEquation',
2334 '0': 'GL_FUNC_SUBTRACT'
2337 'BlendEquationSeparate': {
2339 'state': 'BlendEquation',
2341 '0': 'GL_FUNC_SUBTRACT'
2345 'type': 'StateSetRGBAlpha',
2346 'state': 'BlendFunc',
2348 'BlendFuncSeparate': {
2350 'state': 'BlendFunc',
2352 'BlendBarrierKHR': {
2353 'gl_test_func': 'glBlendBarrierKHR',
2355 'extension_flag': 'blend_equation_advanced',
2356 'client_test': False,
2358 'SampleCoverage': {'decoder_func': 'DoSampleCoverage'},
2360 'type': 'StateSetFrontBack',
2361 'state': 'StencilFunc',
2363 'StencilFuncSeparate': {
2364 'type': 'StateSetFrontBackSeparate',
2365 'state': 'StencilFunc',
2368 'type': 'StateSetFrontBack',
2369 'state': 'StencilOp',
2374 'StencilOpSeparate': {
2375 'type': 'StateSetFrontBackSeparate',
2376 'state': 'StencilOp',
2382 'type': 'StateSetNamedParameter',
2385 'CullFace': {'type': 'StateSet', 'state': 'CullFace'},
2386 'FrontFace': {'type': 'StateSet', 'state': 'FrontFace'},
2387 'DepthFunc': {'type': 'StateSet', 'state': 'DepthFunc'},
2390 'state': 'LineWidth',
2397 'state': 'PolygonOffset',
2401 'gl_test_func': 'glDeleteBuffersARB',
2402 'resource_type': 'Buffer',
2403 'resource_types': 'Buffers',
2405 'DeleteFramebuffers': {
2407 'gl_test_func': 'glDeleteFramebuffersEXT',
2408 'resource_type': 'Framebuffer',
2409 'resource_types': 'Framebuffers',
2411 'DeleteProgram': { 'type': 'Delete' },
2412 'DeleteRenderbuffers': {
2414 'gl_test_func': 'glDeleteRenderbuffersEXT',
2415 'resource_type': 'Renderbuffer',
2416 'resource_types': 'Renderbuffers',
2420 'resource_type': 'Sampler',
2421 'resource_types': 'Samplers',
2424 'DeleteShader': { 'type': 'Delete' },
2427 'cmd_args': 'GLuint sync',
2428 'resource_type': 'Sync',
2433 'resource_type': 'Texture',
2434 'resource_types': 'Textures',
2436 'DeleteTransformFeedbacks': {
2438 'resource_type': 'TransformFeedback',
2439 'resource_types': 'TransformFeedbacks',
2443 'decoder_func': 'DoDepthRangef',
2444 'gl_test_func': 'glDepthRange',
2448 'state': 'DepthMask',
2450 'expectation': False,
2452 'DetachShader': {'decoder_func': 'DoDetachShader'},
2454 'decoder_func': 'DoDisable',
2456 'client_test': False,
2458 'DisableVertexAttribArray': {
2459 'decoder_func': 'DoDisableVertexAttribArray',
2464 'cmd_args': 'GLenumDrawMode mode, GLint first, GLsizei count',
2465 'defer_draws': True,
2470 'cmd_args': 'GLenumDrawMode mode, GLsizei count, '
2471 'GLenumIndexType type, GLuint index_offset',
2472 'client_test': False,
2473 'defer_draws': True,
2476 'DrawRangeElements': {
2482 'decoder_func': 'DoEnable',
2484 'client_test': False,
2486 'EnableVertexAttribArray': {
2487 'decoder_func': 'DoEnableVertexAttribArray',
2492 'client_test': False,
2497 'client_test': False,
2498 'decoder_func': 'DoFinish',
2499 'defer_reads': True,
2503 'decoder_func': 'DoFlush',
2505 'FramebufferRenderbuffer': {
2506 'decoder_func': 'DoFramebufferRenderbuffer',
2507 'gl_test_func': 'glFramebufferRenderbufferEXT',
2509 'FramebufferTexture2D': {
2510 'decoder_func': 'DoFramebufferTexture2D',
2511 'gl_test_func': 'glFramebufferTexture2DEXT',
2514 'FramebufferTexture2DMultisampleEXT': {
2515 'decoder_func': 'DoFramebufferTexture2DMultisample',
2516 'gl_test_func': 'glFramebufferTexture2DMultisampleEXT',
2517 'expectation': False,
2519 'extension_flag': 'multisampled_render_to_texture',
2522 'FramebufferTextureLayer': {
2523 'decoder_func': 'DoFramebufferTextureLayer',
2527 'decoder_func': 'DoGenerateMipmap',
2528 'gl_test_func': 'glGenerateMipmapEXT',
2532 'gl_test_func': 'glGenBuffersARB',
2533 'resource_type': 'Buffer',
2534 'resource_types': 'Buffers',
2536 'GenMailboxCHROMIUM': {
2537 'type': 'HandWritten',
2539 'extension': "CHROMIUM_texture_mailbox",
2542 'GenFramebuffers': {
2544 'gl_test_func': 'glGenFramebuffersEXT',
2545 'resource_type': 'Framebuffer',
2546 'resource_types': 'Framebuffers',
2548 'GenRenderbuffers': {
2549 'type': 'GENn', 'gl_test_func': 'glGenRenderbuffersEXT',
2550 'resource_type': 'Renderbuffer',
2551 'resource_types': 'Renderbuffers',
2555 'gl_test_func': 'glGenSamplers',
2556 'resource_type': 'Sampler',
2557 'resource_types': 'Samplers',
2562 'gl_test_func': 'glGenTextures',
2563 'resource_type': 'Texture',
2564 'resource_types': 'Textures',
2566 'GenTransformFeedbacks': {
2568 'gl_test_func': 'glGenTransformFeedbacks',
2569 'resource_type': 'TransformFeedback',
2570 'resource_types': 'TransformFeedbacks',
2573 'GetActiveAttrib': {
2575 'data_transfer_methods': ['shm'],
2577 'GLidProgram program, GLuint index, uint32_t name_bucket_id, '
2585 'GetActiveUniform': {
2587 'data_transfer_methods': ['shm'],
2589 'GLidProgram program, GLuint index, uint32_t name_bucket_id, '
2597 'GetActiveUniformBlockiv': {
2599 'data_transfer_methods': ['shm'],
2600 'result': ['SizedResult<GLint>'],
2603 'GetActiveUniformBlockName': {
2605 'data_transfer_methods': ['shm'],
2607 'GLidProgram program, GLuint index, uint32_t name_bucket_id, '
2609 'result': ['int32_t'],
2612 'GetActiveUniformsiv': {
2614 'data_transfer_methods': ['shm'],
2616 'GLidProgram program, uint32_t indices_bucket_id, GLenum pname, '
2618 'result': ['SizedResult<GLint>'],
2621 'GetAttachedShaders': {
2623 'data_transfer_methods': ['shm'],
2624 'cmd_args': 'GLidProgram program, void* result, uint32_t result_size',
2625 'result': ['SizedResult<GLuint>'],
2627 'GetAttribLocation': {
2629 'data_transfer_methods': ['shm'],
2631 'GLidProgram program, uint32_t name_bucket_id, GLint* location',
2632 'result': ['GLint'],
2635 'GetFragDataLocation': {
2637 'data_transfer_methods': ['shm'],
2639 'GLidProgram program, uint32_t name_bucket_id, GLint* location',
2640 'result': ['GLint'],
2646 'result': ['SizedResult<GLboolean>'],
2647 'decoder_func': 'DoGetBooleanv',
2648 'gl_test_func': 'glGetBooleanv',
2650 'GetBufferParameteriv': {
2652 'result': ['SizedResult<GLint>'],
2653 'decoder_func': 'DoGetBufferParameteriv',
2654 'expectation': False,
2659 'decoder_func': 'GetErrorState()->GetGLError',
2661 'result': ['GLenum'],
2662 'client_test': False,
2666 'result': ['SizedResult<GLfloat>'],
2667 'decoder_func': 'DoGetFloatv',
2668 'gl_test_func': 'glGetFloatv',
2670 'GetFramebufferAttachmentParameteriv': {
2672 'decoder_func': 'DoGetFramebufferAttachmentParameteriv',
2673 'gl_test_func': 'glGetFramebufferAttachmentParameterivEXT',
2674 'result': ['SizedResult<GLint>'],
2678 'result': ['SizedResult<GLint64>'],
2679 'client_test': False,
2680 'decoder_func': 'DoGetInteger64v',
2685 'result': ['SizedResult<GLint>'],
2686 'decoder_func': 'DoGetIntegerv',
2687 'client_test': False,
2689 'GetInteger64i_v': {
2691 'result': ['SizedResult<GLint64>'],
2692 'client_test': False,
2697 'result': ['SizedResult<GLint>'],
2698 'client_test': False,
2701 'GetInternalformativ': {
2703 'result': ['SizedResult<GLint>'],
2706 'GetMaxValueInBufferCHROMIUM': {
2708 'decoder_func': 'DoGetMaxValueInBufferCHROMIUM',
2709 'result': ['GLuint'],
2711 'client_test': False,
2718 'decoder_func': 'DoGetProgramiv',
2719 'result': ['SizedResult<GLint>'],
2720 'expectation': False,
2722 'GetProgramInfoCHROMIUM': {
2724 'expectation': False,
2728 'client_test': False,
2729 'cmd_args': 'GLidProgram program, uint32_t bucket_id',
2731 'uint32_t link_status',
2732 'uint32_t num_attribs',
2733 'uint32_t num_uniforms',
2736 'GetProgramInfoLog': {
2738 'expectation': False,
2740 'GetRenderbufferParameteriv': {
2742 'decoder_func': 'DoGetRenderbufferParameteriv',
2743 'gl_test_func': 'glGetRenderbufferParameterivEXT',
2744 'result': ['SizedResult<GLint>'],
2746 'GetSamplerParameterfv': {
2748 'result': ['SizedResult<GLfloat>'],
2749 'id_mapping': [ 'Sampler' ],
2752 'GetSamplerParameteriv': {
2754 'result': ['SizedResult<GLint>'],
2755 'id_mapping': [ 'Sampler' ],
2760 'decoder_func': 'DoGetShaderiv',
2761 'result': ['SizedResult<GLint>'],
2763 'GetShaderInfoLog': {
2765 'get_len_func': 'glGetShaderiv',
2766 'get_len_enum': 'GL_INFO_LOG_LENGTH',
2769 'GetShaderPrecisionFormat': {
2771 'data_transfer_methods': ['shm'],
2773 'GLenumShaderType shadertype, GLenumShaderPrecision precisiontype, '
2777 'int32_t min_range',
2778 'int32_t max_range',
2779 'int32_t precision',
2782 'GetShaderSource': {
2784 'get_len_func': 'DoGetShaderiv',
2785 'get_len_enum': 'GL_SHADER_SOURCE_LENGTH',
2787 'client_test': False,
2791 'client_test': False,
2792 'cmd_args': 'GLenumStringType name, uint32_t bucket_id',
2796 'cmd_args': 'GLuint sync, GLenumSyncParameter pname, void* values',
2797 'result': ['SizedResult<GLint>'],
2798 'id_mapping': ['Sync'],
2801 'GetTexParameterfv': {
2803 'decoder_func': 'DoGetTexParameterfv',
2804 'result': ['SizedResult<GLfloat>']
2806 'GetTexParameteriv': {
2808 'decoder_func': 'DoGetTexParameteriv',
2809 'result': ['SizedResult<GLint>']
2811 'GetTranslatedShaderSourceANGLE': {
2813 'get_len_func': 'DoGetShaderiv',
2814 'get_len_enum': 'GL_TRANSLATED_SHADER_SOURCE_LENGTH_ANGLE',
2818 'GetUniformBlockIndex': {
2820 'data_transfer_methods': ['shm'],
2822 'GLidProgram program, uint32_t name_bucket_id, GLuint* index',
2823 'result': ['GLuint'],
2824 'error_return': 'GL_INVALID_INDEX',
2827 'GetUniformBlocksCHROMIUM': {
2829 'expectation': False,
2833 'client_test': False,
2834 'cmd_args': 'GLidProgram program, uint32_t bucket_id',
2835 'result': ['uint32_t'],
2838 'GetUniformsES3CHROMIUM': {
2840 'expectation': False,
2844 'client_test': False,
2845 'cmd_args': 'GLidProgram program, uint32_t bucket_id',
2846 'result': ['uint32_t'],
2849 'GetTransformFeedbackVarying': {
2851 'data_transfer_methods': ['shm'],
2853 'GLidProgram program, GLuint index, uint32_t name_bucket_id, '
2862 'GetTransformFeedbackVaryingsCHROMIUM': {
2864 'expectation': False,
2868 'client_test': False,
2869 'cmd_args': 'GLidProgram program, uint32_t bucket_id',
2870 'result': ['uint32_t'],
2875 'data_transfer_methods': ['shm'],
2876 'result': ['SizedResult<GLfloat>'],
2880 'data_transfer_methods': ['shm'],
2881 'result': ['SizedResult<GLint>'],
2885 'data_transfer_methods': ['shm'],
2886 'result': ['SizedResult<GLuint>'],
2889 'GetUniformIndices': {
2891 'data_transfer_methods': ['shm'],
2892 'result': ['SizedResult<GLuint>'],
2893 'cmd_args': 'GLidProgram program, uint32_t names_bucket_id, '
2897 'GetUniformLocation': {
2899 'data_transfer_methods': ['shm'],
2901 'GLidProgram program, uint32_t name_bucket_id, GLint* location',
2902 'result': ['GLint'],
2903 'error_return': -1, # http://www.opengl.org/sdk/docs/man/xhtml/glGetUniformLocation.xml
2905 'GetVertexAttribfv': {
2907 'result': ['SizedResult<GLfloat>'],
2909 'decoder_func': 'DoGetVertexAttribfv',
2910 'expectation': False,
2911 'client_test': False,
2913 'GetVertexAttribiv': {
2915 'result': ['SizedResult<GLint>'],
2917 'decoder_func': 'DoGetVertexAttribiv',
2918 'expectation': False,
2919 'client_test': False,
2921 'GetVertexAttribIiv': {
2923 'result': ['SizedResult<GLint>'],
2925 'decoder_func': 'DoGetVertexAttribIiv',
2926 'expectation': False,
2927 'client_test': False,
2930 'GetVertexAttribIuiv': {
2932 'result': ['SizedResult<GLuint>'],
2934 'decoder_func': 'DoGetVertexAttribIuiv',
2935 'expectation': False,
2936 'client_test': False,
2939 'GetVertexAttribPointerv': {
2941 'data_transfer_methods': ['shm'],
2942 'result': ['SizedResult<GLuint>'],
2943 'client_test': False,
2945 'InvalidateFramebuffer': {
2948 'client_test': False,
2952 'InvalidateSubFramebuffer': {
2955 'client_test': False,
2961 'decoder_func': 'DoIsBuffer',
2962 'expectation': False,
2966 'decoder_func': 'DoIsEnabled',
2967 'client_test': False,
2969 'expectation': False,
2973 'decoder_func': 'DoIsFramebuffer',
2974 'expectation': False,
2978 'decoder_func': 'DoIsProgram',
2979 'expectation': False,
2983 'decoder_func': 'DoIsRenderbuffer',
2984 'expectation': False,
2988 'decoder_func': 'DoIsShader',
2989 'expectation': False,
2993 'id_mapping': [ 'Sampler' ],
2994 'expectation': False,
2999 'id_mapping': [ 'Sync' ],
3000 'cmd_args': 'GLuint sync',
3001 'expectation': False,
3006 'decoder_func': 'DoIsTexture',
3007 'expectation': False,
3009 'IsTransformFeedback': {
3011 'id_mapping': [ 'TransformFeedback' ],
3012 'expectation': False,
3016 'decoder_func': 'DoLinkProgram',
3019 'MapBufferCHROMIUM': {
3023 'client_test': False,
3025 'MapBufferSubDataCHROMIUM': {
3029 'client_test': False,
3030 'pepper_interface': 'ChromiumMapSub',
3032 'MapTexSubImage2DCHROMIUM': {
3034 'extension': "CHROMIUM_sub_image",
3036 'client_test': False,
3037 'pepper_interface': 'ChromiumMapSub',
3041 'data_transfer_methods': ['shm'],
3042 'cmd_args': 'GLenumBufferTarget target, GLintptrNotNegative offset, '
3043 'GLsizeiptr size, GLbitfieldMapBufferAccess access, '
3044 'uint32_t data_shm_id, uint32_t data_shm_offset, '
3045 'uint32_t result_shm_id, uint32_t result_shm_offset',
3047 'result': ['uint32_t'],
3049 'PauseTransformFeedback': {
3052 'PixelStorei': {'type': 'Manual'},
3053 'PostSubBufferCHROMIUM': {
3057 'client_test': False,
3061 'ProduceTextureCHROMIUM': {
3062 'decoder_func': 'DoProduceTextureCHROMIUM',
3065 'count': 64, # GL_MAILBOX_SIZE_CHROMIUM
3067 'client_test': False,
3068 'extension': "CHROMIUM_texture_mailbox",
3072 'ProduceTextureDirectCHROMIUM': {
3073 'decoder_func': 'DoProduceTextureDirectCHROMIUM',
3076 'count': 64, # GL_MAILBOX_SIZE_CHROMIUM
3078 'client_test': False,
3079 'extension': "CHROMIUM_texture_mailbox",
3083 'RenderbufferStorage': {
3084 'decoder_func': 'DoRenderbufferStorage',
3085 'gl_test_func': 'glRenderbufferStorageEXT',
3086 'expectation': False,
3088 'RenderbufferStorageMultisampleCHROMIUM': {
3090 '// GL_CHROMIUM_framebuffer_multisample\n',
3091 'decoder_func': 'DoRenderbufferStorageMultisampleCHROMIUM',
3092 'gl_test_func': 'glRenderbufferStorageMultisampleCHROMIUM',
3093 'expectation': False,
3095 'extension_flag': 'chromium_framebuffer_multisample',
3096 'pepper_interface': 'FramebufferMultisample',
3097 'pepper_name': 'RenderbufferStorageMultisampleEXT',
3099 'RenderbufferStorageMultisampleEXT': {
3101 '// GL_EXT_multisampled_render_to_texture\n',
3102 'decoder_func': 'DoRenderbufferStorageMultisampleEXT',
3103 'gl_test_func': 'glRenderbufferStorageMultisampleEXT',
3104 'expectation': False,
3106 'extension_flag': 'multisampled_render_to_texture',
3113 '// ReadPixels has the result separated from the pixel buffer so that\n'
3114 '// it is easier to specify the result going to some specific place\n'
3115 '// that exactly fits the rectangle of pixels.\n',
3117 'data_transfer_methods': ['shm'],
3119 'client_test': False,
3121 'GLint x, GLint y, GLsizei width, GLsizei height, '
3122 'GLenumReadPixelFormat format, GLenumReadPixelType type, '
3123 'uint32_t pixels_shm_id, uint32_t pixels_shm_offset, '
3124 'uint32_t result_shm_id, uint32_t result_shm_offset, '
3126 'result': ['uint32_t'],
3127 'defer_reads': True,
3129 'ReleaseShaderCompiler': {
3130 'decoder_func': 'DoReleaseShaderCompiler',
3133 'ResumeTransformFeedback': {
3136 'SamplerParameterf': {
3140 'id_mapping': [ 'Sampler' ],
3143 'SamplerParameterfv': {
3145 'data_value': 'GL_NEAREST',
3147 'gl_test_func': 'glSamplerParameterf',
3148 'decoder_func': 'DoSamplerParameterfv',
3149 'first_element_only': True,
3150 'id_mapping': [ 'Sampler' ],
3153 'SamplerParameteri': {
3157 'id_mapping': [ 'Sampler' ],
3160 'SamplerParameteriv': {
3162 'data_value': 'GL_NEAREST',
3164 'gl_test_func': 'glSamplerParameteri',
3165 'decoder_func': 'DoSamplerParameteriv',
3166 'first_element_only': True,
3171 'client_test': False,
3175 'decoder_func': 'DoShaderSource',
3176 'expectation': False,
3177 'data_transfer_methods': ['bucket'],
3179 'GLuint shader, const char** str',
3181 'GLuint shader, GLsizei count, const char** str, const GLint* length',
3184 'type': 'StateSetFrontBack',
3185 'state': 'StencilMask',
3187 'expectation': False,
3189 'StencilMaskSeparate': {
3190 'type': 'StateSetFrontBackSeparate',
3191 'state': 'StencilMask',
3193 'expectation': False,
3197 'decoder_func': 'DoSwapBuffers',
3199 'client_test': False,
3205 'decoder_func': 'DoSwapInterval',
3207 'client_test': False,
3213 'data_transfer_methods': ['shm'],
3214 'client_test': False,
3218 'data_transfer_methods': ['shm'],
3219 'client_test': False,
3223 'decoder_func': 'DoTexParameterf',
3229 'decoder_func': 'DoTexParameteri',
3236 'data_value': 'GL_NEAREST',
3238 'decoder_func': 'DoTexParameterfv',
3239 'gl_test_func': 'glTexParameterf',
3240 'first_element_only': True,
3244 'data_value': 'GL_NEAREST',
3246 'decoder_func': 'DoTexParameteriv',
3247 'gl_test_func': 'glTexParameteri',
3248 'first_element_only': True,
3255 'data_transfer_methods': ['shm'],
3256 'client_test': False,
3257 'cmd_args': 'GLenumTextureTarget target, GLint level, '
3258 'GLint xoffset, GLint yoffset, '
3259 'GLsizei width, GLsizei height, '
3260 'GLenumTextureFormat format, GLenumPixelType type, '
3261 'const void* pixels, GLboolean internal'
3265 'data_transfer_methods': ['shm'],
3266 'client_test': False,
3267 'cmd_args': 'GLenumTextureTarget target, GLint level, '
3268 'GLint xoffset, GLint yoffset, GLint zoffset, '
3269 'GLsizei width, GLsizei height, GLsizei depth, '
3270 'GLenumTextureFormat format, GLenumPixelType type, '
3271 'const void* pixels, GLboolean internal',
3274 'TransformFeedbackVaryings': {
3276 'data_transfer_methods': ['bucket'],
3277 'decoder_func': 'DoTransformFeedbackVaryings',
3279 'GLuint program, const char** varyings, GLenum buffermode',
3282 'Uniform1f': {'type': 'PUTXn', 'count': 1},
3286 'decoder_func': 'DoUniform1fv',
3288 'Uniform1i': {'decoder_func': 'DoUniform1i', 'unit_test': False},
3292 'decoder_func': 'DoUniform1iv',
3305 'Uniform2i': {'type': 'PUTXn', 'count': 2},
3306 'Uniform2f': {'type': 'PUTXn', 'count': 2},
3310 'decoder_func': 'DoUniform2fv',
3315 'decoder_func': 'DoUniform2iv',
3327 'Uniform3i': {'type': 'PUTXn', 'count': 3},
3328 'Uniform3f': {'type': 'PUTXn', 'count': 3},
3332 'decoder_func': 'DoUniform3fv',
3337 'decoder_func': 'DoUniform3iv',
3349 'Uniform4i': {'type': 'PUTXn', 'count': 4},
3350 'Uniform4f': {'type': 'PUTXn', 'count': 4},
3354 'decoder_func': 'DoUniform4fv',
3359 'decoder_func': 'DoUniform4iv',
3371 'UniformMatrix2fv': {
3374 'decoder_func': 'DoUniformMatrix2fv',
3376 'UniformMatrix2x3fv': {
3381 'UniformMatrix2x4fv': {
3386 'UniformMatrix3fv': {
3389 'decoder_func': 'DoUniformMatrix3fv',
3391 'UniformMatrix3x2fv': {
3396 'UniformMatrix3x4fv': {
3401 'UniformMatrix4fv': {
3404 'decoder_func': 'DoUniformMatrix4fv',
3406 'UniformMatrix4x2fv': {
3411 'UniformMatrix4x3fv': {
3416 'UniformBlockBinding': {
3421 'UnmapBufferCHROMIUM': {
3425 'client_test': False,
3427 'UnmapBufferSubDataCHROMIUM': {
3431 'client_test': False,
3432 'pepper_interface': 'ChromiumMapSub',
3438 'UnmapTexSubImage2DCHROMIUM': {
3440 'extension': "CHROMIUM_sub_image",
3442 'client_test': False,
3443 'pepper_interface': 'ChromiumMapSub',
3447 'decoder_func': 'DoUseProgram',
3449 'ValidateProgram': {'decoder_func': 'DoValidateProgram'},
3450 'VertexAttrib1f': {'decoder_func': 'DoVertexAttrib1f'},
3451 'VertexAttrib1fv': {
3454 'decoder_func': 'DoVertexAttrib1fv',
3456 'VertexAttrib2f': {'decoder_func': 'DoVertexAttrib2f'},
3457 'VertexAttrib2fv': {
3460 'decoder_func': 'DoVertexAttrib2fv',
3462 'VertexAttrib3f': {'decoder_func': 'DoVertexAttrib3f'},
3463 'VertexAttrib3fv': {
3466 'decoder_func': 'DoVertexAttrib3fv',
3468 'VertexAttrib4f': {'decoder_func': 'DoVertexAttrib4f'},
3469 'VertexAttrib4fv': {
3472 'decoder_func': 'DoVertexAttrib4fv',
3474 'VertexAttribI4i': {
3476 'decoder_func': 'DoVertexAttribI4i',
3478 'VertexAttribI4iv': {
3482 'decoder_func': 'DoVertexAttribI4iv',
3484 'VertexAttribI4ui': {
3486 'decoder_func': 'DoVertexAttribI4ui',
3488 'VertexAttribI4uiv': {
3492 'decoder_func': 'DoVertexAttribI4uiv',
3494 'VertexAttribIPointer': {
3496 'cmd_args': 'GLuint indx, GLintVertexAttribSize size, '
3497 'GLenumVertexAttribIType type, GLsizei stride, '
3499 'client_test': False,
3502 'VertexAttribPointer': {
3504 'cmd_args': 'GLuint indx, GLintVertexAttribSize size, '
3505 'GLenumVertexAttribType type, GLboolean normalized, '
3506 'GLsizei stride, GLuint offset',
3507 'client_test': False,
3511 'cmd_args': 'GLuint sync, GLbitfieldSyncFlushFlags flags, '
3512 'GLuint timeout_0, GLuint timeout_1',
3514 'client_test': False,
3522 'decoder_func': 'DoViewport',
3531 'GetRequestableExtensionsCHROMIUM': {
3534 'cmd_args': 'uint32_t bucket_id',
3538 'RequestExtensionCHROMIUM': {
3541 'client_test': False,
3542 'cmd_args': 'uint32_t bucket_id',
3546 'RateLimitOffscreenContextCHROMIUM': {
3550 'client_test': False,
3552 'CreateStreamTextureCHROMIUM': {
3553 'type': 'HandWritten',
3559 'TexImageIOSurface2DCHROMIUM': {
3560 'decoder_func': 'DoTexImageIOSurface2DCHROMIUM',
3565 'CopyTextureCHROMIUM': {
3566 'decoder_func': 'DoCopyTextureCHROMIUM',
3571 'CopySubTextureCHROMIUM': {
3572 'decoder_func': 'DoCopySubTextureCHROMIUM',
3577 'TexStorage2DEXT': {
3580 'decoder_func': 'DoTexStorage2DEXT',
3582 'DrawArraysInstancedANGLE': {
3584 'cmd_args': 'GLenumDrawMode mode, GLint first, GLsizei count, '
3585 'GLsizei primcount',
3588 'pepper_interface': 'InstancedArrays',
3589 'defer_draws': True,
3593 'decoder_func': 'DoDrawBuffersEXT',
3595 'client_test': False,
3597 # could use 'extension_flag': 'ext_draw_buffers' but currently expected to
3600 'pepper_interface': 'DrawBuffers',
3602 'DrawElementsInstancedANGLE': {
3604 'cmd_args': 'GLenumDrawMode mode, GLsizei count, '
3605 'GLenumIndexType type, GLuint index_offset, GLsizei primcount',
3608 'client_test': False,
3609 'pepper_interface': 'InstancedArrays',
3610 'defer_draws': True,
3612 'VertexAttribDivisorANGLE': {
3614 'cmd_args': 'GLuint index, GLuint divisor',
3617 'pepper_interface': 'InstancedArrays',
3621 'gl_test_func': 'glGenQueriesARB',
3622 'resource_type': 'Query',
3623 'resource_types': 'Queries',
3625 'pepper_interface': 'Query',
3626 'not_shared': 'True',
3627 'extension': "occlusion_query_EXT",
3629 'DeleteQueriesEXT': {
3631 'gl_test_func': 'glDeleteQueriesARB',
3632 'resource_type': 'Query',
3633 'resource_types': 'Queries',
3635 'pepper_interface': 'Query',
3636 'extension': "occlusion_query_EXT",
3640 'client_test': False,
3641 'pepper_interface': 'Query',
3642 'extension': "occlusion_query_EXT",
3646 'cmd_args': 'GLenumQueryTarget target, GLidQuery id, void* sync_data',
3647 'data_transfer_methods': ['shm'],
3648 'gl_test_func': 'glBeginQuery',
3649 'pepper_interface': 'Query',
3650 'extension': "occlusion_query_EXT",
3652 'BeginTransformFeedback': {
3657 'cmd_args': 'GLenumQueryTarget target, GLuint submit_count',
3658 'gl_test_func': 'glEndnQuery',
3659 'client_test': False,
3660 'pepper_interface': 'Query',
3661 'extension': "occlusion_query_EXT",
3663 'EndTransformFeedback': {
3668 'client_test': False,
3669 'gl_test_func': 'glGetQueryiv',
3670 'pepper_interface': 'Query',
3671 'extension': "occlusion_query_EXT",
3673 'GetQueryObjectuivEXT': {
3675 'client_test': False,
3676 'gl_test_func': 'glGetQueryObjectuiv',
3677 'pepper_interface': 'Query',
3678 'extension': "occlusion_query_EXT",
3680 'BindUniformLocationCHROMIUM': {
3683 'data_transfer_methods': ['bucket'],
3685 'gl_test_func': 'DoBindUniformLocationCHROMIUM',
3687 'InsertEventMarkerEXT': {
3689 'decoder_func': 'DoInsertEventMarkerEXT',
3690 'expectation': False,
3693 'PushGroupMarkerEXT': {
3695 'decoder_func': 'DoPushGroupMarkerEXT',
3696 'expectation': False,
3699 'PopGroupMarkerEXT': {
3700 'decoder_func': 'DoPopGroupMarkerEXT',
3701 'expectation': False,
3706 'GenVertexArraysOES': {
3709 'gl_test_func': 'glGenVertexArraysOES',
3710 'resource_type': 'VertexArray',
3711 'resource_types': 'VertexArrays',
3713 'pepper_interface': 'VertexArrayObject',
3715 'BindVertexArrayOES': {
3718 'gl_test_func': 'glBindVertexArrayOES',
3719 'decoder_func': 'DoBindVertexArrayOES',
3720 'gen_func': 'GenVertexArraysOES',
3722 'client_test': False,
3723 'pepper_interface': 'VertexArrayObject',
3725 'DeleteVertexArraysOES': {
3728 'gl_test_func': 'glDeleteVertexArraysOES',
3729 'resource_type': 'VertexArray',
3730 'resource_types': 'VertexArrays',
3732 'pepper_interface': 'VertexArrayObject',
3734 'IsVertexArrayOES': {
3737 'gl_test_func': 'glIsVertexArrayOES',
3738 'decoder_func': 'DoIsVertexArrayOES',
3739 'expectation': False,
3741 'pepper_interface': 'VertexArrayObject',
3743 'BindTexImage2DCHROMIUM': {
3744 'decoder_func': 'DoBindTexImage2DCHROMIUM',
3749 'ReleaseTexImage2DCHROMIUM': {
3750 'decoder_func': 'DoReleaseTexImage2DCHROMIUM',
3755 'ShallowFinishCHROMIUM': {
3760 'client_test': False,
3762 'ShallowFlushCHROMIUM': {
3765 'extension': "CHROMIUM_miscellaneous",
3767 'client_test': False,
3769 'OrderingBarrierCHROMIUM': {
3774 'client_test': False,
3776 'TraceBeginCHROMIUM': {
3779 'client_test': False,
3780 'cmd_args': 'GLuint category_bucket_id, GLuint name_bucket_id',
3784 'TraceEndCHROMIUM': {
3786 'client_test': False,
3787 'decoder_func': 'DoTraceEndCHROMIUM',
3792 'AsyncTexImage2DCHROMIUM': {
3794 'data_transfer_methods': ['shm'],
3795 'client_test': False,
3796 'cmd_args': 'GLenumTextureTarget target, GLint level, '
3797 'GLintTextureInternalFormat internalformat, '
3798 'GLsizei width, GLsizei height, '
3799 'GLintTextureBorder border, '
3800 'GLenumTextureFormat format, GLenumPixelType type, '
3801 'const void* pixels, '
3802 'uint32_t async_upload_token, '
3807 'AsyncTexSubImage2DCHROMIUM': {
3809 'data_transfer_methods': ['shm'],
3810 'client_test': False,
3811 'cmd_args': 'GLenumTextureTarget target, GLint level, '
3812 'GLint xoffset, GLint yoffset, '
3813 'GLsizei width, GLsizei height, '
3814 'GLenumTextureFormat format, GLenumPixelType type, '
3815 'const void* data, '
3816 'uint32_t async_upload_token, '
3821 'WaitAsyncTexImage2DCHROMIUM': {
3823 'client_test': False,
3827 'WaitAllAsyncTexImage2DCHROMIUM': {
3829 'client_test': False,
3833 'DiscardFramebufferEXT': {
3836 'decoder_func': 'DoDiscardFramebufferEXT',
3838 'client_test': False,
3839 'extension_flag': 'ext_discard_framebuffer',
3841 'LoseContextCHROMIUM': {
3842 'decoder_func': 'DoLoseContextCHROMIUM',
3847 'InsertSyncPointCHROMIUM': {
3848 'type': 'HandWritten',
3850 'extension': "CHROMIUM_sync_point",
3853 'WaitSyncPointCHROMIUM': {
3856 'extension': "CHROMIUM_sync_point",
3860 'DiscardBackbufferCHROMIUM': {
3866 'ScheduleOverlayPlaneCHROMIUM': {
3870 'client_test': False,
3874 'MatrixLoadfCHROMIUM': {
3877 'data_type': 'GLfloat',
3878 'decoder_func': 'DoMatrixLoadfCHROMIUM',
3879 'gl_test_func': 'glMatrixLoadfEXT',
3882 'extension_flag': 'chromium_path_rendering',
3884 'MatrixLoadIdentityCHROMIUM': {
3885 'decoder_func': 'DoMatrixLoadIdentityCHROMIUM',
3886 'gl_test_func': 'glMatrixLoadIdentityEXT',
3889 'extension_flag': 'chromium_path_rendering',
3894 def Grouper(n
, iterable
, fillvalue
=None):
3895 """Collect data into fixed-length chunks or blocks"""
3896 args
= [iter(iterable
)] * n
3897 return itertools
.izip_longest(fillvalue
=fillvalue
, *args
)
3900 def SplitWords(input_string
):
3901 """Transforms a input_string into a list of lower-case components.
3904 input_string: the input string.
3907 a list of lower-case words.
3909 if input_string
.find('_') > -1:
3910 # 'some_TEXT_' -> 'some text'
3911 return input_string
.replace('_', ' ').strip().lower().split()
3913 if re
.search('[A-Z]', input_string
) and re
.search('[a-z]', input_string
):
3915 # look for capitalization to cut input_strings
3916 # 'SomeText' -> 'Some Text'
3917 input_string
= re
.sub('([A-Z])', r
' \1', input_string
).strip()
3918 # 'Vector3' -> 'Vector 3'
3919 input_string
= re
.sub('([^0-9])([0-9])', r
'\1 \2', input_string
)
3920 return input_string
.lower().split()
3924 """Makes a lower-case identifier from words.
3927 words: a list of lower-case words.
3930 the lower-case identifier.
3932 return '_'.join(words
)
3935 def ToUnderscore(input_string
):
3936 """converts CamelCase to camel_case."""
3937 words
= SplitWords(input_string
)
3940 def CachedStateName(item
):
3941 if item
.get('cached', False):
3942 return 'cached_' + item
['name']
3945 def ToGLExtensionString(extension_flag
):
3946 """Returns GL-type extension string of a extension flag."""
3947 if extension_flag
== "oes_compressed_etc1_rgb8_texture":
3948 return "OES_compressed_ETC1_RGB8_texture" # Fixup inconsitency with rgb8,
3950 uppercase_words
= [ 'img', 'ext', 'arb', 'chromium', 'oes', 'amd', 'bgra8888',
3951 'egl', 'atc', 'etc1', 'angle']
3952 parts
= extension_flag
.split('_')
3954 [part
.upper() if part
in uppercase_words
else part
for part
in parts
])
3956 def ToCamelCase(input_string
):
3957 """converts ABC_underscore_case to ABCUnderscoreCase."""
3958 return ''.join(w
[0].upper() + w
[1:] for w
in input_string
.split('_'))
3960 def GetGLGetTypeConversion(result_type
, value_type
, value
):
3961 """Makes a gl compatible type conversion string for accessing state variables.
3963 Useful when accessing state variables through glGetXXX calls.
3964 glGet documetation (for example, the manual pages):
3965 [...] If glGetIntegerv is called, [...] most floating-point values are
3966 rounded to the nearest integer value. [...]
3969 result_type: the gl type to be obtained
3970 value_type: the GL type of the state variable
3971 value: the name of the state variable
3974 String that converts the state variable to desired GL type according to GL
3978 if result_type
== 'GLint':
3979 if value_type
== 'GLfloat':
3980 return 'static_cast<GLint>(round(%s))' % value
3981 return 'static_cast<%s>(%s)' % (result_type
, value
)
3983 class CWriter(object):
3984 """Writes to a file formatting it for Google's style guidelines."""
3986 def __init__(self
, filename
):
3987 self
.filename
= filename
3990 def Write(self
, string
):
3991 """Writes a string to a file spliting if it's > 80 characters."""
3992 lines
= string
.splitlines()
3993 num_lines
= len(lines
)
3994 for ii
in range(0, num_lines
):
3995 self
.content
.append(lines
[ii
])
3996 if ii
< (num_lines
- 1) or string
[-1] == '\n':
3997 self
.content
.append('\n')
4000 """Close the file."""
4001 content
= "".join(self
.content
)
4003 if os
.path
.exists(self
.filename
):
4004 old_file
= open(self
.filename
, "rb");
4005 old_content
= old_file
.read()
4007 if content
== old_content
:
4010 file = open(self
.filename
, "wb")
4015 class CHeaderWriter(CWriter
):
4016 """Writes a C Header file."""
4018 _non_alnum_re
= re
.compile(r
'[^a-zA-Z0-9]')
4020 def __init__(self
, filename
, file_comment
= None):
4021 CWriter
.__init
__(self
, filename
)
4023 base
= os
.path
.abspath(filename
)
4024 while os
.path
.basename(base
) != 'src':
4025 new_base
= os
.path
.dirname(base
)
4026 assert new_base
!= base
# Prevent infinite loop.
4029 hpath
= os
.path
.relpath(filename
, base
)
4030 self
.guard
= self
._non
_alnum
_re
.sub('_', hpath
).upper() + '_'
4032 self
.Write(_LICENSE
)
4033 self
.Write(_DO_NOT_EDIT_WARNING
)
4034 if not file_comment
== None:
4035 self
.Write(file_comment
)
4036 self
.Write("#ifndef %s\n" % self
.guard
)
4037 self
.Write("#define %s\n\n" % self
.guard
)
4040 self
.Write("#endif // %s\n\n" % self
.guard
)
4043 class TypeHandler(object):
4044 """This class emits code for a particular type of function."""
4046 _remove_expected_call_re
= re
.compile(r
' EXPECT_CALL.*?;\n', re
.S
)
4051 def InitFunction(self
, func
):
4052 """Add or adjust anything type specific for this function."""
4053 if func
.GetInfo('needs_size') and not func
.name
.endswith('Bucket'):
4054 func
.AddCmdArg(DataSizeArgument('data_size'))
4056 def NeedsDataTransferFunction(self
, func
):
4057 """Overriden from TypeHandler."""
4058 return func
.num_pointer_args
>= 1
4060 def WriteStruct(self
, func
, file):
4061 """Writes a structure that matches the arguments to a function."""
4062 comment
= func
.GetInfo('cmd_comment')
4063 if not comment
== None:
4065 file.Write("struct %s {\n" % func
.name
)
4066 file.Write(" typedef %s ValueType;\n" % func
.name
)
4067 file.Write(" static const CommandId kCmdId = k%s;\n" % func
.name
)
4068 func
.WriteCmdArgFlag(file)
4069 func
.WriteCmdFlag(file)
4071 result
= func
.GetInfo('result')
4072 if not result
== None:
4073 if len(result
) == 1:
4074 file.Write(" typedef %s Result;\n\n" % result
[0])
4076 file.Write(" struct Result {\n")
4078 file.Write(" %s;\n" % line
)
4079 file.Write(" };\n\n")
4081 func
.WriteCmdComputeSize(file)
4082 func
.WriteCmdSetHeader(file)
4083 func
.WriteCmdInit(file)
4084 func
.WriteCmdSet(file)
4086 file.Write(" gpu::CommandHeader header;\n")
4087 args
= func
.GetCmdArgs()
4089 file.Write(" %s %s;\n" % (arg
.cmd_type
, arg
.name
))
4091 consts
= func
.GetCmdConstants()
4092 for const
in consts
:
4093 file.Write(" static const %s %s = %s;\n" %
4094 (const
.cmd_type
, const
.name
, const
.GetConstantValue()))
4099 size
= len(args
) * _SIZE_OF_UINT32
+ _SIZE_OF_COMMAND_HEADER
4100 file.Write("static_assert(sizeof(%s) == %d,\n" % (func
.name
, size
))
4101 file.Write(" \"size of %s should be %d\");\n" %
4103 file.Write("static_assert(offsetof(%s, header) == 0,\n" % func
.name
)
4104 file.Write(" \"offset of %s header should be 0\");\n" %
4106 offset
= _SIZE_OF_COMMAND_HEADER
4108 file.Write("static_assert(offsetof(%s, %s) == %d,\n" %
4109 (func
.name
, arg
.name
, offset
))
4110 file.Write(" \"offset of %s %s should be %d\");\n" %
4111 (func
.name
, arg
.name
, offset
))
4112 offset
+= _SIZE_OF_UINT32
4113 if not result
== None and len(result
) > 1:
4116 parts
= line
.split()
4119 static_assert(offsetof(%(cmd_name)s::Result, %(field_name)s) == %(offset)d,
4120 "offset of %(cmd_name)s Result %(field_name)s should be "
4123 file.Write((check
.strip() + "\n") % {
4124 'cmd_name': func
.name
,
4128 offset
+= _SIZE_OF_UINT32
4131 def WriteHandlerImplementation(self
, func
, file):
4132 """Writes the handler implementation for this command."""
4133 if func
.IsUnsafe() and func
.GetInfo('id_mapping'):
4134 code_no_gen
= """ if (!group_->Get%(type)sServiceId(
4135 %(var)s, &%(service_var)s)) {
4136 LOCAL_SET_GL_ERROR(GL_INVALID_OPERATION, "%(func)s", "invalid %(var)s id");
4137 return error::kNoError;
4140 code_gen
= """ if (!group_->Get%(type)sServiceId(
4141 %(var)s, &%(service_var)s)) {
4142 if (!group_->bind_generates_resource()) {
4144 GL_INVALID_OPERATION, "%(func)s", "invalid %(var)s id");
4145 return error::kNoError;
4147 GLuint client_id = %(var)s;
4148 gl%(gen_func)s(1, &%(service_var)s);
4149 Create%(type)s(client_id, %(service_var)s);
4152 gen_func
= func
.GetInfo('gen_func')
4153 for id_type
in func
.GetInfo('id_mapping'):
4154 service_var
= id_type
.lower()
4155 if id_type
== 'Sync':
4156 service_var
= "service_%s" % service_var
4157 file.Write(" GLsync %s = 0;\n" % service_var
)
4158 if gen_func
and id_type
in gen_func
:
4159 file.Write(code_gen
% { 'type': id_type
,
4160 'var': id_type
.lower(),
4161 'service_var': service_var
,
4162 'func': func
.GetGLFunctionName(),
4163 'gen_func': gen_func
})
4165 file.Write(code_no_gen
% { 'type': id_type
,
4166 'var': id_type
.lower(),
4167 'service_var': service_var
,
4168 'func': func
.GetGLFunctionName() })
4170 for arg
in func
.GetOriginalArgs():
4171 if arg
.type == "GLsync":
4172 args
.append("service_%s" % arg
.name
)
4173 elif arg
.name
.endswith("size") and arg
.type == "GLsizei":
4174 args
.append("num_%s" % func
.GetLastOriginalArg().name
)
4175 elif arg
.name
== "length":
4176 args
.append("nullptr")
4178 args
.append(arg
.name
)
4179 file.Write(" %s(%s);\n" %
4180 (func
.GetGLFunctionName(), ", ".join(args
)))
4182 def WriteCmdSizeTest(self
, func
, file):
4183 """Writes the size test for a command."""
4184 file.Write(" EXPECT_EQ(sizeof(cmd), cmd.header.size * 4u);\n")
4186 def WriteFormatTest(self
, func
, file):
4187 """Writes a format test for a command."""
4188 file.Write("TEST_F(GLES2FormatTest, %s) {\n" % func
.name
)
4189 file.Write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
4190 (func
.name
, func
.name
))
4191 file.Write(" void* next_cmd = cmd.Set(\n")
4193 args
= func
.GetCmdArgs()
4194 for value
, arg
in enumerate(args
):
4195 file.Write(",\n static_cast<%s>(%d)" % (arg
.type, value
+ 11))
4197 file.Write(" EXPECT_EQ(static_cast<uint32_t>(cmds::%s::kCmdId),\n" %
4199 file.Write(" cmd.header.command);\n")
4200 func
.type_handler
.WriteCmdSizeTest(func
, file)
4201 for value
, arg
in enumerate(args
):
4202 file.Write(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);\n" %
4203 (arg
.type, value
+ 11, arg
.name
))
4204 file.Write(" CheckBytesWrittenMatchesExpectedSize(\n")
4205 file.Write(" next_cmd, sizeof(cmd));\n")
4209 def WriteImmediateFormatTest(self
, func
, file):
4210 """Writes a format test for an immediate version of a command."""
4213 def WriteBucketFormatTest(self
, func
, file):
4214 """Writes a format test for a bucket version of a command."""
4217 def WriteGetDataSizeCode(self
, func
, file):
4218 """Writes the code to set data_size used in validation"""
4221 def WriteImmediateCmdSizeTest(self
, func
, file):
4222 """Writes a size test for an immediate version of a command."""
4223 file.Write(" // TODO(gman): Compute correct size.\n")
4224 file.Write(" EXPECT_EQ(sizeof(cmd), cmd.header.size * 4u);\n")
4226 def __WriteIdMapping(self
, func
, file):
4227 """Writes client side / service side ID mapping."""
4228 if not func
.IsUnsafe() or not func
.GetInfo('id_mapping'):
4230 for id_type
in func
.GetInfo('id_mapping'):
4231 file.Write(" group_->Get%sServiceId(%s, &%s);\n" %
4232 (id_type
, id_type
.lower(), id_type
.lower()))
4234 def WriteImmediateHandlerImplementation (self
, func
, file):
4235 """Writes the handler impl for the immediate version of a command."""
4236 self
.__WriteIdMapping
(func
, file)
4237 file.Write(" %s(%s);\n" %
4238 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
4240 def WriteBucketHandlerImplementation (self
, func
, file):
4241 """Writes the handler impl for the bucket version of a command."""
4242 self
.__WriteIdMapping
(func
, file)
4243 file.Write(" %s(%s);\n" %
4244 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
4246 def WriteServiceHandlerFunctionHeader(self
, func
, file):
4247 """Writes function header for service implementation handlers."""
4248 file.Write("""error::Error GLES2DecoderImpl::Handle%(name)s(
4249 uint32_t immediate_data_size, const void* cmd_data) {
4250 """ % {'name': func
.name
})
4252 file.Write("""if (!unsafe_es3_apis_enabled())
4253 return error::kUnknownCommand;
4255 file.Write("""const gles2::cmds::%(name)s& c =
4256 *static_cast<const gles2::cmds::%(name)s*>(cmd_data);
4258 """ % {'name': func
.name
})
4260 def WriteServiceImplementation(self
, func
, file):
4261 """Writes the service implementation for a command."""
4262 self
.WriteServiceHandlerFunctionHeader(func
, file)
4263 self
.WriteHandlerExtensionCheck(func
, file)
4264 self
.WriteHandlerDeferReadWrite(func
, file);
4265 if len(func
.GetOriginalArgs()) > 0:
4266 last_arg
= func
.GetLastOriginalArg()
4267 all_but_last_arg
= func
.GetOriginalArgs()[:-1]
4268 for arg
in all_but_last_arg
:
4269 arg
.WriteGetCode(file)
4270 self
.WriteGetDataSizeCode(func
, file)
4271 last_arg
.WriteGetCode(file)
4272 func
.WriteHandlerValidation(file)
4273 func
.WriteHandlerImplementation(file)
4274 file.Write(" return error::kNoError;\n")
4278 def WriteImmediateServiceImplementation(self
, func
, file):
4279 """Writes the service implementation for an immediate version of command."""
4280 self
.WriteServiceHandlerFunctionHeader(func
, file)
4281 self
.WriteHandlerExtensionCheck(func
, file)
4282 self
.WriteHandlerDeferReadWrite(func
, file);
4283 for arg
in func
.GetOriginalArgs():
4285 self
.WriteGetDataSizeCode(func
, file)
4286 arg
.WriteGetCode(file)
4287 func
.WriteHandlerValidation(file)
4288 func
.WriteHandlerImplementation(file)
4289 file.Write(" return error::kNoError;\n")
4293 def WriteBucketServiceImplementation(self
, func
, file):
4294 """Writes the service implementation for a bucket version of command."""
4295 self
.WriteServiceHandlerFunctionHeader(func
, file)
4296 self
.WriteHandlerExtensionCheck(func
, file)
4297 self
.WriteHandlerDeferReadWrite(func
, file);
4298 for arg
in func
.GetCmdArgs():
4299 arg
.WriteGetCode(file)
4300 func
.WriteHandlerValidation(file)
4301 func
.WriteHandlerImplementation(file)
4302 file.Write(" return error::kNoError;\n")
4306 def WriteHandlerExtensionCheck(self
, func
, file):
4307 if func
.GetInfo('extension_flag'):
4308 file.Write(" if (!features().%s) {\n" % func
.GetInfo('extension_flag'))
4309 file.Write(" LOCAL_SET_GL_ERROR(GL_INVALID_OPERATION, \"gl%s\","
4310 " \"function not available\");\n" % func
.original_name
)
4311 file.Write(" return error::kNoError;")
4312 file.Write(" }\n\n")
4314 def WriteHandlerDeferReadWrite(self
, func
, file):
4315 """Writes the code to handle deferring reads or writes."""
4316 defer_draws
= func
.GetInfo('defer_draws')
4317 defer_reads
= func
.GetInfo('defer_reads')
4318 if defer_draws
or defer_reads
:
4319 file.Write(" error::Error error;\n")
4321 file.Write(" error = WillAccessBoundFramebufferForDraw();\n")
4322 file.Write(" if (error != error::kNoError)\n")
4323 file.Write(" return error;\n")
4325 file.Write(" error = WillAccessBoundFramebufferForRead();\n")
4326 file.Write(" if (error != error::kNoError)\n")
4327 file.Write(" return error;\n")
4329 def WriteValidUnitTest(self
, func
, file, test
, *extras
):
4330 """Writes a valid unit test for the service implementation."""
4331 if func
.GetInfo('expectation') == False:
4332 test
= self
._remove
_expected
_call
_re
.sub('', test
)
4335 arg
.GetValidArg(func
) \
4336 for arg
in func
.GetOriginalArgs() if not arg
.IsConstant()
4339 arg
.GetValidGLArg(func
) \
4340 for arg
in func
.GetOriginalArgs()
4342 gl_func_name
= func
.GetGLTestFunctionName()
4345 'gl_func_name': gl_func_name
,
4346 'args': ", ".join(arg_strings
),
4347 'gl_args': ", ".join(gl_arg_strings
),
4349 for extra
in extras
:
4352 while (old_test
!= test
):
4355 file.Write(test
% vars)
4357 def WriteInvalidUnitTest(self
, func
, file, test
, *extras
):
4358 """Writes an invalid unit test for the service implementation."""
4361 for invalid_arg_index
, invalid_arg
in enumerate(func
.GetOriginalArgs()):
4362 # Service implementation does not test constants, as they are not part of
4363 # the call in the service side.
4364 if invalid_arg
.IsConstant():
4367 num_invalid_values
= invalid_arg
.GetNumInvalidValues(func
)
4368 for value_index
in range(0, num_invalid_values
):
4370 parse_result
= "kNoError"
4372 for arg
in func
.GetOriginalArgs():
4373 if arg
.IsConstant():
4375 if invalid_arg
is arg
:
4376 (arg_string
, parse_result
, gl_error
) = arg
.GetInvalidArg(
4379 arg_string
= arg
.GetValidArg(func
)
4380 arg_strings
.append(arg_string
)
4382 for arg
in func
.GetOriginalArgs():
4383 gl_arg_strings
.append("_")
4384 gl_func_name
= func
.GetGLTestFunctionName()
4386 if not gl_error
== None:
4387 gl_error_test
= '\n EXPECT_EQ(%s, GetGLError());' % gl_error
4391 'arg_index': invalid_arg_index
,
4392 'value_index': value_index
,
4393 'gl_func_name': gl_func_name
,
4394 'args': ", ".join(arg_strings
),
4395 'all_but_last_args': ", ".join(arg_strings
[:-1]),
4396 'gl_args': ", ".join(gl_arg_strings
),
4397 'parse_result': parse_result
,
4398 'gl_error_test': gl_error_test
,
4400 for extra
in extras
:
4402 file.Write(test
% vars)
4404 def WriteServiceUnitTest(self
, func
, file, *extras
):
4405 """Writes the service unit test for a command."""
4407 if func
.name
== 'Enable':
4409 TEST_P(%(test_name)s, %(name)sValidArgs) {
4410 SetupExpectationsForEnableDisable(%(gl_args)s, true);
4411 SpecializedSetup<cmds::%(name)s, 0>(true);
4413 cmd.Init(%(args)s);"""
4414 elif func
.name
== 'Disable':
4416 TEST_P(%(test_name)s, %(name)sValidArgs) {
4417 SetupExpectationsForEnableDisable(%(gl_args)s, false);
4418 SpecializedSetup<cmds::%(name)s, 0>(true);
4420 cmd.Init(%(args)s);"""
4423 TEST_P(%(test_name)s, %(name)sValidArgs) {
4424 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
4425 SpecializedSetup<cmds::%(name)s, 0>(true);
4427 cmd.Init(%(args)s);"""
4430 decoder_->set_unsafe_es3_apis_enabled(true);
4431 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4432 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4433 decoder_->set_unsafe_es3_apis_enabled(false);
4434 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));
4439 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4440 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4443 self
.WriteValidUnitTest(func
, file, valid_test
, *extras
)
4445 if not func
.IsUnsafe():
4447 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
4448 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
4449 SpecializedSetup<cmds::%(name)s, 0>(false);
4452 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
4455 self
.WriteInvalidUnitTest(func
, file, invalid_test
, *extras
)
4457 def WriteImmediateServiceUnitTest(self
, func
, file, *extras
):
4458 """Writes the service unit test for an immediate command."""
4459 file.Write("// TODO(gman): %s\n" % func
.name
)
4461 def WriteImmediateValidationCode(self
, func
, file):
4462 """Writes the validation code for an immediate version of a command."""
4465 def WriteBucketServiceUnitTest(self
, func
, file, *extras
):
4466 """Writes the service unit test for a bucket command."""
4467 file.Write("// TODO(gman): %s\n" % func
.name
)
4469 def WriteBucketValidationCode(self
, func
, file):
4470 """Writes the validation code for a bucket version of a command."""
4471 file.Write("// TODO(gman): %s\n" % func
.name
)
4473 def WriteGLES2ImplementationDeclaration(self
, func
, file):
4474 """Writes the GLES2 Implemention declaration."""
4475 impl_decl
= func
.GetInfo('impl_decl')
4476 if impl_decl
== None or impl_decl
== True:
4477 file.Write("%s %s(%s) override;\n" %
4478 (func
.return_type
, func
.original_name
,
4479 func
.MakeTypedOriginalArgString("")))
4482 def WriteGLES2CLibImplementation(self
, func
, file):
4483 file.Write("%s GLES2%s(%s) {\n" %
4484 (func
.return_type
, func
.name
,
4485 func
.MakeTypedOriginalArgString("")))
4486 result_string
= "return "
4487 if func
.return_type
== "void":
4489 file.Write(" %sgles2::GetGLContext()->%s(%s);\n" %
4490 (result_string
, func
.original_name
,
4491 func
.MakeOriginalArgString("")))
4494 def WriteGLES2Header(self
, func
, file):
4495 """Writes a re-write macro for GLES"""
4496 file.Write("#define gl%s GLES2_GET_FUN(%s)\n" %(func
.name
, func
.name
))
4498 def WriteClientGLCallLog(self
, func
, file):
4499 """Writes a logging macro for the client side code."""
4501 if len(func
.GetOriginalArgs()):
4504 ' GPU_CLIENT_LOG("[" << GetLogPrefix() << "] gl%s("%s%s << ")");\n' %
4505 (func
.original_name
, comma
, func
.MakeLogArgString()))
4507 def WriteClientGLReturnLog(self
, func
, file):
4508 """Writes the return value logging code."""
4509 if func
.return_type
!= "void":
4510 file.Write(' GPU_CLIENT_LOG("return:" << result)\n')
4512 def WriteGLES2ImplementationHeader(self
, func
, file):
4513 """Writes the GLES2 Implemention."""
4514 self
.WriteGLES2ImplementationDeclaration(func
, file)
4516 def WriteGLES2TraceImplementationHeader(self
, func
, file):
4517 """Writes the GLES2 Trace Implemention header."""
4518 file.Write("%s %s(%s) override;\n" %
4519 (func
.return_type
, func
.original_name
,
4520 func
.MakeTypedOriginalArgString("")))
4522 def WriteGLES2TraceImplementation(self
, func
, file):
4523 """Writes the GLES2 Trace Implemention."""
4524 file.Write("%s GLES2TraceImplementation::%s(%s) {\n" %
4525 (func
.return_type
, func
.original_name
,
4526 func
.MakeTypedOriginalArgString("")))
4527 result_string
= "return "
4528 if func
.return_type
== "void":
4530 file.Write(' TRACE_EVENT_BINARY_EFFICIENT0("gpu", "GLES2Trace::%s");\n' %
4532 file.Write(" %sgl_->%s(%s);\n" %
4533 (result_string
, func
.name
, func
.MakeOriginalArgString("")))
4537 def WriteGLES2Implementation(self
, func
, file):
4538 """Writes the GLES2 Implemention."""
4539 impl_func
= func
.GetInfo('impl_func')
4540 impl_decl
= func
.GetInfo('impl_decl')
4541 gen_cmd
= func
.GetInfo('gen_cmd')
4542 if (func
.can_auto_generate
and
4543 (impl_func
== None or impl_func
== True) and
4544 (impl_decl
== None or impl_decl
== True) and
4545 (gen_cmd
== None or gen_cmd
== True)):
4546 file.Write("%s GLES2Implementation::%s(%s) {\n" %
4547 (func
.return_type
, func
.original_name
,
4548 func
.MakeTypedOriginalArgString("")))
4549 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
4550 self
.WriteClientGLCallLog(func
, file)
4551 func
.WriteDestinationInitalizationValidation(file)
4552 for arg
in func
.GetOriginalArgs():
4553 arg
.WriteClientSideValidationCode(file, func
)
4554 file.Write(" helper_->%s(%s);\n" %
4555 (func
.name
, func
.MakeHelperArgString("")))
4556 file.Write(" CheckGLError();\n")
4557 self
.WriteClientGLReturnLog(func
, file)
4561 def WriteGLES2InterfaceHeader(self
, func
, file):
4562 """Writes the GLES2 Interface."""
4563 file.Write("virtual %s %s(%s) = 0;\n" %
4564 (func
.return_type
, func
.original_name
,
4565 func
.MakeTypedOriginalArgString("")))
4567 def WriteMojoGLES2ImplHeader(self
, func
, file):
4568 """Writes the Mojo GLES2 implementation header."""
4569 file.Write("%s %s(%s) override;\n" %
4570 (func
.return_type
, func
.original_name
,
4571 func
.MakeTypedOriginalArgString("")))
4573 def WriteMojoGLES2Impl(self
, func
, file):
4574 """Writes the Mojo GLES2 implementation."""
4575 file.Write("%s MojoGLES2Impl::%s(%s) {\n" %
4576 (func
.return_type
, func
.original_name
,
4577 func
.MakeTypedOriginalArgString("")))
4578 extensions
= ["CHROMIUM_sync_point", "CHROMIUM_texture_mailbox",
4579 "CHROMIUM_sub_image", "CHROMIUM_miscellaneous",
4580 "occlusion_query_EXT"]
4581 if func
.IsCoreGLFunction() or func
.GetInfo("extension") in extensions
:
4582 file.Write("MojoGLES2MakeCurrent(context_);");
4583 func_return
= "gl" + func
.original_name
+ "(" + \
4584 func
.MakeOriginalArgString("") + ");"
4585 if func
.return_type
== "void":
4586 file.Write(func_return
);
4588 file.Write("return " + func_return
);
4590 file.Write("NOTREACHED() << \"Unimplemented %s.\";\n" %
4591 func
.original_name
);
4592 if func
.return_type
!= "void":
4593 file.Write("return 0;")
4596 def WriteGLES2InterfaceStub(self
, func
, file):
4597 """Writes the GLES2 Interface stub declaration."""
4598 file.Write("%s %s(%s) override;\n" %
4599 (func
.return_type
, func
.original_name
,
4600 func
.MakeTypedOriginalArgString("")))
4602 def WriteGLES2InterfaceStubImpl(self
, func
, file):
4603 """Writes the GLES2 Interface stub declaration."""
4604 args
= func
.GetOriginalArgs()
4605 arg_string
= ", ".join(
4606 ["%s /* %s */" % (arg
.type, arg
.name
) for arg
in args
])
4607 file.Write("%s GLES2InterfaceStub::%s(%s) {\n" %
4608 (func
.return_type
, func
.original_name
, arg_string
))
4609 if func
.return_type
!= "void":
4610 file.Write(" return 0;\n")
4613 def WriteGLES2ImplementationUnitTest(self
, func
, file):
4614 """Writes the GLES2 Implemention unit test."""
4615 client_test
= func
.GetInfo('client_test')
4616 if (func
.can_auto_generate
and
4617 (client_test
== None or client_test
== True)):
4619 TEST_F(GLES2ImplementationTest, %(name)s) {
4624 expected.cmd.Init(%(cmd_args)s);
4626 gl_->%(name)s(%(args)s);
4627 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
4631 arg
.GetValidClientSideCmdArg(func
) for arg
in func
.GetCmdArgs()
4635 arg
.GetValidClientSideArg(func
) for arg
in func
.GetOriginalArgs()
4640 'args': ", ".join(gl_arg_strings
),
4641 'cmd_args': ", ".join(cmd_arg_strings
),
4644 # Test constants for invalid values, as they are not tested by the
4646 constants
= [arg
for arg
in func
.GetOriginalArgs() if arg
.IsConstant()]
4649 TEST_F(GLES2ImplementationTest, %(name)sInvalidConstantArg%(invalid_index)d) {
4650 gl_->%(name)s(%(args)s);
4651 EXPECT_TRUE(NoCommandsWritten());
4652 EXPECT_EQ(%(gl_error)s, CheckError());
4655 for invalid_arg
in constants
:
4657 invalid
= invalid_arg
.GetInvalidArg(func
)
4658 for arg
in func
.GetOriginalArgs():
4659 if arg
is invalid_arg
:
4660 gl_arg_strings
.append(invalid
[0])
4662 gl_arg_strings
.append(arg
.GetValidClientSideArg(func
))
4666 'invalid_index': func
.GetOriginalArgs().index(invalid_arg
),
4667 'args': ", ".join(gl_arg_strings
),
4668 'gl_error': invalid
[2],
4671 if client_test
!= False:
4672 file.Write("// TODO(zmo): Implement unit test for %s\n" % func
.name
)
4674 def WriteDestinationInitalizationValidation(self
, func
, file):
4675 """Writes the client side destintion initialization validation."""
4676 for arg
in func
.GetOriginalArgs():
4677 arg
.WriteDestinationInitalizationValidation(file, func
)
4679 def WriteTraceEvent(self
, func
, file):
4680 file.Write(' TRACE_EVENT0("gpu", "GLES2Implementation::%s");\n' %
4683 def WriteImmediateCmdComputeSize(self
, func
, file):
4684 """Writes the size computation code for the immediate version of a cmd."""
4685 file.Write(" static uint32_t ComputeSize(uint32_t size_in_bytes) {\n")
4686 file.Write(" return static_cast<uint32_t>(\n")
4687 file.Write(" sizeof(ValueType) + // NOLINT\n")
4688 file.Write(" RoundSizeToMultipleOfEntries(size_in_bytes));\n")
4692 def WriteImmediateCmdSetHeader(self
, func
, file):
4693 """Writes the SetHeader function for the immediate version of a cmd."""
4694 file.Write(" void SetHeader(uint32_t size_in_bytes) {\n")
4695 file.Write(" header.SetCmdByTotalSize<ValueType>(size_in_bytes);\n")
4699 def WriteImmediateCmdInit(self
, func
, file):
4700 """Writes the Init function for the immediate version of a command."""
4701 raise NotImplementedError(func
.name
)
4703 def WriteImmediateCmdSet(self
, func
, file):
4704 """Writes the Set function for the immediate version of a command."""
4705 raise NotImplementedError(func
.name
)
4707 def WriteCmdHelper(self
, func
, file):
4708 """Writes the cmd helper definition for a cmd."""
4709 code
= """ void %(name)s(%(typed_args)s) {
4710 gles2::cmds::%(name)s* c = GetCmdSpace<gles2::cmds::%(name)s>();
4719 "typed_args": func
.MakeTypedCmdArgString(""),
4720 "args": func
.MakeCmdArgString(""),
4723 def WriteImmediateCmdHelper(self
, func
, file):
4724 """Writes the cmd helper definition for the immediate version of a cmd."""
4725 code
= """ void %(name)s(%(typed_args)s) {
4726 const uint32_t s = 0; // TODO(gman): compute correct size
4727 gles2::cmds::%(name)s* c =
4728 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(s);
4737 "typed_args": func
.MakeTypedCmdArgString(""),
4738 "args": func
.MakeCmdArgString(""),
4742 class StateSetHandler(TypeHandler
):
4743 """Handler for commands that simply set state."""
4746 TypeHandler
.__init
__(self
)
4748 def WriteHandlerImplementation(self
, func
, file):
4749 """Overrriden from TypeHandler."""
4750 state_name
= func
.GetInfo('state')
4751 state
= _STATES
[state_name
]
4752 states
= state
['states']
4753 args
= func
.GetOriginalArgs()
4754 for ndx
,item
in enumerate(states
):
4756 if 'range_checks' in item
:
4757 for range_check
in item
['range_checks']:
4758 code
.append("%s %s" % (args
[ndx
].name
, range_check
['check']))
4759 if 'nan_check' in item
:
4760 # Drivers might generate an INVALID_VALUE error when a value is set
4761 # to NaN. This is allowed behavior under GLES 3.0 section 2.1.1 or
4762 # OpenGL 4.5 section 2.3.4.1 - providing NaN allows undefined results.
4763 # Make this behavior consistent within Chromium, and avoid leaking GL
4764 # errors by generating the error in the command buffer instead of
4765 # letting the GL driver generate it.
4766 code
.append("std::isnan(%s)" % args
[ndx
].name
)
4768 file.Write(" if (%s) {\n" % " ||\n ".join(code
))
4770 ' LOCAL_SET_GL_ERROR(GL_INVALID_VALUE,'
4771 ' "%s", "%s out of range");\n' %
4772 (func
.name
, args
[ndx
].name
))
4773 file.Write(" return error::kNoError;\n")
4776 for ndx
,item
in enumerate(states
):
4777 code
.append("state_.%s != %s" % (item
['name'], args
[ndx
].name
))
4778 file.Write(" if (%s) {\n" % " ||\n ".join(code
))
4779 for ndx
,item
in enumerate(states
):
4780 file.Write(" state_.%s = %s;\n" % (item
['name'], args
[ndx
].name
))
4781 if 'state_flag' in state
:
4782 file.Write(" %s = true;\n" % state
['state_flag'])
4783 if not func
.GetInfo("no_gl"):
4784 for ndx
,item
in enumerate(states
):
4785 if item
.get('cached', False):
4786 file.Write(" state_.%s = %s;\n" %
4787 (CachedStateName(item
), args
[ndx
].name
))
4788 file.Write(" %s(%s);\n" %
4789 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
4792 def WriteServiceUnitTest(self
, func
, file, *extras
):
4793 """Overrriden from TypeHandler."""
4794 TypeHandler
.WriteServiceUnitTest(self
, func
, file, *extras
)
4795 state_name
= func
.GetInfo('state')
4796 state
= _STATES
[state_name
]
4797 states
= state
['states']
4798 for ndx
,item
in enumerate(states
):
4799 if 'range_checks' in item
:
4800 for check_ndx
, range_check
in enumerate(item
['range_checks']):
4802 TEST_P(%(test_name)s, %(name)sInvalidValue%(ndx)d_%(check_ndx)d) {
4803 SpecializedSetup<cmds::%(name)s, 0>(false);
4806 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4807 EXPECT_EQ(GL_INVALID_VALUE, GetGLError());
4812 arg
.GetValidArg(func
) \
4813 for arg
in func
.GetOriginalArgs() if not arg
.IsConstant()
4816 arg_strings
[ndx
] = range_check
['test_value']
4820 'check_ndx': check_ndx
,
4821 'args': ", ".join(arg_strings
),
4823 for extra
in extras
:
4825 file.Write(valid_test
% vars)
4826 if 'nan_check' in item
:
4828 TEST_P(%(test_name)s, %(name)sNaNValue%(ndx)d) {
4829 SpecializedSetup<cmds::%(name)s, 0>(false);
4832 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4833 EXPECT_EQ(GL_INVALID_VALUE, GetGLError());
4838 arg
.GetValidArg(func
) \
4839 for arg
in func
.GetOriginalArgs() if not arg
.IsConstant()
4842 arg_strings
[ndx
] = 'nanf("")'
4846 'args': ", ".join(arg_strings
),
4848 for extra
in extras
:
4850 file.Write(valid_test
% vars)
4853 class StateSetRGBAlphaHandler(TypeHandler
):
4854 """Handler for commands that simply set state that have rgb/alpha."""
4857 TypeHandler
.__init
__(self
)
4859 def WriteHandlerImplementation(self
, func
, file):
4860 """Overrriden from TypeHandler."""
4861 state_name
= func
.GetInfo('state')
4862 state
= _STATES
[state_name
]
4863 states
= state
['states']
4864 args
= func
.GetOriginalArgs()
4865 num_args
= len(args
)
4867 for ndx
,item
in enumerate(states
):
4868 code
.append("state_.%s != %s" % (item
['name'], args
[ndx
% num_args
].name
))
4869 file.Write(" if (%s) {\n" % " ||\n ".join(code
))
4870 for ndx
, item
in enumerate(states
):
4871 file.Write(" state_.%s = %s;\n" %
4872 (item
['name'], args
[ndx
% num_args
].name
))
4873 if 'state_flag' in state
:
4874 file.Write(" %s = true;\n" % state
['state_flag'])
4875 if not func
.GetInfo("no_gl"):
4876 file.Write(" %s(%s);\n" %
4877 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
4881 class StateSetFrontBackSeparateHandler(TypeHandler
):
4882 """Handler for commands that simply set state that have front/back."""
4885 TypeHandler
.__init
__(self
)
4887 def WriteHandlerImplementation(self
, func
, file):
4888 """Overrriden from TypeHandler."""
4889 state_name
= func
.GetInfo('state')
4890 state
= _STATES
[state_name
]
4891 states
= state
['states']
4892 args
= func
.GetOriginalArgs()
4894 num_args
= len(args
)
4895 file.Write(" bool changed = false;\n")
4896 for group_ndx
, group
in enumerate(Grouper(num_args
- 1, states
)):
4897 file.Write(" if (%s == %s || %s == GL_FRONT_AND_BACK) {\n" %
4898 (face
, ('GL_FRONT', 'GL_BACK')[group_ndx
], face
))
4900 for ndx
, item
in enumerate(group
):
4901 code
.append("state_.%s != %s" % (item
['name'], args
[ndx
+ 1].name
))
4902 file.Write(" changed |= %s;\n" % " ||\n ".join(code
))
4904 file.Write(" if (changed) {\n")
4905 for group_ndx
, group
in enumerate(Grouper(num_args
- 1, states
)):
4906 file.Write(" if (%s == %s || %s == GL_FRONT_AND_BACK) {\n" %
4907 (face
, ('GL_FRONT', 'GL_BACK')[group_ndx
], face
))
4908 for ndx
, item
in enumerate(group
):
4909 file.Write(" state_.%s = %s;\n" %
4910 (item
['name'], args
[ndx
+ 1].name
))
4912 if 'state_flag' in state
:
4913 file.Write(" %s = true;\n" % state
['state_flag'])
4914 if not func
.GetInfo("no_gl"):
4915 file.Write(" %s(%s);\n" %
4916 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
4920 class StateSetFrontBackHandler(TypeHandler
):
4921 """Handler for commands that simply set state that set both front/back."""
4924 TypeHandler
.__init
__(self
)
4926 def WriteHandlerImplementation(self
, func
, file):
4927 """Overrriden from TypeHandler."""
4928 state_name
= func
.GetInfo('state')
4929 state
= _STATES
[state_name
]
4930 states
= state
['states']
4931 args
= func
.GetOriginalArgs()
4932 num_args
= len(args
)
4934 for group_ndx
, group
in enumerate(Grouper(num_args
, states
)):
4935 for ndx
, item
in enumerate(group
):
4936 code
.append("state_.%s != %s" % (item
['name'], args
[ndx
].name
))
4937 file.Write(" if (%s) {\n" % " ||\n ".join(code
))
4938 for group_ndx
, group
in enumerate(Grouper(num_args
, states
)):
4939 for ndx
, item
in enumerate(group
):
4940 file.Write(" state_.%s = %s;\n" % (item
['name'], args
[ndx
].name
))
4941 if 'state_flag' in state
:
4942 file.Write(" %s = true;\n" % state
['state_flag'])
4943 if not func
.GetInfo("no_gl"):
4944 file.Write(" %s(%s);\n" %
4945 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
4949 class StateSetNamedParameter(TypeHandler
):
4950 """Handler for commands that set a state chosen with an enum parameter."""
4953 TypeHandler
.__init
__(self
)
4955 def WriteHandlerImplementation(self
, func
, file):
4956 """Overridden from TypeHandler."""
4957 state_name
= func
.GetInfo('state')
4958 state
= _STATES
[state_name
]
4959 states
= state
['states']
4960 args
= func
.GetOriginalArgs()
4961 num_args
= len(args
)
4962 assert num_args
== 2
4963 file.Write(" switch (%s) {\n" % args
[0].name
)
4964 for state
in states
:
4965 file.Write(" case %s:\n" % state
['enum'])
4966 file.Write(" if (state_.%s != %s) {\n" %
4967 (state
['name'], args
[1].name
))
4968 file.Write(" state_.%s = %s;\n" % (state
['name'], args
[1].name
))
4969 if not func
.GetInfo("no_gl"):
4970 file.Write(" %s(%s);\n" %
4971 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
4973 file.Write(" break;\n")
4974 file.Write(" default:\n")
4975 file.Write(" NOTREACHED();\n")
4979 class CustomHandler(TypeHandler
):
4980 """Handler for commands that are auto-generated but require minor tweaks."""
4983 TypeHandler
.__init
__(self
)
4985 def WriteServiceImplementation(self
, func
, file):
4986 """Overrriden from TypeHandler."""
4989 def WriteImmediateServiceImplementation(self
, func
, file):
4990 """Overrriden from TypeHandler."""
4993 def WriteBucketServiceImplementation(self
, func
, file):
4994 """Overrriden from TypeHandler."""
4997 def WriteServiceUnitTest(self
, func
, file, *extras
):
4998 """Overrriden from TypeHandler."""
4999 file.Write("// TODO(gman): %s\n\n" % func
.name
)
5001 def WriteImmediateServiceUnitTest(self
, func
, file, *extras
):
5002 """Overrriden from TypeHandler."""
5003 file.Write("// TODO(gman): %s\n\n" % func
.name
)
5005 def WriteImmediateCmdGetTotalSize(self
, func
, file):
5006 """Overrriden from TypeHandler."""
5008 " uint32_t total_size = 0; // TODO(gman): get correct size.\n")
5010 def WriteImmediateCmdInit(self
, func
, file):
5011 """Overrriden from TypeHandler."""
5012 file.Write(" void Init(%s) {\n" % func
.MakeTypedCmdArgString("_"))
5013 self
.WriteImmediateCmdGetTotalSize(func
, file)
5014 file.Write(" SetHeader(total_size);\n")
5015 args
= func
.GetCmdArgs()
5017 file.Write(" %s = _%s;\n" % (arg
.name
, arg
.name
))
5021 def WriteImmediateCmdSet(self
, func
, file):
5022 """Overrriden from TypeHandler."""
5023 copy_args
= func
.MakeCmdArgString("_", False)
5024 file.Write(" void* Set(void* cmd%s) {\n" %
5025 func
.MakeTypedCmdArgString("_", True))
5026 self
.WriteImmediateCmdGetTotalSize(func
, file)
5027 file.Write(" static_cast<ValueType*>(cmd)->Init(%s);\n" % copy_args
)
5028 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
5029 "cmd, total_size);\n")
5034 class TodoHandler(CustomHandler
):
5035 """Handle for commands that are not yet implemented."""
5037 def NeedsDataTransferFunction(self
, func
):
5038 """Overriden from TypeHandler."""
5041 def WriteImmediateFormatTest(self
, func
, file):
5042 """Overrriden from TypeHandler."""
5045 def WriteGLES2ImplementationUnitTest(self
, func
, file):
5046 """Overrriden from TypeHandler."""
5049 def WriteGLES2Implementation(self
, func
, file):
5050 """Overrriden from TypeHandler."""
5051 file.Write("%s GLES2Implementation::%s(%s) {\n" %
5052 (func
.return_type
, func
.original_name
,
5053 func
.MakeTypedOriginalArgString("")))
5054 file.Write(" // TODO: for now this is a no-op\n")
5057 "GL_INVALID_OPERATION, \"gl%s\", \"not implemented\");\n" %
5059 if func
.return_type
!= "void":
5060 file.Write(" return 0;\n")
5064 def WriteServiceImplementation(self
, func
, file):
5065 """Overrriden from TypeHandler."""
5066 self
.WriteServiceHandlerFunctionHeader(func
, file)
5067 file.Write(" // TODO: for now this is a no-op\n")
5069 " LOCAL_SET_GL_ERROR("
5070 "GL_INVALID_OPERATION, \"gl%s\", \"not implemented\");\n" %
5072 file.Write(" return error::kNoError;\n")
5077 class HandWrittenHandler(CustomHandler
):
5078 """Handler for comands where everything must be written by hand."""
5080 def InitFunction(self
, func
):
5081 """Add or adjust anything type specific for this function."""
5082 CustomHandler
.InitFunction(self
, func
)
5083 func
.can_auto_generate
= False
5085 def NeedsDataTransferFunction(self
, func
):
5086 """Overriden from TypeHandler."""
5087 # If specified explicitly, force the data transfer method.
5088 if func
.GetInfo('data_transfer_methods'):
5092 def WriteStruct(self
, func
, file):
5093 """Overrriden from TypeHandler."""
5096 def WriteDocs(self
, func
, file):
5097 """Overrriden from TypeHandler."""
5100 def WriteServiceUnitTest(self
, func
, file, *extras
):
5101 """Overrriden from TypeHandler."""
5102 file.Write("// TODO(gman): %s\n\n" % func
.name
)
5104 def WriteImmediateServiceUnitTest(self
, func
, file, *extras
):
5105 """Overrriden from TypeHandler."""
5106 file.Write("// TODO(gman): %s\n\n" % func
.name
)
5108 def WriteBucketServiceUnitTest(self
, func
, file, *extras
):
5109 """Overrriden from TypeHandler."""
5110 file.Write("// TODO(gman): %s\n\n" % func
.name
)
5112 def WriteServiceImplementation(self
, func
, file):
5113 """Overrriden from TypeHandler."""
5116 def WriteImmediateServiceImplementation(self
, func
, file):
5117 """Overrriden from TypeHandler."""
5120 def WriteBucketServiceImplementation(self
, func
, file):
5121 """Overrriden from TypeHandler."""
5124 def WriteImmediateCmdHelper(self
, func
, file):
5125 """Overrriden from TypeHandler."""
5128 def WriteCmdHelper(self
, func
, file):
5129 """Overrriden from TypeHandler."""
5132 def WriteFormatTest(self
, func
, file):
5133 """Overrriden from TypeHandler."""
5134 file.Write("// TODO(gman): Write test for %s\n" % func
.name
)
5136 def WriteImmediateFormatTest(self
, func
, file):
5137 """Overrriden from TypeHandler."""
5138 file.Write("// TODO(gman): Write test for %s\n" % func
.name
)
5140 def WriteBucketFormatTest(self
, func
, file):
5141 """Overrriden from TypeHandler."""
5142 file.Write("// TODO(gman): Write test for %s\n" % func
.name
)
5146 class ManualHandler(CustomHandler
):
5147 """Handler for commands who's handlers must be written by hand."""
5150 CustomHandler
.__init
__(self
)
5152 def InitFunction(self
, func
):
5153 """Overrriden from TypeHandler."""
5154 if (func
.name
== 'CompressedTexImage2DBucket' or
5155 func
.name
== 'CompressedTexImage3DBucket'):
5156 func
.cmd_args
= func
.cmd_args
[:-1]
5157 func
.AddCmdArg(Argument('bucket_id', 'GLuint'))
5159 CustomHandler
.InitFunction(self
, func
)
5161 def WriteServiceImplementation(self
, func
, file):
5162 """Overrriden from TypeHandler."""
5165 def WriteBucketServiceImplementation(self
, func
, file):
5166 """Overrriden from TypeHandler."""
5169 def WriteServiceUnitTest(self
, func
, file, *extras
):
5170 """Overrriden from TypeHandler."""
5171 file.Write("// TODO(gman): %s\n\n" % func
.name
)
5173 def WriteImmediateServiceUnitTest(self
, func
, file, *extras
):
5174 """Overrriden from TypeHandler."""
5175 file.Write("// TODO(gman): %s\n\n" % func
.name
)
5177 def WriteImmediateServiceImplementation(self
, func
, file):
5178 """Overrriden from TypeHandler."""
5181 def WriteImmediateFormatTest(self
, func
, file):
5182 """Overrriden from TypeHandler."""
5183 file.Write("// TODO(gman): Implement test for %s\n" % func
.name
)
5185 def WriteGLES2Implementation(self
, func
, file):
5186 """Overrriden from TypeHandler."""
5187 if func
.GetInfo('impl_func'):
5188 super(ManualHandler
, self
).WriteGLES2Implementation(func
, file)
5190 def WriteGLES2ImplementationHeader(self
, func
, file):
5191 """Overrriden from TypeHandler."""
5192 file.Write("%s %s(%s) override;\n" %
5193 (func
.return_type
, func
.original_name
,
5194 func
.MakeTypedOriginalArgString("")))
5197 def WriteImmediateCmdGetTotalSize(self
, func
, file):
5198 """Overrriden from TypeHandler."""
5199 # TODO(gman): Move this data to _FUNCTION_INFO?
5200 CustomHandler
.WriteImmediateCmdGetTotalSize(self
, func
, file)
5203 class DataHandler(TypeHandler
):
5204 """Handler for glBufferData, glBufferSubData, glTexImage*D, glTexSubImage*D,
5205 glCompressedTexImage*D, glCompressedTexImageSub*D."""
5207 TypeHandler
.__init
__(self
)
5209 def InitFunction(self
, func
):
5210 """Overrriden from TypeHandler."""
5211 if (func
.name
== 'CompressedTexSubImage2DBucket' or
5212 func
.name
== 'CompressedTexSubImage3DBucket'):
5213 func
.cmd_args
= func
.cmd_args
[:-1]
5214 func
.AddCmdArg(Argument('bucket_id', 'GLuint'))
5216 def WriteGetDataSizeCode(self
, func
, file):
5217 """Overrriden from TypeHandler."""
5218 # TODO(gman): Move this data to _FUNCTION_INFO?
5220 if name
.endswith("Immediate"):
5222 if name
== 'BufferData' or name
== 'BufferSubData':
5223 file.Write(" uint32_t data_size = size;\n")
5224 elif (name
== 'CompressedTexImage2D' or
5225 name
== 'CompressedTexSubImage2D' or
5226 name
== 'CompressedTexImage3D' or
5227 name
== 'CompressedTexSubImage3D'):
5228 file.Write(" uint32_t data_size = imageSize;\n")
5229 elif (name
== 'CompressedTexSubImage2DBucket' or
5230 name
== 'CompressedTexSubImage3DBucket'):
5231 file.Write(" Bucket* bucket = GetBucket(c.bucket_id);\n")
5232 file.Write(" uint32_t data_size = bucket->size();\n")
5233 file.Write(" GLsizei imageSize = data_size;\n")
5234 elif name
== 'TexImage2D' or name
== 'TexSubImage2D':
5235 code
= """ uint32_t data_size;
5236 if (!GLES2Util::ComputeImageDataSize(
5237 width, height, format, type, unpack_alignment_, &data_size)) {
5238 return error::kOutOfBounds;
5244 "// uint32_t data_size = 0; // TODO(gman): get correct size!\n")
5246 def WriteImmediateCmdGetTotalSize(self
, func
, file):
5247 """Overrriden from TypeHandler."""
5250 def WriteImmediateCmdSizeTest(self
, func
, file):
5251 """Overrriden from TypeHandler."""
5252 file.Write(" EXPECT_EQ(sizeof(cmd), total_size);\n")
5254 def WriteImmediateCmdInit(self
, func
, file):
5255 """Overrriden from TypeHandler."""
5256 file.Write(" void Init(%s) {\n" % func
.MakeTypedCmdArgString("_"))
5257 self
.WriteImmediateCmdGetTotalSize(func
, file)
5258 file.Write(" SetHeader(total_size);\n")
5259 args
= func
.GetCmdArgs()
5261 file.Write(" %s = _%s;\n" % (arg
.name
, arg
.name
))
5265 def WriteImmediateCmdSet(self
, func
, file):
5266 """Overrriden from TypeHandler."""
5267 copy_args
= func
.MakeCmdArgString("_", False)
5268 file.Write(" void* Set(void* cmd%s) {\n" %
5269 func
.MakeTypedCmdArgString("_", True))
5270 self
.WriteImmediateCmdGetTotalSize(func
, file)
5271 file.Write(" static_cast<ValueType*>(cmd)->Init(%s);\n" % copy_args
)
5272 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
5273 "cmd, total_size);\n")
5277 def WriteImmediateFormatTest(self
, func
, file):
5278 """Overrriden from TypeHandler."""
5279 # TODO(gman): Remove this exception.
5280 file.Write("// TODO(gman): Implement test for %s\n" % func
.name
)
5283 def WriteServiceUnitTest(self
, func
, file, *extras
):
5284 """Overrriden from TypeHandler."""
5285 file.Write("// TODO(gman): %s\n\n" % func
.name
)
5287 def WriteImmediateServiceUnitTest(self
, func
, file, *extras
):
5288 """Overrriden from TypeHandler."""
5289 file.Write("// TODO(gman): %s\n\n" % func
.name
)
5291 def WriteBucketServiceImplementation(self
, func
, file):
5292 """Overrriden from TypeHandler."""
5293 if ((not func
.name
== 'CompressedTexSubImage2DBucket') and
5294 (not func
.name
== 'CompressedTexSubImage3DBucket')):
5295 TypeHandler
.WriteBucketServiceImplemenation(self
, func
, file)
5298 class BindHandler(TypeHandler
):
5299 """Handler for glBind___ type functions."""
5302 TypeHandler
.__init
__(self
)
5304 def WriteServiceUnitTest(self
, func
, file, *extras
):
5305 """Overrriden from TypeHandler."""
5307 if len(func
.GetOriginalArgs()) == 1:
5309 TEST_P(%(test_name)s, %(name)sValidArgs) {
5310 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
5311 SpecializedSetup<cmds::%(name)s, 0>(true);
5313 cmd.Init(%(args)s);"""
5316 decoder_->set_unsafe_es3_apis_enabled(true);
5317 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5318 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5319 decoder_->set_unsafe_es3_apis_enabled(false);
5320 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));
5325 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5326 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5329 if func
.GetInfo("gen_func"):
5331 TEST_P(%(test_name)s, %(name)sValidArgsNewId) {
5332 EXPECT_CALL(*gl_, %(gl_func_name)s(kNewServiceId));
5333 EXPECT_CALL(*gl_, %(gl_gen_func_name)s(1, _))
5334 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
5335 SpecializedSetup<cmds::%(name)s, 0>(true);
5337 cmd.Init(kNewClientId);
5338 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5339 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5340 EXPECT_TRUE(Get%(resource_type)s(kNewClientId) != NULL);
5343 self
.WriteValidUnitTest(func
, file, valid_test
, {
5344 'resource_type': func
.GetOriginalArgs()[0].resource_type
,
5345 'gl_gen_func_name': func
.GetInfo("gen_func"),
5349 TEST_P(%(test_name)s, %(name)sValidArgs) {
5350 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
5351 SpecializedSetup<cmds::%(name)s, 0>(true);
5353 cmd.Init(%(args)s);"""
5356 decoder_->set_unsafe_es3_apis_enabled(true);
5357 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5358 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5359 decoder_->set_unsafe_es3_apis_enabled(false);
5360 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));
5365 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5366 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5369 if func
.GetInfo("gen_func"):
5371 TEST_P(%(test_name)s, %(name)sValidArgsNewId) {
5373 %(gl_func_name)s(%(gl_args_with_new_id)s));
5374 EXPECT_CALL(*gl_, %(gl_gen_func_name)s(1, _))
5375 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
5376 SpecializedSetup<cmds::%(name)s, 0>(true);
5378 cmd.Init(%(args_with_new_id)s);"""
5381 decoder_->set_unsafe_es3_apis_enabled(true);
5382 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5383 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5384 EXPECT_TRUE(Get%(resource_type)s(kNewClientId) != NULL);
5385 decoder_->set_unsafe_es3_apis_enabled(false);
5386 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));
5391 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5392 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5393 EXPECT_TRUE(Get%(resource_type)s(kNewClientId) != NULL);
5397 gl_args_with_new_id
= []
5398 args_with_new_id
= []
5399 for arg
in func
.GetOriginalArgs():
5400 if hasattr(arg
, 'resource_type'):
5401 gl_args_with_new_id
.append('kNewServiceId')
5402 args_with_new_id
.append('kNewClientId')
5404 gl_args_with_new_id
.append(arg
.GetValidGLArg(func
))
5405 args_with_new_id
.append(arg
.GetValidArg(func
))
5406 self
.WriteValidUnitTest(func
, file, valid_test
, {
5407 'args_with_new_id': ", ".join(args_with_new_id
),
5408 'gl_args_with_new_id': ", ".join(gl_args_with_new_id
),
5409 'resource_type': func
.GetResourceIdArg().resource_type
,
5410 'gl_gen_func_name': func
.GetInfo("gen_func"),
5414 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
5415 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
5416 SpecializedSetup<cmds::%(name)s, 0>(false);
5419 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
5422 self
.WriteInvalidUnitTest(func
, file, invalid_test
, *extras
)
5424 def WriteGLES2Implementation(self
, func
, file):
5425 """Writes the GLES2 Implemention."""
5427 impl_func
= func
.GetInfo('impl_func')
5428 impl_decl
= func
.GetInfo('impl_decl')
5430 if (func
.can_auto_generate
and
5431 (impl_func
== None or impl_func
== True) and
5432 (impl_decl
== None or impl_decl
== True)):
5434 file.Write("%s GLES2Implementation::%s(%s) {\n" %
5435 (func
.return_type
, func
.original_name
,
5436 func
.MakeTypedOriginalArgString("")))
5437 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
5438 func
.WriteDestinationInitalizationValidation(file)
5439 self
.WriteClientGLCallLog(func
, file)
5440 for arg
in func
.GetOriginalArgs():
5441 arg
.WriteClientSideValidationCode(file, func
)
5443 code
= """ if (Is%(type)sReservedId(%(id)s)) {
5444 SetGLError(GL_INVALID_OPERATION, "%(name)s\", \"%(id)s reserved id");
5447 %(name)sHelper(%(arg_string)s);
5452 name_arg
= func
.GetResourceIdArg()
5455 'arg_string': func
.MakeOriginalArgString(""),
5456 'id': name_arg
.name
,
5457 'type': name_arg
.resource_type
,
5458 'lc_type': name_arg
.resource_type
.lower(),
5461 def WriteGLES2ImplementationUnitTest(self
, func
, file):
5462 """Overrriden from TypeHandler."""
5463 client_test
= func
.GetInfo('client_test')
5464 if client_test
== False:
5467 TEST_F(GLES2ImplementationTest, %(name)s) {
5472 expected.cmd.Init(%(cmd_args)s);
5474 gl_->%(name)s(%(args)s);
5475 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));"""
5476 if not func
.IsUnsafe():
5479 gl_->%(name)s(%(args)s);
5480 EXPECT_TRUE(NoCommandsWritten());"""
5485 arg
.GetValidClientSideCmdArg(func
) for arg
in func
.GetCmdArgs()
5488 arg
.GetValidClientSideArg(func
) for arg
in func
.GetOriginalArgs()
5493 'args': ", ".join(gl_arg_strings
),
5494 'cmd_args': ", ".join(cmd_arg_strings
),
5498 class GENnHandler(TypeHandler
):
5499 """Handler for glGen___ type functions."""
5502 TypeHandler
.__init
__(self
)
5504 def InitFunction(self
, func
):
5505 """Overrriden from TypeHandler."""
5508 def WriteGetDataSizeCode(self
, func
, file):
5509 """Overrriden from TypeHandler."""
5510 code
= """ uint32_t data_size;
5511 if (!SafeMultiplyUint32(n, sizeof(GLuint), &data_size)) {
5512 return error::kOutOfBounds;
5517 def WriteHandlerImplementation (self
, func
, file):
5518 """Overrriden from TypeHandler."""
5519 file.Write(" if (!%sHelper(n, %s)) {\n"
5520 " return error::kInvalidArguments;\n"
5522 (func
.name
, func
.GetLastOriginalArg().name
))
5524 def WriteImmediateHandlerImplementation(self
, func
, file):
5525 """Overrriden from TypeHandler."""
5527 file.Write(""" for (GLsizei ii = 0; ii < n; ++ii) {
5528 if (group_->Get%(resource_name)sServiceId(%(last_arg_name)s[ii], NULL)) {
5529 return error::kInvalidArguments;
5532 scoped_ptr<GLuint[]> service_ids(new GLuint[n]);
5533 gl%(func_name)s(n, service_ids.get());
5534 for (GLsizei ii = 0; ii < n; ++ii) {
5535 group_->Add%(resource_name)sId(%(last_arg_name)s[ii], service_ids[ii]);
5537 """ % { 'func_name': func
.original_name
,
5538 'last_arg_name': func
.GetLastOriginalArg().name
,
5539 'resource_name': func
.GetInfo('resource_type') })
5541 file.Write(" if (!%sHelper(n, %s)) {\n"
5542 " return error::kInvalidArguments;\n"
5544 (func
.original_name
, func
.GetLastOriginalArg().name
))
5546 def WriteGLES2Implementation(self
, func
, file):
5547 """Overrriden from TypeHandler."""
5548 log_code
= (""" GPU_CLIENT_LOG_CODE_BLOCK({
5549 for (GLsizei i = 0; i < n; ++i) {
5550 GPU_CLIENT_LOG(" " << i << ": " << %s[i]);
5552 });""" % func
.GetOriginalArgs()[1].name
)
5554 'log_code': log_code
,
5555 'return_type': func
.return_type
,
5556 'name': func
.original_name
,
5557 'typed_args': func
.MakeTypedOriginalArgString(""),
5558 'args': func
.MakeOriginalArgString(""),
5559 'resource_types': func
.GetInfo('resource_types'),
5560 'count_name': func
.GetOriginalArgs()[0].name
,
5563 "%(return_type)s GLES2Implementation::%(name)s(%(typed_args)s) {\n" %
5565 func
.WriteDestinationInitalizationValidation(file)
5566 self
.WriteClientGLCallLog(func
, file)
5567 for arg
in func
.GetOriginalArgs():
5568 arg
.WriteClientSideValidationCode(file, func
)
5569 not_shared
= func
.GetInfo('not_shared')
5573 """ IdAllocator* id_allocator = GetIdAllocator(id_namespaces::k%s);
5574 for (GLsizei ii = 0; ii < n; ++ii)
5575 %s[ii] = id_allocator->AllocateID();""" %
5576 (func
.GetInfo('resource_types'), func
.GetOriginalArgs()[1].name
))
5578 alloc_code
= (""" GetIdHandler(id_namespaces::k%(resource_types)s)->
5579 MakeIds(this, 0, %(args)s);""" % args
)
5580 args
['alloc_code'] = alloc_code
5582 code
= """ GPU_CLIENT_SINGLE_THREAD_CHECK();
5584 %(name)sHelper(%(args)s);
5585 helper_->%(name)sImmediate(%(args)s);
5586 if (share_group_->bind_generates_resource())
5587 helper_->CommandBufferHelper::Flush();
5593 file.Write(code
% args
)
5595 def WriteGLES2ImplementationUnitTest(self
, func
, file):
5596 """Overrriden from TypeHandler."""
5598 TEST_F(GLES2ImplementationTest, %(name)s) {
5599 GLuint ids[2] = { 0, };
5601 cmds::%(name)sImmediate gen;
5605 expected.gen.Init(arraysize(ids), &ids[0]);
5606 expected.data[0] = k%(types)sStartId;
5607 expected.data[1] = k%(types)sStartId + 1;
5608 gl_->%(name)s(arraysize(ids), &ids[0]);
5609 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
5610 EXPECT_EQ(k%(types)sStartId, ids[0]);
5611 EXPECT_EQ(k%(types)sStartId + 1, ids[1]);
5616 'types': func
.GetInfo('resource_types'),
5619 def WriteServiceUnitTest(self
, func
, file, *extras
):
5620 """Overrriden from TypeHandler."""
5622 TEST_P(%(test_name)s, %(name)sValidArgs) {
5623 EXPECT_CALL(*gl_, %(gl_func_name)s(1, _))
5624 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
5625 GetSharedMemoryAs<GLuint*>()[0] = kNewClientId;
5626 SpecializedSetup<cmds::%(name)s, 0>(true);
5629 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5630 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
5634 EXPECT_TRUE(Get%(resource_name)sServiceId(kNewClientId, &service_id));
5635 EXPECT_EQ(kNewServiceId, service_id)
5640 EXPECT_TRUE(Get%(resource_name)s(kNewClientId, &service_id) != NULL);
5643 self
.WriteValidUnitTest(func
, file, valid_test
, {
5644 'resource_name': func
.GetInfo('resource_type'),
5647 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
5648 EXPECT_CALL(*gl_, %(gl_func_name)s(_, _)).Times(0);
5649 GetSharedMemoryAs<GLuint*>()[0] = client_%(resource_name)s_id_;
5650 SpecializedSetup<cmds::%(name)s, 0>(false);
5653 EXPECT_EQ(error::kInvalidArguments, ExecuteCmd(cmd));
5656 self
.WriteValidUnitTest(func
, file, invalid_test
, {
5657 'resource_name': func
.GetInfo('resource_type').lower(),
5660 def WriteImmediateServiceUnitTest(self
, func
, file, *extras
):
5661 """Overrriden from TypeHandler."""
5663 TEST_P(%(test_name)s, %(name)sValidArgs) {
5664 EXPECT_CALL(*gl_, %(gl_func_name)s(1, _))
5665 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
5666 cmds::%(name)s* cmd = GetImmediateAs<cmds::%(name)s>();
5667 GLuint temp = kNewClientId;
5668 SpecializedSetup<cmds::%(name)s, 0>(true);"""
5671 decoder_->set_unsafe_es3_apis_enabled(true);"""
5673 cmd->Init(1, &temp);
5674 EXPECT_EQ(error::kNoError,
5675 ExecuteImmediateCmd(*cmd, sizeof(temp)));
5676 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
5680 EXPECT_TRUE(Get%(resource_name)sServiceId(kNewClientId, &service_id));
5681 EXPECT_EQ(kNewServiceId, service_id);
5682 decoder_->set_unsafe_es3_apis_enabled(false);
5683 EXPECT_EQ(error::kUnknownCommand,
5684 ExecuteImmediateCmd(*cmd, sizeof(temp)));
5689 EXPECT_TRUE(Get%(resource_name)s(kNewClientId) != NULL);
5692 self
.WriteValidUnitTest(func
, file, valid_test
, {
5693 'resource_name': func
.GetInfo('resource_type'),
5696 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
5697 EXPECT_CALL(*gl_, %(gl_func_name)s(_, _)).Times(0);
5698 cmds::%(name)s* cmd = GetImmediateAs<cmds::%(name)s>();
5699 SpecializedSetup<cmds::%(name)s, 0>(false);
5700 cmd->Init(1, &client_%(resource_name)s_id_);"""
5703 decoder_->set_unsafe_es3_apis_enabled(true);
5704 EXPECT_EQ(error::kInvalidArguments,
5705 ExecuteImmediateCmd(*cmd, sizeof(&client_%(resource_name)s_id_)));
5706 decoder_->set_unsafe_es3_apis_enabled(false);
5711 EXPECT_EQ(error::kInvalidArguments,
5712 ExecuteImmediateCmd(*cmd, sizeof(&client_%(resource_name)s_id_)));
5715 self
.WriteValidUnitTest(func
, file, invalid_test
, {
5716 'resource_name': func
.GetInfo('resource_type').lower(),
5719 def WriteImmediateCmdComputeSize(self
, func
, file):
5720 """Overrriden from TypeHandler."""
5721 file.Write(" static uint32_t ComputeDataSize(GLsizei n) {\n")
5723 " return static_cast<uint32_t>(sizeof(GLuint) * n); // NOLINT\n")
5726 file.Write(" static uint32_t ComputeSize(GLsizei n) {\n")
5727 file.Write(" return static_cast<uint32_t>(\n")
5728 file.Write(" sizeof(ValueType) + ComputeDataSize(n)); // NOLINT\n")
5732 def WriteImmediateCmdSetHeader(self
, func
, file):
5733 """Overrriden from TypeHandler."""
5734 file.Write(" void SetHeader(GLsizei n) {\n")
5735 file.Write(" header.SetCmdByTotalSize<ValueType>(ComputeSize(n));\n")
5739 def WriteImmediateCmdInit(self
, func
, file):
5740 """Overrriden from TypeHandler."""
5741 last_arg
= func
.GetLastOriginalArg()
5742 file.Write(" void Init(%s, %s _%s) {\n" %
5743 (func
.MakeTypedCmdArgString("_"),
5744 last_arg
.type, last_arg
.name
))
5745 file.Write(" SetHeader(_n);\n")
5746 args
= func
.GetCmdArgs()
5748 file.Write(" %s = _%s;\n" % (arg
.name
, arg
.name
))
5749 file.Write(" memcpy(ImmediateDataAddress(this),\n")
5750 file.Write(" _%s, ComputeDataSize(_n));\n" % last_arg
.name
)
5754 def WriteImmediateCmdSet(self
, func
, file):
5755 """Overrriden from TypeHandler."""
5756 last_arg
= func
.GetLastOriginalArg()
5757 copy_args
= func
.MakeCmdArgString("_", False)
5758 file.Write(" void* Set(void* cmd%s, %s _%s) {\n" %
5759 (func
.MakeTypedCmdArgString("_", True),
5760 last_arg
.type, last_arg
.name
))
5761 file.Write(" static_cast<ValueType*>(cmd)->Init(%s, _%s);\n" %
5762 (copy_args
, last_arg
.name
))
5763 file.Write(" const uint32_t size = ComputeSize(_n);\n")
5764 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
5769 def WriteImmediateCmdHelper(self
, func
, file):
5770 """Overrriden from TypeHandler."""
5771 code
= """ void %(name)s(%(typed_args)s) {
5772 const uint32_t size = gles2::cmds::%(name)s::ComputeSize(n);
5773 gles2::cmds::%(name)s* c =
5774 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
5783 "typed_args": func
.MakeTypedOriginalArgString(""),
5784 "args": func
.MakeOriginalArgString(""),
5787 def WriteImmediateFormatTest(self
, func
, file):
5788 """Overrriden from TypeHandler."""
5789 file.Write("TEST_F(GLES2FormatTest, %s) {\n" % func
.name
)
5790 file.Write(" static GLuint ids[] = { 12, 23, 34, };\n")
5791 file.Write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
5792 (func
.name
, func
.name
))
5793 file.Write(" void* next_cmd = cmd.Set(\n")
5794 file.Write(" &cmd, static_cast<GLsizei>(arraysize(ids)), ids);\n")
5795 file.Write(" EXPECT_EQ(static_cast<uint32_t>(cmds::%s::kCmdId),\n" %
5797 file.Write(" cmd.header.command);\n")
5798 file.Write(" EXPECT_EQ(sizeof(cmd) +\n")
5799 file.Write(" RoundSizeToMultipleOfEntries(cmd.n * 4u),\n")
5800 file.Write(" cmd.header.size * 4u);\n")
5801 file.Write(" EXPECT_EQ(static_cast<GLsizei>(arraysize(ids)), cmd.n);\n");
5802 file.Write(" CheckBytesWrittenMatchesExpectedSize(\n")
5803 file.Write(" next_cmd, sizeof(cmd) +\n")
5804 file.Write(" RoundSizeToMultipleOfEntries(arraysize(ids) * 4u));\n")
5805 file.Write(" // TODO(gman): Check that ids were inserted;\n")
5810 class CreateHandler(TypeHandler
):
5811 """Handler for glCreate___ type functions."""
5814 TypeHandler
.__init
__(self
)
5816 def InitFunction(self
, func
):
5817 """Overrriden from TypeHandler."""
5818 func
.AddCmdArg(Argument("client_id", 'uint32_t'))
5820 def __GetResourceType(self
, func
):
5821 if func
.return_type
== "GLsync":
5824 return func
.name
[6:] # Create*
5826 def WriteServiceUnitTest(self
, func
, file, *extras
):
5827 """Overrriden from TypeHandler."""
5829 TEST_P(%(test_name)s, %(name)sValidArgs) {
5830 %(id_type_cast)sEXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s))
5831 .WillOnce(Return(%(const_service_id)s));
5832 SpecializedSetup<cmds::%(name)s, 0>(true);
5834 cmd.Init(%(args)s%(comma)skNewClientId);"""
5837 decoder_->set_unsafe_es3_apis_enabled(true);"""
5839 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5840 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
5843 %(return_type)s service_id = 0;
5844 EXPECT_TRUE(Get%(resource_type)sServiceId(kNewClientId, &service_id));
5845 EXPECT_EQ(%(const_service_id)s, service_id);
5846 decoder_->set_unsafe_es3_apis_enabled(false);
5847 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));
5852 EXPECT_TRUE(Get%(resource_type)s(kNewClientId));
5857 for arg
in func
.GetOriginalArgs():
5858 if not arg
.IsConstant():
5862 if func
.return_type
== 'GLsync':
5863 id_type_cast
= ("const GLsync kNewServiceIdGLuint = reinterpret_cast"
5864 "<GLsync>(kNewServiceId);\n ")
5865 const_service_id
= "kNewServiceIdGLuint"
5868 const_service_id
= "kNewServiceId"
5869 self
.WriteValidUnitTest(func
, file, valid_test
, {
5871 'resource_type': self
.__GetResourceType
(func
),
5872 'return_type': func
.return_type
,
5873 'id_type_cast': id_type_cast
,
5874 'const_service_id': const_service_id
,
5877 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
5878 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
5879 SpecializedSetup<cmds::%(name)s, 0>(false);
5881 cmd.Init(%(args)s%(comma)skNewClientId);
5882 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));%(gl_error_test)s
5885 self
.WriteInvalidUnitTest(func
, file, invalid_test
, {
5889 def WriteHandlerImplementation (self
, func
, file):
5890 """Overrriden from TypeHandler."""
5892 code
= """ uint32_t client_id = c.client_id;
5893 %(return_type)s service_id = 0;
5894 if (group_->Get%(resource_name)sServiceId(client_id, &service_id)) {
5895 return error::kInvalidArguments;
5897 service_id = %(gl_func_name)s(%(gl_args)s);
5899 group_->Add%(resource_name)sId(client_id, service_id);
5903 code
= """ uint32_t client_id = c.client_id;
5904 if (Get%(resource_name)s(client_id)) {
5905 return error::kInvalidArguments;
5907 %(return_type)s service_id = %(gl_func_name)s(%(gl_args)s);
5909 Create%(resource_name)s(client_id, service_id%(gl_args_with_comma)s);
5913 'resource_name': self
.__GetResourceType
(func
),
5914 'return_type': func
.return_type
,
5915 'gl_func_name': func
.GetGLFunctionName(),
5916 'gl_args': func
.MakeOriginalArgString(""),
5917 'gl_args_with_comma': func
.MakeOriginalArgString("", True) })
5919 def WriteGLES2Implementation(self
, func
, file):
5920 """Overrriden from TypeHandler."""
5921 file.Write("%s GLES2Implementation::%s(%s) {\n" %
5922 (func
.return_type
, func
.original_name
,
5923 func
.MakeTypedOriginalArgString("")))
5924 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
5925 func
.WriteDestinationInitalizationValidation(file)
5926 self
.WriteClientGLCallLog(func
, file)
5927 for arg
in func
.GetOriginalArgs():
5928 arg
.WriteClientSideValidationCode(file, func
)
5929 file.Write(" GLuint client_id;\n")
5930 if func
.return_type
== "GLsync":
5932 " GetIdHandler(id_namespaces::kSyncs)->\n")
5935 " GetIdHandler(id_namespaces::kProgramsAndShaders)->\n")
5936 file.Write(" MakeIds(this, 0, 1, &client_id);\n")
5937 file.Write(" helper_->%s(%s);\n" %
5938 (func
.name
, func
.MakeCmdArgString("")))
5939 file.Write(' GPU_CLIENT_LOG("returned " << client_id);\n')
5940 file.Write(" CheckGLError();\n")
5941 if func
.return_type
== "GLsync":
5942 file.Write(" return reinterpret_cast<GLsync>(client_id);\n")
5944 file.Write(" return client_id;\n")
5949 class DeleteHandler(TypeHandler
):
5950 """Handler for glDelete___ single resource type functions."""
5953 TypeHandler
.__init
__(self
)
5955 def WriteServiceImplementation(self
, func
, file):
5956 """Overrriden from TypeHandler."""
5958 TypeHandler
.WriteServiceImplementation(self
, func
, file)
5959 # HandleDeleteShader and HandleDeleteProgram are manually written.
5962 def WriteGLES2Implementation(self
, func
, file):
5963 """Overrriden from TypeHandler."""
5964 file.Write("%s GLES2Implementation::%s(%s) {\n" %
5965 (func
.return_type
, func
.original_name
,
5966 func
.MakeTypedOriginalArgString("")))
5967 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
5968 func
.WriteDestinationInitalizationValidation(file)
5969 self
.WriteClientGLCallLog(func
, file)
5970 for arg
in func
.GetOriginalArgs():
5971 arg
.WriteClientSideValidationCode(file, func
)
5973 " GPU_CLIENT_DCHECK(%s != 0);\n" % func
.GetOriginalArgs()[-1].name
)
5974 file.Write(" %sHelper(%s);\n" %
5975 (func
.original_name
, func
.GetOriginalArgs()[-1].name
))
5976 file.Write(" CheckGLError();\n")
5980 def WriteHandlerImplementation (self
, func
, file):
5981 """Overrriden from TypeHandler."""
5982 assert len(func
.GetOriginalArgs()) == 1
5983 arg
= func
.GetOriginalArgs()[0]
5985 file.Write(""" %(arg_type)s service_id = 0;
5986 if (group_->Get%(resource_type)sServiceId(%(arg_name)s, &service_id)) {
5987 glDelete%(resource_type)s(service_id);
5988 group_->Remove%(resource_type)sId(%(arg_name)s);
5991 GL_INVALID_VALUE, "gl%(func_name)s", "unknown %(arg_name)s");
5993 """ % { 'resource_type': func
.GetInfo('resource_type'),
5994 'arg_name': arg
.name
,
5995 'arg_type': arg
.type,
5996 'func_name': func
.original_name
})
5998 file.Write(" %sHelper(%s);\n" % (func
.original_name
, arg
.name
))
6000 class DELnHandler(TypeHandler
):
6001 """Handler for glDelete___ type functions."""
6004 TypeHandler
.__init
__(self
)
6006 def WriteGetDataSizeCode(self
, func
, file):
6007 """Overrriden from TypeHandler."""
6008 code
= """ uint32_t data_size;
6009 if (!SafeMultiplyUint32(n, sizeof(GLuint), &data_size)) {
6010 return error::kOutOfBounds;
6015 def WriteGLES2ImplementationUnitTest(self
, func
, file):
6016 """Overrriden from TypeHandler."""
6018 TEST_F(GLES2ImplementationTest, %(name)s) {
6019 GLuint ids[2] = { k%(types)sStartId, k%(types)sStartId + 1 };
6021 cmds::%(name)sImmediate del;
6025 expected.del.Init(arraysize(ids), &ids[0]);
6026 expected.data[0] = k%(types)sStartId;
6027 expected.data[1] = k%(types)sStartId + 1;
6028 gl_->%(name)s(arraysize(ids), &ids[0]);
6029 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
6034 'types': func
.GetInfo('resource_types'),
6037 def WriteServiceUnitTest(self
, func
, file, *extras
):
6038 """Overrriden from TypeHandler."""
6040 TEST_P(%(test_name)s, %(name)sValidArgs) {
6043 %(gl_func_name)s(1, Pointee(kService%(upper_resource_name)sId)))
6045 GetSharedMemoryAs<GLuint*>()[0] = client_%(resource_name)s_id_;
6046 SpecializedSetup<cmds::%(name)s, 0>(true);
6049 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
6050 EXPECT_EQ(GL_NO_ERROR, GetGLError());
6052 Get%(upper_resource_name)s(client_%(resource_name)s_id_) == NULL);
6055 self
.WriteValidUnitTest(func
, file, valid_test
, {
6056 'resource_name': func
.GetInfo('resource_type').lower(),
6057 'upper_resource_name': func
.GetInfo('resource_type'),
6060 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
6061 GetSharedMemoryAs<GLuint*>()[0] = kInvalidClientId;
6062 SpecializedSetup<cmds::%(name)s, 0>(false);
6065 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
6068 self
.WriteValidUnitTest(func
, file, invalid_test
, *extras
)
6070 def WriteImmediateServiceUnitTest(self
, func
, file, *extras
):
6071 """Overrriden from TypeHandler."""
6073 TEST_P(%(test_name)s, %(name)sValidArgs) {
6076 %(gl_func_name)s(1, Pointee(kService%(upper_resource_name)sId)))
6078 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
6079 SpecializedSetup<cmds::%(name)s, 0>(true);
6080 cmd.Init(1, &client_%(resource_name)s_id_);"""
6083 decoder_->set_unsafe_es3_apis_enabled(true);"""
6085 EXPECT_EQ(error::kNoError,
6086 ExecuteImmediateCmd(cmd, sizeof(client_%(resource_name)s_id_)));
6087 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
6090 EXPECT_FALSE(Get%(upper_resource_name)sServiceId(
6091 client_%(resource_name)s_id_, NULL));
6092 decoder_->set_unsafe_es3_apis_enabled(false);
6093 EXPECT_EQ(error::kUnknownCommand,
6094 ExecuteImmediateCmd(cmd, sizeof(client_%(resource_name)s_id_)));
6100 Get%(upper_resource_name)s(client_%(resource_name)s_id_) == NULL);
6103 self
.WriteValidUnitTest(func
, file, valid_test
, {
6104 'resource_name': func
.GetInfo('resource_type').lower(),
6105 'upper_resource_name': func
.GetInfo('resource_type'),
6108 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
6109 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
6110 SpecializedSetup<cmds::%(name)s, 0>(false);
6111 GLuint temp = kInvalidClientId;
6112 cmd.Init(1, &temp);"""
6115 decoder_->set_unsafe_es3_apis_enabled(true);
6116 EXPECT_EQ(error::kNoError,
6117 ExecuteImmediateCmd(cmd, sizeof(temp)));
6118 decoder_->set_unsafe_es3_apis_enabled(false);
6119 EXPECT_EQ(error::kUnknownCommand,
6120 ExecuteImmediateCmd(cmd, sizeof(temp)));
6125 EXPECT_EQ(error::kNoError,
6126 ExecuteImmediateCmd(cmd, sizeof(temp)));
6129 self
.WriteValidUnitTest(func
, file, invalid_test
, *extras
)
6131 def WriteHandlerImplementation (self
, func
, file):
6132 """Overrriden from TypeHandler."""
6133 file.Write(" %sHelper(n, %s);\n" %
6134 (func
.name
, func
.GetLastOriginalArg().name
))
6136 def WriteImmediateHandlerImplementation (self
, func
, file):
6137 """Overrriden from TypeHandler."""
6139 file.Write(""" for (GLsizei ii = 0; ii < n; ++ii) {
6140 GLuint service_id = 0;
6141 if (group_->Get%(resource_type)sServiceId(
6142 %(last_arg_name)s[ii], &service_id)) {
6143 glDelete%(resource_type)ss(1, &service_id);
6144 group_->Remove%(resource_type)sId(%(last_arg_name)s[ii]);
6147 """ % { 'resource_type': func
.GetInfo('resource_type'),
6148 'last_arg_name': func
.GetLastOriginalArg().name
})
6150 file.Write(" %sHelper(n, %s);\n" %
6151 (func
.original_name
, func
.GetLastOriginalArg().name
))
6153 def WriteGLES2Implementation(self
, func
, file):
6154 """Overrriden from TypeHandler."""
6155 impl_decl
= func
.GetInfo('impl_decl')
6156 if impl_decl
== None or impl_decl
== True:
6158 'return_type': func
.return_type
,
6159 'name': func
.original_name
,
6160 'typed_args': func
.MakeTypedOriginalArgString(""),
6161 'args': func
.MakeOriginalArgString(""),
6162 'resource_type': func
.GetInfo('resource_type').lower(),
6163 'count_name': func
.GetOriginalArgs()[0].name
,
6166 "%(return_type)s GLES2Implementation::%(name)s(%(typed_args)s) {\n" %
6168 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
6169 func
.WriteDestinationInitalizationValidation(file)
6170 self
.WriteClientGLCallLog(func
, file)
6171 file.Write(""" GPU_CLIENT_LOG_CODE_BLOCK({
6172 for (GLsizei i = 0; i < n; ++i) {
6173 GPU_CLIENT_LOG(" " << i << ": " << %s[i]);
6176 """ % func
.GetOriginalArgs()[1].name
)
6177 file.Write(""" GPU_CLIENT_DCHECK_CODE_BLOCK({
6178 for (GLsizei i = 0; i < n; ++i) {
6182 """ % func
.GetOriginalArgs()[1].name
)
6183 for arg
in func
.GetOriginalArgs():
6184 arg
.WriteClientSideValidationCode(file, func
)
6185 code
= """ %(name)sHelper(%(args)s);
6190 file.Write(code
% args
)
6192 def WriteImmediateCmdComputeSize(self
, func
, file):
6193 """Overrriden from TypeHandler."""
6194 file.Write(" static uint32_t ComputeDataSize(GLsizei n) {\n")
6196 " return static_cast<uint32_t>(sizeof(GLuint) * n); // NOLINT\n")
6199 file.Write(" static uint32_t ComputeSize(GLsizei n) {\n")
6200 file.Write(" return static_cast<uint32_t>(\n")
6201 file.Write(" sizeof(ValueType) + ComputeDataSize(n)); // NOLINT\n")
6205 def WriteImmediateCmdSetHeader(self
, func
, file):
6206 """Overrriden from TypeHandler."""
6207 file.Write(" void SetHeader(GLsizei n) {\n")
6208 file.Write(" header.SetCmdByTotalSize<ValueType>(ComputeSize(n));\n")
6212 def WriteImmediateCmdInit(self
, func
, file):
6213 """Overrriden from TypeHandler."""
6214 last_arg
= func
.GetLastOriginalArg()
6215 file.Write(" void Init(%s, %s _%s) {\n" %
6216 (func
.MakeTypedCmdArgString("_"),
6217 last_arg
.type, last_arg
.name
))
6218 file.Write(" SetHeader(_n);\n")
6219 args
= func
.GetCmdArgs()
6221 file.Write(" %s = _%s;\n" % (arg
.name
, arg
.name
))
6222 file.Write(" memcpy(ImmediateDataAddress(this),\n")
6223 file.Write(" _%s, ComputeDataSize(_n));\n" % last_arg
.name
)
6227 def WriteImmediateCmdSet(self
, func
, file):
6228 """Overrriden from TypeHandler."""
6229 last_arg
= func
.GetLastOriginalArg()
6230 copy_args
= func
.MakeCmdArgString("_", False)
6231 file.Write(" void* Set(void* cmd%s, %s _%s) {\n" %
6232 (func
.MakeTypedCmdArgString("_", True),
6233 last_arg
.type, last_arg
.name
))
6234 file.Write(" static_cast<ValueType*>(cmd)->Init(%s, _%s);\n" %
6235 (copy_args
, last_arg
.name
))
6236 file.Write(" const uint32_t size = ComputeSize(_n);\n")
6237 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
6242 def WriteImmediateCmdHelper(self
, func
, file):
6243 """Overrriden from TypeHandler."""
6244 code
= """ void %(name)s(%(typed_args)s) {
6245 const uint32_t size = gles2::cmds::%(name)s::ComputeSize(n);
6246 gles2::cmds::%(name)s* c =
6247 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
6256 "typed_args": func
.MakeTypedOriginalArgString(""),
6257 "args": func
.MakeOriginalArgString(""),
6260 def WriteImmediateFormatTest(self
, func
, file):
6261 """Overrriden from TypeHandler."""
6262 file.Write("TEST_F(GLES2FormatTest, %s) {\n" % func
.name
)
6263 file.Write(" static GLuint ids[] = { 12, 23, 34, };\n")
6264 file.Write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
6265 (func
.name
, func
.name
))
6266 file.Write(" void* next_cmd = cmd.Set(\n")
6267 file.Write(" &cmd, static_cast<GLsizei>(arraysize(ids)), ids);\n")
6268 file.Write(" EXPECT_EQ(static_cast<uint32_t>(cmds::%s::kCmdId),\n" %
6270 file.Write(" cmd.header.command);\n")
6271 file.Write(" EXPECT_EQ(sizeof(cmd) +\n")
6272 file.Write(" RoundSizeToMultipleOfEntries(cmd.n * 4u),\n")
6273 file.Write(" cmd.header.size * 4u);\n")
6274 file.Write(" EXPECT_EQ(static_cast<GLsizei>(arraysize(ids)), cmd.n);\n");
6275 file.Write(" CheckBytesWrittenMatchesExpectedSize(\n")
6276 file.Write(" next_cmd, sizeof(cmd) +\n")
6277 file.Write(" RoundSizeToMultipleOfEntries(arraysize(ids) * 4u));\n")
6278 file.Write(" // TODO(gman): Check that ids were inserted;\n")
6283 class GETnHandler(TypeHandler
):
6284 """Handler for GETn for glGetBooleanv, glGetFloatv, ... type functions."""
6287 TypeHandler
.__init
__(self
)
6289 def NeedsDataTransferFunction(self
, func
):
6290 """Overriden from TypeHandler."""
6293 def WriteServiceImplementation(self
, func
, file):
6294 """Overrriden from TypeHandler."""
6295 self
.WriteServiceHandlerFunctionHeader(func
, file)
6296 last_arg
= func
.GetLastOriginalArg()
6297 # All except shm_id and shm_offset.
6298 all_but_last_args
= func
.GetCmdArgs()[:-2]
6299 for arg
in all_but_last_args
:
6300 arg
.WriteGetCode(file)
6302 code
= """ typedef cmds::%(func_name)s::Result Result;
6303 GLsizei num_values = 0;
6304 GetNumValuesReturnedForGLGet(pname, &num_values);
6305 Result* result = GetSharedMemoryAs<Result*>(
6306 c.%(last_arg_name)s_shm_id, c.%(last_arg_name)s_shm_offset,
6307 Result::ComputeSize(num_values));
6308 %(last_arg_type)s %(last_arg_name)s = result ? result->GetData() : NULL;
6311 'last_arg_type': last_arg
.type,
6312 'last_arg_name': last_arg
.name
,
6313 'func_name': func
.name
,
6315 func
.WriteHandlerValidation(file)
6316 code
= """ // Check that the client initialized the result.
6317 if (result->size != 0) {
6318 return error::kInvalidArguments;
6321 shadowed
= func
.GetInfo('shadowed')
6323 file.Write(' LOCAL_COPY_REAL_GL_ERRORS_TO_WRAPPER("%s");\n' % func
.name
)
6325 func
.WriteHandlerImplementation(file)
6327 code
= """ result->SetNumResults(num_values);
6328 return error::kNoError;
6332 code
= """ GLenum error = glGetError();
6333 if (error == GL_NO_ERROR) {
6334 result->SetNumResults(num_values);
6336 LOCAL_SET_GL_ERROR(error, "%(func_name)s", "");
6338 return error::kNoError;
6342 file.Write(code
% {'func_name': func
.name
})
6344 def WriteGLES2Implementation(self
, func
, file):
6345 """Overrriden from TypeHandler."""
6346 impl_decl
= func
.GetInfo('impl_decl')
6347 if impl_decl
== None or impl_decl
== True:
6348 file.Write("%s GLES2Implementation::%s(%s) {\n" %
6349 (func
.return_type
, func
.original_name
,
6350 func
.MakeTypedOriginalArgString("")))
6351 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
6352 func
.WriteDestinationInitalizationValidation(file)
6353 self
.WriteClientGLCallLog(func
, file)
6354 for arg
in func
.GetOriginalArgs():
6355 arg
.WriteClientSideValidationCode(file, func
)
6356 all_but_last_args
= func
.GetOriginalArgs()[:-1]
6358 has_length_arg
= False
6359 for arg
in all_but_last_args
:
6360 if arg
.type == 'GLsync':
6361 args
.append('ToGLuint(%s)' % arg
.name
)
6362 elif arg
.name
.endswith('size') and arg
.type == 'GLsizei':
6364 elif arg
.name
== 'length':
6365 has_length_arg
= True
6368 args
.append(arg
.name
)
6369 arg_string
= ", ".join(args
)
6373 for arg
in func
.GetOriginalArgs() if not arg
.IsConstant()]))
6374 self
.WriteTraceEvent(func
, file)
6375 code
= """ if (%(func_name)sHelper(%(all_arg_string)s)) {
6378 typedef cmds::%(func_name)s::Result Result;
6379 Result* result = GetResultAs<Result*>();
6383 result->SetNumResults(0);
6384 helper_->%(func_name)s(%(arg_string)s,
6385 GetResultShmId(), GetResultShmOffset());
6387 result->CopyResult(%(last_arg_name)s);
6388 GPU_CLIENT_LOG_CODE_BLOCK({
6389 for (int32_t i = 0; i < result->GetNumResults(); ++i) {
6390 GPU_CLIENT_LOG(" " << i << ": " << result->GetData()[i]);
6396 *length = result->GetNumResults();
6403 'func_name': func
.name
,
6404 'arg_string': arg_string
,
6405 'all_arg_string': all_arg_string
,
6406 'last_arg_name': func
.GetLastOriginalArg().name
,
6409 def WriteGLES2ImplementationUnitTest(self
, func
, file):
6410 """Writes the GLES2 Implemention unit test."""
6412 TEST_F(GLES2ImplementationTest, %(name)s) {
6416 typedef cmds::%(name)s::Result::Type ResultType;
6417 ResultType result = 0;
6419 ExpectedMemoryInfo result1 = GetExpectedResultMemory(
6420 sizeof(uint32_t) + sizeof(ResultType));
6421 expected.cmd.Init(%(cmd_args)s, result1.id, result1.offset);
6422 EXPECT_CALL(*command_buffer(), OnFlush())
6423 .WillOnce(SetMemory(result1.ptr, SizedResultHelper<ResultType>(1)))
6424 .RetiresOnSaturation();
6425 gl_->%(name)s(%(args)s, &result);
6426 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
6427 EXPECT_EQ(static_cast<ResultType>(1), result);
6430 first_cmd_arg
= func
.GetCmdArgs()[0].GetValidNonCachedClientSideCmdArg(func
)
6431 if not first_cmd_arg
:
6434 first_gl_arg
= func
.GetOriginalArgs()[0].GetValidNonCachedClientSideArg(
6437 cmd_arg_strings
= [first_cmd_arg
]
6438 for arg
in func
.GetCmdArgs()[1:-2]:
6439 cmd_arg_strings
.append(arg
.GetValidClientSideCmdArg(func
))
6440 gl_arg_strings
= [first_gl_arg
]
6441 for arg
in func
.GetOriginalArgs()[1:-1]:
6442 gl_arg_strings
.append(arg
.GetValidClientSideArg(func
))
6446 'args': ", ".join(gl_arg_strings
),
6447 'cmd_args': ", ".join(cmd_arg_strings
),
6450 def WriteServiceUnitTest(self
, func
, file, *extras
):
6451 """Overrriden from TypeHandler."""
6453 TEST_P(%(test_name)s, %(name)sValidArgs) {
6454 EXPECT_CALL(*gl_, GetError())
6455 .WillOnce(Return(GL_NO_ERROR))
6456 .WillOnce(Return(GL_NO_ERROR))
6457 .RetiresOnSaturation();
6458 SpecializedSetup<cmds::%(name)s, 0>(true);
6459 typedef cmds::%(name)s::Result Result;
6460 Result* result = static_cast<Result*>(shared_memory_address_);
6461 EXPECT_CALL(*gl_, %(gl_func_name)s(%(local_gl_args)s));
6464 cmd.Init(%(cmd_args)s);"""
6467 decoder_->set_unsafe_es3_apis_enabled(true);"""
6469 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
6470 EXPECT_EQ(decoder_->GetGLES2Util()->GLGetNumValuesReturned(
6472 result->GetNumResults());
6473 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
6476 decoder_->set_unsafe_es3_apis_enabled(false);
6477 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));"""
6482 cmd_arg_strings
= []
6484 for arg
in func
.GetOriginalArgs()[:-1]:
6485 if arg
.name
== 'length':
6486 gl_arg_value
= 'nullptr'
6487 elif arg
.name
.endswith('size'):
6488 gl_arg_value
= ("decoder_->GetGLES2Util()->GLGetNumValuesReturned(%s)" %
6490 elif arg
.type == 'GLsync':
6491 gl_arg_value
= 'reinterpret_cast<GLsync>(kServiceSyncId)'
6493 gl_arg_value
= arg
.GetValidGLArg(func
)
6494 gl_arg_strings
.append(gl_arg_value
)
6495 if arg
.name
== 'pname':
6496 valid_pname
= gl_arg_value
6497 if arg
.name
.endswith('size') or arg
.name
== 'length':
6499 if arg
.type == 'GLsync':
6500 arg_value
= 'client_sync_id_'
6502 arg_value
= arg
.GetValidArg(func
)
6503 cmd_arg_strings
.append(arg_value
)
6504 if func
.GetInfo('gl_test_func') == 'glGetIntegerv':
6505 gl_arg_strings
.append("_")
6507 gl_arg_strings
.append("result->GetData()")
6508 cmd_arg_strings
.append("shared_memory_id_")
6509 cmd_arg_strings
.append("shared_memory_offset_")
6511 self
.WriteValidUnitTest(func
, file, valid_test
, {
6512 'local_gl_args': ", ".join(gl_arg_strings
),
6513 'cmd_args': ", ".join(cmd_arg_strings
),
6514 'valid_pname': valid_pname
,
6517 if not func
.IsUnsafe():
6519 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
6520 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
6521 SpecializedSetup<cmds::%(name)s, 0>(false);
6522 cmds::%(name)s::Result* result =
6523 static_cast<cmds::%(name)s::Result*>(shared_memory_address_);
6527 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));
6528 EXPECT_EQ(0u, result->size);%(gl_error_test)s
6531 self
.WriteInvalidUnitTest(func
, file, invalid_test
, *extras
)
6533 class ArrayArgTypeHandler(TypeHandler
):
6534 """Base class for type handlers that handle args that are arrays"""
6537 TypeHandler
.__init
__(self
)
6539 def GetArrayType(self
, func
):
6540 """Returns the type of the element in the element array being PUT to."""
6541 for arg
in func
.GetOriginalArgs():
6543 element_type
= arg
.GetPointedType()
6546 # Special case: array type handler is used for a function that is forwarded
6547 # to the actual array type implementation
6548 element_type
= func
.GetOriginalArgs()[-1].type
6549 assert all(arg
.type == element_type \
6550 for arg
in func
.GetOriginalArgs()[-self
.GetArrayCount(func
):])
6553 def GetArrayCount(self
, func
):
6554 """Returns the count of the elements in the array being PUT to."""
6555 return func
.GetInfo('count')
6557 class PUTHandler(ArrayArgTypeHandler
):
6558 """Handler for glTexParameter_v, glVertexAttrib_v functions."""
6561 ArrayArgTypeHandler
.__init
__(self
)
6563 def WriteServiceUnitTest(self
, func
, file, *extras
):
6564 """Writes the service unit test for a command."""
6565 expected_call
= "EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));"
6566 if func
.GetInfo("first_element_only"):
6568 arg
.GetValidGLArg(func
) for arg
in func
.GetOriginalArgs()
6570 gl_arg_strings
[-1] = "*" + gl_arg_strings
[-1]
6571 expected_call
= ("EXPECT_CALL(*gl_, %%(gl_func_name)s(%s));" %
6572 ", ".join(gl_arg_strings
))
6574 TEST_P(%(test_name)s, %(name)sValidArgs) {
6575 SpecializedSetup<cmds::%(name)s, 0>(true);
6578 GetSharedMemoryAs<%(data_type)s*>()[0] = %(data_value)s;
6580 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
6581 EXPECT_EQ(GL_NO_ERROR, GetGLError());
6585 'data_type': self
.GetArrayType(func
),
6586 'data_value': func
.GetInfo('data_value') or '0',
6587 'expected_call': expected_call
,
6589 self
.WriteValidUnitTest(func
, file, valid_test
, extra
, *extras
)
6592 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
6593 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
6594 SpecializedSetup<cmds::%(name)s, 0>(false);
6597 GetSharedMemoryAs<%(data_type)s*>()[0] = %(data_value)s;
6598 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
6601 self
.WriteInvalidUnitTest(func
, file, invalid_test
, extra
, *extras
)
6603 def WriteImmediateServiceUnitTest(self
, func
, file, *extras
):
6604 """Writes the service unit test for a command."""
6606 TEST_P(%(test_name)s, %(name)sValidArgs) {
6607 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
6608 SpecializedSetup<cmds::%(name)s, 0>(true);
6609 %(data_type)s temp[%(data_count)s] = { %(data_value)s, };
6610 cmd.Init(%(gl_args)s, &temp[0]);
6613 %(gl_func_name)s(%(gl_args)s, %(data_ref)sreinterpret_cast<
6614 %(data_type)s*>(ImmediateDataAddress(&cmd))));"""
6617 decoder_->set_unsafe_es3_apis_enabled(true);"""
6619 EXPECT_EQ(error::kNoError,
6620 ExecuteImmediateCmd(cmd, sizeof(temp)));
6621 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
6624 decoder_->set_unsafe_es3_apis_enabled(false);
6625 EXPECT_EQ(error::kUnknownCommand,
6626 ExecuteImmediateCmd(cmd, sizeof(temp)));"""
6631 arg
.GetValidGLArg(func
) for arg
in func
.GetOriginalArgs()[0:-1]
6633 gl_any_strings
= ["_"] * len(gl_arg_strings
)
6636 'data_ref': ("*" if func
.GetInfo('first_element_only') else ""),
6637 'data_type': self
.GetArrayType(func
),
6638 'data_count': self
.GetArrayCount(func
),
6639 'data_value': func
.GetInfo('data_value') or '0',
6640 'gl_args': ", ".join(gl_arg_strings
),
6641 'gl_any_args': ", ".join(gl_any_strings
),
6643 self
.WriteValidUnitTest(func
, file, valid_test
, extra
, *extras
)
6646 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
6647 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();"""
6650 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_any_args)s, _)).Times(1);
6654 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_any_args)s, _)).Times(0);
6657 SpecializedSetup<cmds::%(name)s, 0>(false);
6658 %(data_type)s temp[%(data_count)s] = { %(data_value)s, };
6659 cmd.Init(%(all_but_last_args)s, &temp[0]);"""
6662 decoder_->set_unsafe_es3_apis_enabled(true);
6663 EXPECT_EQ(error::%(parse_result)s,
6664 ExecuteImmediateCmd(cmd, sizeof(temp)));
6665 decoder_->set_unsafe_es3_apis_enabled(false);
6670 EXPECT_EQ(error::%(parse_result)s,
6671 ExecuteImmediateCmd(cmd, sizeof(temp)));
6675 self
.WriteInvalidUnitTest(func
, file, invalid_test
, extra
, *extras
)
6677 def WriteGetDataSizeCode(self
, func
, file):
6678 """Overrriden from TypeHandler."""
6679 code
= """ uint32_t data_size;
6680 if (!ComputeDataSize(1, sizeof(%s), %d, &data_size)) {
6681 return error::kOutOfBounds;
6684 file.Write(code
% (self
.GetArrayType(func
), self
.GetArrayCount(func
)))
6685 if func
.IsImmediate():
6686 file.Write(" if (data_size > immediate_data_size) {\n")
6687 file.Write(" return error::kOutOfBounds;\n")
6690 def __NeedsToCalcDataCount(self
, func
):
6691 use_count_func
= func
.GetInfo('use_count_func')
6692 return use_count_func
!= None and use_count_func
!= False
6694 def WriteGLES2Implementation(self
, func
, file):
6695 """Overrriden from TypeHandler."""
6696 impl_func
= func
.GetInfo('impl_func')
6697 if (impl_func
!= None and impl_func
!= True):
6699 file.Write("%s GLES2Implementation::%s(%s) {\n" %
6700 (func
.return_type
, func
.original_name
,
6701 func
.MakeTypedOriginalArgString("")))
6702 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
6703 func
.WriteDestinationInitalizationValidation(file)
6704 self
.WriteClientGLCallLog(func
, file)
6706 if self
.__NeedsToCalcDataCount
(func
):
6707 file.Write(" size_t count = GLES2Util::Calc%sDataCount(%s);\n" %
6708 (func
.name
, func
.GetOriginalArgs()[0].name
))
6709 file.Write(" DCHECK_LE(count, %du);\n" % self
.GetArrayCount(func
))
6711 file.Write(" size_t count = %d;" % self
.GetArrayCount(func
))
6712 file.Write(" for (size_t ii = 0; ii < count; ++ii)\n")
6713 file.Write(' GPU_CLIENT_LOG("value[" << ii << "]: " << %s[ii]);\n' %
6714 func
.GetLastOriginalArg().name
)
6715 for arg
in func
.GetOriginalArgs():
6716 arg
.WriteClientSideValidationCode(file, func
)
6717 file.Write(" helper_->%sImmediate(%s);\n" %
6718 (func
.name
, func
.MakeOriginalArgString("")))
6719 file.Write(" CheckGLError();\n")
6723 def WriteGLES2ImplementationUnitTest(self
, func
, file):
6724 """Writes the GLES2 Implemention unit test."""
6725 client_test
= func
.GetInfo('client_test')
6726 if (client_test
!= None and client_test
!= True):
6729 TEST_F(GLES2ImplementationTest, %(name)s) {
6730 %(type)s data[%(count)d] = {0};
6732 cmds::%(name)sImmediate cmd;
6733 %(type)s data[%(count)d];
6736 for (int jj = 0; jj < %(count)d; ++jj) {
6737 data[jj] = static_cast<%(type)s>(jj);
6740 expected.cmd.Init(%(cmd_args)s, &data[0]);
6741 gl_->%(name)s(%(args)s, &data[0]);
6742 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
6746 arg
.GetValidClientSideCmdArg(func
) for arg
in func
.GetCmdArgs()[0:-2]
6749 arg
.GetValidClientSideArg(func
) for arg
in func
.GetOriginalArgs()[0:-1]
6754 'type': self
.GetArrayType(func
),
6755 'count': self
.GetArrayCount(func
),
6756 'args': ", ".join(gl_arg_strings
),
6757 'cmd_args': ", ".join(cmd_arg_strings
),
6760 def WriteImmediateCmdComputeSize(self
, func
, file):
6761 """Overrriden from TypeHandler."""
6762 file.Write(" static uint32_t ComputeDataSize() {\n")
6763 file.Write(" return static_cast<uint32_t>(\n")
6764 file.Write(" sizeof(%s) * %d);\n" %
6765 (self
.GetArrayType(func
), self
.GetArrayCount(func
)))
6768 if self
.__NeedsToCalcDataCount
(func
):
6769 file.Write(" static uint32_t ComputeEffectiveDataSize(%s %s) {\n" %
6770 (func
.GetOriginalArgs()[0].type,
6771 func
.GetOriginalArgs()[0].name
))
6772 file.Write(" return static_cast<uint32_t>(\n")
6773 file.Write(" sizeof(%s) * GLES2Util::Calc%sDataCount(%s));\n" %
6774 (self
.GetArrayType(func
), func
.original_name
,
6775 func
.GetOriginalArgs()[0].name
))
6778 file.Write(" static uint32_t ComputeSize() {\n")
6779 file.Write(" return static_cast<uint32_t>(\n")
6781 " sizeof(ValueType) + ComputeDataSize());\n")
6785 def WriteImmediateCmdSetHeader(self
, func
, file):
6786 """Overrriden from TypeHandler."""
6787 file.Write(" void SetHeader() {\n")
6789 " header.SetCmdByTotalSize<ValueType>(ComputeSize());\n")
6793 def WriteImmediateCmdInit(self
, func
, file):
6794 """Overrriden from TypeHandler."""
6795 last_arg
= func
.GetLastOriginalArg()
6796 file.Write(" void Init(%s, %s _%s) {\n" %
6797 (func
.MakeTypedCmdArgString("_"),
6798 last_arg
.type, last_arg
.name
))
6799 file.Write(" SetHeader();\n")
6800 args
= func
.GetCmdArgs()
6802 file.Write(" %s = _%s;\n" % (arg
.name
, arg
.name
))
6803 file.Write(" memcpy(ImmediateDataAddress(this),\n")
6804 if self
.__NeedsToCalcDataCount
(func
):
6805 file.Write(" _%s, ComputeEffectiveDataSize(%s));" %
6806 (last_arg
.name
, func
.GetOriginalArgs()[0].name
))
6808 DCHECK_GE(ComputeDataSize(), ComputeEffectiveDataSize(%(arg)s));
6809 char* pointer = reinterpret_cast<char*>(ImmediateDataAddress(this)) +
6810 ComputeEffectiveDataSize(%(arg)s);
6811 memset(pointer, 0, ComputeDataSize() - ComputeEffectiveDataSize(%(arg)s));
6812 """ % { 'arg': func
.GetOriginalArgs()[0].name
, })
6814 file.Write(" _%s, ComputeDataSize());\n" % last_arg
.name
)
6818 def WriteImmediateCmdSet(self
, func
, file):
6819 """Overrriden from TypeHandler."""
6820 last_arg
= func
.GetLastOriginalArg()
6821 copy_args
= func
.MakeCmdArgString("_", False)
6822 file.Write(" void* Set(void* cmd%s, %s _%s) {\n" %
6823 (func
.MakeTypedCmdArgString("_", True),
6824 last_arg
.type, last_arg
.name
))
6825 file.Write(" static_cast<ValueType*>(cmd)->Init(%s, _%s);\n" %
6826 (copy_args
, last_arg
.name
))
6827 file.Write(" const uint32_t size = ComputeSize();\n")
6828 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
6833 def WriteImmediateCmdHelper(self
, func
, file):
6834 """Overrriden from TypeHandler."""
6835 code
= """ void %(name)s(%(typed_args)s) {
6836 const uint32_t size = gles2::cmds::%(name)s::ComputeSize();
6837 gles2::cmds::%(name)s* c =
6838 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
6847 "typed_args": func
.MakeTypedOriginalArgString(""),
6848 "args": func
.MakeOriginalArgString(""),
6851 def WriteImmediateFormatTest(self
, func
, file):
6852 """Overrriden from TypeHandler."""
6853 file.Write("TEST_F(GLES2FormatTest, %s) {\n" % func
.name
)
6854 file.Write(" const int kSomeBaseValueToTestWith = 51;\n")
6855 file.Write(" static %s data[] = {\n" % self
.GetArrayType(func
))
6856 for v
in range(0, self
.GetArrayCount(func
)):
6857 file.Write(" static_cast<%s>(kSomeBaseValueToTestWith + %d),\n" %
6858 (self
.GetArrayType(func
), v
))
6860 file.Write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
6861 (func
.name
, func
.name
))
6862 file.Write(" void* next_cmd = cmd.Set(\n")
6864 args
= func
.GetCmdArgs()
6865 for value
, arg
in enumerate(args
):
6866 file.Write(",\n static_cast<%s>(%d)" % (arg
.type, value
+ 11))
6867 file.Write(",\n data);\n")
6868 args
= func
.GetCmdArgs()
6869 file.Write(" EXPECT_EQ(static_cast<uint32_t>(cmds::%s::kCmdId),\n"
6871 file.Write(" cmd.header.command);\n")
6872 file.Write(" EXPECT_EQ(sizeof(cmd) +\n")
6873 file.Write(" RoundSizeToMultipleOfEntries(sizeof(data)),\n")
6874 file.Write(" cmd.header.size * 4u);\n")
6875 for value
, arg
in enumerate(args
):
6876 file.Write(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);\n" %
6877 (arg
.type, value
+ 11, arg
.name
))
6878 file.Write(" CheckBytesWrittenMatchesExpectedSize(\n")
6879 file.Write(" next_cmd, sizeof(cmd) +\n")
6880 file.Write(" RoundSizeToMultipleOfEntries(sizeof(data)));\n")
6881 file.Write(" // TODO(gman): Check that data was inserted;\n")
6886 class PUTnHandler(ArrayArgTypeHandler
):
6887 """Handler for PUTn 'glUniform__v' type functions."""
6890 ArrayArgTypeHandler
.__init
__(self
)
6892 def WriteServiceUnitTest(self
, func
, file, *extras
):
6893 """Overridden from TypeHandler."""
6894 ArrayArgTypeHandler
.WriteServiceUnitTest(self
, func
, file, *extras
)
6897 TEST_P(%(test_name)s, %(name)sValidArgsCountTooLarge) {
6898 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
6899 SpecializedSetup<cmds::%(name)s, 0>(true);
6902 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
6903 EXPECT_EQ(GL_NO_ERROR, GetGLError());
6908 for count
, arg
in enumerate(func
.GetOriginalArgs()):
6909 # hardcoded to match unit tests.
6911 # the location of the second element of the 2nd uniform.
6912 # defined in GLES2DecoderBase::SetupShaderForUniform
6913 gl_arg_strings
.append("3")
6914 arg_strings
.append("ProgramManager::MakeFakeLocation(1, 1)")
6916 # the number of elements that gl will be called with.
6917 gl_arg_strings
.append("3")
6918 # the number of elements requested in the command.
6919 arg_strings
.append("5")
6921 gl_arg_strings
.append(arg
.GetValidGLArg(func
))
6922 if not arg
.IsConstant():
6923 arg_strings
.append(arg
.GetValidArg(func
))
6925 'gl_args': ", ".join(gl_arg_strings
),
6926 'args': ", ".join(arg_strings
),
6928 self
.WriteValidUnitTest(func
, file, valid_test
, extra
, *extras
)
6930 def WriteImmediateServiceUnitTest(self
, func
, file, *extras
):
6931 """Overridden from TypeHandler."""
6933 TEST_P(%(test_name)s, %(name)sValidArgs) {
6934 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
6937 %(gl_func_name)s(%(gl_args)s,
6938 reinterpret_cast<%(data_type)s*>(ImmediateDataAddress(&cmd))));
6939 SpecializedSetup<cmds::%(name)s, 0>(true);
6940 %(data_type)s temp[%(data_count)s * 2] = { 0, };
6941 cmd.Init(%(args)s, &temp[0]);"""
6944 decoder_->set_unsafe_es3_apis_enabled(true);"""
6946 EXPECT_EQ(error::kNoError,
6947 ExecuteImmediateCmd(cmd, sizeof(temp)));
6948 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
6951 decoder_->set_unsafe_es3_apis_enabled(false);
6952 EXPECT_EQ(error::kUnknownCommand,
6953 ExecuteImmediateCmd(cmd, sizeof(temp)));"""
6960 for arg
in func
.GetOriginalArgs()[0:-1]:
6961 gl_arg_strings
.append(arg
.GetValidGLArg(func
))
6962 gl_any_strings
.append("_")
6963 if not arg
.IsConstant():
6964 arg_strings
.append(arg
.GetValidArg(func
))
6966 'data_type': self
.GetArrayType(func
),
6967 'data_count': self
.GetArrayCount(func
),
6968 'args': ", ".join(arg_strings
),
6969 'gl_args': ", ".join(gl_arg_strings
),
6970 'gl_any_args': ", ".join(gl_any_strings
),
6972 self
.WriteValidUnitTest(func
, file, valid_test
, extra
, *extras
)
6975 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
6976 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
6977 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_any_args)s, _)).Times(0);
6978 SpecializedSetup<cmds::%(name)s, 0>(false);
6979 %(data_type)s temp[%(data_count)s * 2] = { 0, };
6980 cmd.Init(%(all_but_last_args)s, &temp[0]);
6981 EXPECT_EQ(error::%(parse_result)s,
6982 ExecuteImmediateCmd(cmd, sizeof(temp)));%(gl_error_test)s
6985 self
.WriteInvalidUnitTest(func
, file, invalid_test
, extra
, *extras
)
6987 def WriteGetDataSizeCode(self
, func
, file):
6988 """Overrriden from TypeHandler."""
6989 code
= """ uint32_t data_size;
6990 if (!ComputeDataSize(count, sizeof(%s), %d, &data_size)) {
6991 return error::kOutOfBounds;
6994 file.Write(code
% (self
.GetArrayType(func
), self
.GetArrayCount(func
)))
6995 if func
.IsImmediate():
6996 file.Write(" if (data_size > immediate_data_size) {\n")
6997 file.Write(" return error::kOutOfBounds;\n")
7000 def WriteGLES2Implementation(self
, func
, file):
7001 """Overrriden from TypeHandler."""
7002 file.Write("%s GLES2Implementation::%s(%s) {\n" %
7003 (func
.return_type
, func
.original_name
,
7004 func
.MakeTypedOriginalArgString("")))
7005 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
7006 func
.WriteDestinationInitalizationValidation(file)
7007 self
.WriteClientGLCallLog(func
, file)
7008 last_pointer_name
= func
.GetLastOriginalPointerArg().name
7009 file.Write(""" GPU_CLIENT_LOG_CODE_BLOCK({
7010 for (GLsizei i = 0; i < count; ++i) {
7012 values_str
= ' << ", " << '.join(
7013 ["%s[%d + i * %d]" % (
7014 last_pointer_name
, ndx
, self
.GetArrayCount(func
)) for ndx
in range(
7015 0, self
.GetArrayCount(func
))])
7016 file.Write(' GPU_CLIENT_LOG(" " << i << ": " << %s);\n' % values_str
)
7017 file.Write(" }\n });\n")
7018 for arg
in func
.GetOriginalArgs():
7019 arg
.WriteClientSideValidationCode(file, func
)
7020 file.Write(" helper_->%sImmediate(%s);\n" %
7021 (func
.name
, func
.MakeInitString("")))
7022 file.Write(" CheckGLError();\n")
7026 def WriteGLES2ImplementationUnitTest(self
, func
, file):
7027 """Writes the GLES2 Implemention unit test."""
7029 TEST_F(GLES2ImplementationTest, %(name)s) {
7030 %(type)s data[%(count_param)d][%(count)d] = {{0}};
7032 cmds::%(name)sImmediate cmd;
7033 %(type)s data[%(count_param)d][%(count)d];
7037 for (int ii = 0; ii < %(count_param)d; ++ii) {
7038 for (int jj = 0; jj < %(count)d; ++jj) {
7039 data[ii][jj] = static_cast<%(type)s>(ii * %(count)d + jj);
7042 expected.cmd.Init(%(cmd_args)s);
7043 gl_->%(name)s(%(args)s);
7044 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
7047 cmd_arg_strings
= []
7048 for arg
in func
.GetCmdArgs():
7049 if arg
.name
.endswith("_shm_id"):
7050 cmd_arg_strings
.append("&data[0][0]")
7051 elif arg
.name
.endswith("_shm_offset"):
7054 cmd_arg_strings
.append(arg
.GetValidClientSideCmdArg(func
))
7057 for arg
in func
.GetOriginalArgs():
7059 valid_value
= "&data[0][0]"
7061 valid_value
= arg
.GetValidClientSideArg(func
)
7062 gl_arg_strings
.append(valid_value
)
7063 if arg
.name
== "count":
7064 count_param
= int(valid_value
)
7067 'type': self
.GetArrayType(func
),
7068 'count': self
.GetArrayCount(func
),
7069 'args': ", ".join(gl_arg_strings
),
7070 'cmd_args': ", ".join(cmd_arg_strings
),
7071 'count_param': count_param
,
7074 # Test constants for invalid values, as they are not tested by the
7077 arg
for arg
in func
.GetOriginalArgs()[0:-1] if arg
.IsConstant()
7083 TEST_F(GLES2ImplementationTest, %(name)sInvalidConstantArg%(invalid_index)d) {
7084 %(type)s data[%(count_param)d][%(count)d] = {{0}};
7085 for (int ii = 0; ii < %(count_param)d; ++ii) {
7086 for (int jj = 0; jj < %(count)d; ++jj) {
7087 data[ii][jj] = static_cast<%(type)s>(ii * %(count)d + jj);
7090 gl_->%(name)s(%(args)s);
7091 EXPECT_TRUE(NoCommandsWritten());
7092 EXPECT_EQ(%(gl_error)s, CheckError());
7095 for invalid_arg
in constants
:
7097 invalid
= invalid_arg
.GetInvalidArg(func
)
7098 for arg
in func
.GetOriginalArgs():
7099 if arg
is invalid_arg
:
7100 gl_arg_strings
.append(invalid
[0])
7101 elif arg
.IsPointer():
7102 gl_arg_strings
.append("&data[0][0]")
7104 valid_value
= arg
.GetValidClientSideArg(func
)
7105 gl_arg_strings
.append(valid_value
)
7106 if arg
.name
== "count":
7107 count_param
= int(valid_value
)
7111 'invalid_index': func
.GetOriginalArgs().index(invalid_arg
),
7112 'type': self
.GetArrayType(func
),
7113 'count': self
.GetArrayCount(func
),
7114 'args': ", ".join(gl_arg_strings
),
7115 'gl_error': invalid
[2],
7116 'count_param': count_param
,
7120 def WriteImmediateCmdComputeSize(self
, func
, file):
7121 """Overrriden from TypeHandler."""
7122 file.Write(" static uint32_t ComputeDataSize(GLsizei count) {\n")
7123 file.Write(" return static_cast<uint32_t>(\n")
7124 file.Write(" sizeof(%s) * %d * count); // NOLINT\n" %
7125 (self
.GetArrayType(func
), self
.GetArrayCount(func
)))
7128 file.Write(" static uint32_t ComputeSize(GLsizei count) {\n")
7129 file.Write(" return static_cast<uint32_t>(\n")
7131 " sizeof(ValueType) + ComputeDataSize(count)); // NOLINT\n")
7135 def WriteImmediateCmdSetHeader(self
, func
, file):
7136 """Overrriden from TypeHandler."""
7137 file.Write(" void SetHeader(GLsizei count) {\n")
7139 " header.SetCmdByTotalSize<ValueType>(ComputeSize(count));\n")
7143 def WriteImmediateCmdInit(self
, func
, file):
7144 """Overrriden from TypeHandler."""
7145 file.Write(" void Init(%s) {\n" %
7146 func
.MakeTypedInitString("_"))
7147 file.Write(" SetHeader(_count);\n")
7148 args
= func
.GetCmdArgs()
7150 file.Write(" %s = _%s;\n" % (arg
.name
, arg
.name
))
7151 file.Write(" memcpy(ImmediateDataAddress(this),\n")
7152 pointer_arg
= func
.GetLastOriginalPointerArg()
7153 file.Write(" _%s, ComputeDataSize(_count));\n" % pointer_arg
.name
)
7157 def WriteImmediateCmdSet(self
, func
, file):
7158 """Overrriden from TypeHandler."""
7159 file.Write(" void* Set(void* cmd%s) {\n" %
7160 func
.MakeTypedInitString("_", True))
7161 file.Write(" static_cast<ValueType*>(cmd)->Init(%s);\n" %
7162 func
.MakeInitString("_"))
7163 file.Write(" const uint32_t size = ComputeSize(_count);\n")
7164 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
7169 def WriteImmediateCmdHelper(self
, func
, file):
7170 """Overrriden from TypeHandler."""
7171 code
= """ void %(name)s(%(typed_args)s) {
7172 const uint32_t size = gles2::cmds::%(name)s::ComputeSize(count);
7173 gles2::cmds::%(name)s* c =
7174 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
7183 "typed_args": func
.MakeTypedInitString(""),
7184 "args": func
.MakeInitString("")
7187 def WriteImmediateFormatTest(self
, func
, file):
7188 """Overrriden from TypeHandler."""
7189 args
= func
.GetOriginalArgs()
7192 if arg
.name
== "count":
7193 count_param
= int(arg
.GetValidClientSideCmdArg(func
))
7194 file.Write("TEST_F(GLES2FormatTest, %s) {\n" % func
.name
)
7195 file.Write(" const int kSomeBaseValueToTestWith = 51;\n")
7196 file.Write(" static %s data[] = {\n" % self
.GetArrayType(func
))
7197 for v
in range(0, self
.GetArrayCount(func
) * count_param
):
7198 file.Write(" static_cast<%s>(kSomeBaseValueToTestWith + %d),\n" %
7199 (self
.GetArrayType(func
), v
))
7201 file.Write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
7202 (func
.name
, func
.name
))
7203 file.Write(" const GLsizei kNumElements = %d;\n" % count_param
)
7204 file.Write(" const size_t kExpectedCmdSize =\n")
7205 file.Write(" sizeof(cmd) + kNumElements * sizeof(%s) * %d;\n" %
7206 (self
.GetArrayType(func
), self
.GetArrayCount(func
)))
7207 file.Write(" void* next_cmd = cmd.Set(\n")
7209 for value
, arg
in enumerate(args
):
7211 file.Write(",\n data")
7212 elif arg
.IsConstant():
7215 file.Write(",\n static_cast<%s>(%d)" % (arg
.type, value
+ 1))
7217 file.Write(" EXPECT_EQ(static_cast<uint32_t>(cmds::%s::kCmdId),\n" %
7219 file.Write(" cmd.header.command);\n")
7220 file.Write(" EXPECT_EQ(kExpectedCmdSize, cmd.header.size * 4u);\n")
7221 for value
, arg
in enumerate(args
):
7222 if arg
.IsPointer() or arg
.IsConstant():
7224 file.Write(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);\n" %
7225 (arg
.type, value
+ 1, arg
.name
))
7226 file.Write(" CheckBytesWrittenMatchesExpectedSize(\n")
7227 file.Write(" next_cmd, sizeof(cmd) +\n")
7228 file.Write(" RoundSizeToMultipleOfEntries(sizeof(data)));\n")
7229 file.Write(" // TODO(gman): Check that data was inserted;\n")
7233 class PUTSTRHandler(ArrayArgTypeHandler
):
7234 """Handler for functions that pass a string array."""
7237 ArrayArgTypeHandler
.__init
__(self
)
7239 def __GetDataArg(self
, func
):
7240 """Return the argument that points to the 2D char arrays"""
7241 for arg
in func
.GetOriginalArgs():
7242 if arg
.IsPointer2D():
7246 def __GetLengthArg(self
, func
):
7247 """Return the argument that holds length for each char array"""
7248 for arg
in func
.GetOriginalArgs():
7249 if arg
.IsPointer() and not arg
.IsPointer2D():
7253 def WriteGLES2Implementation(self
, func
, file):
7254 """Overrriden from TypeHandler."""
7255 file.Write("%s GLES2Implementation::%s(%s) {\n" %
7256 (func
.return_type
, func
.original_name
,
7257 func
.MakeTypedOriginalArgString("")))
7258 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
7259 func
.WriteDestinationInitalizationValidation(file)
7260 self
.WriteClientGLCallLog(func
, file)
7261 data_arg
= self
.__GetDataArg
(func
)
7262 length_arg
= self
.__GetLengthArg
(func
)
7263 log_code_block
= """ GPU_CLIENT_LOG_CODE_BLOCK({
7264 for (GLsizei ii = 0; ii < count; ++ii) {
7265 if (%(data)s[ii]) {"""
7266 if length_arg
== None:
7267 log_code_block
+= """
7268 GPU_CLIENT_LOG(" " << ii << ": ---\\n" << %(data)s[ii] << "\\n---");"""
7270 log_code_block
+= """
7271 if (%(length)s && %(length)s[ii] >= 0) {
7272 const std::string my_str(%(data)s[ii], %(length)s[ii]);
7273 GPU_CLIENT_LOG(" " << ii << ": ---\\n" << my_str << "\\n---");
7275 GPU_CLIENT_LOG(" " << ii << ": ---\\n" << %(data)s[ii] << "\\n---");
7277 log_code_block
+= """
7279 GPU_CLIENT_LOG(" " << ii << ": NULL");
7284 file.Write(log_code_block
% {
7285 'data': data_arg
.name
,
7286 'length': length_arg
.name
if not length_arg
== None else ''
7288 for arg
in func
.GetOriginalArgs():
7289 arg
.WriteClientSideValidationCode(file, func
)
7292 for arg
in func
.GetOriginalArgs():
7293 if arg
.name
== 'count' or arg
== self
.__GetLengthArg
(func
):
7295 if arg
== self
.__GetDataArg
(func
):
7296 bucket_args
.append('kResultBucketId')
7298 bucket_args
.append(arg
.name
)
7300 if (!PackStringsToBucket(count, %(data)s, %(length)s, "gl%(func_name)s")) {
7303 helper_->%(func_name)sBucket(%(bucket_args)s);
7304 helper_->SetBucketSize(kResultBucketId, 0);
7309 file.Write(code_block
% {
7310 'data': data_arg
.name
,
7311 'length': length_arg
.name
if not length_arg
== None else 'NULL',
7312 'func_name': func
.name
,
7313 'bucket_args': ', '.join(bucket_args
),
7316 def WriteGLES2ImplementationUnitTest(self
, func
, file):
7317 """Overrriden from TypeHandler."""
7319 TEST_F(GLES2ImplementationTest, %(name)s) {
7320 const uint32 kBucketId = GLES2Implementation::kResultBucketId;
7321 const char* kString1 = "happy";
7322 const char* kString2 = "ending";
7323 const size_t kString1Size = ::strlen(kString1) + 1;
7324 const size_t kString2Size = ::strlen(kString2) + 1;
7325 const size_t kHeaderSize = sizeof(GLint) * 3;
7326 const size_t kSourceSize = kHeaderSize + kString1Size + kString2Size;
7327 const size_t kPaddedHeaderSize =
7328 transfer_buffer_->RoundToAlignment(kHeaderSize);
7329 const size_t kPaddedString1Size =
7330 transfer_buffer_->RoundToAlignment(kString1Size);
7331 const size_t kPaddedString2Size =
7332 transfer_buffer_->RoundToAlignment(kString2Size);
7334 cmd::SetBucketSize set_bucket_size;
7335 cmd::SetBucketData set_bucket_header;
7336 cmd::SetToken set_token1;
7337 cmd::SetBucketData set_bucket_data1;
7338 cmd::SetToken set_token2;
7339 cmd::SetBucketData set_bucket_data2;
7340 cmd::SetToken set_token3;
7341 cmds::%(name)sBucket cmd_bucket;
7342 cmd::SetBucketSize clear_bucket_size;
7345 ExpectedMemoryInfo mem0 = GetExpectedMemory(kPaddedHeaderSize);
7346 ExpectedMemoryInfo mem1 = GetExpectedMemory(kPaddedString1Size);
7347 ExpectedMemoryInfo mem2 = GetExpectedMemory(kPaddedString2Size);
7350 expected.set_bucket_size.Init(kBucketId, kSourceSize);
7351 expected.set_bucket_header.Init(
7352 kBucketId, 0, kHeaderSize, mem0.id, mem0.offset);
7353 expected.set_token1.Init(GetNextToken());
7354 expected.set_bucket_data1.Init(
7355 kBucketId, kHeaderSize, kString1Size, mem1.id, mem1.offset);
7356 expected.set_token2.Init(GetNextToken());
7357 expected.set_bucket_data2.Init(
7358 kBucketId, kHeaderSize + kString1Size, kString2Size, mem2.id,
7360 expected.set_token3.Init(GetNextToken());
7361 expected.cmd_bucket.Init(%(bucket_args)s);
7362 expected.clear_bucket_size.Init(kBucketId, 0);
7363 const char* kStrings[] = { kString1, kString2 };
7364 gl_->%(name)s(%(gl_args)s);
7365 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
7370 for arg
in func
.GetOriginalArgs():
7371 if arg
== self
.__GetDataArg
(func
):
7372 gl_args
.append('kStrings')
7373 bucket_args
.append('kBucketId')
7374 elif arg
== self
.__GetLengthArg
(func
):
7375 gl_args
.append('NULL')
7376 elif arg
.name
== 'count':
7379 gl_args
.append(arg
.GetValidClientSideArg(func
))
7380 bucket_args
.append(arg
.GetValidClientSideArg(func
))
7383 'gl_args': ", ".join(gl_args
),
7384 'bucket_args': ", ".join(bucket_args
),
7387 if self
.__GetLengthArg
(func
) == None:
7390 TEST_F(GLES2ImplementationTest, %(name)sWithLength) {
7391 const uint32 kBucketId = GLES2Implementation::kResultBucketId;
7392 const char* kString = "foobar******";
7393 const size_t kStringSize = 6; // We only need "foobar".
7394 const size_t kHeaderSize = sizeof(GLint) * 2;
7395 const size_t kSourceSize = kHeaderSize + kStringSize + 1;
7396 const size_t kPaddedHeaderSize =
7397 transfer_buffer_->RoundToAlignment(kHeaderSize);
7398 const size_t kPaddedStringSize =
7399 transfer_buffer_->RoundToAlignment(kStringSize + 1);
7401 cmd::SetBucketSize set_bucket_size;
7402 cmd::SetBucketData set_bucket_header;
7403 cmd::SetToken set_token1;
7404 cmd::SetBucketData set_bucket_data;
7405 cmd::SetToken set_token2;
7406 cmds::ShaderSourceBucket shader_source_bucket;
7407 cmd::SetBucketSize clear_bucket_size;
7410 ExpectedMemoryInfo mem0 = GetExpectedMemory(kPaddedHeaderSize);
7411 ExpectedMemoryInfo mem1 = GetExpectedMemory(kPaddedStringSize);
7414 expected.set_bucket_size.Init(kBucketId, kSourceSize);
7415 expected.set_bucket_header.Init(
7416 kBucketId, 0, kHeaderSize, mem0.id, mem0.offset);
7417 expected.set_token1.Init(GetNextToken());
7418 expected.set_bucket_data.Init(
7419 kBucketId, kHeaderSize, kStringSize + 1, mem1.id, mem1.offset);
7420 expected.set_token2.Init(GetNextToken());
7421 expected.shader_source_bucket.Init(%(bucket_args)s);
7422 expected.clear_bucket_size.Init(kBucketId, 0);
7423 const char* kStrings[] = { kString };
7424 const GLint kLength[] = { kStringSize };
7425 gl_->%(name)s(%(gl_args)s);
7426 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
7430 for arg
in func
.GetOriginalArgs():
7431 if arg
== self
.__GetDataArg
(func
):
7432 gl_args
.append('kStrings')
7433 elif arg
== self
.__GetLengthArg
(func
):
7434 gl_args
.append('kLength')
7435 elif arg
.name
== 'count':
7438 gl_args
.append(arg
.GetValidClientSideArg(func
))
7441 'gl_args': ", ".join(gl_args
),
7442 'bucket_args': ", ".join(bucket_args
),
7445 def WriteBucketServiceUnitTest(self
, func
, file, *extras
):
7446 """Overrriden from TypeHandler."""
7448 cmd_args_with_invalid_id
= []
7450 for index
, arg
in enumerate(func
.GetOriginalArgs()):
7451 if arg
== self
.__GetLengthArg
(func
):
7453 elif arg
.name
== 'count':
7455 elif arg
== self
.__GetDataArg
(func
):
7456 cmd_args
.append('kBucketId')
7457 cmd_args_with_invalid_id
.append('kBucketId')
7459 elif index
== 0: # Resource ID arg
7460 cmd_args
.append(arg
.GetValidArg(func
))
7461 cmd_args_with_invalid_id
.append('kInvalidClientId')
7462 gl_args
.append(arg
.GetValidGLArg(func
))
7464 cmd_args
.append(arg
.GetValidArg(func
))
7465 cmd_args_with_invalid_id
.append(arg
.GetValidArg(func
))
7466 gl_args
.append(arg
.GetValidGLArg(func
))
7469 TEST_P(%(test_name)s, %(name)sValidArgs) {
7470 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
7471 const uint32 kBucketId = 123;
7472 const char kSource0[] = "hello";
7473 const char* kSource[] = { kSource0 };
7474 const char kValidStrEnd = 0;
7475 SetBucketAsCStrings(kBucketId, 1, kSource, 1, kValidStrEnd);
7477 cmd.Init(%(cmd_args)s);
7478 decoder_->set_unsafe_es3_apis_enabled(true);
7479 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));"""
7482 decoder_->set_unsafe_es3_apis_enabled(false);
7483 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));
7488 self
.WriteValidUnitTest(func
, file, test
, {
7489 'cmd_args': ", ".join(cmd_args
),
7490 'gl_args': ", ".join(gl_args
),
7494 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
7495 const uint32 kBucketId = 123;
7496 const char kSource0[] = "hello";
7497 const char* kSource[] = { kSource0 };
7498 const char kValidStrEnd = 0;
7499 decoder_->set_unsafe_es3_apis_enabled(true);
7502 cmd.Init(%(cmd_args)s);
7503 EXPECT_NE(error::kNoError, ExecuteCmd(cmd));
7504 // Test invalid client.
7505 SetBucketAsCStrings(kBucketId, 1, kSource, 1, kValidStrEnd);
7506 cmd.Init(%(cmd_args_with_invalid_id)s);
7507 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
7508 EXPECT_EQ(GL_INVALID_VALUE, GetGLError());
7511 self
.WriteValidUnitTest(func
, file, test
, {
7512 'cmd_args': ", ".join(cmd_args
),
7513 'cmd_args_with_invalid_id': ", ".join(cmd_args_with_invalid_id
),
7517 TEST_P(%(test_name)s, %(name)sInvalidHeader) {
7518 const uint32 kBucketId = 123;
7519 const char kSource0[] = "hello";
7520 const char* kSource[] = { kSource0 };
7521 const char kValidStrEnd = 0;
7522 const GLsizei kCount = static_cast<GLsizei>(arraysize(kSource));
7523 const GLsizei kTests[] = {
7526 std::numeric_limits<GLsizei>::max(),
7529 decoder_->set_unsafe_es3_apis_enabled(true);
7530 for (size_t ii = 0; ii < arraysize(kTests); ++ii) {
7531 SetBucketAsCStrings(kBucketId, 1, kSource, kTests[ii], kValidStrEnd);
7533 cmd.Init(%(cmd_args)s);
7534 EXPECT_EQ(error::kInvalidArguments, ExecuteCmd(cmd));
7538 self
.WriteValidUnitTest(func
, file, test
, {
7539 'cmd_args': ", ".join(cmd_args
),
7543 TEST_P(%(test_name)s, %(name)sInvalidStringEnding) {
7544 const uint32 kBucketId = 123;
7545 const char kSource0[] = "hello";
7546 const char* kSource[] = { kSource0 };
7547 const char kInvalidStrEnd = '*';
7548 SetBucketAsCStrings(kBucketId, 1, kSource, 1, kInvalidStrEnd);
7550 cmd.Init(%(cmd_args)s);
7551 decoder_->set_unsafe_es3_apis_enabled(true);
7552 EXPECT_EQ(error::kInvalidArguments, ExecuteCmd(cmd));
7555 self
.WriteValidUnitTest(func
, file, test
, {
7556 'cmd_args': ", ".join(cmd_args
),
7560 class PUTXnHandler(ArrayArgTypeHandler
):
7561 """Handler for glUniform?f functions."""
7563 ArrayArgTypeHandler
.__init
__(self
)
7565 def WriteHandlerImplementation(self
, func
, file):
7566 """Overrriden from TypeHandler."""
7567 code
= """ %(type)s temp[%(count)s] = { %(values)s};"""
7570 gl%(name)sv(%(location)s, 1, &temp[0]);
7574 Do%(name)sv(%(location)s, 1, &temp[0]);
7577 args
= func
.GetOriginalArgs()
7578 count
= int(self
.GetArrayCount(func
))
7579 num_args
= len(args
)
7580 for ii
in range(count
):
7581 values
+= "%s, " % args
[len(args
) - count
+ ii
].name
7585 'count': self
.GetArrayCount(func
),
7586 'type': self
.GetArrayType(func
),
7587 'location': args
[0].name
,
7588 'args': func
.MakeOriginalArgString(""),
7592 def WriteServiceUnitTest(self
, func
, file, *extras
):
7593 """Overrriden from TypeHandler."""
7595 TEST_P(%(test_name)s, %(name)sValidArgs) {
7596 EXPECT_CALL(*gl_, %(name)sv(%(local_args)s));
7597 SpecializedSetup<cmds::%(name)s, 0>(true);
7599 cmd.Init(%(args)s);"""
7602 decoder_->set_unsafe_es3_apis_enabled(true);"""
7604 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
7605 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
7608 decoder_->set_unsafe_es3_apis_enabled(false);
7609 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));"""
7613 args
= func
.GetOriginalArgs()
7614 local_args
= "%s, 1, _" % args
[0].GetValidGLArg(func
)
7615 self
.WriteValidUnitTest(func
, file, valid_test
, {
7617 'count': self
.GetArrayCount(func
),
7618 'local_args': local_args
,
7622 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
7623 EXPECT_CALL(*gl_, %(name)sv(_, _, _).Times(0);
7624 SpecializedSetup<cmds::%(name)s, 0>(false);
7627 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
7630 self
.WriteInvalidUnitTest(func
, file, invalid_test
, {
7631 'name': func
.GetInfo('name'),
7632 'count': self
.GetArrayCount(func
),
7636 class GLcharHandler(CustomHandler
):
7637 """Handler for functions that pass a single string ."""
7640 CustomHandler
.__init
__(self
)
7642 def WriteImmediateCmdComputeSize(self
, func
, file):
7643 """Overrriden from TypeHandler."""
7644 file.Write(" static uint32_t ComputeSize(uint32_t data_size) {\n")
7645 file.Write(" return static_cast<uint32_t>(\n")
7646 file.Write(" sizeof(ValueType) + data_size); // NOLINT\n")
7649 def WriteImmediateCmdSetHeader(self
, func
, file):
7650 """Overrriden from TypeHandler."""
7652 void SetHeader(uint32_t data_size) {
7653 header.SetCmdBySize<ValueType>(data_size);
7658 def WriteImmediateCmdInit(self
, func
, file):
7659 """Overrriden from TypeHandler."""
7660 last_arg
= func
.GetLastOriginalArg()
7661 args
= func
.GetCmdArgs()
7664 set_code
.append(" %s = _%s;" % (arg
.name
, arg
.name
))
7666 void Init(%(typed_args)s, uint32_t _data_size) {
7667 SetHeader(_data_size);
7669 memcpy(ImmediateDataAddress(this), _%(last_arg)s, _data_size);
7674 "typed_args": func
.MakeTypedArgString("_"),
7675 "set_code": "\n".join(set_code
),
7676 "last_arg": last_arg
.name
7679 def WriteImmediateCmdSet(self
, func
, file):
7680 """Overrriden from TypeHandler."""
7681 last_arg
= func
.GetLastOriginalArg()
7682 file.Write(" void* Set(void* cmd%s, uint32_t _data_size) {\n" %
7683 func
.MakeTypedCmdArgString("_", True))
7684 file.Write(" static_cast<ValueType*>(cmd)->Init(%s, _data_size);\n" %
7685 func
.MakeCmdArgString("_"))
7686 file.Write(" return NextImmediateCmdAddress<ValueType>("
7687 "cmd, _data_size);\n")
7691 def WriteImmediateCmdHelper(self
, func
, file):
7692 """Overrriden from TypeHandler."""
7693 code
= """ void %(name)s(%(typed_args)s) {
7694 const uint32_t data_size = strlen(name);
7695 gles2::cmds::%(name)s* c =
7696 GetImmediateCmdSpace<gles2::cmds::%(name)s>(data_size);
7698 c->Init(%(args)s, data_size);
7705 "typed_args": func
.MakeTypedOriginalArgString(""),
7706 "args": func
.MakeOriginalArgString(""),
7710 def WriteImmediateFormatTest(self
, func
, file):
7711 """Overrriden from TypeHandler."""
7714 all_but_last_arg
= func
.GetCmdArgs()[:-1]
7715 for value
, arg
in enumerate(all_but_last_arg
):
7716 init_code
.append(" static_cast<%s>(%d)," % (arg
.type, value
+ 11))
7717 for value
, arg
in enumerate(all_but_last_arg
):
7718 check_code
.append(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);" %
7719 (arg
.type, value
+ 11, arg
.name
))
7721 TEST_F(GLES2FormatTest, %(func_name)s) {
7722 cmds::%(func_name)s& cmd = *GetBufferAs<cmds::%(func_name)s>();
7723 static const char* const test_str = \"test string\";
7724 void* next_cmd = cmd.Set(
7729 EXPECT_EQ(static_cast<uint32_t>(cmds::%(func_name)s::kCmdId),
7730 cmd.header.command);
7731 EXPECT_EQ(sizeof(cmd) +
7732 RoundSizeToMultipleOfEntries(strlen(test_str)),
7733 cmd.header.size * 4u);
7734 EXPECT_EQ(static_cast<char*>(next_cmd),
7735 reinterpret_cast<char*>(&cmd) + sizeof(cmd) +
7736 RoundSizeToMultipleOfEntries(strlen(test_str)));
7738 EXPECT_EQ(static_cast<uint32_t>(strlen(test_str)), cmd.data_size);
7739 EXPECT_EQ(0, memcmp(test_str, ImmediateDataAddress(&cmd), strlen(test_str)));
7742 sizeof(cmd) + RoundSizeToMultipleOfEntries(strlen(test_str)),
7743 sizeof(cmd) + strlen(test_str));
7748 'func_name': func
.name
,
7749 'init_code': "\n".join(init_code
),
7750 'check_code': "\n".join(check_code
),
7754 class GLcharNHandler(CustomHandler
):
7755 """Handler for functions that pass a single string with an optional len."""
7758 CustomHandler
.__init
__(self
)
7760 def InitFunction(self
, func
):
7761 """Overrriden from TypeHandler."""
7763 func
.AddCmdArg(Argument('bucket_id', 'GLuint'))
7765 def NeedsDataTransferFunction(self
, func
):
7766 """Overriden from TypeHandler."""
7769 def AddBucketFunction(self
, generator
, func
):
7770 """Overrriden from TypeHandler."""
7773 def WriteServiceImplementation(self
, func
, file):
7774 """Overrriden from TypeHandler."""
7775 self
.WriteServiceHandlerFunctionHeader(func
, file)
7777 GLuint bucket_id = static_cast<GLuint>(c.%(bucket_id)s);
7778 Bucket* bucket = GetBucket(bucket_id);
7779 if (!bucket || bucket->size() == 0) {
7780 return error::kInvalidArguments;
7783 if (!bucket->GetAsString(&str)) {
7784 return error::kInvalidArguments;
7786 %(gl_func_name)s(0, str.c_str());
7787 return error::kNoError;
7792 'gl_func_name': func
.GetGLFunctionName(),
7793 'bucket_id': func
.cmd_args
[0].name
,
7797 class IsHandler(TypeHandler
):
7798 """Handler for glIs____ type and glGetError functions."""
7801 TypeHandler
.__init
__(self
)
7803 def InitFunction(self
, func
):
7804 """Overrriden from TypeHandler."""
7805 func
.AddCmdArg(Argument("result_shm_id", 'uint32_t'))
7806 func
.AddCmdArg(Argument("result_shm_offset", 'uint32_t'))
7807 if func
.GetInfo('result') == None:
7808 func
.AddInfo('result', ['uint32_t'])
7810 def WriteServiceUnitTest(self
, func
, file, *extras
):
7811 """Overrriden from TypeHandler."""
7813 TEST_P(%(test_name)s, %(name)sValidArgs) {
7814 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
7815 SpecializedSetup<cmds::%(name)s, 0>(true);
7817 cmd.Init(%(args)s%(comma)sshared_memory_id_, shared_memory_offset_);"""
7820 decoder_->set_unsafe_es3_apis_enabled(true);"""
7822 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
7823 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
7826 decoder_->set_unsafe_es3_apis_enabled(false);
7827 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));"""
7832 if len(func
.GetOriginalArgs()):
7834 self
.WriteValidUnitTest(func
, file, valid_test
, {
7839 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
7840 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
7841 SpecializedSetup<cmds::%(name)s, 0>(false);
7843 cmd.Init(%(args)s%(comma)sshared_memory_id_, shared_memory_offset_);
7844 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
7847 self
.WriteInvalidUnitTest(func
, file, invalid_test
, {
7852 TEST_P(%(test_name)s, %(name)sInvalidArgsBadSharedMemoryId) {
7853 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
7854 SpecializedSetup<cmds::%(name)s, 0>(false);"""
7857 decoder_->set_unsafe_es3_apis_enabled(true);"""
7860 cmd.Init(%(args)s%(comma)skInvalidSharedMemoryId, shared_memory_offset_);
7861 EXPECT_EQ(error::kOutOfBounds, ExecuteCmd(cmd));
7862 cmd.Init(%(args)s%(comma)sshared_memory_id_, kInvalidSharedMemoryOffset);
7863 EXPECT_EQ(error::kOutOfBounds, ExecuteCmd(cmd));"""
7866 decoder_->set_unsafe_es3_apis_enabled(true);"""
7870 self
.WriteValidUnitTest(func
, file, invalid_test
, {
7874 def WriteServiceImplementation(self
, func
, file):
7875 """Overrriden from TypeHandler."""
7876 self
.WriteServiceHandlerFunctionHeader(func
, file)
7877 args
= func
.GetOriginalArgs()
7879 arg
.WriteGetCode(file)
7881 code
= """ typedef cmds::%(func_name)s::Result Result;
7882 Result* result_dst = GetSharedMemoryAs<Result*>(
7883 c.result_shm_id, c.result_shm_offset, sizeof(*result_dst));
7885 return error::kOutOfBounds;
7888 file.Write(code
% {'func_name': func
.name
})
7889 func
.WriteHandlerValidation(file)
7891 assert func
.GetInfo('id_mapping')
7892 assert len(func
.GetInfo('id_mapping')) == 1
7893 assert len(args
) == 1
7894 id_type
= func
.GetInfo('id_mapping')[0]
7895 file.Write(" %s service_%s = 0;\n" % (args
[0].type, id_type
.lower()))
7896 file.Write(" *result_dst = group_->Get%sServiceId(%s, &service_%s);\n" %
7897 (id_type
, id_type
.lower(), id_type
.lower()))
7899 file.Write(" *result_dst = %s(%s);\n" %
7900 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
7901 file.Write(" return error::kNoError;\n")
7905 def WriteGLES2Implementation(self
, func
, file):
7906 """Overrriden from TypeHandler."""
7907 impl_func
= func
.GetInfo('impl_func')
7908 if impl_func
== None or impl_func
== True:
7909 error_value
= func
.GetInfo("error_value") or "GL_FALSE"
7910 file.Write("%s GLES2Implementation::%s(%s) {\n" %
7911 (func
.return_type
, func
.original_name
,
7912 func
.MakeTypedOriginalArgString("")))
7913 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
7914 self
.WriteTraceEvent(func
, file)
7915 func
.WriteDestinationInitalizationValidation(file)
7916 self
.WriteClientGLCallLog(func
, file)
7917 file.Write(" typedef cmds::%s::Result Result;\n" % func
.name
)
7918 file.Write(" Result* result = GetResultAs<Result*>();\n")
7919 file.Write(" if (!result) {\n")
7920 file.Write(" return %s;\n" % error_value
)
7922 file.Write(" *result = 0;\n")
7923 assert len(func
.GetOriginalArgs()) == 1
7924 id_arg
= func
.GetOriginalArgs()[0]
7925 if id_arg
.type == 'GLsync':
7926 arg_string
= "ToGLuint(%s)" % func
.MakeOriginalArgString("")
7928 arg_string
= func
.MakeOriginalArgString("")
7930 " helper_->%s(%s, GetResultShmId(), GetResultShmOffset());\n" %
7931 (func
.name
, arg_string
))
7932 file.Write(" WaitForCmd();\n")
7933 file.Write(" %s result_value = *result" % func
.return_type
)
7934 if func
.return_type
== "GLboolean":
7936 file.Write(';\n GPU_CLIENT_LOG("returned " << result_value);\n')
7937 file.Write(" CheckGLError();\n")
7938 file.Write(" return result_value;\n")
7942 def WriteGLES2ImplementationUnitTest(self
, func
, file):
7943 """Overrriden from TypeHandler."""
7944 client_test
= func
.GetInfo('client_test')
7945 if client_test
== None or client_test
== True:
7947 TEST_F(GLES2ImplementationTest, %(name)s) {
7953 ExpectedMemoryInfo result1 =
7954 GetExpectedResultMemory(sizeof(cmds::%(name)s::Result));
7955 expected.cmd.Init(%(cmd_id_value)s, result1.id, result1.offset);
7957 EXPECT_CALL(*command_buffer(), OnFlush())
7958 .WillOnce(SetMemory(result1.ptr, uint32_t(GL_TRUE)))
7959 .RetiresOnSaturation();
7961 GLboolean result = gl_->%(name)s(%(gl_id_value)s);
7962 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
7963 EXPECT_TRUE(result);
7966 args
= func
.GetOriginalArgs()
7967 assert len(args
) == 1
7970 'cmd_id_value': args
[0].GetValidClientSideCmdArg(func
),
7971 'gl_id_value': args
[0].GetValidClientSideArg(func
) })
7974 class STRnHandler(TypeHandler
):
7975 """Handler for GetProgramInfoLog, GetShaderInfoLog, GetShaderSource, and
7976 GetTranslatedShaderSourceANGLE."""
7979 TypeHandler
.__init
__(self
)
7981 def InitFunction(self
, func
):
7982 """Overrriden from TypeHandler."""
7983 # remove all but the first cmd args.
7984 cmd_args
= func
.GetCmdArgs()
7986 func
.AddCmdArg(cmd_args
[0])
7987 # add on a bucket id.
7988 func
.AddCmdArg(Argument('bucket_id', 'uint32_t'))
7990 def WriteGLES2Implementation(self
, func
, file):
7991 """Overrriden from TypeHandler."""
7992 code_1
= """%(return_type)s GLES2Implementation::%(func_name)s(%(args)s) {
7993 GPU_CLIENT_SINGLE_THREAD_CHECK();
7995 code_2
= """ GPU_CLIENT_LOG("[" << GetLogPrefix()
7996 << "] gl%(func_name)s" << "("
7999 << static_cast<void*>(%(arg2)s) << ", "
8000 << static_cast<void*>(%(arg3)s) << ")");
8001 helper_->SetBucketSize(kResultBucketId, 0);
8002 helper_->%(func_name)s(%(id_name)s, kResultBucketId);
8004 GLsizei max_size = 0;
8005 if (GetBucketAsString(kResultBucketId, &str)) {
8008 std::min(static_cast<size_t>(%(bufsize_name)s) - 1, str.size());
8009 memcpy(%(dest_name)s, str.c_str(), max_size);
8010 %(dest_name)s[max_size] = '\\0';
8011 GPU_CLIENT_LOG("------\\n" << %(dest_name)s << "\\n------");
8014 if (%(length_name)s != NULL) {
8015 *%(length_name)s = max_size;
8020 args
= func
.GetOriginalArgs()
8022 'return_type': func
.return_type
,
8023 'func_name': func
.original_name
,
8024 'args': func
.MakeTypedOriginalArgString(""),
8025 'id_name': args
[0].name
,
8026 'bufsize_name': args
[1].name
,
8027 'length_name': args
[2].name
,
8028 'dest_name': args
[3].name
,
8029 'arg0': args
[0].name
,
8030 'arg1': args
[1].name
,
8031 'arg2': args
[2].name
,
8032 'arg3': args
[3].name
,
8034 file.Write(code_1
% str_args
)
8035 func
.WriteDestinationInitalizationValidation(file)
8036 file.Write(code_2
% str_args
)
8038 def WriteServiceUnitTest(self
, func
, file, *extras
):
8039 """Overrriden from TypeHandler."""
8041 TEST_P(%(test_name)s, %(name)sValidArgs) {
8042 const char* kInfo = "hello";
8043 const uint32_t kBucketId = 123;
8044 SpecializedSetup<cmds::%(name)s, 0>(true);
8046 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s))
8047 .WillOnce(DoAll(SetArgumentPointee<2>(strlen(kInfo)),
8048 SetArrayArgument<3>(kInfo, kInfo + strlen(kInfo) + 1)));
8051 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
8052 CommonDecoder::Bucket* bucket = decoder_->GetBucket(kBucketId);
8053 ASSERT_TRUE(bucket != NULL);
8054 EXPECT_EQ(strlen(kInfo) + 1, bucket->size());
8055 EXPECT_EQ(0, memcmp(bucket->GetData(0, bucket->size()), kInfo,
8057 EXPECT_EQ(GL_NO_ERROR, GetGLError());
8060 args
= func
.GetOriginalArgs()
8061 id_name
= args
[0].GetValidGLArg(func
)
8062 get_len_func
= func
.GetInfo('get_len_func')
8063 get_len_enum
= func
.GetInfo('get_len_enum')
8066 'get_len_func': get_len_func
,
8067 'get_len_enum': get_len_enum
,
8068 'gl_args': '%s, strlen(kInfo) + 1, _, _' %
8069 args
[0].GetValidGLArg(func
),
8070 'args': '%s, kBucketId' % args
[0].GetValidArg(func
),
8071 'expect_len_code': '',
8073 if get_len_func
and get_len_func
[0:2] == 'gl':
8074 sub
['expect_len_code'] = (
8075 " EXPECT_CALL(*gl_, %s(%s, %s, _))\n"
8076 " .WillOnce(SetArgumentPointee<2>(strlen(kInfo) + 1));") % (
8077 get_len_func
[2:], id_name
, get_len_enum
)
8078 self
.WriteValidUnitTest(func
, file, valid_test
, sub
, *extras
)
8081 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
8082 const uint32_t kBucketId = 123;
8083 EXPECT_CALL(*gl_, %(gl_func_name)s(_, _, _, _))
8086 cmd.Init(kInvalidClientId, kBucketId);
8087 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
8088 EXPECT_EQ(GL_INVALID_VALUE, GetGLError());
8091 self
.WriteValidUnitTest(func
, file, invalid_test
, *extras
)
8093 def WriteServiceImplementation(self
, func
, file):
8094 """Overrriden from TypeHandler."""
8097 class NamedType(object):
8098 """A class that represents a type of an argument in a client function.
8100 A type of an argument that is to be passed through in the command buffer
8101 command. Currently used only for the arguments that are specificly named in
8102 the 'cmd_buffer_functions.txt' file, mostly enums.
8105 def __init__(self
, info
):
8106 assert not 'is_complete' in info
or info
['is_complete'] == True
8108 self
.valid
= info
['valid']
8109 if 'invalid' in info
:
8110 self
.invalid
= info
['invalid']
8113 if 'valid_es3' in info
:
8114 self
.valid_es3
= info
['valid_es3']
8117 if 'deprecated_es3' in info
:
8118 self
.deprecated_es3
= info
['deprecated_es3']
8120 self
.deprecated_es3
= []
8123 return self
.info
['type']
8125 def GetInvalidValues(self
):
8128 def GetValidValues(self
):
8131 def GetValidValuesES3(self
):
8132 return self
.valid_es3
8134 def GetDeprecatedValuesES3(self
):
8135 return self
.deprecated_es3
8137 def IsConstant(self
):
8138 if not 'is_complete' in self
.info
:
8141 return len(self
.GetValidValues()) == 1
8143 def GetConstantValue(self
):
8144 return self
.GetValidValues()[0]
8146 class Argument(object):
8147 """A class that represents a function argument."""
8150 'GLenum': 'uint32_t',
8152 'GLintptr': 'int32_t',
8153 'GLsizei': 'int32_t',
8154 'GLsizeiptr': 'int32_t',
8156 'GLclampf': 'float',
8158 need_validation_
= ['GLsizei*', 'GLboolean*', 'GLenum*', 'GLint*']
8160 def __init__(self
, name
, type):
8162 self
.optional
= type.endswith("Optional*")
8164 type = type[:-9] + "*"
8167 if type in self
.cmd_type_map_
:
8168 self
.cmd_type
= self
.cmd_type_map_
[type]
8170 self
.cmd_type
= 'uint32_t'
8172 def IsPointer(self
):
8173 """Returns true if argument is a pointer."""
8176 def IsPointer2D(self
):
8177 """Returns true if argument is a 2D pointer."""
8180 def IsConstant(self
):
8181 """Returns true if the argument has only one valid value."""
8184 def AddCmdArgs(self
, args
):
8185 """Adds command arguments for this argument to the given list."""
8186 if not self
.IsConstant():
8187 return args
.append(self
)
8189 def AddInitArgs(self
, args
):
8190 """Adds init arguments for this argument to the given list."""
8191 if not self
.IsConstant():
8192 return args
.append(self
)
8194 def GetValidArg(self
, func
):
8195 """Gets a valid value for this argument."""
8196 valid_arg
= func
.GetValidArg(self
)
8197 if valid_arg
!= None:
8200 index
= func
.GetOriginalArgs().index(self
)
8201 return str(index
+ 1)
8203 def GetValidClientSideArg(self
, func
):
8204 """Gets a valid value for this argument."""
8205 valid_arg
= func
.GetValidArg(self
)
8206 if valid_arg
!= None:
8209 if self
.IsPointer():
8211 index
= func
.GetOriginalArgs().index(self
)
8212 if self
.type == 'GLsync':
8213 return ("reinterpret_cast<GLsync>(%d)" % (index
+ 1))
8214 return str(index
+ 1)
8216 def GetValidClientSideCmdArg(self
, func
):
8217 """Gets a valid value for this argument."""
8218 valid_arg
= func
.GetValidArg(self
)
8219 if valid_arg
!= None:
8222 index
= func
.GetOriginalArgs().index(self
)
8223 return str(index
+ 1)
8226 index
= func
.GetCmdArgs().index(self
)
8227 return str(index
+ 1)
8229 def GetValidGLArg(self
, func
):
8230 """Gets a valid GL value for this argument."""
8231 value
= self
.GetValidArg(func
)
8232 if self
.type == 'GLsync':
8233 return ("reinterpret_cast<GLsync>(%s)" % value
)
8236 def GetValidNonCachedClientSideArg(self
, func
):
8237 """Returns a valid value for this argument in a GL call.
8238 Using the value will produce a command buffer service invocation.
8239 Returns None if there is no such value."""
8241 if self
.type == 'GLsync':
8242 return ("reinterpret_cast<GLsync>(%s)" % value
)
8245 def GetValidNonCachedClientSideCmdArg(self
, func
):
8246 """Returns a valid value for this argument in a command buffer command.
8247 Calling the GL function with the value returned by
8248 GetValidNonCachedClientSideArg will result in a command buffer command
8249 that contains the value returned by this function. """
8252 def GetNumInvalidValues(self
, func
):
8253 """returns the number of invalid values to be tested."""
8256 def GetInvalidArg(self
, index
):
8257 """returns an invalid value and expected parse result by index."""
8258 return ("---ERROR0---", "---ERROR2---", None)
8260 def GetLogArg(self
):
8261 """Get argument appropriate for LOG macro."""
8262 if self
.type == 'GLboolean':
8263 return 'GLES2Util::GetStringBool(%s)' % self
.name
8264 if self
.type == 'GLenum':
8265 return 'GLES2Util::GetStringEnum(%s)' % self
.name
8268 def WriteGetCode(self
, file):
8269 """Writes the code to get an argument from a command structure."""
8270 if self
.type == 'GLsync':
8274 file.Write(" %s %s = static_cast<%s>(c.%s);\n" %
8275 (my_type
, self
.name
, my_type
, self
.name
))
8277 def WriteValidationCode(self
, file, func
):
8278 """Writes the validation code for an argument."""
8281 def WriteClientSideValidationCode(self
, file, func
):
8282 """Writes the validation code for an argument."""
8285 def WriteDestinationInitalizationValidation(self
, file, func
):
8286 """Writes the client side destintion initialization validation."""
8289 def WriteDestinationInitalizationValidatationIfNeeded(self
, file, func
):
8290 """Writes the client side destintion initialization validation if needed."""
8291 parts
= self
.type.split(" ")
8294 if parts
[0] in self
.need_validation_
:
8296 " GPU_CLIENT_VALIDATE_DESTINATION_%sINITALIZATION(%s, %s);\n" %
8297 ("OPTIONAL_" if self
.optional
else "", self
.type[:-1], self
.name
))
8300 def WriteGetAddress(self
, file):
8301 """Writes the code to get the address this argument refers to."""
8304 def GetImmediateVersion(self
):
8305 """Gets the immediate version of this argument."""
8308 def GetBucketVersion(self
):
8309 """Gets the bucket version of this argument."""
8313 class BoolArgument(Argument
):
8314 """class for GLboolean"""
8316 def __init__(self
, name
, type):
8317 Argument
.__init
__(self
, name
, 'GLboolean')
8319 def GetValidArg(self
, func
):
8320 """Gets a valid value for this argument."""
8323 def GetValidClientSideArg(self
, func
):
8324 """Gets a valid value for this argument."""
8327 def GetValidClientSideCmdArg(self
, func
):
8328 """Gets a valid value for this argument."""
8331 def GetValidGLArg(self
, func
):
8332 """Gets a valid GL value for this argument."""
8336 class UniformLocationArgument(Argument
):
8337 """class for uniform locations."""
8339 def __init__(self
, name
):
8340 Argument
.__init
__(self
, name
, "GLint")
8342 def WriteGetCode(self
, file):
8343 """Writes the code to get an argument from a command structure."""
8344 code
= """ %s %s = static_cast<%s>(c.%s);
8346 file.Write(code
% (self
.type, self
.name
, self
.type, self
.name
))
8348 class DataSizeArgument(Argument
):
8349 """class for data_size which Bucket commands do not need."""
8351 def __init__(self
, name
):
8352 Argument
.__init
__(self
, name
, "uint32_t")
8354 def GetBucketVersion(self
):
8358 class SizeArgument(Argument
):
8359 """class for GLsizei and GLsizeiptr."""
8361 def __init__(self
, name
, type):
8362 Argument
.__init
__(self
, name
, type)
8364 def GetNumInvalidValues(self
, func
):
8365 """overridden from Argument."""
8366 if func
.IsImmediate():
8370 def GetInvalidArg(self
, index
):
8371 """overridden from Argument."""
8372 return ("-1", "kNoError", "GL_INVALID_VALUE")
8374 def WriteValidationCode(self
, file, func
):
8375 """overridden from Argument."""
8378 code
= """ if (%(var_name)s < 0) {
8379 LOCAL_SET_GL_ERROR(GL_INVALID_VALUE, "gl%(func_name)s", "%(var_name)s < 0");
8380 return error::kNoError;
8384 "var_name": self
.name
,
8385 "func_name": func
.original_name
,
8388 def WriteClientSideValidationCode(self
, file, func
):
8389 """overridden from Argument."""
8390 code
= """ if (%(var_name)s < 0) {
8391 SetGLError(GL_INVALID_VALUE, "gl%(func_name)s", "%(var_name)s < 0");
8396 "var_name": self
.name
,
8397 "func_name": func
.original_name
,
8401 class SizeNotNegativeArgument(SizeArgument
):
8402 """class for GLsizeiNotNegative. It's NEVER allowed to be negative"""
8404 def __init__(self
, name
, type, gl_type
):
8405 SizeArgument
.__init
__(self
, name
, gl_type
)
8407 def GetInvalidArg(self
, index
):
8408 """overridden from SizeArgument."""
8409 return ("-1", "kOutOfBounds", "GL_NO_ERROR")
8411 def WriteValidationCode(self
, file, func
):
8412 """overridden from SizeArgument."""
8416 class EnumBaseArgument(Argument
):
8417 """Base class for EnumArgument, IntArgument, BitfieldArgument, and
8418 ValidatedBoolArgument."""
8420 def __init__(self
, name
, gl_type
, type, gl_error
):
8421 Argument
.__init
__(self
, name
, gl_type
)
8423 self
.local_type
= type
8424 self
.gl_error
= gl_error
8425 name
= type[len(gl_type
):]
8426 self
.type_name
= name
8427 self
.named_type
= NamedType(_NAMED_TYPE_INFO
[name
])
8429 def IsConstant(self
):
8430 return self
.named_type
.IsConstant()
8432 def GetConstantValue(self
):
8433 return self
.named_type
.GetConstantValue()
8435 def WriteValidationCode(self
, file, func
):
8438 if self
.named_type
.IsConstant():
8440 file.Write(" if (!validators_->%s.IsValid(%s)) {\n" %
8441 (ToUnderscore(self
.type_name
), self
.name
))
8442 if self
.gl_error
== "GL_INVALID_ENUM":
8444 " LOCAL_SET_GL_ERROR_INVALID_ENUM(\"gl%s\", %s, \"%s\");\n" %
8445 (func
.original_name
, self
.name
, self
.name
))
8448 " LOCAL_SET_GL_ERROR(%s, \"gl%s\", \"%s %s\");\n" %
8449 (self
.gl_error
, func
.original_name
, self
.name
, self
.gl_error
))
8450 file.Write(" return error::kNoError;\n")
8453 def WriteClientSideValidationCode(self
, file, func
):
8454 if not self
.named_type
.IsConstant():
8456 file.Write(" if (%s != %s) {" % (self
.name
,
8457 self
.GetConstantValue()))
8459 " SetGLError(%s, \"gl%s\", \"%s %s\");\n" %
8460 (self
.gl_error
, func
.original_name
, self
.name
, self
.gl_error
))
8461 if func
.return_type
== "void":
8462 file.Write(" return;\n")
8464 file.Write(" return %s;\n" % func
.GetErrorReturnString())
8467 def GetValidArg(self
, func
):
8468 valid_arg
= func
.GetValidArg(self
)
8469 if valid_arg
!= None:
8471 valid
= self
.named_type
.GetValidValues()
8473 num_valid
= len(valid
)
8476 index
= func
.GetOriginalArgs().index(self
)
8477 return str(index
+ 1)
8479 def GetValidClientSideArg(self
, func
):
8480 """Gets a valid value for this argument."""
8481 return self
.GetValidArg(func
)
8483 def GetValidClientSideCmdArg(self
, func
):
8484 """Gets a valid value for this argument."""
8485 valid_arg
= func
.GetValidArg(self
)
8486 if valid_arg
!= None:
8489 valid
= self
.named_type
.GetValidValues()
8491 num_valid
= len(valid
)
8495 index
= func
.GetOriginalArgs().index(self
)
8496 return str(index
+ 1)
8499 index
= func
.GetCmdArgs().index(self
)
8500 return str(index
+ 1)
8502 def GetValidGLArg(self
, func
):
8503 """Gets a valid value for this argument."""
8504 return self
.GetValidArg(func
)
8506 def GetNumInvalidValues(self
, func
):
8507 """returns the number of invalid values to be tested."""
8508 return len(self
.named_type
.GetInvalidValues())
8510 def GetInvalidArg(self
, index
):
8511 """returns an invalid value by index."""
8512 invalid
= self
.named_type
.GetInvalidValues()
8514 num_invalid
= len(invalid
)
8515 if index
>= num_invalid
:
8516 index
= num_invalid
- 1
8517 return (invalid
[index
], "kNoError", self
.gl_error
)
8518 return ("---ERROR1---", "kNoError", self
.gl_error
)
8521 class EnumArgument(EnumBaseArgument
):
8522 """A class that represents a GLenum argument"""
8524 def __init__(self
, name
, type):
8525 EnumBaseArgument
.__init
__(self
, name
, "GLenum", type, "GL_INVALID_ENUM")
8527 def GetLogArg(self
):
8528 """Overridden from Argument."""
8529 return ("GLES2Util::GetString%s(%s)" %
8530 (self
.type_name
, self
.name
))
8533 class IntArgument(EnumBaseArgument
):
8534 """A class for a GLint argument that can only accept specific values.
8536 For example glTexImage2D takes a GLint for its internalformat
8537 argument instead of a GLenum.
8540 def __init__(self
, name
, type):
8541 EnumBaseArgument
.__init
__(self
, name
, "GLint", type, "GL_INVALID_VALUE")
8544 class ValidatedBoolArgument(EnumBaseArgument
):
8545 """A class for a GLboolean argument that can only accept specific values.
8547 For example glUniformMatrix takes a GLboolean for it's transpose but it
8551 def __init__(self
, name
, type):
8552 EnumBaseArgument
.__init
__(self
, name
, "GLboolean", type, "GL_INVALID_VALUE")
8554 def GetLogArg(self
):
8555 """Overridden from Argument."""
8556 return 'GLES2Util::GetStringBool(%s)' % self
.name
8559 class BitFieldArgument(EnumBaseArgument
):
8560 """A class for a GLbitfield argument that can only accept specific values.
8562 For example glFenceSync takes a GLbitfield for its flags argument bit it
8566 def __init__(self
, name
, type):
8567 EnumBaseArgument
.__init
__(self
, name
, "GLbitfield", type,
8571 class ImmediatePointerArgument(Argument
):
8572 """A class that represents an immediate argument to a function.
8574 An immediate argument is one where the data follows the command.
8577 def __init__(self
, name
, type):
8578 Argument
.__init
__(self
, name
, type)
8580 def IsPointer(self
):
8583 def GetPointedType(self
):
8584 match
= re
.match('(const\s+)?(?P<element_type>[\w]+)\s*\*', self
.type)
8586 return match
.groupdict()['element_type']
8588 def AddCmdArgs(self
, args
):
8589 """Overridden from Argument."""
8592 def WriteGetCode(self
, file):
8593 """Overridden from Argument."""
8595 " %s %s = GetImmediateDataAs<%s>(\n" %
8596 (self
.type, self
.name
, self
.type))
8597 file.Write(" c, data_size, immediate_data_size);\n")
8599 def WriteValidationCode(self
, file, func
):
8600 """Overridden from Argument."""
8603 file.Write(" if (%s == NULL) {\n" % self
.name
)
8604 file.Write(" return error::kOutOfBounds;\n")
8607 def GetImmediateVersion(self
):
8608 """Overridden from Argument."""
8611 def WriteDestinationInitalizationValidation(self
, file, func
):
8612 """Overridden from Argument."""
8613 self
.WriteDestinationInitalizationValidatationIfNeeded(file, func
)
8615 def GetLogArg(self
):
8616 """Overridden from Argument."""
8617 return "static_cast<const void*>(%s)" % self
.name
8620 class PointerArgument(Argument
):
8621 """A class that represents a pointer argument to a function."""
8623 def __init__(self
, name
, type):
8624 Argument
.__init
__(self
, name
, type)
8626 def IsPointer(self
):
8627 """Overridden from Argument."""
8630 def IsPointer2D(self
):
8631 """Overridden from Argument."""
8632 return self
.type.count('*') == 2
8634 def GetPointedType(self
):
8635 match
= re
.match('(const\s+)?(?P<element_type>[\w]+)\s*\*', self
.type)
8637 return match
.groupdict()['element_type']
8639 def GetValidArg(self
, func
):
8640 """Overridden from Argument."""
8641 return "shared_memory_id_, shared_memory_offset_"
8643 def GetValidGLArg(self
, func
):
8644 """Overridden from Argument."""
8645 return "reinterpret_cast<%s>(shared_memory_address_)" % self
.type
8647 def GetNumInvalidValues(self
, func
):
8648 """Overridden from Argument."""
8651 def GetInvalidArg(self
, index
):
8652 """Overridden from Argument."""
8654 return ("kInvalidSharedMemoryId, 0", "kOutOfBounds", None)
8656 return ("shared_memory_id_, kInvalidSharedMemoryOffset",
8657 "kOutOfBounds", None)
8659 def GetLogArg(self
):
8660 """Overridden from Argument."""
8661 return "static_cast<const void*>(%s)" % self
.name
8663 def AddCmdArgs(self
, args
):
8664 """Overridden from Argument."""
8665 args
.append(Argument("%s_shm_id" % self
.name
, 'uint32_t'))
8666 args
.append(Argument("%s_shm_offset" % self
.name
, 'uint32_t'))
8668 def WriteGetCode(self
, file):
8669 """Overridden from Argument."""
8671 " %s %s = GetSharedMemoryAs<%s>(\n" %
8672 (self
.type, self
.name
, self
.type))
8674 " c.%s_shm_id, c.%s_shm_offset, data_size);\n" %
8675 (self
.name
, self
.name
))
8677 def WriteGetAddress(self
, file):
8678 """Overridden from Argument."""
8680 " %s %s = GetSharedMemoryAs<%s>(\n" %
8681 (self
.type, self
.name
, self
.type))
8683 " %s_shm_id, %s_shm_offset, %s_size);\n" %
8684 (self
.name
, self
.name
, self
.name
))
8686 def WriteValidationCode(self
, file, func
):
8687 """Overridden from Argument."""
8690 file.Write(" if (%s == NULL) {\n" % self
.name
)
8691 file.Write(" return error::kOutOfBounds;\n")
8694 def GetImmediateVersion(self
):
8695 """Overridden from Argument."""
8696 return ImmediatePointerArgument(self
.name
, self
.type)
8698 def GetBucketVersion(self
):
8699 """Overridden from Argument."""
8700 if self
.type.find('char') >= 0:
8701 if self
.IsPointer2D():
8702 return InputStringArrayBucketArgument(self
.name
, self
.type)
8703 return InputStringBucketArgument(self
.name
, self
.type)
8704 return BucketPointerArgument(self
.name
, self
.type)
8706 def WriteDestinationInitalizationValidation(self
, file, func
):
8707 """Overridden from Argument."""
8708 self
.WriteDestinationInitalizationValidatationIfNeeded(file, func
)
8711 class BucketPointerArgument(PointerArgument
):
8712 """A class that represents an bucket argument to a function."""
8714 def __init__(self
, name
, type):
8715 Argument
.__init
__(self
, name
, type)
8717 def AddCmdArgs(self
, args
):
8718 """Overridden from Argument."""
8721 def WriteGetCode(self
, file):
8722 """Overridden from Argument."""
8724 " %s %s = bucket->GetData(0, data_size);\n" %
8725 (self
.type, self
.name
))
8727 def WriteValidationCode(self
, file, func
):
8728 """Overridden from Argument."""
8731 def GetImmediateVersion(self
):
8732 """Overridden from Argument."""
8735 def WriteDestinationInitalizationValidation(self
, file, func
):
8736 """Overridden from Argument."""
8737 self
.WriteDestinationInitalizationValidatationIfNeeded(file, func
)
8739 def GetLogArg(self
):
8740 """Overridden from Argument."""
8741 return "static_cast<const void*>(%s)" % self
.name
8744 class InputStringBucketArgument(Argument
):
8745 """A string input argument where the string is passed in a bucket."""
8747 def __init__(self
, name
, type):
8748 Argument
.__init
__(self
, name
+ "_bucket_id", "uint32_t")
8750 def IsPointer(self
):
8751 """Overridden from Argument."""
8754 def IsPointer2D(self
):
8755 """Overridden from Argument."""
8759 class InputStringArrayBucketArgument(Argument
):
8760 """A string array input argument where the strings are passed in a bucket."""
8762 def __init__(self
, name
, type):
8763 Argument
.__init
__(self
, name
+ "_bucket_id", "uint32_t")
8764 self
._original
_name
= name
8766 def WriteGetCode(self
, file):
8767 """Overridden from Argument."""
8769 Bucket* bucket = GetBucket(c.%(name)s);
8771 return error::kInvalidArguments;
8774 std::vector<char*> strs;
8775 std::vector<GLint> len;
8776 if (!bucket->GetAsStrings(&count, &strs, &len)) {
8777 return error::kInvalidArguments;
8779 const char** %(original_name)s =
8780 strs.size() > 0 ? const_cast<const char**>(&strs[0]) : NULL;
8781 const GLint* length =
8782 len.size() > 0 ? const_cast<const GLint*>(&len[0]) : NULL;
8787 'original_name': self
._original
_name
,
8790 def GetValidArg(self
, func
):
8791 return "kNameBucketId"
8793 def GetValidGLArg(self
, func
):
8796 def IsPointer(self
):
8797 """Overridden from Argument."""
8800 def IsPointer2D(self
):
8801 """Overridden from Argument."""
8805 class ResourceIdArgument(Argument
):
8806 """A class that represents a resource id argument to a function."""
8808 def __init__(self
, name
, type):
8809 match
= re
.match("(GLid\w+)", type)
8810 self
.resource_type
= match
.group(1)[4:]
8811 if self
.resource_type
== "Sync":
8812 type = type.replace(match
.group(1), "GLsync")
8814 type = type.replace(match
.group(1), "GLuint")
8815 Argument
.__init
__(self
, name
, type)
8817 def WriteGetCode(self
, file):
8818 """Overridden from Argument."""
8819 if self
.type == "GLsync":
8823 file.Write(" %s %s = c.%s;\n" % (my_type
, self
.name
, self
.name
))
8825 def GetValidArg(self
, func
):
8826 return "client_%s_id_" % self
.resource_type
.lower()
8828 def GetValidGLArg(self
, func
):
8829 if self
.resource_type
== "Sync":
8830 return "reinterpret_cast<GLsync>(kService%sId)" % self
.resource_type
8831 return "kService%sId" % self
.resource_type
8834 class ResourceIdBindArgument(Argument
):
8835 """Represents a resource id argument to a bind function."""
8837 def __init__(self
, name
, type):
8838 match
= re
.match("(GLidBind\w+)", type)
8839 self
.resource_type
= match
.group(1)[8:]
8840 type = type.replace(match
.group(1), "GLuint")
8841 Argument
.__init
__(self
, name
, type)
8843 def WriteGetCode(self
, file):
8844 """Overridden from Argument."""
8845 code
= """ %(type)s %(name)s = c.%(name)s;
8847 file.Write(code
% {'type': self
.type, 'name': self
.name
})
8849 def GetValidArg(self
, func
):
8850 return "client_%s_id_" % self
.resource_type
.lower()
8852 def GetValidGLArg(self
, func
):
8853 return "kService%sId" % self
.resource_type
8856 class ResourceIdZeroArgument(Argument
):
8857 """Represents a resource id argument to a function that can be zero."""
8859 def __init__(self
, name
, type):
8860 match
= re
.match("(GLidZero\w+)", type)
8861 self
.resource_type
= match
.group(1)[8:]
8862 type = type.replace(match
.group(1), "GLuint")
8863 Argument
.__init
__(self
, name
, type)
8865 def WriteGetCode(self
, file):
8866 """Overridden from Argument."""
8867 file.Write(" %s %s = c.%s;\n" % (self
.type, self
.name
, self
.name
))
8869 def GetValidArg(self
, func
):
8870 return "client_%s_id_" % self
.resource_type
.lower()
8872 def GetValidGLArg(self
, func
):
8873 return "kService%sId" % self
.resource_type
8875 def GetNumInvalidValues(self
, func
):
8876 """returns the number of invalid values to be tested."""
8879 def GetInvalidArg(self
, index
):
8880 """returns an invalid value by index."""
8881 return ("kInvalidClientId", "kNoError", "GL_INVALID_VALUE")
8884 class Function(object):
8885 """A class that represents a function."""
8889 'Bind': BindHandler(),
8890 'Create': CreateHandler(),
8891 'Custom': CustomHandler(),
8892 'Data': DataHandler(),
8893 'Delete': DeleteHandler(),
8894 'DELn': DELnHandler(),
8895 'GENn': GENnHandler(),
8896 'GETn': GETnHandler(),
8897 'GLchar': GLcharHandler(),
8898 'GLcharN': GLcharNHandler(),
8899 'HandWritten': HandWrittenHandler(),
8901 'Manual': ManualHandler(),
8902 'PUT': PUTHandler(),
8903 'PUTn': PUTnHandler(),
8904 'PUTSTR': PUTSTRHandler(),
8905 'PUTXn': PUTXnHandler(),
8906 'StateSet': StateSetHandler(),
8907 'StateSetRGBAlpha': StateSetRGBAlphaHandler(),
8908 'StateSetFrontBack': StateSetFrontBackHandler(),
8909 'StateSetFrontBackSeparate': StateSetFrontBackSeparateHandler(),
8910 'StateSetNamedParameter': StateSetNamedParameter(),
8911 'STRn': STRnHandler(),
8912 'Todo': TodoHandler(),
8915 def __init__(self
, name
, info
):
8917 self
.original_name
= info
['original_name']
8919 self
.original_args
= self
.ParseArgs(info
['original_args'])
8921 if 'cmd_args' in info
:
8922 self
.args_for_cmds
= self
.ParseArgs(info
['cmd_args'])
8924 self
.args_for_cmds
= self
.original_args
[:]
8926 self
.return_type
= info
['return_type']
8927 if self
.return_type
!= 'void':
8928 self
.return_arg
= CreateArg(info
['return_type'] + " result")
8930 self
.return_arg
= None
8932 self
.num_pointer_args
= sum(
8933 [1 for arg
in self
.args_for_cmds
if arg
.IsPointer()])
8934 if self
.num_pointer_args
> 0:
8935 for arg
in reversed(self
.original_args
):
8937 self
.last_original_pointer_arg
= arg
8940 self
.last_original_pointer_arg
= None
8942 self
.type_handler
= self
.type_handlers
[info
['type']]
8943 self
.can_auto_generate
= (self
.num_pointer_args
== 0 and
8944 info
['return_type'] == "void")
8947 def ParseArgs(self
, arg_string
):
8948 """Parses a function arg string."""
8950 parts
= arg_string
.split(',')
8951 for arg_string
in parts
:
8952 arg
= CreateArg(arg_string
)
8957 def IsType(self
, type_name
):
8958 """Returns true if function is a certain type."""
8959 return self
.info
['type'] == type_name
8961 def InitFunction(self
):
8962 """Creates command args and calls the init function for the type handler.
8964 Creates argument lists for command buffer commands, eg. self.cmd_args and
8966 Calls the type function initialization.
8967 Override to create different kind of command buffer command argument lists.
8970 for arg
in self
.args_for_cmds
:
8971 arg
.AddCmdArgs(self
.cmd_args
)
8974 for arg
in self
.args_for_cmds
:
8975 arg
.AddInitArgs(self
.init_args
)
8978 self
.init_args
.append(self
.return_arg
)
8980 self
.type_handler
.InitFunction(self
)
8982 def IsImmediate(self
):
8983 """Returns whether the function is immediate data function or not."""
8987 """Returns whether the function has service side validation or not."""
8988 return self
.GetInfo('unsafe', False)
8990 def GetInfo(self
, name
, default
= None):
8991 """Returns a value from the function info for this function."""
8992 if name
in self
.info
:
8993 return self
.info
[name
]
8996 def GetValidArg(self
, arg
):
8997 """Gets a valid argument value for the parameter arg from the function info
9000 index
= self
.GetOriginalArgs().index(arg
)
9004 valid_args
= self
.GetInfo('valid_args')
9005 if valid_args
and str(index
) in valid_args
:
9006 return valid_args
[str(index
)]
9009 def AddInfo(self
, name
, value
):
9011 self
.info
[name
] = value
9013 def IsExtension(self
):
9014 return self
.GetInfo('extension') or self
.GetInfo('extension_flag')
9016 def IsCoreGLFunction(self
):
9017 return (not self
.IsExtension() and
9018 not self
.GetInfo('pepper_interface') and
9019 not self
.IsUnsafe())
9021 def InPepperInterface(self
, interface
):
9022 ext
= self
.GetInfo('pepper_interface')
9023 if not interface
.GetName():
9024 return self
.IsCoreGLFunction()
9025 return ext
== interface
.GetName()
9027 def InAnyPepperExtension(self
):
9028 return self
.IsCoreGLFunction() or self
.GetInfo('pepper_interface')
9030 def GetErrorReturnString(self
):
9031 if self
.GetInfo("error_return"):
9032 return self
.GetInfo("error_return")
9033 elif self
.return_type
== "GLboolean":
9035 elif "*" in self
.return_type
:
9039 def GetGLFunctionName(self
):
9040 """Gets the function to call to execute GL for this command."""
9041 if self
.GetInfo('decoder_func'):
9042 return self
.GetInfo('decoder_func')
9043 return "gl%s" % self
.original_name
9045 def GetGLTestFunctionName(self
):
9046 gl_func_name
= self
.GetInfo('gl_test_func')
9047 if gl_func_name
== None:
9048 gl_func_name
= self
.GetGLFunctionName()
9049 if gl_func_name
.startswith("gl"):
9050 gl_func_name
= gl_func_name
[2:]
9052 gl_func_name
= self
.original_name
9055 def GetDataTransferMethods(self
):
9056 return self
.GetInfo('data_transfer_methods',
9057 ['immediate' if self
.num_pointer_args
== 1 else 'shm'])
9059 def AddCmdArg(self
, arg
):
9060 """Adds a cmd argument to this function."""
9061 self
.cmd_args
.append(arg
)
9063 def GetCmdArgs(self
):
9064 """Gets the command args for this function."""
9065 return self
.cmd_args
9067 def ClearCmdArgs(self
):
9068 """Clears the command args for this function."""
9071 def GetCmdConstants(self
):
9072 """Gets the constants for this function."""
9073 return [arg
for arg
in self
.args_for_cmds
if arg
.IsConstant()]
9075 def GetInitArgs(self
):
9076 """Gets the init args for this function."""
9077 return self
.init_args
9079 def GetOriginalArgs(self
):
9080 """Gets the original arguments to this function."""
9081 return self
.original_args
9083 def GetLastOriginalArg(self
):
9084 """Gets the last original argument to this function."""
9085 return self
.original_args
[len(self
.original_args
) - 1]
9087 def GetLastOriginalPointerArg(self
):
9088 return self
.last_original_pointer_arg
9090 def GetResourceIdArg(self
):
9091 for arg
in self
.original_args
:
9092 if hasattr(arg
, 'resource_type'):
9096 def _MaybePrependComma(self
, arg_string
, add_comma
):
9097 """Adds a comma if arg_string is not empty and add_comma is true."""
9099 if add_comma
and len(arg_string
):
9101 return "%s%s" % (comma
, arg_string
)
9103 def MakeTypedOriginalArgString(self
, prefix
, add_comma
= False):
9104 """Gets a list of arguments as they are in GL."""
9105 args
= self
.GetOriginalArgs()
9106 arg_string
= ", ".join(
9107 ["%s %s%s" % (arg
.type, prefix
, arg
.name
) for arg
in args
])
9108 return self
._MaybePrependComma
(arg_string
, add_comma
)
9110 def MakeOriginalArgString(self
, prefix
, add_comma
= False, separator
= ", "):
9111 """Gets the list of arguments as they are in GL."""
9112 args
= self
.GetOriginalArgs()
9113 arg_string
= separator
.join(
9114 ["%s%s" % (prefix
, arg
.name
) for arg
in args
])
9115 return self
._MaybePrependComma
(arg_string
, add_comma
)
9117 def MakeTypedHelperArgString(self
, prefix
, add_comma
= False):
9118 """Gets a list of typed GL arguments after removing unneeded arguments."""
9119 args
= self
.GetOriginalArgs()
9120 arg_string
= ", ".join(
9125 ) for arg
in args
if not arg
.IsConstant()])
9126 return self
._MaybePrependComma
(arg_string
, add_comma
)
9128 def MakeHelperArgString(self
, prefix
, add_comma
= False, separator
= ", "):
9129 """Gets a list of GL arguments after removing unneeded arguments."""
9130 args
= self
.GetOriginalArgs()
9131 arg_string
= separator
.join(
9132 ["%s%s" % (prefix
, arg
.name
)
9133 for arg
in args
if not arg
.IsConstant()])
9134 return self
._MaybePrependComma
(arg_string
, add_comma
)
9136 def MakeTypedPepperArgString(self
, prefix
):
9137 """Gets a list of arguments as they need to be for Pepper."""
9138 if self
.GetInfo("pepper_args"):
9139 return self
.GetInfo("pepper_args")
9141 return self
.MakeTypedOriginalArgString(prefix
, False)
9143 def MapCTypeToPepperIdlType(self
, ctype
, is_for_return_type
=False):
9144 """Converts a C type name to the corresponding Pepper IDL type."""
9146 'char*': '[out] str_t',
9147 'const GLchar* const*': '[out] cstr_t',
9148 'const char*': 'cstr_t',
9149 'const void*': 'mem_t',
9150 'void*': '[out] mem_t',
9151 'void**': '[out] mem_ptr_t',
9153 # We use "GLxxx_ptr_t" for "GLxxx*".
9154 matched
= re
.match(r
'(const )?(GL\w+)\*$', ctype
)
9156 idltype
= matched
.group(2) + '_ptr_t'
9157 if not matched
.group(1):
9158 idltype
= '[out] ' + idltype
9159 # If an in/out specifier is not specified yet, prepend [in].
9160 if idltype
[0] != '[':
9161 idltype
= '[in] ' + idltype
9162 # Strip the in/out specifier for a return type.
9163 if is_for_return_type
:
9164 idltype
= re
.sub(r
'\[\w+\] ', '', idltype
)
9167 def MakeTypedPepperIdlArgStrings(self
):
9168 """Gets a list of arguments as they need to be for Pepper IDL."""
9169 args
= self
.GetOriginalArgs()
9170 return ["%s %s" % (self
.MapCTypeToPepperIdlType(arg
.type), arg
.name
)
9173 def GetPepperName(self
):
9174 if self
.GetInfo("pepper_name"):
9175 return self
.GetInfo("pepper_name")
9178 def MakeTypedCmdArgString(self
, prefix
, add_comma
= False):
9179 """Gets a typed list of arguments as they need to be for command buffers."""
9180 args
= self
.GetCmdArgs()
9181 arg_string
= ", ".join(
9182 ["%s %s%s" % (arg
.type, prefix
, arg
.name
) for arg
in args
])
9183 return self
._MaybePrependComma
(arg_string
, add_comma
)
9185 def MakeCmdArgString(self
, prefix
, add_comma
= False):
9186 """Gets the list of arguments as they need to be for command buffers."""
9187 args
= self
.GetCmdArgs()
9188 arg_string
= ", ".join(
9189 ["%s%s" % (prefix
, arg
.name
) for arg
in args
])
9190 return self
._MaybePrependComma
(arg_string
, add_comma
)
9192 def MakeTypedInitString(self
, prefix
, add_comma
= False):
9193 """Gets a typed list of arguments as they need to be for cmd Init/Set."""
9194 args
= self
.GetInitArgs()
9195 arg_string
= ", ".join(
9196 ["%s %s%s" % (arg
.type, prefix
, arg
.name
) for arg
in args
])
9197 return self
._MaybePrependComma
(arg_string
, add_comma
)
9199 def MakeInitString(self
, prefix
, add_comma
= False):
9200 """Gets the list of arguments as they need to be for cmd Init/Set."""
9201 args
= self
.GetInitArgs()
9202 arg_string
= ", ".join(
9203 ["%s%s" % (prefix
, arg
.name
) for arg
in args
])
9204 return self
._MaybePrependComma
(arg_string
, add_comma
)
9206 def MakeLogArgString(self
):
9207 """Makes a string of the arguments for the LOG macros"""
9208 args
= self
.GetOriginalArgs()
9209 return ' << ", " << '.join([arg
.GetLogArg() for arg
in args
])
9211 def WriteCommandDescription(self
, file):
9212 """Writes a description of the command."""
9213 file.Write("//! Command that corresponds to gl%s.\n" % self
.original_name
)
9215 def WriteHandlerValidation(self
, file):
9216 """Writes validation code for the function."""
9217 for arg
in self
.GetOriginalArgs():
9218 arg
.WriteValidationCode(file, self
)
9219 self
.WriteValidationCode(file)
9221 def WriteHandlerImplementation(self
, file):
9222 """Writes the handler implementation for this command."""
9223 self
.type_handler
.WriteHandlerImplementation(self
, file)
9225 def WriteValidationCode(self
, file):
9226 """Writes the validation code for a command."""
9229 def WriteCmdFlag(self
, file):
9230 """Writes the cmd cmd_flags constant."""
9232 # By default trace only at the highest level 3.
9233 trace_level
= int(self
.GetInfo('trace_level', default
= 3))
9234 if trace_level
not in xrange(0, 4):
9235 raise KeyError("Unhandled trace_level: %d" % trace_level
)
9237 flags
.append('CMD_FLAG_SET_TRACE_LEVEL(%d)' % trace_level
)
9240 cmd_flags
= ' | '.join(flags
)
9244 file.Write(" static const uint8 cmd_flags = %s;\n" % cmd_flags
)
9247 def WriteCmdArgFlag(self
, file):
9248 """Writes the cmd kArgFlags constant."""
9249 file.Write(" static const cmd::ArgFlags kArgFlags = cmd::kFixed;\n")
9251 def WriteCmdComputeSize(self
, file):
9252 """Writes the ComputeSize function for the command."""
9253 file.Write(" static uint32_t ComputeSize() {\n")
9255 " return static_cast<uint32_t>(sizeof(ValueType)); // NOLINT\n")
9259 def WriteCmdSetHeader(self
, file):
9260 """Writes the cmd's SetHeader function."""
9261 file.Write(" void SetHeader() {\n")
9262 file.Write(" header.SetCmd<ValueType>();\n")
9266 def WriteCmdInit(self
, file):
9267 """Writes the cmd's Init function."""
9268 file.Write(" void Init(%s) {\n" % self
.MakeTypedCmdArgString("_"))
9269 file.Write(" SetHeader();\n")
9270 args
= self
.GetCmdArgs()
9272 file.Write(" %s = _%s;\n" % (arg
.name
, arg
.name
))
9276 def WriteCmdSet(self
, file):
9277 """Writes the cmd's Set function."""
9278 copy_args
= self
.MakeCmdArgString("_", False)
9279 file.Write(" void* Set(void* cmd%s) {\n" %
9280 self
.MakeTypedCmdArgString("_", True))
9281 file.Write(" static_cast<ValueType*>(cmd)->Init(%s);\n" % copy_args
)
9282 file.Write(" return NextCmdAddress<ValueType>(cmd);\n")
9286 def WriteStruct(self
, file):
9287 self
.type_handler
.WriteStruct(self
, file)
9289 def WriteDocs(self
, file):
9290 self
.type_handler
.WriteDocs(self
, file)
9292 def WriteCmdHelper(self
, file):
9293 """Writes the cmd's helper."""
9294 self
.type_handler
.WriteCmdHelper(self
, file)
9296 def WriteServiceImplementation(self
, file):
9297 """Writes the service implementation for a command."""
9298 self
.type_handler
.WriteServiceImplementation(self
, file)
9300 def WriteServiceUnitTest(self
, file, *extras
):
9301 """Writes the service implementation for a command."""
9302 self
.type_handler
.WriteServiceUnitTest(self
, file, *extras
)
9304 def WriteGLES2CLibImplementation(self
, file):
9305 """Writes the GLES2 C Lib Implemention."""
9306 self
.type_handler
.WriteGLES2CLibImplementation(self
, file)
9308 def WriteGLES2InterfaceHeader(self
, file):
9309 """Writes the GLES2 Interface declaration."""
9310 self
.type_handler
.WriteGLES2InterfaceHeader(self
, file)
9312 def WriteMojoGLES2ImplHeader(self
, file):
9313 """Writes the Mojo GLES2 implementation header declaration."""
9314 self
.type_handler
.WriteMojoGLES2ImplHeader(self
, file)
9316 def WriteMojoGLES2Impl(self
, file):
9317 """Writes the Mojo GLES2 implementation declaration."""
9318 self
.type_handler
.WriteMojoGLES2Impl(self
, file)
9320 def WriteGLES2InterfaceStub(self
, file):
9321 """Writes the GLES2 Interface Stub declaration."""
9322 self
.type_handler
.WriteGLES2InterfaceStub(self
, file)
9324 def WriteGLES2InterfaceStubImpl(self
, file):
9325 """Writes the GLES2 Interface Stub declaration."""
9326 self
.type_handler
.WriteGLES2InterfaceStubImpl(self
, file)
9328 def WriteGLES2ImplementationHeader(self
, file):
9329 """Writes the GLES2 Implemention declaration."""
9330 self
.type_handler
.WriteGLES2ImplementationHeader(self
, file)
9332 def WriteGLES2Implementation(self
, file):
9333 """Writes the GLES2 Implemention definition."""
9334 self
.type_handler
.WriteGLES2Implementation(self
, file)
9336 def WriteGLES2TraceImplementationHeader(self
, file):
9337 """Writes the GLES2 Trace Implemention declaration."""
9338 self
.type_handler
.WriteGLES2TraceImplementationHeader(self
, file)
9340 def WriteGLES2TraceImplementation(self
, file):
9341 """Writes the GLES2 Trace Implemention definition."""
9342 self
.type_handler
.WriteGLES2TraceImplementation(self
, file)
9344 def WriteGLES2Header(self
, file):
9345 """Writes the GLES2 Implemention unit test."""
9346 self
.type_handler
.WriteGLES2Header(self
, file)
9348 def WriteGLES2ImplementationUnitTest(self
, file):
9349 """Writes the GLES2 Implemention unit test."""
9350 self
.type_handler
.WriteGLES2ImplementationUnitTest(self
, file)
9352 def WriteDestinationInitalizationValidation(self
, file):
9353 """Writes the client side destintion initialization validation."""
9354 self
.type_handler
.WriteDestinationInitalizationValidation(self
, file)
9356 def WriteFormatTest(self
, file):
9357 """Writes the cmd's format test."""
9358 self
.type_handler
.WriteFormatTest(self
, file)
9361 class PepperInterface(object):
9362 """A class that represents a function."""
9364 def __init__(self
, info
):
9365 self
.name
= info
["name"]
9366 self
.dev
= info
["dev"]
9371 def GetInterfaceName(self
):
9375 upperint
= "_" + self
.name
.upper()
9378 return "PPB_OPENGLES2%s%s_INTERFACE" % (upperint
, dev
)
9380 def GetInterfaceString(self
):
9384 return "PPB_OpenGLES2%s%s" % (self
.name
, dev
)
9386 def GetStructName(self
):
9390 return "PPB_OpenGLES2%s%s" % (self
.name
, dev
)
9393 class ImmediateFunction(Function
):
9394 """A class that represnets an immediate function command."""
9396 def __init__(self
, func
):
9399 "%sImmediate" % func
.name
,
9402 def InitFunction(self
):
9403 # Override args in original_args and args_for_cmds with immediate versions
9406 new_original_args
= []
9407 for arg
in self
.original_args
:
9408 new_arg
= arg
.GetImmediateVersion()
9410 new_original_args
.append(new_arg
)
9411 self
.original_args
= new_original_args
9413 new_args_for_cmds
= []
9414 for arg
in self
.args_for_cmds
:
9415 new_arg
= arg
.GetImmediateVersion()
9417 new_args_for_cmds
.append(new_arg
)
9419 self
.args_for_cmds
= new_args_for_cmds
9421 Function
.InitFunction(self
)
9423 def IsImmediate(self
):
9426 def WriteCommandDescription(self
, file):
9427 """Overridden from Function"""
9428 file.Write("//! Immediate version of command that corresponds to gl%s.\n" %
9431 def WriteServiceImplementation(self
, file):
9432 """Overridden from Function"""
9433 self
.type_handler
.WriteImmediateServiceImplementation(self
, file)
9435 def WriteHandlerImplementation(self
, file):
9436 """Overridden from Function"""
9437 self
.type_handler
.WriteImmediateHandlerImplementation(self
, file)
9439 def WriteServiceUnitTest(self
, file, *extras
):
9440 """Writes the service implementation for a command."""
9441 self
.type_handler
.WriteImmediateServiceUnitTest(self
, file, *extras
)
9443 def WriteValidationCode(self
, file):
9444 """Overridden from Function"""
9445 self
.type_handler
.WriteImmediateValidationCode(self
, file)
9447 def WriteCmdArgFlag(self
, file):
9448 """Overridden from Function"""
9449 file.Write(" static const cmd::ArgFlags kArgFlags = cmd::kAtLeastN;\n")
9451 def WriteCmdComputeSize(self
, file):
9452 """Overridden from Function"""
9453 self
.type_handler
.WriteImmediateCmdComputeSize(self
, file)
9455 def WriteCmdSetHeader(self
, file):
9456 """Overridden from Function"""
9457 self
.type_handler
.WriteImmediateCmdSetHeader(self
, file)
9459 def WriteCmdInit(self
, file):
9460 """Overridden from Function"""
9461 self
.type_handler
.WriteImmediateCmdInit(self
, file)
9463 def WriteCmdSet(self
, file):
9464 """Overridden from Function"""
9465 self
.type_handler
.WriteImmediateCmdSet(self
, file)
9467 def WriteCmdHelper(self
, file):
9468 """Overridden from Function"""
9469 self
.type_handler
.WriteImmediateCmdHelper(self
, file)
9471 def WriteFormatTest(self
, file):
9472 """Overridden from Function"""
9473 self
.type_handler
.WriteImmediateFormatTest(self
, file)
9476 class BucketFunction(Function
):
9477 """A class that represnets a bucket version of a function command."""
9479 def __init__(self
, func
):
9482 "%sBucket" % func
.name
,
9485 def InitFunction(self
):
9486 # Override args in original_args and args_for_cmds with bucket versions
9489 new_original_args
= []
9490 for arg
in self
.original_args
:
9491 new_arg
= arg
.GetBucketVersion()
9493 new_original_args
.append(new_arg
)
9494 self
.original_args
= new_original_args
9496 new_args_for_cmds
= []
9497 for arg
in self
.args_for_cmds
:
9498 new_arg
= arg
.GetBucketVersion()
9500 new_args_for_cmds
.append(new_arg
)
9502 self
.args_for_cmds
= new_args_for_cmds
9504 Function
.InitFunction(self
)
9506 def WriteCommandDescription(self
, file):
9507 """Overridden from Function"""
9508 file.Write("//! Bucket version of command that corresponds to gl%s.\n" %
9511 def WriteServiceImplementation(self
, file):
9512 """Overridden from Function"""
9513 self
.type_handler
.WriteBucketServiceImplementation(self
, file)
9515 def WriteHandlerImplementation(self
, file):
9516 """Overridden from Function"""
9517 self
.type_handler
.WriteBucketHandlerImplementation(self
, file)
9519 def WriteServiceUnitTest(self
, file, *extras
):
9520 """Overridden from Function"""
9521 self
.type_handler
.WriteBucketServiceUnitTest(self
, file, *extras
)
9523 def MakeOriginalArgString(self
, prefix
, add_comma
= False, separator
= ", "):
9524 """Overridden from Function"""
9525 args
= self
.GetOriginalArgs()
9526 arg_string
= separator
.join(
9527 ["%s%s" % (prefix
, arg
.name
[0:-10] if arg
.name
.endswith("_bucket_id")
9528 else arg
.name
) for arg
in args
])
9529 return super(BucketFunction
, self
)._MaybePrependComma
(arg_string
, add_comma
)
9532 def CreateArg(arg_string
):
9533 """Creates an Argument."""
9534 arg_parts
= arg_string
.split()
9535 if len(arg_parts
) == 1 and arg_parts
[0] == 'void':
9537 # Is this a pointer argument?
9538 elif arg_string
.find('*') >= 0:
9539 return PointerArgument(
9541 " ".join(arg_parts
[0:-1]))
9542 # Is this a resource argument? Must come after pointer check.
9543 elif arg_parts
[0].startswith('GLidBind'):
9544 return ResourceIdBindArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
9545 elif arg_parts
[0].startswith('GLidZero'):
9546 return ResourceIdZeroArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
9547 elif arg_parts
[0].startswith('GLid'):
9548 return ResourceIdArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
9549 elif arg_parts
[0].startswith('GLenum') and len(arg_parts
[0]) > 6:
9550 return EnumArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
9551 elif arg_parts
[0].startswith('GLbitfield') and len(arg_parts
[0]) > 10:
9552 return BitFieldArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
9553 elif arg_parts
[0].startswith('GLboolean') and len(arg_parts
[0]) > 9:
9554 return ValidatedBoolArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
9555 elif arg_parts
[0].startswith('GLboolean'):
9556 return BoolArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
9557 elif arg_parts
[0].startswith('GLintUniformLocation'):
9558 return UniformLocationArgument(arg_parts
[-1])
9559 elif (arg_parts
[0].startswith('GLint') and len(arg_parts
[0]) > 5 and
9560 not arg_parts
[0].startswith('GLintptr')):
9561 return IntArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
9562 elif (arg_parts
[0].startswith('GLsizeiNotNegative') or
9563 arg_parts
[0].startswith('GLintptrNotNegative')):
9564 return SizeNotNegativeArgument(arg_parts
[-1],
9565 " ".join(arg_parts
[0:-1]),
9566 arg_parts
[0][0:-11])
9567 elif arg_parts
[0].startswith('GLsize'):
9568 return SizeArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
9570 return Argument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
9573 class GLGenerator(object):
9574 """A class to generate GL command buffers."""
9576 _function_re
= re
.compile(r
'GL_APICALL(.*?)GL_APIENTRY (.*?) \((.*?)\);')
9578 def __init__(self
, verbose
):
9579 self
.original_functions
= []
9581 self
.verbose
= verbose
9583 self
.pepper_interfaces
= []
9584 self
.interface_info
= {}
9585 self
.generated_cpp_filenames
= []
9587 for interface
in _PEPPER_INTERFACES
:
9588 interface
= PepperInterface(interface
)
9589 self
.pepper_interfaces
.append(interface
)
9590 self
.interface_info
[interface
.GetName()] = interface
9592 def AddFunction(self
, func
):
9593 """Adds a function."""
9594 self
.functions
.append(func
)
9596 def GetFunctionInfo(self
, name
):
9597 """Gets a type info for the given function name."""
9598 if name
in _FUNCTION_INFO
:
9599 func_info
= _FUNCTION_INFO
[name
].copy()
9603 if not 'type' in func_info
:
9604 func_info
['type'] = ''
9609 """Prints something if verbose is true."""
9613 def Error(self
, msg
):
9614 """Prints an error."""
9615 print "Error: %s" % msg
9618 def WriteLicense(self
, file):
9619 """Writes the license."""
9620 file.Write(_LICENSE
)
9622 def WriteNamespaceOpen(self
, file):
9623 """Writes the code for the namespace."""
9624 file.Write("namespace gpu {\n")
9625 file.Write("namespace gles2 {\n")
9628 def WriteNamespaceClose(self
, file):
9629 """Writes the code to close the namespace."""
9630 file.Write("} // namespace gles2\n")
9631 file.Write("} // namespace gpu\n")
9634 def ParseGLH(self
, filename
):
9635 """Parses the cmd_buffer_functions.txt file and extracts the functions"""
9636 f
= open(filename
, "r")
9637 functions
= f
.read()
9639 for line
in functions
.splitlines():
9640 match
= self
._function
_re
.match(line
)
9642 func_name
= match
.group(2)[2:]
9643 func_info
= self
.GetFunctionInfo(func_name
)
9644 if func_info
['type'] == 'Noop':
9647 parsed_func_info
= {
9648 'original_name': func_name
,
9649 'original_args': match
.group(3),
9650 'return_type': match
.group(1).strip(),
9653 for k
in parsed_func_info
.keys():
9654 if not k
in func_info
:
9655 func_info
[k
] = parsed_func_info
[k
]
9657 f
= Function(func_name
, func_info
)
9658 self
.original_functions
.append(f
)
9660 #for arg in f.GetOriginalArgs():
9661 # if not isinstance(arg, EnumArgument) and arg.type == 'GLenum':
9662 # self.Log("%s uses bare GLenum %s." % (func_name, arg.name))
9664 gen_cmd
= f
.GetInfo('gen_cmd')
9665 if gen_cmd
== True or gen_cmd
== None:
9666 if f
.type_handler
.NeedsDataTransferFunction(f
):
9667 methods
= f
.GetDataTransferMethods()
9668 if 'immediate' in methods
:
9669 self
.AddFunction(ImmediateFunction(f
))
9670 if 'bucket' in methods
:
9671 self
.AddFunction(BucketFunction(f
))
9672 if 'shm' in methods
:
9677 self
.Log("Auto Generated Functions : %d" %
9678 len([f
for f
in self
.functions
if f
.can_auto_generate
or
9679 (not f
.IsType('') and not f
.IsType('Custom') and
9680 not f
.IsType('Todo'))]))
9682 funcs
= [f
for f
in self
.functions
if not f
.can_auto_generate
and
9683 (f
.IsType('') or f
.IsType('Custom') or f
.IsType('Todo'))]
9684 self
.Log("Non Auto Generated Functions: %d" % len(funcs
))
9687 self
.Log(" %-10s %-20s gl%s" % (f
.info
['type'], f
.return_type
, f
.name
))
9689 def WriteCommandIds(self
, filename
):
9690 """Writes the command buffer format"""
9691 file = CHeaderWriter(filename
)
9692 file.Write("#define GLES2_COMMAND_LIST(OP) \\\n")
9694 for func
in self
.functions
:
9695 file.Write(" %-60s /* %d */ \\\n" %
9696 ("OP(%s)" % func
.name
, id))
9700 file.Write("enum CommandId {\n")
9701 file.Write(" kStartPoint = cmd::kLastCommonId, "
9702 "// All GLES2 commands start after this.\n")
9703 file.Write("#define GLES2_CMD_OP(name) k ## name,\n")
9704 file.Write(" GLES2_COMMAND_LIST(GLES2_CMD_OP)\n")
9705 file.Write("#undef GLES2_CMD_OP\n")
9706 file.Write(" kNumCommands\n")
9710 self
.generated_cpp_filenames
.append(file.filename
)
9712 def WriteFormat(self
, filename
):
9713 """Writes the command buffer format"""
9714 file = CHeaderWriter(filename
)
9715 # Forward declaration of a few enums used in constant argument
9716 # to avoid including GL header files.
9718 'GL_SYNC_GPU_COMMANDS_COMPLETE': '0x9117',
9719 'GL_SYNC_FLUSH_COMMANDS_BIT': '0x00000001',
9722 for enum
in enum_defines
:
9723 file.Write("#define %s %s\n" % (enum
, enum_defines
[enum
]))
9725 for func
in self
.functions
:
9727 #gen_cmd = func.GetInfo('gen_cmd')
9728 #if gen_cmd == True or gen_cmd == None:
9729 func
.WriteStruct(file)
9732 self
.generated_cpp_filenames
.append(file.filename
)
9734 def WriteDocs(self
, filename
):
9735 """Writes the command buffer doc version of the commands"""
9736 file = CWriter(filename
)
9737 for func
in self
.functions
:
9739 #gen_cmd = func.GetInfo('gen_cmd')
9740 #if gen_cmd == True or gen_cmd == None:
9741 func
.WriteDocs(file)
9744 self
.generated_cpp_filenames
.append(file.filename
)
9746 def WriteFormatTest(self
, filename
):
9747 """Writes the command buffer format test."""
9748 file = CHeaderWriter(
9750 "// This file contains unit tests for gles2 commmands\n"
9751 "// It is included by gles2_cmd_format_test.cc\n"
9754 for func
in self
.functions
:
9756 #gen_cmd = func.GetInfo('gen_cmd')
9757 #if gen_cmd == True or gen_cmd == None:
9758 func
.WriteFormatTest(file)
9761 self
.generated_cpp_filenames
.append(file.filename
)
9763 def WriteCmdHelperHeader(self
, filename
):
9764 """Writes the gles2 command helper."""
9765 file = CHeaderWriter(filename
)
9767 for func
in self
.functions
:
9769 #gen_cmd = func.GetInfo('gen_cmd')
9770 #if gen_cmd == True or gen_cmd == None:
9771 func
.WriteCmdHelper(file)
9774 self
.generated_cpp_filenames
.append(file.filename
)
9776 def WriteServiceContextStateHeader(self
, filename
):
9777 """Writes the service context state header."""
9778 file = CHeaderWriter(
9780 "// It is included by context_state.h\n")
9781 file.Write("struct EnableFlags {\n")
9782 file.Write(" EnableFlags();\n")
9783 for capability
in _CAPABILITY_FLAGS
:
9784 file.Write(" bool %s;\n" % capability
['name'])
9785 file.Write(" bool cached_%s;\n" % capability
['name'])
9786 file.Write("};\n\n")
9788 for state_name
in sorted(_STATES
.keys()):
9789 state
= _STATES
[state_name
]
9790 for item
in state
['states']:
9791 if isinstance(item
['default'], list):
9792 file.Write("%s %s[%d];\n" % (item
['type'], item
['name'],
9793 len(item
['default'])))
9795 file.Write("%s %s;\n" % (item
['type'], item
['name']))
9797 if item
.get('cached', False):
9798 if isinstance(item
['default'], list):
9799 file.Write("%s cached_%s[%d];\n" % (item
['type'], item
['name'],
9800 len(item
['default'])))
9802 file.Write("%s cached_%s;\n" % (item
['type'], item
['name']))
9807 inline void SetDeviceCapabilityState(GLenum cap, bool enable) {
9810 for capability
in _CAPABILITY_FLAGS
:
9813 """ % capability
['name'].upper())
9815 if (enable_flags.cached_%(name)s == enable &&
9816 !ignore_cached_state)
9818 enable_flags.cached_%(name)s = enable;
9835 self
.generated_cpp_filenames
.append(file.filename
)
9837 def WriteClientContextStateHeader(self
, filename
):
9838 """Writes the client context state header."""
9839 file = CHeaderWriter(
9841 "// It is included by client_context_state.h\n")
9842 file.Write("struct EnableFlags {\n")
9843 file.Write(" EnableFlags();\n")
9844 for capability
in _CAPABILITY_FLAGS
:
9845 file.Write(" bool %s;\n" % capability
['name'])
9846 file.Write("};\n\n")
9849 self
.generated_cpp_filenames
.append(file.filename
)
9851 def WriteContextStateGetters(self
, file, class_name
):
9852 """Writes the state getters."""
9853 for gl_type
in ["GLint", "GLfloat"]:
9855 bool %s::GetStateAs%s(
9856 GLenum pname, %s* params, GLsizei* num_written) const {
9858 """ % (class_name
, gl_type
, gl_type
))
9859 for state_name
in sorted(_STATES
.keys()):
9860 state
= _STATES
[state_name
]
9862 file.Write(" case %s:\n" % state
['enum'])
9863 file.Write(" *num_written = %d;\n" % len(state
['states']))
9864 file.Write(" if (params) {\n")
9865 for ndx
,item
in enumerate(state
['states']):
9866 file.Write(" params[%d] = static_cast<%s>(%s);\n" %
9867 (ndx
, gl_type
, item
['name']))
9869 file.Write(" return true;\n")
9871 for item
in state
['states']:
9872 file.Write(" case %s:\n" % item
['enum'])
9873 if isinstance(item
['default'], list):
9874 item_len
= len(item
['default'])
9875 file.Write(" *num_written = %d;\n" % item_len
)
9876 file.Write(" if (params) {\n")
9877 if item
['type'] == gl_type
:
9878 file.Write(" memcpy(params, %s, sizeof(%s) * %d);\n" %
9879 (item
['name'], item
['type'], item_len
))
9881 file.Write(" for (size_t i = 0; i < %s; ++i) {\n" %
9883 file.Write(" params[i] = %s;\n" %
9884 (GetGLGetTypeConversion(gl_type
, item
['type'],
9885 "%s[i]" % item
['name'])))
9888 file.Write(" *num_written = 1;\n")
9889 file.Write(" if (params) {\n")
9890 file.Write(" params[0] = %s;\n" %
9891 (GetGLGetTypeConversion(gl_type
, item
['type'],
9894 file.Write(" return true;\n")
9895 for capability
in _CAPABILITY_FLAGS
:
9896 file.Write(" case GL_%s:\n" % capability
['name'].upper())
9897 file.Write(" *num_written = 1;\n")
9898 file.Write(" if (params) {\n")
9900 " params[0] = static_cast<%s>(enable_flags.%s);\n" %
9901 (gl_type
, capability
['name']))
9903 file.Write(" return true;\n")
9904 file.Write(""" default:
9910 def WriteServiceContextStateImpl(self
, filename
):
9911 """Writes the context state service implementation."""
9912 file = CHeaderWriter(
9914 "// It is included by context_state.cc\n")
9916 for capability
in _CAPABILITY_FLAGS
:
9917 code
.append("%s(%s)" %
9918 (capability
['name'],
9919 ('false', 'true')['default' in capability
]))
9920 code
.append("cached_%s(%s)" %
9921 (capability
['name'],
9922 ('false', 'true')['default' in capability
]))
9923 file.Write("ContextState::EnableFlags::EnableFlags()\n : %s {\n}\n" %
9927 file.Write("void ContextState::Initialize() {\n")
9928 for state_name
in sorted(_STATES
.keys()):
9929 state
= _STATES
[state_name
]
9930 for item
in state
['states']:
9931 if isinstance(item
['default'], list):
9932 for ndx
, value
in enumerate(item
['default']):
9933 file.Write(" %s[%d] = %s;\n" % (item
['name'], ndx
, value
))
9935 file.Write(" %s = %s;\n" % (item
['name'], item
['default']))
9936 if item
.get('cached', False):
9937 if isinstance(item
['default'], list):
9938 for ndx
, value
in enumerate(item
['default']):
9939 file.Write(" cached_%s[%d] = %s;\n" % (item
['name'], ndx
, value
))
9941 file.Write(" cached_%s = %s;\n" % (item
['name'], item
['default']))
9945 void ContextState::InitCapabilities(const ContextState* prev_state) const {
9947 def WriteCapabilities(test_prev
, es3_caps
):
9948 for capability
in _CAPABILITY_FLAGS
:
9949 capability_name
= capability
['name']
9950 capability_es3
= 'es3' in capability
and capability
['es3'] == True
9951 if capability_es3
and not es3_caps
or not capability_es3
and es3_caps
:
9954 file.Write(""" if (prev_state->enable_flags.cached_%s !=
9955 enable_flags.cached_%s) {\n""" %
9956 (capability_name
, capability_name
))
9957 file.Write(" EnableDisable(GL_%s, enable_flags.cached_%s);\n" %
9958 (capability_name
.upper(), capability_name
))
9962 file.Write(" if (prev_state) {")
9963 WriteCapabilities(True, False)
9964 file.Write(" if (feature_info_->IsES3Capable()) {\n")
9965 WriteCapabilities(True, True)
9967 file.Write(" } else {")
9968 WriteCapabilities(False, False)
9969 file.Write(" if (feature_info_->IsES3Capable()) {\n")
9970 WriteCapabilities(False, True)
9976 void ContextState::InitState(const ContextState *prev_state) const {
9979 def WriteStates(test_prev
):
9980 # We need to sort the keys so the expectations match
9981 for state_name
in sorted(_STATES
.keys()):
9982 state
= _STATES
[state_name
]
9983 if state
['type'] == 'FrontBack':
9984 num_states
= len(state
['states'])
9985 for ndx
, group
in enumerate(Grouper(num_states
/ 2, state
['states'])):
9989 for place
, item
in enumerate(group
):
9990 item_name
= CachedStateName(item
)
9991 args
.append('%s' % item_name
)
9995 file.Write("(%s != prev_state->%s)" % (item_name
, item_name
))
9999 " gl%s(%s, %s);\n" %
10000 (state
['func'], ('GL_FRONT', 'GL_BACK')[ndx
], ", ".join(args
)))
10001 elif state
['type'] == 'NamedParameter':
10002 for item
in state
['states']:
10003 item_name
= CachedStateName(item
)
10005 if 'extension_flag' in item
:
10006 file.Write(" if (feature_info_->feature_flags().%s) {\n " %
10007 item
['extension_flag'])
10009 if isinstance(item
['default'], list):
10010 file.Write(" if (memcmp(prev_state->%s, %s, "
10011 "sizeof(%s) * %d)) {\n" %
10012 (item_name
, item_name
, item
['type'],
10013 len(item
['default'])))
10015 file.Write(" if (prev_state->%s != %s) {\n " %
10016 (item_name
, item_name
))
10017 if 'gl_version_flag' in item
:
10018 item_name
= item
['gl_version_flag']
10020 if item_name
[0] == '!':
10022 item_name
= item_name
[1:]
10023 file.Write(" if (%sfeature_info_->gl_version_info().%s) {\n" %
10024 (inverted
, item_name
))
10025 file.Write(" gl%s(%s, %s);\n" %
10028 if 'enum_set' in item
else item
['enum']),
10030 if 'gl_version_flag' in item
:
10033 if 'extension_flag' in item
:
10036 if 'extension_flag' in item
:
10039 if 'extension_flag' in state
:
10040 file.Write(" if (feature_info_->feature_flags().%s)\n " %
10041 state
['extension_flag'])
10043 file.Write(" if (")
10045 for place
, item
in enumerate(state
['states']):
10046 item_name
= CachedStateName(item
)
10047 args
.append('%s' % item_name
)
10050 file.Write(' ||\n')
10051 file.Write("(%s != prev_state->%s)" %
10052 (item_name
, item_name
))
10055 file.Write(" gl%s(%s);\n" % (state
['func'], ", ".join(args
)))
10057 file.Write(" if (prev_state) {")
10059 file.Write(" } else {")
10064 file.Write("""bool ContextState::GetEnabled(GLenum cap) const {
10067 for capability
in _CAPABILITY_FLAGS
:
10068 file.Write(" case GL_%s:\n" % capability
['name'].upper())
10069 file.Write(" return enable_flags.%s;\n" % capability
['name'])
10070 file.Write(""" default:
10077 self
.WriteContextStateGetters(file, "ContextState")
10079 self
.generated_cpp_filenames
.append(file.filename
)
10081 def WriteClientContextStateImpl(self
, filename
):
10082 """Writes the context state client side implementation."""
10083 file = CHeaderWriter(
10085 "// It is included by client_context_state.cc\n")
10087 for capability
in _CAPABILITY_FLAGS
:
10088 code
.append("%s(%s)" %
10089 (capability
['name'],
10090 ('false', 'true')['default' in capability
]))
10092 "ClientContextState::EnableFlags::EnableFlags()\n : %s {\n}\n" %
10097 bool ClientContextState::SetCapabilityState(
10098 GLenum cap, bool enabled, bool* changed) {
10102 for capability
in _CAPABILITY_FLAGS
:
10103 file.Write(" case GL_%s:\n" % capability
['name'].upper())
10104 file.Write(""" if (enable_flags.%(name)s != enabled) {
10106 enable_flags.%(name)s = enabled;
10110 file.Write(""" default:
10115 file.Write("""bool ClientContextState::GetEnabled(
10116 GLenum cap, bool* enabled) const {
10119 for capability
in _CAPABILITY_FLAGS
:
10120 file.Write(" case GL_%s:\n" % capability
['name'].upper())
10121 file.Write(" *enabled = enable_flags.%s;\n" % capability
['name'])
10122 file.Write(" return true;\n")
10123 file.Write(""" default:
10129 self
.generated_cpp_filenames
.append(file.filename
)
10131 def WriteServiceImplementation(self
, filename
):
10132 """Writes the service decorder implementation."""
10133 file = CHeaderWriter(
10135 "// It is included by gles2_cmd_decoder.cc\n")
10137 for func
in self
.functions
:
10139 #gen_cmd = func.GetInfo('gen_cmd')
10140 #if gen_cmd == True or gen_cmd == None:
10141 func
.WriteServiceImplementation(file)
10144 bool GLES2DecoderImpl::SetCapabilityState(GLenum cap, bool enabled) {
10147 for capability
in _CAPABILITY_FLAGS
:
10148 file.Write(" case GL_%s:\n" % capability
['name'].upper())
10149 if 'state_flag' in capability
:
10152 state_.enable_flags.%(name)s = enabled;
10153 if (state_.enable_flags.cached_%(name)s != enabled
10154 || state_.ignore_cached_state) {
10155 %(state_flag)s = true;
10161 state_.enable_flags.%(name)s = enabled;
10162 if (state_.enable_flags.cached_%(name)s != enabled
10163 || state_.ignore_cached_state) {
10164 state_.enable_flags.cached_%(name)s = enabled;
10169 file.Write(""" default:
10176 self
.generated_cpp_filenames
.append(file.filename
)
10178 def WriteServiceUnitTests(self
, filename
):
10179 """Writes the service decorder unit tests."""
10180 num_tests
= len(self
.functions
)
10181 FUNCTIONS_PER_FILE
= 98 # hard code this so it doesn't change.
10183 for test_num
in range(0, num_tests
, FUNCTIONS_PER_FILE
):
10185 name
= filename
% count
10186 file = CHeaderWriter(
10188 "// It is included by gles2_cmd_decoder_unittest_%d.cc\n" % count
)
10189 test_name
= 'GLES2DecoderTest%d' % count
10190 end
= test_num
+ FUNCTIONS_PER_FILE
10191 if end
> num_tests
:
10193 for idx
in range(test_num
, end
):
10194 func
= self
.functions
[idx
]
10196 # Do any filtering of the functions here, so that the functions
10197 # will not move between the numbered files if filtering properties
10199 if func
.GetInfo('extension_flag'):
10203 #gen_cmd = func.GetInfo('gen_cmd')
10204 #if gen_cmd == True or gen_cmd == None:
10205 if func
.GetInfo('unit_test') == False:
10206 file.Write("// TODO(gman): %s\n" % func
.name
)
10208 func
.WriteServiceUnitTest(file, {
10209 'test_name': test_name
10212 self
.generated_cpp_filenames
.append(file.filename
)
10213 file = CHeaderWriter(
10215 "// It is included by gles2_cmd_decoder_unittest_base.cc\n")
10217 """void GLES2DecoderTestBase::SetupInitCapabilitiesExpectations(
10218 bool es3_capable) {""")
10219 for capability
in _CAPABILITY_FLAGS
:
10220 capability_es3
= 'es3' in capability
and capability
['es3'] == True
10221 if not capability_es3
:
10222 file.Write(" ExpectEnableDisable(GL_%s, %s);\n" %
10223 (capability
['name'].upper(),
10224 ('false', 'true')['default' in capability
]))
10226 file.Write(" if (es3_capable) {")
10227 for capability
in _CAPABILITY_FLAGS
:
10228 capability_es3
= 'es3' in capability
and capability
['es3'] == True
10230 file.Write(" ExpectEnableDisable(GL_%s, %s);\n" %
10231 (capability
['name'].upper(),
10232 ('false', 'true')['default' in capability
]))
10236 void GLES2DecoderTestBase::SetupInitStateExpectations() {
10239 # We need to sort the keys so the expectations match
10240 for state_name
in sorted(_STATES
.keys()):
10241 state
= _STATES
[state_name
]
10242 if state
['type'] == 'FrontBack':
10243 num_states
= len(state
['states'])
10244 for ndx
, group
in enumerate(Grouper(num_states
/ 2, state
['states'])):
10247 if 'expected' in item
:
10248 args
.append(item
['expected'])
10250 args
.append(item
['default'])
10252 " EXPECT_CALL(*gl_, %s(%s, %s))\n" %
10253 (state
['func'], ('GL_FRONT', 'GL_BACK')[ndx
], ", ".join(args
)))
10254 file.Write(" .Times(1)\n")
10255 file.Write(" .RetiresOnSaturation();\n")
10256 elif state
['type'] == 'NamedParameter':
10257 for item
in state
['states']:
10258 if 'extension_flag' in item
:
10259 file.Write(" if (group_->feature_info()->feature_flags().%s) {\n" %
10260 item
['extension_flag'])
10262 expect_value
= item
['default']
10263 if isinstance(expect_value
, list):
10264 # TODO: Currently we do not check array values.
10268 " EXPECT_CALL(*gl_, %s(%s, %s))\n" %
10271 if 'enum_set' in item
else item
['enum']),
10273 file.Write(" .Times(1)\n")
10274 file.Write(" .RetiresOnSaturation();\n")
10275 if 'extension_flag' in item
:
10278 if 'extension_flag' in state
:
10279 file.Write(" if (group_->feature_info()->feature_flags().%s) {\n" %
10280 state
['extension_flag'])
10283 for item
in state
['states']:
10284 if 'expected' in item
:
10285 args
.append(item
['expected'])
10287 args
.append(item
['default'])
10288 # TODO: Currently we do not check array values.
10289 args
= ["_" if isinstance(arg
, list) else arg
for arg
in args
]
10290 file.Write(" EXPECT_CALL(*gl_, %s(%s))\n" %
10291 (state
['func'], ", ".join(args
)))
10292 file.Write(" .Times(1)\n")
10293 file.Write(" .RetiresOnSaturation();\n")
10294 if 'extension_flag' in state
:
10299 self
.generated_cpp_filenames
.append(file.filename
)
10301 def WriteServiceUnitTestsForExtensions(self
, filename
):
10302 """Writes the service decorder unit tests for functions with extension_flag.
10304 The functions are special in that they need a specific unit test
10305 baseclass to turn on the extension.
10307 functions
= [f
for f
in self
.functions
if f
.GetInfo('extension_flag')]
10308 file = CHeaderWriter(
10310 "// It is included by gles2_cmd_decoder_unittest_extensions.cc\n")
10311 for func
in functions
:
10313 if func
.GetInfo('unit_test') == False:
10314 file.Write("// TODO(gman): %s\n" % func
.name
)
10316 extension
= ToCamelCase(
10317 ToGLExtensionString(func
.GetInfo('extension_flag')))
10318 func
.WriteServiceUnitTest(file, {
10319 'test_name': 'GLES2DecoderTestWith%s' % extension
10323 self
.generated_cpp_filenames
.append(file.filename
)
10325 def WriteGLES2Header(self
, filename
):
10326 """Writes the GLES2 header."""
10327 file = CHeaderWriter(
10329 "// This file contains Chromium-specific GLES2 declarations.\n\n")
10331 for func
in self
.original_functions
:
10332 func
.WriteGLES2Header(file)
10336 self
.generated_cpp_filenames
.append(file.filename
)
10338 def WriteGLES2CLibImplementation(self
, filename
):
10339 """Writes the GLES2 c lib implementation."""
10340 file = CHeaderWriter(
10342 "// These functions emulate GLES2 over command buffers.\n")
10344 for func
in self
.original_functions
:
10345 func
.WriteGLES2CLibImplementation(file)
10350 extern const NameToFunc g_gles2_function_table[] = {
10352 for func
in self
.original_functions
:
10354 ' { "gl%s", reinterpret_cast<GLES2FunctionPointer>(gl%s), },\n' %
10355 (func
.name
, func
.name
))
10356 file.Write(""" { NULL, NULL, },
10359 } // namespace gles2
10362 self
.generated_cpp_filenames
.append(file.filename
)
10364 def WriteGLES2InterfaceHeader(self
, filename
):
10365 """Writes the GLES2 interface header."""
10366 file = CHeaderWriter(
10368 "// This file is included by gles2_interface.h to declare the\n"
10369 "// GL api functions.\n")
10370 for func
in self
.original_functions
:
10371 func
.WriteGLES2InterfaceHeader(file)
10373 self
.generated_cpp_filenames
.append(file.filename
)
10375 def WriteMojoGLES2ImplHeader(self
, filename
):
10376 """Writes the Mojo GLES2 implementation header."""
10377 file = CHeaderWriter(
10379 "// This file is included by gles2_interface.h to declare the\n"
10380 "// GL api functions.\n")
10383 #include "gpu/command_buffer/client/gles2_interface.h"
10384 #include "third_party/mojo/src/mojo/public/c/gles2/gles2.h"
10388 class MojoGLES2Impl : public gpu::gles2::GLES2Interface {
10390 explicit MojoGLES2Impl(MojoGLES2Context context) {
10391 context_ = context;
10393 ~MojoGLES2Impl() override {}
10396 for func
in self
.original_functions
:
10397 func
.WriteMojoGLES2ImplHeader(file)
10400 MojoGLES2Context context_;
10403 } // namespace mojo
10407 self
.generated_cpp_filenames
.append(file.filename
)
10409 def WriteMojoGLES2Impl(self
, filename
):
10410 """Writes the Mojo GLES2 implementation."""
10411 file = CWriter(filename
)
10412 file.Write(_LICENSE
)
10413 file.Write(_DO_NOT_EDIT_WARNING
)
10416 #include "mojo/gpu/mojo_gles2_impl_autogen.h"
10418 #include "base/logging.h"
10419 #include "third_party/mojo/src/mojo/public/c/gles2/chromium_miscellaneous.h"
10420 #include "third_party/mojo/src/mojo/public/c/gles2/chromium_sub_image.h"
10421 #include "third_party/mojo/src/mojo/public/c/gles2/chromium_sync_point.h"
10422 #include "third_party/mojo/src/mojo/public/c/gles2/chromium_texture_mailbox.h"
10423 #include "third_party/mojo/src/mojo/public/c/gles2/gles2.h"
10424 #include "third_party/mojo/src/mojo/public/c/gles2/occlusion_query_ext.h"
10430 for func
in self
.original_functions
:
10431 func
.WriteMojoGLES2Impl(file)
10434 } // namespace mojo
10438 self
.generated_cpp_filenames
.append(file.filename
)
10440 def WriteGLES2InterfaceStub(self
, filename
):
10441 """Writes the GLES2 interface stub header."""
10442 file = CHeaderWriter(
10444 "// This file is included by gles2_interface_stub.h.\n")
10445 for func
in self
.original_functions
:
10446 func
.WriteGLES2InterfaceStub(file)
10448 self
.generated_cpp_filenames
.append(file.filename
)
10450 def WriteGLES2InterfaceStubImpl(self
, filename
):
10451 """Writes the GLES2 interface header."""
10452 file = CHeaderWriter(
10454 "// This file is included by gles2_interface_stub.cc.\n")
10455 for func
in self
.original_functions
:
10456 func
.WriteGLES2InterfaceStubImpl(file)
10458 self
.generated_cpp_filenames
.append(file.filename
)
10460 def WriteGLES2ImplementationHeader(self
, filename
):
10461 """Writes the GLES2 Implementation header."""
10462 file = CHeaderWriter(
10464 "// This file is included by gles2_implementation.h to declare the\n"
10465 "// GL api functions.\n")
10466 for func
in self
.original_functions
:
10467 func
.WriteGLES2ImplementationHeader(file)
10469 self
.generated_cpp_filenames
.append(file.filename
)
10471 def WriteGLES2Implementation(self
, filename
):
10472 """Writes the GLES2 Implementation."""
10473 file = CHeaderWriter(
10475 "// This file is included by gles2_implementation.cc to define the\n"
10476 "// GL api functions.\n")
10477 for func
in self
.original_functions
:
10478 func
.WriteGLES2Implementation(file)
10480 self
.generated_cpp_filenames
.append(file.filename
)
10482 def WriteGLES2TraceImplementationHeader(self
, filename
):
10483 """Writes the GLES2 Trace Implementation header."""
10484 file = CHeaderWriter(
10486 "// This file is included by gles2_trace_implementation.h\n")
10487 for func
in self
.original_functions
:
10488 func
.WriteGLES2TraceImplementationHeader(file)
10490 self
.generated_cpp_filenames
.append(file.filename
)
10492 def WriteGLES2TraceImplementation(self
, filename
):
10493 """Writes the GLES2 Trace Implementation."""
10494 file = CHeaderWriter(
10496 "// This file is included by gles2_trace_implementation.cc\n")
10497 for func
in self
.original_functions
:
10498 func
.WriteGLES2TraceImplementation(file)
10500 self
.generated_cpp_filenames
.append(file.filename
)
10502 def WriteGLES2ImplementationUnitTests(self
, filename
):
10503 """Writes the GLES2 helper header."""
10504 file = CHeaderWriter(
10506 "// This file is included by gles2_implementation.h to declare the\n"
10507 "// GL api functions.\n")
10508 for func
in self
.original_functions
:
10509 func
.WriteGLES2ImplementationUnitTest(file)
10511 self
.generated_cpp_filenames
.append(file.filename
)
10513 def WriteServiceUtilsHeader(self
, filename
):
10514 """Writes the gles2 auto generated utility header."""
10515 file = CHeaderWriter(filename
)
10516 for name
in sorted(_NAMED_TYPE_INFO
.keys()):
10517 named_type
= NamedType(_NAMED_TYPE_INFO
[name
])
10518 if named_type
.IsConstant():
10520 file.Write("ValueValidator<%s> %s;\n" %
10521 (named_type
.GetType(), ToUnderscore(name
)))
10524 self
.generated_cpp_filenames
.append(file.filename
)
10526 def WriteServiceUtilsImplementation(self
, filename
):
10527 """Writes the gles2 auto generated utility implementation."""
10528 file = CHeaderWriter(filename
)
10529 names
= sorted(_NAMED_TYPE_INFO
.keys())
10531 named_type
= NamedType(_NAMED_TYPE_INFO
[name
])
10532 if named_type
.IsConstant():
10534 if named_type
.GetValidValues():
10535 file.Write("static const %s valid_%s_table[] = {\n" %
10536 (named_type
.GetType(), ToUnderscore(name
)))
10537 for value
in named_type
.GetValidValues():
10538 file.Write(" %s,\n" % value
)
10541 if named_type
.GetValidValuesES3():
10542 file.Write("static const %s valid_%s_table_es3[] = {\n" %
10543 (named_type
.GetType(), ToUnderscore(name
)))
10544 for value
in named_type
.GetValidValuesES3():
10545 file.Write(" %s,\n" % value
)
10548 if named_type
.GetDeprecatedValuesES3():
10549 file.Write("static const %s deprecated_%s_table_es3[] = {\n" %
10550 (named_type
.GetType(), ToUnderscore(name
)))
10551 for value
in named_type
.GetDeprecatedValuesES3():
10552 file.Write(" %s,\n" % value
)
10555 file.Write("Validators::Validators()")
10557 for count
, name
in enumerate(names
):
10558 named_type
= NamedType(_NAMED_TYPE_INFO
[name
])
10559 if named_type
.IsConstant():
10561 if named_type
.GetValidValues():
10562 code
= """%(pre)s%(name)s(
10563 valid_%(name)s_table, arraysize(valid_%(name)s_table))"""
10565 code
= "%(pre)s%(name)s()"
10566 file.Write(code
% {
10567 'name': ToUnderscore(name
),
10571 file.Write(" {\n");
10572 file.Write("}\n\n");
10574 file.Write("void Validators::UpdateValuesES3() {\n")
10576 named_type
= NamedType(_NAMED_TYPE_INFO
[name
])
10577 if named_type
.GetDeprecatedValuesES3():
10578 code
= """ %(name)s.RemoveValues(
10579 deprecated_%(name)s_table_es3, arraysize(deprecated_%(name)s_table_es3));
10581 file.Write(code
% {
10582 'name': ToUnderscore(name
),
10584 if named_type
.GetValidValuesES3():
10585 code
= """ %(name)s.AddValues(
10586 valid_%(name)s_table_es3, arraysize(valid_%(name)s_table_es3));
10588 file.Write(code
% {
10589 'name': ToUnderscore(name
),
10591 file.Write("}\n\n");
10593 self
.generated_cpp_filenames
.append(file.filename
)
10595 def WriteCommonUtilsHeader(self
, filename
):
10596 """Writes the gles2 common utility header."""
10597 file = CHeaderWriter(filename
)
10598 type_infos
= sorted(_NAMED_TYPE_INFO
.keys())
10599 for type_info
in type_infos
:
10600 if _NAMED_TYPE_INFO
[type_info
]['type'] == 'GLenum':
10601 file.Write("static std::string GetString%s(uint32_t value);\n" %
10605 self
.generated_cpp_filenames
.append(file.filename
)
10607 def WriteCommonUtilsImpl(self
, filename
):
10608 """Writes the gles2 common utility header."""
10609 enum_re
= re
.compile(r
'\#define\s+(GL_[a-zA-Z0-9_]+)\s+([0-9A-Fa-fx]+)')
10611 for fname
in ['third_party/khronos/GLES2/gl2.h',
10612 'third_party/khronos/GLES2/gl2ext.h',
10613 'third_party/khronos/GLES3/gl3.h',
10614 'gpu/GLES2/gl2chromium.h',
10615 'gpu/GLES2/gl2extchromium.h']:
10616 lines
= open(fname
).readlines()
10618 m
= enum_re
.match(line
)
10622 if len(value
) <= 10:
10623 if not value
in dict:
10625 # check our own _CHROMIUM macro conflicts with khronos GL headers.
10626 elif dict[value
] != name
and (name
.endswith('_CHROMIUM') or
10627 dict[value
].endswith('_CHROMIUM')):
10628 self
.Error("code collision: %s and %s have the same code %s" %
10629 (dict[value
], name
, value
))
10631 file = CHeaderWriter(filename
)
10632 file.Write("static const GLES2Util::EnumToString "
10633 "enum_to_string_table[] = {\n")
10635 file.Write(' { %s, "%s", },\n' % (value
, dict[value
]))
10638 const GLES2Util::EnumToString* const GLES2Util::enum_to_string_table_ =
10639 enum_to_string_table;
10640 const size_t GLES2Util::enum_to_string_table_len_ =
10641 sizeof(enum_to_string_table) / sizeof(enum_to_string_table[0]);
10645 enums
= sorted(_NAMED_TYPE_INFO
.keys())
10647 if _NAMED_TYPE_INFO
[enum
]['type'] == 'GLenum':
10648 file.Write("std::string GLES2Util::GetString%s(uint32_t value) {\n" %
10650 valid_list
= _NAMED_TYPE_INFO
[enum
]['valid']
10651 if 'valid_es3' in _NAMED_TYPE_INFO
[enum
]:
10652 valid_list
= valid_list
+ _NAMED_TYPE_INFO
[enum
]['valid_es3']
10653 assert len(valid_list
) == len(set(valid_list
))
10654 if len(valid_list
) > 0:
10655 file.Write(" static const EnumToString string_table[] = {\n")
10656 for value
in valid_list
:
10657 file.Write(' { %s, "%s" },\n' % (value
, value
))
10659 return GLES2Util::GetQualifiedEnumString(
10660 string_table, arraysize(string_table), value);
10665 file.Write(""" return GLES2Util::GetQualifiedEnumString(
10671 self
.generated_cpp_filenames
.append(file.filename
)
10673 def WritePepperGLES2Interface(self
, filename
, dev
):
10674 """Writes the Pepper OpenGLES interface definition."""
10675 file = CWriter(filename
)
10676 file.Write(_LICENSE
)
10677 file.Write(_DO_NOT_EDIT_WARNING
)
10679 file.Write("label Chrome {\n")
10680 file.Write(" M39 = 1.0\n")
10681 file.Write("};\n\n")
10684 # Declare GL types.
10685 file.Write("[version=1.0]\n")
10686 file.Write("describe {\n")
10687 for gltype
in ['GLbitfield', 'GLboolean', 'GLbyte', 'GLclampf',
10688 'GLclampx', 'GLenum', 'GLfixed', 'GLfloat', 'GLint',
10689 'GLintptr', 'GLshort', 'GLsizei', 'GLsizeiptr',
10690 'GLubyte', 'GLuint', 'GLushort']:
10691 file.Write(" %s;\n" % gltype
)
10692 file.Write(" %s_ptr_t;\n" % gltype
)
10693 file.Write("};\n\n")
10695 # C level typedefs.
10696 file.Write("#inline c\n")
10697 file.Write("#include \"ppapi/c/pp_resource.h\"\n")
10699 file.Write("#include \"ppapi/c/ppb_opengles2.h\"\n\n")
10701 file.Write("\n#ifndef __gl2_h_\n")
10702 for (k
, v
) in _GL_TYPES
.iteritems():
10703 file.Write("typedef %s %s;\n" % (v
, k
))
10704 file.Write("#ifdef _WIN64\n")
10705 for (k
, v
) in _GL_TYPES_64
.iteritems():
10706 file.Write("typedef %s %s;\n" % (v
, k
))
10707 file.Write("#else\n")
10708 for (k
, v
) in _GL_TYPES_32
.iteritems():
10709 file.Write("typedef %s %s;\n" % (v
, k
))
10710 file.Write("#endif // _WIN64\n")
10711 file.Write("#endif // __gl2_h_\n\n")
10712 file.Write("#endinl\n")
10714 for interface
in self
.pepper_interfaces
:
10715 if interface
.dev
!= dev
:
10717 # Historically, we provide OpenGLES2 interfaces with struct
10718 # namespace. Not to break code which uses the interface as
10719 # "struct OpenGLES2", we put it in struct namespace.
10720 file.Write('\n[macro="%s", force_struct_namespace]\n' %
10721 interface
.GetInterfaceName())
10722 file.Write("interface %s {\n" % interface
.GetStructName())
10723 for func
in self
.original_functions
:
10724 if not func
.InPepperInterface(interface
):
10727 ret_type
= func
.MapCTypeToPepperIdlType(func
.return_type
,
10728 is_for_return_type
=True)
10729 func_prefix
= " %s %s(" % (ret_type
, func
.GetPepperName())
10730 file.Write(func_prefix
)
10731 file.Write("[in] PP_Resource context")
10732 for arg
in func
.MakeTypedPepperIdlArgStrings():
10733 file.Write(",\n" + " " * len(func_prefix
) + arg
)
10735 file.Write("};\n\n")
10740 def WritePepperGLES2Implementation(self
, filename
):
10741 """Writes the Pepper OpenGLES interface implementation."""
10743 file = CWriter(filename
)
10744 file.Write(_LICENSE
)
10745 file.Write(_DO_NOT_EDIT_WARNING
)
10747 file.Write("#include \"ppapi/shared_impl/ppb_opengles2_shared.h\"\n\n")
10748 file.Write("#include \"base/logging.h\"\n")
10749 file.Write("#include \"gpu/command_buffer/client/gles2_implementation.h\"\n")
10750 file.Write("#include \"ppapi/shared_impl/ppb_graphics_3d_shared.h\"\n")
10751 file.Write("#include \"ppapi/thunk/enter.h\"\n\n")
10753 file.Write("namespace ppapi {\n\n")
10754 file.Write("namespace {\n\n")
10756 file.Write("typedef thunk::EnterResource<thunk::PPB_Graphics3D_API>"
10759 file.Write("gpu::gles2::GLES2Implementation* ToGles2Impl(Enter3D*"
10761 file.Write(" DCHECK(enter);\n")
10762 file.Write(" DCHECK(enter->succeeded());\n")
10763 file.Write(" return static_cast<PPB_Graphics3D_Shared*>(enter->object())->"
10764 "gles2_impl();\n");
10765 file.Write("}\n\n");
10767 for func
in self
.original_functions
:
10768 if not func
.InAnyPepperExtension():
10771 original_arg
= func
.MakeTypedPepperArgString("")
10772 context_arg
= "PP_Resource context_id"
10773 if len(original_arg
):
10774 arg
= context_arg
+ ", " + original_arg
10777 file.Write("%s %s(%s) {\n" %
10778 (func
.return_type
, func
.GetPepperName(), arg
))
10779 file.Write(" Enter3D enter(context_id, true);\n")
10780 file.Write(" if (enter.succeeded()) {\n")
10782 return_str
= "" if func
.return_type
== "void" else "return "
10783 file.Write(" %sToGles2Impl(&enter)->%s(%s);\n" %
10784 (return_str
, func
.original_name
,
10785 func
.MakeOriginalArgString("")))
10787 if func
.return_type
== "void":
10790 file.Write(" else {\n")
10791 file.Write(" return %s;\n" % func
.GetErrorReturnString())
10793 file.Write("}\n\n")
10795 file.Write("} // namespace\n")
10797 for interface
in self
.pepper_interfaces
:
10798 file.Write("const %s* PPB_OpenGLES2_Shared::Get%sInterface() {\n" %
10799 (interface
.GetStructName(), interface
.GetName()))
10800 file.Write(" static const struct %s "
10801 "ppb_opengles2 = {\n" % interface
.GetStructName())
10803 file.Write(",\n &".join(
10804 f
.GetPepperName() for f
in self
.original_functions
10805 if f
.InPepperInterface(interface
)))
10808 file.Write(" };\n")
10809 file.Write(" return &ppb_opengles2;\n")
10812 file.Write("} // namespace ppapi\n")
10814 self
.generated_cpp_filenames
.append(file.filename
)
10816 def WriteGLES2ToPPAPIBridge(self
, filename
):
10817 """Connects GLES2 helper library to PPB_OpenGLES2 interface"""
10819 file = CWriter(filename
)
10820 file.Write(_LICENSE
)
10821 file.Write(_DO_NOT_EDIT_WARNING
)
10823 file.Write("#ifndef GL_GLEXT_PROTOTYPES\n")
10824 file.Write("#define GL_GLEXT_PROTOTYPES\n")
10825 file.Write("#endif\n")
10826 file.Write("#include <GLES2/gl2.h>\n")
10827 file.Write("#include <GLES2/gl2ext.h>\n")
10828 file.Write("#include \"ppapi/lib/gl/gles2/gl2ext_ppapi.h\"\n\n")
10830 for func
in self
.original_functions
:
10831 if not func
.InAnyPepperExtension():
10834 interface
= self
.interface_info
[func
.GetInfo('pepper_interface') or '']
10836 file.Write("%s GL_APIENTRY gl%s(%s) {\n" %
10837 (func
.return_type
, func
.GetPepperName(),
10838 func
.MakeTypedPepperArgString("")))
10839 return_str
= "" if func
.return_type
== "void" else "return "
10840 interface_str
= "glGet%sInterfacePPAPI()" % interface
.GetName()
10841 original_arg
= func
.MakeOriginalArgString("")
10842 context_arg
= "glGetCurrentContextPPAPI()"
10843 if len(original_arg
):
10844 arg
= context_arg
+ ", " + original_arg
10847 if interface
.GetName():
10848 file.Write(" const struct %s* ext = %s;\n" %
10849 (interface
.GetStructName(), interface_str
))
10850 file.Write(" if (ext)\n")
10851 file.Write(" %sext->%s(%s);\n" %
10852 (return_str
, func
.GetPepperName(), arg
))
10854 file.Write(" %s0;\n" % return_str
)
10856 file.Write(" %s%s->%s(%s);\n" %
10857 (return_str
, interface_str
, func
.GetPepperName(), arg
))
10858 file.Write("}\n\n")
10860 self
.generated_cpp_filenames
.append(file.filename
)
10862 def WriteMojoGLCallVisitor(self
, filename
):
10863 """Provides the GL implementation for mojo"""
10864 file = CWriter(filename
)
10865 file.Write(_LICENSE
)
10866 file.Write(_DO_NOT_EDIT_WARNING
)
10868 for func
in self
.original_functions
:
10869 if not func
.IsCoreGLFunction():
10871 file.Write("VISIT_GL_CALL(%s, %s, (%s), (%s))\n" %
10872 (func
.name
, func
.return_type
,
10873 func
.MakeTypedOriginalArgString(""),
10874 func
.MakeOriginalArgString("")))
10877 self
.generated_cpp_filenames
.append(file.filename
)
10879 def WriteMojoGLCallVisitorForExtension(self
, filename
, extension
):
10880 """Provides the GL implementation for mojo for a particular extension"""
10881 file = CWriter(filename
)
10882 file.Write(_LICENSE
)
10883 file.Write(_DO_NOT_EDIT_WARNING
)
10885 for func
in self
.original_functions
:
10886 if func
.GetInfo("extension") != extension
:
10888 file.Write("VISIT_GL_CALL(%s, %s, (%s), (%s))\n" %
10889 (func
.name
, func
.return_type
,
10890 func
.MakeTypedOriginalArgString(""),
10891 func
.MakeOriginalArgString("")))
10894 self
.generated_cpp_filenames
.append(file.filename
)
10896 def Format(generated_files
):
10897 formatter
= "clang-format"
10898 if platform
.system() == "Windows":
10899 formatter
+= ".bat"
10900 for filename
in generated_files
:
10901 call([formatter
, "-i", "-style=chromium", filename
])
10904 """This is the main function."""
10905 parser
= OptionParser()
10908 help="base directory for resulting files, under chrome/src. default is "
10909 "empty. Use this if you want the result stored under gen.")
10911 "-v", "--verbose", action
="store_true",
10912 help="prints more output.")
10914 (options
, args
) = parser
.parse_args(args
=argv
)
10916 # Add in states and capabilites to GLState
10917 gl_state_valid
= _NAMED_TYPE_INFO
['GLState']['valid']
10918 for state_name
in sorted(_STATES
.keys()):
10919 state
= _STATES
[state_name
]
10920 if 'extension_flag' in state
:
10922 if 'enum' in state
:
10923 if not state
['enum'] in gl_state_valid
:
10924 gl_state_valid
.append(state
['enum'])
10926 for item
in state
['states']:
10927 if 'extension_flag' in item
:
10929 if not item
['enum'] in gl_state_valid
:
10930 gl_state_valid
.append(item
['enum'])
10931 for capability
in _CAPABILITY_FLAGS
:
10932 valid_value
= "GL_%s" % capability
['name'].upper()
10933 if not valid_value
in gl_state_valid
:
10934 gl_state_valid
.append(valid_value
)
10936 # This script lives under gpu/command_buffer, cd to base directory.
10937 os
.chdir(os
.path
.dirname(__file__
) + "/../..")
10938 base_dir
= os
.getcwd()
10939 gen
= GLGenerator(options
.verbose
)
10940 gen
.ParseGLH("gpu/command_buffer/cmd_buffer_functions.txt")
10942 # Support generating files under gen/
10943 if options
.output_dir
!= None:
10944 os
.chdir(options
.output_dir
)
10946 gen
.WritePepperGLES2Interface("ppapi/api/ppb_opengles2.idl", False)
10947 gen
.WritePepperGLES2Interface("ppapi/api/dev/ppb_opengles2ext_dev.idl", True)
10948 gen
.WriteGLES2ToPPAPIBridge("ppapi/lib/gl/gles2/gles2.c")
10949 gen
.WritePepperGLES2Implementation(
10950 "ppapi/shared_impl/ppb_opengles2_shared.cc")
10952 gen
.WriteCommandIds("gpu/command_buffer/common/gles2_cmd_ids_autogen.h")
10953 gen
.WriteFormat("gpu/command_buffer/common/gles2_cmd_format_autogen.h")
10954 gen
.WriteFormatTest(
10955 "gpu/command_buffer/common/gles2_cmd_format_test_autogen.h")
10956 gen
.WriteGLES2InterfaceHeader(
10957 "gpu/command_buffer/client/gles2_interface_autogen.h")
10958 gen
.WriteMojoGLES2ImplHeader(
10959 "mojo/gpu/mojo_gles2_impl_autogen.h")
10960 gen
.WriteMojoGLES2Impl(
10961 "mojo/gpu/mojo_gles2_impl_autogen.cc")
10962 gen
.WriteGLES2InterfaceStub(
10963 "gpu/command_buffer/client/gles2_interface_stub_autogen.h")
10964 gen
.WriteGLES2InterfaceStubImpl(
10965 "gpu/command_buffer/client/gles2_interface_stub_impl_autogen.h")
10966 gen
.WriteGLES2ImplementationHeader(
10967 "gpu/command_buffer/client/gles2_implementation_autogen.h")
10968 gen
.WriteGLES2Implementation(
10969 "gpu/command_buffer/client/gles2_implementation_impl_autogen.h")
10970 gen
.WriteGLES2ImplementationUnitTests(
10971 "gpu/command_buffer/client/gles2_implementation_unittest_autogen.h")
10972 gen
.WriteGLES2TraceImplementationHeader(
10973 "gpu/command_buffer/client/gles2_trace_implementation_autogen.h")
10974 gen
.WriteGLES2TraceImplementation(
10975 "gpu/command_buffer/client/gles2_trace_implementation_impl_autogen.h")
10976 gen
.WriteGLES2CLibImplementation(
10977 "gpu/command_buffer/client/gles2_c_lib_autogen.h")
10978 gen
.WriteCmdHelperHeader(
10979 "gpu/command_buffer/client/gles2_cmd_helper_autogen.h")
10980 gen
.WriteServiceImplementation(
10981 "gpu/command_buffer/service/gles2_cmd_decoder_autogen.h")
10982 gen
.WriteServiceContextStateHeader(
10983 "gpu/command_buffer/service/context_state_autogen.h")
10984 gen
.WriteServiceContextStateImpl(
10985 "gpu/command_buffer/service/context_state_impl_autogen.h")
10986 gen
.WriteClientContextStateHeader(
10987 "gpu/command_buffer/client/client_context_state_autogen.h")
10988 gen
.WriteClientContextStateImpl(
10989 "gpu/command_buffer/client/client_context_state_impl_autogen.h")
10990 gen
.WriteServiceUnitTests(
10991 "gpu/command_buffer/service/gles2_cmd_decoder_unittest_%d_autogen.h")
10992 gen
.WriteServiceUnitTestsForExtensions(
10993 "gpu/command_buffer/service/"
10994 "gles2_cmd_decoder_unittest_extensions_autogen.h")
10995 gen
.WriteServiceUtilsHeader(
10996 "gpu/command_buffer/service/gles2_cmd_validation_autogen.h")
10997 gen
.WriteServiceUtilsImplementation(
10998 "gpu/command_buffer/service/"
10999 "gles2_cmd_validation_implementation_autogen.h")
11000 gen
.WriteCommonUtilsHeader(
11001 "gpu/command_buffer/common/gles2_cmd_utils_autogen.h")
11002 gen
.WriteCommonUtilsImpl(
11003 "gpu/command_buffer/common/gles2_cmd_utils_implementation_autogen.h")
11004 gen
.WriteGLES2Header("gpu/GLES2/gl2chromium_autogen.h")
11005 mojo_gles2_prefix
= ("third_party/mojo/src/mojo/public/c/gles2/"
11006 "gles2_call_visitor")
11007 gen
.WriteMojoGLCallVisitor(mojo_gles2_prefix
+ "_autogen.h")
11008 gen
.WriteMojoGLCallVisitorForExtension(
11009 mojo_gles2_prefix
+ "_chromium_texture_mailbox_autogen.h",
11010 "CHROMIUM_texture_mailbox")
11011 gen
.WriteMojoGLCallVisitorForExtension(
11012 mojo_gles2_prefix
+ "_chromium_sync_point_autogen.h",
11013 "CHROMIUM_sync_point")
11014 gen
.WriteMojoGLCallVisitorForExtension(
11015 mojo_gles2_prefix
+ "_chromium_sub_image_autogen.h",
11016 "CHROMIUM_sub_image")
11017 gen
.WriteMojoGLCallVisitorForExtension(
11018 mojo_gles2_prefix
+ "_chromium_miscellaneous_autogen.h",
11019 "CHROMIUM_miscellaneous")
11020 gen
.WriteMojoGLCallVisitorForExtension(
11021 mojo_gles2_prefix
+ "_occlusion_query_ext_autogen.h",
11022 "occlusion_query_EXT")
11024 Format(gen
.generated_cpp_filenames
)
11027 print "%d errors" % gen
.errors
11032 if __name__
== '__main__':
11033 sys
.exit(main(sys
.argv
[1:]))