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_BIND_GENERATES_RESOURCE_CHROMIUM',
765 # we can add this because we emulate it if the driver does not support it.
766 'GL_VERTEX_ARRAY_BINDING_OES',
770 'GL_COPY_READ_BUFFER_BINDING',
771 'GL_COPY_WRITE_BUFFER_BINDING',
788 'GL_DRAW_FRAMEBUFFER_BINDING',
789 'GL_FRAGMENT_SHADER_DERIVATIVE_HINT',
791 'GL_MAX_3D_TEXTURE_SIZE',
792 'GL_MAX_ARRAY_TEXTURE_LAYERS',
793 'GL_MAX_COLOR_ATTACHMENTS',
794 'GL_MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS',
795 'GL_MAX_COMBINED_UNIFORM_BLOCKS',
796 'GL_MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS',
797 'GL_MAX_DRAW_BUFFERS',
798 'GL_MAX_ELEMENT_INDEX',
799 'GL_MAX_ELEMENTS_INDICES',
800 'GL_MAX_ELEMENTS_VERTICES',
801 'GL_MAX_FRAGMENT_INPUT_COMPONENTS',
802 'GL_MAX_FRAGMENT_UNIFORM_BLOCKS',
803 'GL_MAX_FRAGMENT_UNIFORM_COMPONENTS',
804 'GL_MAX_PROGRAM_TEXEL_OFFSET',
806 'GL_MAX_SERVER_WAIT_TIMEOUT',
807 'GL_MAX_TEXTURE_LOD_BIAS',
808 'GL_MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS',
809 'GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS',
810 'GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS',
811 'GL_MAX_UNIFORM_BLOCK_SIZE',
812 'GL_MAX_UNIFORM_BUFFER_BINDINGS',
813 'GL_MAX_VARYING_COMPONENTS',
814 'GL_MAX_VERTEX_OUTPUT_COMPONENTS',
815 'GL_MAX_VERTEX_UNIFORM_BLOCKS',
816 'GL_MAX_VERTEX_UNIFORM_COMPONENTS',
817 'GL_MIN_PROGRAM_TEXEL_OFFSET',
820 'GL_NUM_PROGRAM_BINARY_FORMATS',
821 'GL_PACK_ROW_LENGTH',
822 'GL_PACK_SKIP_PIXELS',
824 'GL_PIXEL_PACK_BUFFER_BINDING',
825 'GL_PIXEL_UNPACK_BUFFER_BINDING',
826 'GL_PROGRAM_BINARY_FORMATS',
828 'GL_READ_FRAMEBUFFER_BINDING',
829 'GL_SAMPLER_BINDING',
830 'GL_TEXTURE_BINDING_2D_ARRAY',
831 'GL_TEXTURE_BINDING_3D',
832 'GL_TRANSFORM_FEEDBACK_BINDING',
833 'GL_TRANSFORM_FEEDBACK_ACTIVE',
834 'GL_TRANSFORM_FEEDBACK_BUFFER_BINDING',
835 'GL_TRANSFORM_FEEDBACK_PAUSED',
836 'GL_TRANSFORM_FEEDBACK_BUFFER_SIZE',
837 'GL_TRANSFORM_FEEDBACK_BUFFER_START',
838 'GL_UNIFORM_BUFFER_BINDING',
839 'GL_UNIFORM_BUFFER_OFFSET_ALIGNMENT',
840 'GL_UNIFORM_BUFFER_SIZE',
841 'GL_UNIFORM_BUFFER_START',
842 'GL_UNPACK_IMAGE_HEIGHT',
843 'GL_UNPACK_ROW_LENGTH',
844 'GL_UNPACK_SKIP_IMAGES',
845 'GL_UNPACK_SKIP_PIXELS',
846 'GL_UNPACK_SKIP_ROWS',
847 # GL_VERTEX_ARRAY_BINDING is the same as GL_VERTEX_ARRAY_BINDING_OES
848 # 'GL_VERTEX_ARRAY_BINDING',
857 'GL_TRANSFORM_FEEDBACK_BUFFER_BINDING',
858 'GL_TRANSFORM_FEEDBACK_BUFFER_SIZE',
859 'GL_TRANSFORM_FEEDBACK_BUFFER_START',
860 'GL_UNIFORM_BUFFER_BINDING',
861 'GL_UNIFORM_BUFFER_SIZE',
862 'GL_UNIFORM_BUFFER_START',
868 'GetTexParamTarget': {
872 'GL_TEXTURE_CUBE_MAP',
875 'GL_TEXTURE_2D_ARRAY',
879 'GL_PROXY_TEXTURE_CUBE_MAP',
886 'GL_TEXTURE_CUBE_MAP_POSITIVE_X',
887 'GL_TEXTURE_CUBE_MAP_NEGATIVE_X',
888 'GL_TEXTURE_CUBE_MAP_POSITIVE_Y',
889 'GL_TEXTURE_CUBE_MAP_NEGATIVE_Y',
890 'GL_TEXTURE_CUBE_MAP_POSITIVE_Z',
891 'GL_TEXTURE_CUBE_MAP_NEGATIVE_Z',
894 'GL_PROXY_TEXTURE_CUBE_MAP',
901 'GL_TEXTURE_2D_ARRAY',
907 'TextureBindTarget': {
911 'GL_TEXTURE_CUBE_MAP',
915 'GL_TEXTURE_2D_ARRAY',
922 'TransformFeedbackBindTarget': {
925 'GL_TRANSFORM_FEEDBACK',
931 'TransformFeedbackPrimitiveMode': {
946 'GL_FRAGMENT_SHADER',
949 'GL_GEOMETRY_SHADER',
985 'GL_FUNC_REVERSE_SUBTRACT',
1001 'GL_ONE_MINUS_SRC_COLOR',
1003 'GL_ONE_MINUS_DST_COLOR',
1005 'GL_ONE_MINUS_SRC_ALPHA',
1007 'GL_ONE_MINUS_DST_ALPHA',
1008 'GL_CONSTANT_COLOR',
1009 'GL_ONE_MINUS_CONSTANT_COLOR',
1010 'GL_CONSTANT_ALPHA',
1011 'GL_ONE_MINUS_CONSTANT_ALPHA',
1012 'GL_SRC_ALPHA_SATURATE',
1021 'GL_ONE_MINUS_SRC_COLOR',
1023 'GL_ONE_MINUS_DST_COLOR',
1025 'GL_ONE_MINUS_SRC_ALPHA',
1027 'GL_ONE_MINUS_DST_ALPHA',
1028 'GL_CONSTANT_COLOR',
1029 'GL_ONE_MINUS_CONSTANT_COLOR',
1030 'GL_CONSTANT_ALPHA',
1031 'GL_ONE_MINUS_CONSTANT_ALPHA',
1036 'valid': ["GL_%s" % cap
['name'].upper() for cap
in _CAPABILITY_FLAGS
1037 if 'es3' not in cap
or cap
['es3'] != True],
1038 'valid_es3': ["GL_%s" % cap
['name'].upper() for cap
in _CAPABILITY_FLAGS
1039 if 'es3' in cap
and cap
['es3'] == True],
1052 'GL_TRIANGLE_STRIP',
1065 'GL_UNSIGNED_SHORT',
1074 'GetMaxIndexType': {
1078 'GL_UNSIGNED_SHORT',
1088 'GL_COLOR_ATTACHMENT0',
1089 'GL_DEPTH_ATTACHMENT',
1090 'GL_STENCIL_ATTACHMENT',
1093 'GL_DEPTH_STENCIL_ATTACHMENT',
1096 'BackbufferAttachment': {
1104 'BufferParameter': {
1111 'GL_BUFFER_ACCESS_FLAGS',
1113 'GL_BUFFER_MAP_LENGTH',
1114 'GL_BUFFER_MAP_OFFSET',
1117 'GL_PIXEL_PACK_BUFFER',
1123 'GL_INTERLEAVED_ATTRIBS',
1124 'GL_SEPARATE_ATTRIBS',
1127 'GL_PIXEL_PACK_BUFFER',
1130 'FrameBufferParameter': {
1133 'GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE',
1134 'GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME',
1135 'GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL',
1136 'GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE',
1139 'GL_FRAMEBUFFER_ATTACHMENT_RED_SIZE',
1140 'GL_FRAMEBUFFER_ATTACHMENT_GREEN_SIZE',
1141 'GL_FRAMEBUFFER_ATTACHMENT_BLUE_SIZE',
1142 'GL_FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE',
1143 'GL_FRAMEBUFFER_ATTACHMENT_DEPTH_SIZE',
1144 'GL_FRAMEBUFFER_ATTACHMENT_STENCIL_SIZE',
1145 'GL_FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE',
1146 'GL_FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING',
1147 'GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER',
1153 'GL_PATH_PROJECTION_CHROMIUM',
1154 'GL_PATH_MODELVIEW_CHROMIUM',
1157 'ProgramParameter': {
1162 'GL_VALIDATE_STATUS',
1163 'GL_INFO_LOG_LENGTH',
1164 'GL_ATTACHED_SHADERS',
1165 'GL_ACTIVE_ATTRIBUTES',
1166 'GL_ACTIVE_ATTRIBUTE_MAX_LENGTH',
1167 'GL_ACTIVE_UNIFORMS',
1168 'GL_ACTIVE_UNIFORM_MAX_LENGTH',
1171 'GL_ACTIVE_UNIFORM_BLOCKS',
1172 'GL_ACTIVE_UNIFORM_BLOCK_MAX_NAME_LENGTH',
1173 'GL_TRANSFORM_FEEDBACK_BUFFER_MODE',
1174 'GL_TRANSFORM_FEEDBACK_VARYINGS',
1175 'GL_TRANSFORM_FEEDBACK_VARYING_MAX_LENGTH',
1178 'GL_PROGRAM_BINARY_RETRIEVABLE_HINT', # not supported in Chromium.
1181 'QueryObjectParameter': {
1184 'GL_QUERY_RESULT_EXT',
1185 'GL_QUERY_RESULT_AVAILABLE_EXT',
1191 'GL_CURRENT_QUERY_EXT',
1197 'GL_ANY_SAMPLES_PASSED_EXT',
1198 'GL_ANY_SAMPLES_PASSED_CONSERVATIVE_EXT',
1199 'GL_COMMANDS_ISSUED_CHROMIUM',
1200 'GL_LATENCY_QUERY_CHROMIUM',
1201 'GL_ASYNC_PIXEL_UNPACK_COMPLETED_CHROMIUM',
1202 'GL_ASYNC_PIXEL_PACK_COMPLETED_CHROMIUM',
1203 'GL_COMMANDS_COMPLETED_CHROMIUM',
1206 'RenderBufferParameter': {
1209 'GL_RENDERBUFFER_RED_SIZE',
1210 'GL_RENDERBUFFER_GREEN_SIZE',
1211 'GL_RENDERBUFFER_BLUE_SIZE',
1212 'GL_RENDERBUFFER_ALPHA_SIZE',
1213 'GL_RENDERBUFFER_DEPTH_SIZE',
1214 'GL_RENDERBUFFER_STENCIL_SIZE',
1215 'GL_RENDERBUFFER_WIDTH',
1216 'GL_RENDERBUFFER_HEIGHT',
1217 'GL_RENDERBUFFER_INTERNAL_FORMAT',
1220 'GL_RENDERBUFFER_SAMPLES',
1223 'InternalFormatParameter': {
1226 'GL_NUM_SAMPLE_COUNTS',
1230 'SamplerParameter': {
1233 'GL_TEXTURE_MAG_FILTER',
1234 'GL_TEXTURE_MIN_FILTER',
1235 'GL_TEXTURE_MIN_LOD',
1236 'GL_TEXTURE_MAX_LOD',
1237 'GL_TEXTURE_WRAP_S',
1238 'GL_TEXTURE_WRAP_T',
1239 'GL_TEXTURE_WRAP_R',
1240 'GL_TEXTURE_COMPARE_MODE',
1241 'GL_TEXTURE_COMPARE_FUNC',
1244 'GL_GENERATE_MIPMAP',
1247 'ShaderParameter': {
1252 'GL_COMPILE_STATUS',
1253 'GL_INFO_LOG_LENGTH',
1254 'GL_SHADER_SOURCE_LENGTH',
1255 'GL_TRANSLATED_SHADER_SOURCE_LENGTH_ANGLE',
1258 'ShaderPrecision': {
1275 'GL_SHADING_LANGUAGE_VERSION',
1279 'TextureParameter': {
1282 'GL_TEXTURE_MAG_FILTER',
1283 'GL_TEXTURE_MIN_FILTER',
1284 'GL_TEXTURE_POOL_CHROMIUM',
1285 'GL_TEXTURE_WRAP_S',
1286 'GL_TEXTURE_WRAP_T',
1289 'GL_TEXTURE_BASE_LEVEL',
1290 'GL_TEXTURE_COMPARE_FUNC',
1291 'GL_TEXTURE_COMPARE_MODE',
1292 'GL_TEXTURE_IMMUTABLE_FORMAT',
1293 'GL_TEXTURE_IMMUTABLE_LEVELS',
1294 'GL_TEXTURE_MAX_LEVEL',
1295 'GL_TEXTURE_MAX_LOD',
1296 'GL_TEXTURE_MIN_LOD',
1297 'GL_TEXTURE_WRAP_R',
1300 'GL_GENERATE_MIPMAP',
1306 'GL_TEXTURE_POOL_MANAGED_CHROMIUM',
1307 'GL_TEXTURE_POOL_UNMANAGED_CHROMIUM',
1310 'TextureWrapMode': {
1314 'GL_MIRRORED_REPEAT',
1318 'TextureMinFilterMode': {
1323 'GL_NEAREST_MIPMAP_NEAREST',
1324 'GL_LINEAR_MIPMAP_NEAREST',
1325 'GL_NEAREST_MIPMAP_LINEAR',
1326 'GL_LINEAR_MIPMAP_LINEAR',
1329 'TextureMagFilterMode': {
1336 'TextureCompareFunc': {
1349 'TextureCompareMode': {
1353 'GL_COMPARE_REF_TO_TEXTURE',
1360 'GL_FRAMEBUFFER_ATTACHMENT_ANGLE',
1363 'VertexAttribute': {
1366 # some enum that the decoder actually passes through to GL needs
1367 # to be the first listed here since it's used in unit tests.
1368 'GL_VERTEX_ATTRIB_ARRAY_NORMALIZED',
1369 'GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING',
1370 'GL_VERTEX_ATTRIB_ARRAY_ENABLED',
1371 'GL_VERTEX_ATTRIB_ARRAY_SIZE',
1372 'GL_VERTEX_ATTRIB_ARRAY_STRIDE',
1373 'GL_VERTEX_ATTRIB_ARRAY_TYPE',
1374 'GL_CURRENT_VERTEX_ATTRIB',
1377 'GL_VERTEX_ATTRIB_ARRAY_INTEGER',
1378 'GL_VERTEX_ATTRIB_ARRAY_DIVISOR',
1384 'GL_VERTEX_ATTRIB_ARRAY_POINTER',
1390 'GL_GENERATE_MIPMAP_HINT',
1393 'GL_FRAGMENT_SHADER_DERIVATIVE_HINT',
1396 'GL_PERSPECTIVE_CORRECTION_HINT',
1410 'GL_PACK_ALIGNMENT',
1411 'GL_UNPACK_ALIGNMENT',
1414 'GL_PACK_ROW_LENGTH',
1415 'GL_PACK_SKIP_PIXELS',
1416 'GL_PACK_SKIP_ROWS',
1417 'GL_UNPACK_ROW_LENGTH',
1418 'GL_UNPACK_IMAGE_HEIGHT',
1419 'GL_UNPACK_SKIP_PIXELS',
1420 'GL_UNPACK_SKIP_ROWS',
1421 'GL_UNPACK_SKIP_IMAGES',
1424 'GL_PACK_SWAP_BYTES',
1425 'GL_UNPACK_SWAP_BYTES',
1428 'PixelStoreAlignment': {
1441 'ReadPixelFormat': {
1460 'GL_UNSIGNED_SHORT_5_6_5',
1461 'GL_UNSIGNED_SHORT_4_4_4_4',
1462 'GL_UNSIGNED_SHORT_5_5_5_1',
1466 'GL_UNSIGNED_SHORT',
1472 'GL_UNSIGNED_INT_2_10_10_10_REV',
1473 'GL_UNSIGNED_INT_10F_11F_11F_REV',
1474 'GL_UNSIGNED_INT_5_9_9_9_REV',
1475 'GL_UNSIGNED_INT_24_8',
1476 'GL_FLOAT_32_UNSIGNED_INT_24_8_REV',
1479 'GL_UNSIGNED_BYTE_3_3_2',
1486 'GL_UNSIGNED_SHORT_5_6_5',
1487 'GL_UNSIGNED_SHORT_4_4_4_4',
1488 'GL_UNSIGNED_SHORT_5_5_5_1',
1499 'GL_UNSIGNED_SHORT_5_6_5',
1500 'GL_UNSIGNED_SHORT_4_4_4_4',
1501 'GL_UNSIGNED_SHORT_5_5_5_1',
1504 'RenderBufferFormat': {
1510 'GL_DEPTH_COMPONENT16',
1511 'GL_STENCIL_INDEX8',
1539 'GL_DEPTH_COMPONENT24',
1540 'GL_DEPTH_COMPONENT32F',
1541 'GL_DEPTH24_STENCIL8',
1542 'GL_DEPTH32F_STENCIL8',
1545 'ShaderBinaryFormat': {
1568 'GL_LUMINANCE_ALPHA',
1579 'GL_DEPTH_COMPONENT',
1587 'TextureInternalFormat': {
1592 'GL_LUMINANCE_ALPHA',
1621 'GL_R11F_G11F_B10F',
1646 # The DEPTH/STENCIL formats are not supported in CopyTexImage2D.
1647 # We will reject them dynamically in GPU command buffer.
1648 'GL_DEPTH_COMPONENT16',
1649 'GL_DEPTH_COMPONENT24',
1650 'GL_DEPTH_COMPONENT32F',
1651 'GL_DEPTH24_STENCIL8',
1652 'GL_DEPTH32F_STENCIL8',
1659 'TextureInternalFormatStorage': {
1666 'GL_LUMINANCE8_EXT',
1667 'GL_LUMINANCE8_ALPHA8_EXT',
1695 'GL_R11F_G11F_B10F',
1718 'GL_DEPTH_COMPONENT16',
1719 'GL_DEPTH_COMPONENT24',
1720 'GL_DEPTH_COMPONENT32F',
1721 'GL_DEPTH24_STENCIL8',
1722 'GL_DEPTH32F_STENCIL8',
1723 'GL_COMPRESSED_R11_EAC',
1724 'GL_COMPRESSED_SIGNED_R11_EAC',
1725 'GL_COMPRESSED_RG11_EAC',
1726 'GL_COMPRESSED_SIGNED_RG11_EAC',
1727 'GL_COMPRESSED_RGB8_ETC2',
1728 'GL_COMPRESSED_SRGB8_ETC2',
1729 'GL_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2',
1730 'GL_COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2',
1731 'GL_COMPRESSED_RGBA8_ETC2_EAC',
1732 'GL_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC',
1736 'GL_LUMINANCE8_EXT',
1737 'GL_LUMINANCE8_ALPHA8_EXT',
1739 'GL_LUMINANCE16F_EXT',
1740 'GL_LUMINANCE_ALPHA16F_EXT',
1742 'GL_LUMINANCE32F_EXT',
1743 'GL_LUMINANCE_ALPHA32F_EXT',
1746 'ImageInternalFormat': {
1750 'GL_RGB_YUV_420_CHROMIUM',
1758 'GL_SCANOUT_CHROMIUM'
1761 'ValueBufferTarget': {
1764 'GL_SUBSCRIBED_VALUES_BUFFER_CHROMIUM',
1767 'SubscriptionTarget': {
1770 'GL_MOUSE_POSITION_CHROMIUM',
1773 'UniformParameter': {
1778 'GL_UNIFORM_NAME_LENGTH',
1779 'GL_UNIFORM_BLOCK_INDEX',
1780 'GL_UNIFORM_OFFSET',
1781 'GL_UNIFORM_ARRAY_STRIDE',
1782 'GL_UNIFORM_MATRIX_STRIDE',
1783 'GL_UNIFORM_IS_ROW_MAJOR',
1786 'GL_UNIFORM_BLOCK_NAME_LENGTH',
1789 'UniformBlockParameter': {
1792 'GL_UNIFORM_BLOCK_BINDING',
1793 'GL_UNIFORM_BLOCK_DATA_SIZE',
1794 'GL_UNIFORM_BLOCK_NAME_LENGTH',
1795 'GL_UNIFORM_BLOCK_ACTIVE_UNIFORMS',
1796 'GL_UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES',
1797 'GL_UNIFORM_BLOCK_REFERENCED_BY_VERTEX_SHADER',
1798 'GL_UNIFORM_BLOCK_REFERENCED_BY_FRAGMENT_SHADER',
1804 'VertexAttribType': {
1810 'GL_UNSIGNED_SHORT',
1811 # 'GL_FIXED', // This is not available on Desktop GL.
1818 'GL_INT_2_10_10_10_REV',
1819 'GL_UNSIGNED_INT_2_10_10_10_REV',
1825 'VertexAttribIType': {
1831 'GL_UNSIGNED_SHORT',
1842 'is_complete': True,
1850 'VertexAttribSize': {
1865 'is_complete': True,
1874 'type': 'GLboolean',
1875 'is_complete': True,
1886 'GL_GUILTY_CONTEXT_RESET_ARB',
1887 'GL_INNOCENT_CONTEXT_RESET_ARB',
1888 'GL_UNKNOWN_CONTEXT_RESET_ARB',
1893 'is_complete': True,
1895 'GL_SYNC_GPU_COMMANDS_COMPLETE',
1902 'type': 'GLbitfield',
1903 'is_complete': True,
1912 'type': 'GLbitfield',
1914 'GL_SYNC_FLUSH_COMMANDS_BIT',
1924 'GL_SYNC_STATUS', # This needs to be the 1st; all others are cached.
1926 'GL_SYNC_CONDITION',
1935 # This table specifies the different pepper interfaces that are supported for
1936 # GL commands. 'dev' is true if it's a dev interface.
1937 _PEPPER_INTERFACES
= [
1938 {'name': '', 'dev': False},
1939 {'name': 'InstancedArrays', 'dev': False},
1940 {'name': 'FramebufferBlit', 'dev': False},
1941 {'name': 'FramebufferMultisample', 'dev': False},
1942 {'name': 'ChromiumEnableFeature', 'dev': False},
1943 {'name': 'ChromiumMapSub', 'dev': False},
1944 {'name': 'Query', 'dev': False},
1945 {'name': 'VertexArrayObject', 'dev': False},
1946 {'name': 'DrawBuffers', 'dev': True},
1949 # A function info object specifies the type and other special data for the
1950 # command that will be generated. A base function info object is generated by
1951 # parsing the "cmd_buffer_functions.txt", one for each function in the
1952 # file. These function info objects can be augmented and their values can be
1953 # overridden by adding an object to the table below.
1955 # Must match function names specified in "cmd_buffer_functions.txt".
1957 # cmd_comment: A comment added to the cmd format.
1958 # type: defines which handler will be used to generate code.
1959 # decoder_func: defines which function to call in the decoder to execute the
1960 # corresponding GL command. If not specified the GL command will
1961 # be called directly.
1962 # gl_test_func: GL function that is expected to be called when testing.
1963 # cmd_args: The arguments to use for the command. This overrides generating
1964 # them based on the GL function arguments.
1965 # gen_cmd: Whether or not this function geneates a command. Default = True.
1966 # data_transfer_methods: Array of methods that are used for transfering the
1967 # pointer data. Possible values: 'immediate', 'shm', 'bucket'.
1968 # The default is 'immediate' if the command has one pointer
1969 # argument, otherwise 'shm'. One command is generated for each
1970 # transfer method. Affects only commands which are not of type
1971 # 'HandWritten', 'GETn' or 'GLcharN'.
1972 # Note: the command arguments that affect this are the final args,
1973 # taking cmd_args override into consideration.
1974 # impl_func: Whether or not to generate the GLES2Implementation part of this
1976 # impl_decl: Whether or not to generate the GLES2Implementation declaration
1978 # needs_size: If True a data_size field is added to the command.
1979 # count: The number of units per element. For PUTn or PUT types.
1980 # use_count_func: If True the actual data count needs to be computed; the count
1981 # argument specifies the maximum count.
1982 # unit_test: If False no service side unit test will be generated.
1983 # client_test: If False no client side unit test will be generated.
1984 # expectation: If False the unit test will have no expected calls.
1985 # gen_func: Name of function that generates GL resource for corresponding
1987 # states: array of states that get set by this function corresponding to
1988 # the given arguments
1989 # state_flag: name of flag that is set to true when function is called.
1990 # no_gl: no GL function is called.
1991 # valid_args: A dictionary of argument indices to args to use in unit tests
1992 # when they can not be automatically determined.
1993 # pepper_interface: The pepper interface that is used for this extension
1994 # pepper_name: The name of the function as exposed to pepper.
1995 # pepper_args: A string representing the argument list (what would appear in
1996 # C/C++ between the parentheses for the function declaration)
1997 # that the Pepper API expects for this function. Use this only if
1998 # the stable Pepper API differs from the GLES2 argument list.
1999 # invalid_test: False if no invalid test needed.
2000 # shadowed: True = the value is shadowed so no glGetXXX call will be made.
2001 # first_element_only: For PUT types, True if only the first element of an
2002 # array is used and we end up calling the single value
2003 # corresponding function. eg. TexParameteriv -> TexParameteri
2004 # extension: Function is an extension to GL and should not be exposed to
2005 # pepper unless pepper_interface is defined.
2006 # extension_flag: Function is an extension and should be enabled only when
2007 # the corresponding feature info flag is enabled. Implies
2008 # 'extension': True.
2009 # not_shared: For GENn types, True if objects can't be shared between contexts
2010 # unsafe: True = no validation is implemented on the service side and the
2011 # command is only available with --enable-unsafe-es3-apis.
2012 # id_mapping: A list of resource type names whose client side IDs need to be
2013 # mapped to service side IDs. This is only used for unsafe APIs.
2017 'decoder_func': 'DoActiveTexture',
2020 'client_test': False,
2022 'AttachShader': {'decoder_func': 'DoAttachShader'},
2023 'BindAttribLocation': {
2025 'data_transfer_methods': ['bucket'],
2030 'decoder_func': 'DoBindBuffer',
2031 'gen_func': 'GenBuffersARB',
2035 'id_mapping': [ 'Buffer' ],
2036 'gen_func': 'GenBuffersARB',
2039 'BindBufferRange': {
2041 'id_mapping': [ 'Buffer' ],
2042 'gen_func': 'GenBuffersARB',
2049 'BindFramebuffer': {
2051 'decoder_func': 'DoBindFramebuffer',
2052 'gl_test_func': 'glBindFramebufferEXT',
2053 'gen_func': 'GenFramebuffersEXT',
2056 'BindRenderbuffer': {
2058 'decoder_func': 'DoBindRenderbuffer',
2059 'gl_test_func': 'glBindRenderbufferEXT',
2060 'gen_func': 'GenRenderbuffersEXT',
2064 'id_mapping': [ 'Sampler' ],
2069 'decoder_func': 'DoBindTexture',
2070 'gen_func': 'GenTextures',
2071 # TODO(gman): remove this once client side caching works.
2072 'client_test': False,
2075 'BindTransformFeedback': {
2077 'id_mapping': [ 'TransformFeedback' ],
2080 'BlitFramebufferCHROMIUM': {
2081 'decoder_func': 'DoBlitFramebufferCHROMIUM',
2083 'extension_flag': 'chromium_framebuffer_multisample',
2084 'pepper_interface': 'FramebufferBlit',
2085 'pepper_name': 'BlitFramebufferEXT',
2086 'defer_reads': True,
2087 'defer_draws': True,
2092 'data_transfer_methods': ['shm'],
2093 'client_test': False,
2098 'client_test': False,
2099 'decoder_func': 'DoBufferSubData',
2100 'data_transfer_methods': ['shm'],
2103 'CheckFramebufferStatus': {
2105 'decoder_func': 'DoCheckFramebufferStatus',
2106 'gl_test_func': 'glCheckFramebufferStatusEXT',
2107 'error_value': 'GL_FRAMEBUFFER_UNSUPPORTED',
2108 'result': ['GLenum'],
2111 'decoder_func': 'DoClear',
2112 'defer_draws': True,
2117 'use_count_func': True,
2130 'use_count_func': True,
2141 'state': 'ClearColor',
2145 'state': 'ClearDepthf',
2146 'decoder_func': 'glClearDepth',
2147 'gl_test_func': 'glClearDepth',
2154 'data_transfer_methods': ['shm'],
2155 'cmd_args': 'GLuint sync, GLbitfieldSyncFlushFlags flags, '
2156 'GLuint timeout_0, GLuint timeout_1, GLenum* result',
2158 'result': ['GLenum'],
2163 'state': 'ColorMask',
2165 'expectation': False,
2167 'ConsumeTextureCHROMIUM': {
2168 'decoder_func': 'DoConsumeTextureCHROMIUM',
2171 'count': 64, # GL_MAILBOX_SIZE_CHROMIUM
2173 'client_test': False,
2174 'extension': "CHROMIUM_texture_mailbox",
2178 'CopyBufferSubData': {
2181 'CreateAndConsumeTextureCHROMIUM': {
2182 'decoder_func': 'DoCreateAndConsumeTextureCHROMIUM',
2184 'type': 'HandWritten',
2185 'data_transfer_methods': ['immediate'],
2187 'client_test': False,
2188 'extension': "CHROMIUM_texture_mailbox",
2192 'GenValuebuffersCHROMIUM': {
2194 'gl_test_func': 'glGenValuebuffersCHROMIUM',
2195 'resource_type': 'Valuebuffer',
2196 'resource_types': 'Valuebuffers',
2201 'DeleteValuebuffersCHROMIUM': {
2203 'gl_test_func': 'glDeleteValuebuffersCHROMIUM',
2204 'resource_type': 'Valuebuffer',
2205 'resource_types': 'Valuebuffers',
2210 'IsValuebufferCHROMIUM': {
2212 'decoder_func': 'DoIsValuebufferCHROMIUM',
2213 'expectation': False,
2217 'BindValuebufferCHROMIUM': {
2219 'decoder_func': 'DoBindValueBufferCHROMIUM',
2220 'gen_func': 'GenValueBuffersCHROMIUM',
2225 'SubscribeValueCHROMIUM': {
2226 'decoder_func': 'DoSubscribeValueCHROMIUM',
2231 'PopulateSubscribedValuesCHROMIUM': {
2232 'decoder_func': 'DoPopulateSubscribedValuesCHROMIUM',
2237 'UniformValuebufferCHROMIUM': {
2238 'decoder_func': 'DoUniformValueBufferCHROMIUM',
2245 'state': 'ClearStencil',
2247 'EnableFeatureCHROMIUM': {
2249 'data_transfer_methods': ['shm'],
2250 'decoder_func': 'DoEnableFeatureCHROMIUM',
2251 'expectation': False,
2252 'cmd_args': 'GLuint bucket_id, GLint* result',
2253 'result': ['GLint'],
2256 'pepper_interface': 'ChromiumEnableFeature',
2258 'CompileShader': {'decoder_func': 'DoCompileShader', 'unit_test': False},
2259 'CompressedTexImage2D': {
2261 'data_transfer_methods': ['bucket', 'shm'],
2264 'CompressedTexSubImage2D': {
2266 'data_transfer_methods': ['bucket', 'shm'],
2267 'decoder_func': 'DoCompressedTexSubImage2D',
2271 'decoder_func': 'DoCopyTexImage2D',
2273 'defer_reads': True,
2276 'CopyTexSubImage2D': {
2277 'decoder_func': 'DoCopyTexSubImage2D',
2278 'defer_reads': True,
2281 'CompressedTexImage3D': {
2283 'data_transfer_methods': ['bucket', 'shm'],
2287 'CompressedTexSubImage3D': {
2289 'data_transfer_methods': ['bucket', 'shm'],
2290 'decoder_func': 'DoCompressedTexSubImage3D',
2294 'CopyTexSubImage3D': {
2295 'defer_reads': True,
2299 'CreateImageCHROMIUM': {
2302 'ClientBuffer buffer, GLsizei width, GLsizei height, '
2303 'GLenum internalformat',
2304 'result': ['GLuint'],
2305 'client_test': False,
2307 'expectation': False,
2308 'extension': "CHROMIUM_image",
2312 'DestroyImageCHROMIUM': {
2314 'client_test': False,
2316 'extension': "CHROMIUM_image",
2320 'CreateGpuMemoryBufferImageCHROMIUM': {
2323 'GLsizei width, GLsizei height, GLenum internalformat, GLenum usage',
2324 'result': ['GLuint'],
2325 'client_test': False,
2327 'expectation': False,
2328 'extension': "CHROMIUM_image",
2334 'client_test': False,
2338 'client_test': False,
2342 'state': 'BlendColor',
2345 'type': 'StateSetRGBAlpha',
2346 'state': 'BlendEquation',
2348 '0': 'GL_FUNC_SUBTRACT'
2351 'BlendEquationSeparate': {
2353 'state': 'BlendEquation',
2355 '0': 'GL_FUNC_SUBTRACT'
2359 'type': 'StateSetRGBAlpha',
2360 'state': 'BlendFunc',
2362 'BlendFuncSeparate': {
2364 'state': 'BlendFunc',
2366 'BlendBarrierKHR': {
2367 'gl_test_func': 'glBlendBarrierKHR',
2369 'extension_flag': 'blend_equation_advanced',
2370 'client_test': False,
2372 'SampleCoverage': {'decoder_func': 'DoSampleCoverage'},
2374 'type': 'StateSetFrontBack',
2375 'state': 'StencilFunc',
2377 'StencilFuncSeparate': {
2378 'type': 'StateSetFrontBackSeparate',
2379 'state': 'StencilFunc',
2382 'type': 'StateSetFrontBack',
2383 'state': 'StencilOp',
2388 'StencilOpSeparate': {
2389 'type': 'StateSetFrontBackSeparate',
2390 'state': 'StencilOp',
2396 'type': 'StateSetNamedParameter',
2399 'CullFace': {'type': 'StateSet', 'state': 'CullFace'},
2400 'FrontFace': {'type': 'StateSet', 'state': 'FrontFace'},
2401 'DepthFunc': {'type': 'StateSet', 'state': 'DepthFunc'},
2404 'state': 'LineWidth',
2411 'state': 'PolygonOffset',
2415 'gl_test_func': 'glDeleteBuffersARB',
2416 'resource_type': 'Buffer',
2417 'resource_types': 'Buffers',
2419 'DeleteFramebuffers': {
2421 'gl_test_func': 'glDeleteFramebuffersEXT',
2422 'resource_type': 'Framebuffer',
2423 'resource_types': 'Framebuffers',
2426 'DeleteProgram': { 'type': 'Delete' },
2427 'DeleteRenderbuffers': {
2429 'gl_test_func': 'glDeleteRenderbuffersEXT',
2430 'resource_type': 'Renderbuffer',
2431 'resource_types': 'Renderbuffers',
2436 'resource_type': 'Sampler',
2437 'resource_types': 'Samplers',
2440 'DeleteShader': { 'type': 'Delete' },
2443 'cmd_args': 'GLuint sync',
2444 'resource_type': 'Sync',
2449 'resource_type': 'Texture',
2450 'resource_types': 'Textures',
2452 'DeleteTransformFeedbacks': {
2454 'resource_type': 'TransformFeedback',
2455 'resource_types': 'TransformFeedbacks',
2459 'decoder_func': 'DoDepthRangef',
2460 'gl_test_func': 'glDepthRange',
2464 'state': 'DepthMask',
2466 'expectation': False,
2468 'DetachShader': {'decoder_func': 'DoDetachShader'},
2470 'decoder_func': 'DoDisable',
2472 'client_test': False,
2474 'DisableVertexAttribArray': {
2475 'decoder_func': 'DoDisableVertexAttribArray',
2480 'cmd_args': 'GLenumDrawMode mode, GLint first, GLsizei count',
2481 'defer_draws': True,
2486 'cmd_args': 'GLenumDrawMode mode, GLsizei count, '
2487 'GLenumIndexType type, GLuint index_offset',
2488 'client_test': False,
2489 'defer_draws': True,
2492 'DrawRangeElements': {
2498 'decoder_func': 'DoEnable',
2500 'client_test': False,
2502 'EnableVertexAttribArray': {
2503 'decoder_func': 'DoEnableVertexAttribArray',
2508 'client_test': False,
2514 'client_test': False,
2515 'decoder_func': 'DoFinish',
2516 'defer_reads': True,
2521 'decoder_func': 'DoFlush',
2524 'FramebufferRenderbuffer': {
2525 'decoder_func': 'DoFramebufferRenderbuffer',
2526 'gl_test_func': 'glFramebufferRenderbufferEXT',
2529 'FramebufferTexture2D': {
2530 'decoder_func': 'DoFramebufferTexture2D',
2531 'gl_test_func': 'glFramebufferTexture2DEXT',
2534 'FramebufferTexture2DMultisampleEXT': {
2535 'decoder_func': 'DoFramebufferTexture2DMultisample',
2536 'gl_test_func': 'glFramebufferTexture2DMultisampleEXT',
2537 'expectation': False,
2539 'extension_flag': 'multisampled_render_to_texture',
2542 'FramebufferTextureLayer': {
2543 'decoder_func': 'DoFramebufferTextureLayer',
2548 'decoder_func': 'DoGenerateMipmap',
2549 'gl_test_func': 'glGenerateMipmapEXT',
2554 'gl_test_func': 'glGenBuffersARB',
2555 'resource_type': 'Buffer',
2556 'resource_types': 'Buffers',
2558 'GenMailboxCHROMIUM': {
2559 'type': 'HandWritten',
2561 'extension': "CHROMIUM_texture_mailbox",
2564 'GenFramebuffers': {
2566 'gl_test_func': 'glGenFramebuffersEXT',
2567 'resource_type': 'Framebuffer',
2568 'resource_types': 'Framebuffers',
2570 'GenRenderbuffers': {
2571 'type': 'GENn', 'gl_test_func': 'glGenRenderbuffersEXT',
2572 'resource_type': 'Renderbuffer',
2573 'resource_types': 'Renderbuffers',
2577 'gl_test_func': 'glGenSamplers',
2578 'resource_type': 'Sampler',
2579 'resource_types': 'Samplers',
2584 'gl_test_func': 'glGenTextures',
2585 'resource_type': 'Texture',
2586 'resource_types': 'Textures',
2588 'GenTransformFeedbacks': {
2590 'gl_test_func': 'glGenTransformFeedbacks',
2591 'resource_type': 'TransformFeedback',
2592 'resource_types': 'TransformFeedbacks',
2595 'GetActiveAttrib': {
2597 'data_transfer_methods': ['shm'],
2599 'GLidProgram program, GLuint index, uint32_t name_bucket_id, '
2607 'GetActiveUniform': {
2609 'data_transfer_methods': ['shm'],
2611 'GLidProgram program, GLuint index, uint32_t name_bucket_id, '
2619 'GetActiveUniformBlockiv': {
2621 'data_transfer_methods': ['shm'],
2622 'result': ['SizedResult<GLint>'],
2625 'GetActiveUniformBlockName': {
2627 'data_transfer_methods': ['shm'],
2629 'GLidProgram program, GLuint index, uint32_t name_bucket_id, '
2631 'result': ['int32_t'],
2634 'GetActiveUniformsiv': {
2636 'data_transfer_methods': ['shm'],
2638 'GLidProgram program, uint32_t indices_bucket_id, GLenum pname, '
2640 'result': ['SizedResult<GLint>'],
2643 'GetAttachedShaders': {
2645 'data_transfer_methods': ['shm'],
2646 'cmd_args': 'GLidProgram program, void* result, uint32_t result_size',
2647 'result': ['SizedResult<GLuint>'],
2649 'GetAttribLocation': {
2651 'data_transfer_methods': ['shm'],
2653 'GLidProgram program, uint32_t name_bucket_id, GLint* location',
2654 'result': ['GLint'],
2657 'GetFragDataLocation': {
2659 'data_transfer_methods': ['shm'],
2661 'GLidProgram program, uint32_t name_bucket_id, GLint* location',
2662 'result': ['GLint'],
2668 'result': ['SizedResult<GLboolean>'],
2669 'decoder_func': 'DoGetBooleanv',
2670 'gl_test_func': 'glGetBooleanv',
2672 'GetBufferParameteriv': {
2674 'result': ['SizedResult<GLint>'],
2675 'decoder_func': 'DoGetBufferParameteriv',
2676 'expectation': False,
2681 'decoder_func': 'GetErrorState()->GetGLError',
2683 'result': ['GLenum'],
2684 'client_test': False,
2688 'result': ['SizedResult<GLfloat>'],
2689 'decoder_func': 'DoGetFloatv',
2690 'gl_test_func': 'glGetFloatv',
2692 'GetFramebufferAttachmentParameteriv': {
2694 'decoder_func': 'DoGetFramebufferAttachmentParameteriv',
2695 'gl_test_func': 'glGetFramebufferAttachmentParameterivEXT',
2696 'result': ['SizedResult<GLint>'],
2698 'GetGraphicsResetStatusKHR': {
2700 'client_test': False,
2706 'result': ['SizedResult<GLint64>'],
2707 'client_test': False,
2708 'decoder_func': 'DoGetInteger64v',
2713 'result': ['SizedResult<GLint>'],
2714 'decoder_func': 'DoGetIntegerv',
2715 'client_test': False,
2717 'GetInteger64i_v': {
2719 'result': ['SizedResult<GLint64>'],
2720 'client_test': False,
2725 'result': ['SizedResult<GLint>'],
2726 'client_test': False,
2729 'GetInternalformativ': {
2731 'data_transfer_methods': ['shm'],
2732 'result': ['SizedResult<GLint>'],
2734 'GLenumRenderBufferTarget target, GLenumRenderBufferFormat format, '
2735 'GLenumInternalFormatParameter pname, GLint* params',
2738 'GetMaxValueInBufferCHROMIUM': {
2740 'decoder_func': 'DoGetMaxValueInBufferCHROMIUM',
2741 'result': ['GLuint'],
2743 'client_test': False,
2750 'decoder_func': 'DoGetProgramiv',
2751 'result': ['SizedResult<GLint>'],
2752 'expectation': False,
2754 'GetProgramInfoCHROMIUM': {
2756 'expectation': False,
2760 'client_test': False,
2761 'cmd_args': 'GLidProgram program, uint32_t bucket_id',
2763 'uint32_t link_status',
2764 'uint32_t num_attribs',
2765 'uint32_t num_uniforms',
2768 'GetProgramInfoLog': {
2770 'expectation': False,
2772 'GetRenderbufferParameteriv': {
2774 'decoder_func': 'DoGetRenderbufferParameteriv',
2775 'gl_test_func': 'glGetRenderbufferParameterivEXT',
2776 'result': ['SizedResult<GLint>'],
2778 'GetSamplerParameterfv': {
2780 'result': ['SizedResult<GLfloat>'],
2781 'id_mapping': [ 'Sampler' ],
2784 'GetSamplerParameteriv': {
2786 'result': ['SizedResult<GLint>'],
2787 'id_mapping': [ 'Sampler' ],
2792 'decoder_func': 'DoGetShaderiv',
2793 'result': ['SizedResult<GLint>'],
2795 'GetShaderInfoLog': {
2797 'get_len_func': 'glGetShaderiv',
2798 'get_len_enum': 'GL_INFO_LOG_LENGTH',
2801 'GetShaderPrecisionFormat': {
2803 'data_transfer_methods': ['shm'],
2805 'GLenumShaderType shadertype, GLenumShaderPrecision precisiontype, '
2809 'int32_t min_range',
2810 'int32_t max_range',
2811 'int32_t precision',
2814 'GetShaderSource': {
2816 'get_len_func': 'DoGetShaderiv',
2817 'get_len_enum': 'GL_SHADER_SOURCE_LENGTH',
2819 'client_test': False,
2823 'client_test': False,
2824 'cmd_args': 'GLenumStringType name, uint32_t bucket_id',
2828 'cmd_args': 'GLuint sync, GLenumSyncParameter pname, void* values',
2829 'result': ['SizedResult<GLint>'],
2830 'id_mapping': ['Sync'],
2833 'GetTexParameterfv': {
2835 'decoder_func': 'DoGetTexParameterfv',
2836 'result': ['SizedResult<GLfloat>']
2838 'GetTexParameteriv': {
2840 'decoder_func': 'DoGetTexParameteriv',
2841 'result': ['SizedResult<GLint>']
2843 'GetTranslatedShaderSourceANGLE': {
2845 'get_len_func': 'DoGetShaderiv',
2846 'get_len_enum': 'GL_TRANSLATED_SHADER_SOURCE_LENGTH_ANGLE',
2850 'GetUniformBlockIndex': {
2852 'data_transfer_methods': ['shm'],
2854 'GLidProgram program, uint32_t name_bucket_id, GLuint* index',
2855 'result': ['GLuint'],
2856 'error_return': 'GL_INVALID_INDEX',
2859 'GetUniformBlocksCHROMIUM': {
2861 'expectation': False,
2865 'client_test': False,
2866 'cmd_args': 'GLidProgram program, uint32_t bucket_id',
2867 'result': ['uint32_t'],
2870 'GetUniformsES3CHROMIUM': {
2872 'expectation': False,
2876 'client_test': False,
2877 'cmd_args': 'GLidProgram program, uint32_t bucket_id',
2878 'result': ['uint32_t'],
2881 'GetTransformFeedbackVarying': {
2883 'data_transfer_methods': ['shm'],
2885 'GLidProgram program, GLuint index, uint32_t name_bucket_id, '
2894 'GetTransformFeedbackVaryingsCHROMIUM': {
2896 'expectation': False,
2900 'client_test': False,
2901 'cmd_args': 'GLidProgram program, uint32_t bucket_id',
2902 'result': ['uint32_t'],
2907 'data_transfer_methods': ['shm'],
2908 'result': ['SizedResult<GLfloat>'],
2912 'data_transfer_methods': ['shm'],
2913 'result': ['SizedResult<GLint>'],
2917 'data_transfer_methods': ['shm'],
2918 'result': ['SizedResult<GLuint>'],
2921 'GetUniformIndices': {
2923 'data_transfer_methods': ['shm'],
2924 'result': ['SizedResult<GLuint>'],
2925 'cmd_args': 'GLidProgram program, uint32_t names_bucket_id, '
2929 'GetUniformLocation': {
2931 'data_transfer_methods': ['shm'],
2933 'GLidProgram program, uint32_t name_bucket_id, GLint* location',
2934 'result': ['GLint'],
2935 'error_return': -1, # http://www.opengl.org/sdk/docs/man/xhtml/glGetUniformLocation.xml
2937 'GetVertexAttribfv': {
2939 'result': ['SizedResult<GLfloat>'],
2941 'decoder_func': 'DoGetVertexAttribfv',
2942 'expectation': False,
2943 'client_test': False,
2945 'GetVertexAttribiv': {
2947 'result': ['SizedResult<GLint>'],
2949 'decoder_func': 'DoGetVertexAttribiv',
2950 'expectation': False,
2951 'client_test': False,
2953 'GetVertexAttribIiv': {
2955 'result': ['SizedResult<GLint>'],
2957 'decoder_func': 'DoGetVertexAttribIiv',
2958 'expectation': False,
2959 'client_test': False,
2962 'GetVertexAttribIuiv': {
2964 'result': ['SizedResult<GLuint>'],
2966 'decoder_func': 'DoGetVertexAttribIuiv',
2967 'expectation': False,
2968 'client_test': False,
2971 'GetVertexAttribPointerv': {
2973 'data_transfer_methods': ['shm'],
2974 'result': ['SizedResult<GLuint>'],
2975 'client_test': False,
2977 'InvalidateFramebuffer': {
2980 'client_test': False,
2984 'InvalidateSubFramebuffer': {
2987 'client_test': False,
2993 'decoder_func': 'DoIsBuffer',
2994 'expectation': False,
2998 'decoder_func': 'DoIsEnabled',
2999 'client_test': False,
3001 'expectation': False,
3005 'decoder_func': 'DoIsFramebuffer',
3006 'expectation': False,
3010 'decoder_func': 'DoIsProgram',
3011 'expectation': False,
3015 'decoder_func': 'DoIsRenderbuffer',
3016 'expectation': False,
3020 'decoder_func': 'DoIsShader',
3021 'expectation': False,
3025 'id_mapping': [ 'Sampler' ],
3026 'expectation': False,
3031 'id_mapping': [ 'Sync' ],
3032 'cmd_args': 'GLuint sync',
3033 'expectation': False,
3038 'decoder_func': 'DoIsTexture',
3039 'expectation': False,
3041 'IsTransformFeedback': {
3043 'id_mapping': [ 'TransformFeedback' ],
3044 'expectation': False,
3048 'decoder_func': 'DoLinkProgram',
3052 'MapBufferCHROMIUM': {
3054 'extension': "CHROMIUM_pixel_transfer_buffer_object",
3056 'client_test': False,
3059 'MapBufferSubDataCHROMIUM': {
3063 'client_test': False,
3064 'pepper_interface': 'ChromiumMapSub',
3067 'MapTexSubImage2DCHROMIUM': {
3069 'extension': "CHROMIUM_sub_image",
3071 'client_test': False,
3072 'pepper_interface': 'ChromiumMapSub',
3077 'data_transfer_methods': ['shm'],
3078 'cmd_args': 'GLenumBufferTarget target, GLintptrNotNegative offset, '
3079 'GLsizeiptr size, GLbitfieldMapBufferAccess access, '
3080 'uint32_t data_shm_id, uint32_t data_shm_offset, '
3081 'uint32_t result_shm_id, uint32_t result_shm_offset',
3083 'result': ['uint32_t'],
3086 'PauseTransformFeedback': {
3089 'PixelStorei': {'type': 'Manual'},
3090 'PostSubBufferCHROMIUM': {
3094 'client_test': False,
3098 'ProduceTextureCHROMIUM': {
3099 'decoder_func': 'DoProduceTextureCHROMIUM',
3102 'count': 64, # GL_MAILBOX_SIZE_CHROMIUM
3104 'client_test': False,
3105 'extension': "CHROMIUM_texture_mailbox",
3109 'ProduceTextureDirectCHROMIUM': {
3110 'decoder_func': 'DoProduceTextureDirectCHROMIUM',
3113 'count': 64, # GL_MAILBOX_SIZE_CHROMIUM
3115 'client_test': False,
3116 'extension': "CHROMIUM_texture_mailbox",
3120 'RenderbufferStorage': {
3121 'decoder_func': 'DoRenderbufferStorage',
3122 'gl_test_func': 'glRenderbufferStorageEXT',
3123 'expectation': False,
3126 'RenderbufferStorageMultisampleCHROMIUM': {
3128 '// GL_CHROMIUM_framebuffer_multisample\n',
3129 'decoder_func': 'DoRenderbufferStorageMultisampleCHROMIUM',
3130 'gl_test_func': 'glRenderbufferStorageMultisampleCHROMIUM',
3131 'expectation': False,
3133 'extension_flag': 'chromium_framebuffer_multisample',
3134 'pepper_interface': 'FramebufferMultisample',
3135 'pepper_name': 'RenderbufferStorageMultisampleEXT',
3138 'RenderbufferStorageMultisampleEXT': {
3140 '// GL_EXT_multisampled_render_to_texture\n',
3141 'decoder_func': 'DoRenderbufferStorageMultisampleEXT',
3142 'gl_test_func': 'glRenderbufferStorageMultisampleEXT',
3143 'expectation': False,
3145 'extension_flag': 'multisampled_render_to_texture',
3154 '// ReadPixels has the result separated from the pixel buffer so that\n'
3155 '// it is easier to specify the result going to some specific place\n'
3156 '// that exactly fits the rectangle of pixels.\n',
3158 'data_transfer_methods': ['shm'],
3160 'client_test': False,
3162 'GLint x, GLint y, GLsizei width, GLsizei height, '
3163 'GLenumReadPixelFormat format, GLenumReadPixelType type, '
3164 'uint32_t pixels_shm_id, uint32_t pixels_shm_offset, '
3165 'uint32_t result_shm_id, uint32_t result_shm_offset, '
3167 'result': ['uint32_t'],
3168 'defer_reads': True,
3171 'ReleaseShaderCompiler': {
3172 'decoder_func': 'DoReleaseShaderCompiler',
3175 'ResumeTransformFeedback': {
3178 'SamplerParameterf': {
3182 'id_mapping': [ 'Sampler' ],
3185 'SamplerParameterfv': {
3187 'data_value': 'GL_NEAREST',
3189 'gl_test_func': 'glSamplerParameterf',
3190 'decoder_func': 'DoSamplerParameterfv',
3191 'first_element_only': True,
3192 'id_mapping': [ 'Sampler' ],
3195 'SamplerParameteri': {
3199 'id_mapping': [ 'Sampler' ],
3202 'SamplerParameteriv': {
3204 'data_value': 'GL_NEAREST',
3206 'gl_test_func': 'glSamplerParameteri',
3207 'decoder_func': 'DoSamplerParameteriv',
3208 'first_element_only': True,
3213 'client_test': False,
3217 'decoder_func': 'DoShaderSource',
3218 'expectation': False,
3219 'data_transfer_methods': ['bucket'],
3221 'GLuint shader, const char** str',
3223 'GLuint shader, GLsizei count, const char** str, const GLint* length',
3226 'type': 'StateSetFrontBack',
3227 'state': 'StencilMask',
3229 'expectation': False,
3231 'StencilMaskSeparate': {
3232 'type': 'StateSetFrontBackSeparate',
3233 'state': 'StencilMask',
3235 'expectation': False,
3239 'decoder_func': 'DoSwapBuffers',
3241 'client_test': False,
3247 'decoder_func': 'DoSwapInterval',
3249 'client_test': False,
3255 'data_transfer_methods': ['shm'],
3256 'client_test': False,
3261 'data_transfer_methods': ['shm'],
3262 'client_test': False,
3267 'decoder_func': 'DoTexParameterf',
3273 'decoder_func': 'DoTexParameteri',
3280 'data_value': 'GL_NEAREST',
3282 'decoder_func': 'DoTexParameterfv',
3283 'gl_test_func': 'glTexParameterf',
3284 'first_element_only': True,
3288 'data_value': 'GL_NEAREST',
3290 'decoder_func': 'DoTexParameteriv',
3291 'gl_test_func': 'glTexParameteri',
3292 'first_element_only': True,
3300 'data_transfer_methods': ['shm'],
3301 'client_test': False,
3303 'cmd_args': 'GLenumTextureTarget target, GLint level, '
3304 'GLint xoffset, GLint yoffset, '
3305 'GLsizei width, GLsizei height, '
3306 'GLenumTextureFormat format, GLenumPixelType type, '
3307 'const void* pixels, GLboolean internal'
3311 'data_transfer_methods': ['shm'],
3312 'client_test': False,
3314 'cmd_args': 'GLenumTextureTarget target, GLint level, '
3315 'GLint xoffset, GLint yoffset, GLint zoffset, '
3316 'GLsizei width, GLsizei height, GLsizei depth, '
3317 'GLenumTextureFormat format, GLenumPixelType type, '
3318 'const void* pixels, GLboolean internal',
3321 'TransformFeedbackVaryings': {
3323 'data_transfer_methods': ['bucket'],
3324 'decoder_func': 'DoTransformFeedbackVaryings',
3326 'GLuint program, const char** varyings, GLenum buffermode',
3329 'Uniform1f': {'type': 'PUTXn', 'count': 1},
3333 'decoder_func': 'DoUniform1fv',
3335 'Uniform1i': {'decoder_func': 'DoUniform1i', 'unit_test': False},
3339 'decoder_func': 'DoUniform1iv',
3352 'Uniform2i': {'type': 'PUTXn', 'count': 2},
3353 'Uniform2f': {'type': 'PUTXn', 'count': 2},
3357 'decoder_func': 'DoUniform2fv',
3362 'decoder_func': 'DoUniform2iv',
3374 'Uniform3i': {'type': 'PUTXn', 'count': 3},
3375 'Uniform3f': {'type': 'PUTXn', 'count': 3},
3379 'decoder_func': 'DoUniform3fv',
3384 'decoder_func': 'DoUniform3iv',
3396 'Uniform4i': {'type': 'PUTXn', 'count': 4},
3397 'Uniform4f': {'type': 'PUTXn', 'count': 4},
3401 'decoder_func': 'DoUniform4fv',
3406 'decoder_func': 'DoUniform4iv',
3418 'UniformMatrix2fv': {
3421 'decoder_func': 'DoUniformMatrix2fv',
3423 'UniformMatrix2x3fv': {
3428 'UniformMatrix2x4fv': {
3433 'UniformMatrix3fv': {
3436 'decoder_func': 'DoUniformMatrix3fv',
3438 'UniformMatrix3x2fv': {
3443 'UniformMatrix3x4fv': {
3448 'UniformMatrix4fv': {
3451 'decoder_func': 'DoUniformMatrix4fv',
3453 'UniformMatrix4x2fv': {
3458 'UniformMatrix4x3fv': {
3463 'UniformBlockBinding': {
3468 'UnmapBufferCHROMIUM': {
3470 'extension': "CHROMIUM_pixel_transfer_buffer_object",
3472 'client_test': False,
3475 'UnmapBufferSubDataCHROMIUM': {
3479 'client_test': False,
3480 'pepper_interface': 'ChromiumMapSub',
3488 'UnmapTexSubImage2DCHROMIUM': {
3490 'extension': "CHROMIUM_sub_image",
3492 'client_test': False,
3493 'pepper_interface': 'ChromiumMapSub',
3498 'decoder_func': 'DoUseProgram',
3500 'ValidateProgram': {'decoder_func': 'DoValidateProgram'},
3501 'VertexAttrib1f': {'decoder_func': 'DoVertexAttrib1f'},
3502 'VertexAttrib1fv': {
3505 'decoder_func': 'DoVertexAttrib1fv',
3507 'VertexAttrib2f': {'decoder_func': 'DoVertexAttrib2f'},
3508 'VertexAttrib2fv': {
3511 'decoder_func': 'DoVertexAttrib2fv',
3513 'VertexAttrib3f': {'decoder_func': 'DoVertexAttrib3f'},
3514 'VertexAttrib3fv': {
3517 'decoder_func': 'DoVertexAttrib3fv',
3519 'VertexAttrib4f': {'decoder_func': 'DoVertexAttrib4f'},
3520 'VertexAttrib4fv': {
3523 'decoder_func': 'DoVertexAttrib4fv',
3525 'VertexAttribI4i': {
3527 'decoder_func': 'DoVertexAttribI4i',
3529 'VertexAttribI4iv': {
3533 'decoder_func': 'DoVertexAttribI4iv',
3535 'VertexAttribI4ui': {
3537 'decoder_func': 'DoVertexAttribI4ui',
3539 'VertexAttribI4uiv': {
3543 'decoder_func': 'DoVertexAttribI4uiv',
3545 'VertexAttribIPointer': {
3547 'cmd_args': 'GLuint indx, GLintVertexAttribSize size, '
3548 'GLenumVertexAttribIType type, GLsizei stride, '
3550 'client_test': False,
3553 'VertexAttribPointer': {
3555 'cmd_args': 'GLuint indx, GLintVertexAttribSize size, '
3556 'GLenumVertexAttribType type, GLboolean normalized, '
3557 'GLsizei stride, GLuint offset',
3558 'client_test': False,
3562 'cmd_args': 'GLuint sync, GLbitfieldSyncFlushFlags flags, '
3563 'GLuint timeout_0, GLuint timeout_1',
3565 'client_test': False,
3574 'decoder_func': 'DoViewport',
3584 'GetRequestableExtensionsCHROMIUM': {
3587 'cmd_args': 'uint32_t bucket_id',
3591 'RequestExtensionCHROMIUM': {
3594 'client_test': False,
3595 'cmd_args': 'uint32_t bucket_id',
3599 'RateLimitOffscreenContextCHROMIUM': {
3603 'client_test': False,
3605 'CreateStreamTextureCHROMIUM': {
3606 'type': 'HandWritten',
3613 'TexImageIOSurface2DCHROMIUM': {
3614 'decoder_func': 'DoTexImageIOSurface2DCHROMIUM',
3620 'CopyTextureCHROMIUM': {
3621 'decoder_func': 'DoCopyTextureCHROMIUM',
3623 'extension': "CHROMIUM_copy_texture",
3627 'CopySubTextureCHROMIUM': {
3628 'decoder_func': 'DoCopySubTextureCHROMIUM',
3630 'extension': "CHROMIUM_copy_texture",
3634 'CompressedCopyTextureCHROMIUM': {
3635 'decoder_func': 'DoCompressedCopyTextureCHROMIUM',
3640 'TexStorage2DEXT': {
3643 'decoder_func': 'DoTexStorage2DEXT',
3646 'DrawArraysInstancedANGLE': {
3648 'cmd_args': 'GLenumDrawMode mode, GLint first, GLsizei count, '
3649 'GLsizei primcount',
3652 'pepper_interface': 'InstancedArrays',
3653 'defer_draws': True,
3658 'decoder_func': 'DoDrawBuffersEXT',
3660 'client_test': False,
3662 # could use 'extension_flag': 'ext_draw_buffers' but currently expected to
3665 'pepper_interface': 'DrawBuffers',
3668 'DrawElementsInstancedANGLE': {
3670 'cmd_args': 'GLenumDrawMode mode, GLsizei count, '
3671 'GLenumIndexType type, GLuint index_offset, GLsizei primcount',
3674 'client_test': False,
3675 'pepper_interface': 'InstancedArrays',
3676 'defer_draws': True,
3679 'VertexAttribDivisorANGLE': {
3681 'cmd_args': 'GLuint index, GLuint divisor',
3684 'pepper_interface': 'InstancedArrays',
3688 'gl_test_func': 'glGenQueriesARB',
3689 'resource_type': 'Query',
3690 'resource_types': 'Queries',
3692 'pepper_interface': 'Query',
3693 'not_shared': 'True',
3694 'extension': "occlusion_query_EXT",
3696 'DeleteQueriesEXT': {
3698 'gl_test_func': 'glDeleteQueriesARB',
3699 'resource_type': 'Query',
3700 'resource_types': 'Queries',
3702 'pepper_interface': 'Query',
3703 'extension': "occlusion_query_EXT",
3707 'client_test': False,
3708 'pepper_interface': 'Query',
3709 'extension': "occlusion_query_EXT",
3713 'cmd_args': 'GLenumQueryTarget target, GLidQuery id, void* sync_data',
3714 'data_transfer_methods': ['shm'],
3715 'gl_test_func': 'glBeginQuery',
3716 'pepper_interface': 'Query',
3717 'extension': "occlusion_query_EXT",
3719 'BeginTransformFeedback': {
3724 'cmd_args': 'GLenumQueryTarget target, GLuint submit_count',
3725 'gl_test_func': 'glEndnQuery',
3726 'client_test': False,
3727 'pepper_interface': 'Query',
3728 'extension': "occlusion_query_EXT",
3730 'EndTransformFeedback': {
3735 'client_test': False,
3736 'gl_test_func': 'glGetQueryiv',
3737 'pepper_interface': 'Query',
3738 'extension': "occlusion_query_EXT",
3740 'GetQueryObjectuivEXT': {
3742 'client_test': False,
3743 'gl_test_func': 'glGetQueryObjectuiv',
3744 'pepper_interface': 'Query',
3745 'extension': "occlusion_query_EXT",
3747 'GetQueryObjectui64vEXT': {
3749 'client_test': False,
3750 'gl_test_func': 'glGetQueryObjectui64v',
3751 'extension': "disjoint_timer_query_EXT",
3753 'BindUniformLocationCHROMIUM': {
3756 'data_transfer_methods': ['bucket'],
3758 'gl_test_func': 'DoBindUniformLocationCHROMIUM',
3760 'InsertEventMarkerEXT': {
3762 'decoder_func': 'DoInsertEventMarkerEXT',
3763 'expectation': False,
3766 'PushGroupMarkerEXT': {
3768 'decoder_func': 'DoPushGroupMarkerEXT',
3769 'expectation': False,
3772 'PopGroupMarkerEXT': {
3773 'decoder_func': 'DoPopGroupMarkerEXT',
3774 'expectation': False,
3779 'GenVertexArraysOES': {
3782 'gl_test_func': 'glGenVertexArraysOES',
3783 'resource_type': 'VertexArray',
3784 'resource_types': 'VertexArrays',
3786 'pepper_interface': 'VertexArrayObject',
3788 'BindVertexArrayOES': {
3791 'gl_test_func': 'glBindVertexArrayOES',
3792 'decoder_func': 'DoBindVertexArrayOES',
3793 'gen_func': 'GenVertexArraysOES',
3795 'client_test': False,
3796 'pepper_interface': 'VertexArrayObject',
3798 'DeleteVertexArraysOES': {
3801 'gl_test_func': 'glDeleteVertexArraysOES',
3802 'resource_type': 'VertexArray',
3803 'resource_types': 'VertexArrays',
3805 'pepper_interface': 'VertexArrayObject',
3807 'IsVertexArrayOES': {
3810 'gl_test_func': 'glIsVertexArrayOES',
3811 'decoder_func': 'DoIsVertexArrayOES',
3812 'expectation': False,
3814 'pepper_interface': 'VertexArrayObject',
3816 'BindTexImage2DCHROMIUM': {
3817 'decoder_func': 'DoBindTexImage2DCHROMIUM',
3819 'extension': "CHROMIUM_image",
3822 'ReleaseTexImage2DCHROMIUM': {
3823 'decoder_func': 'DoReleaseTexImage2DCHROMIUM',
3825 'extension': "CHROMIUM_image",
3828 'ShallowFinishCHROMIUM': {
3833 'client_test': False,
3835 'ShallowFlushCHROMIUM': {
3838 'extension': "CHROMIUM_miscellaneous",
3840 'client_test': False,
3842 'OrderingBarrierCHROMIUM': {
3847 'client_test': False,
3849 'TraceBeginCHROMIUM': {
3852 'client_test': False,
3853 'cmd_args': 'GLuint category_bucket_id, GLuint name_bucket_id',
3857 'TraceEndCHROMIUM': {
3859 'client_test': False,
3860 'decoder_func': 'DoTraceEndCHROMIUM',
3865 'AsyncTexImage2DCHROMIUM': {
3867 'data_transfer_methods': ['shm'],
3868 'client_test': False,
3869 'cmd_args': 'GLenumTextureTarget target, GLint level, '
3870 'GLintTextureInternalFormat internalformat, '
3871 'GLsizei width, GLsizei height, '
3872 'GLintTextureBorder border, '
3873 'GLenumTextureFormat format, GLenumPixelType type, '
3874 'const void* pixels, '
3875 'uint32_t async_upload_token, '
3881 'AsyncTexSubImage2DCHROMIUM': {
3883 'data_transfer_methods': ['shm'],
3884 'client_test': False,
3885 'cmd_args': 'GLenumTextureTarget target, GLint level, '
3886 'GLint xoffset, GLint yoffset, '
3887 'GLsizei width, GLsizei height, '
3888 'GLenumTextureFormat format, GLenumPixelType type, '
3889 'const void* data, '
3890 'uint32_t async_upload_token, '
3896 'WaitAsyncTexImage2DCHROMIUM': {
3898 'client_test': False,
3903 'WaitAllAsyncTexImage2DCHROMIUM': {
3905 'client_test': False,
3910 'DiscardFramebufferEXT': {
3913 'decoder_func': 'DoDiscardFramebufferEXT',
3915 'client_test': False,
3916 'extension_flag': 'ext_discard_framebuffer',
3919 'LoseContextCHROMIUM': {
3920 'decoder_func': 'DoLoseContextCHROMIUM',
3926 'InsertSyncPointCHROMIUM': {
3927 'type': 'HandWritten',
3929 'extension': "CHROMIUM_sync_point",
3933 'WaitSyncPointCHROMIUM': {
3936 'extension': "CHROMIUM_sync_point",
3940 'DiscardBackbufferCHROMIUM': {
3947 'ScheduleOverlayPlaneCHROMIUM': {
3951 'client_test': False,
3955 'MatrixLoadfCHROMIUM': {
3958 'data_type': 'GLfloat',
3959 'decoder_func': 'DoMatrixLoadfCHROMIUM',
3960 'gl_test_func': 'glMatrixLoadfEXT',
3963 'extension_flag': 'chromium_path_rendering',
3965 'MatrixLoadIdentityCHROMIUM': {
3966 'decoder_func': 'DoMatrixLoadIdentityCHROMIUM',
3967 'gl_test_func': 'glMatrixLoadIdentityEXT',
3970 'extension_flag': 'chromium_path_rendering',
3975 def Grouper(n
, iterable
, fillvalue
=None):
3976 """Collect data into fixed-length chunks or blocks"""
3977 args
= [iter(iterable
)] * n
3978 return itertools
.izip_longest(fillvalue
=fillvalue
, *args
)
3981 def SplitWords(input_string
):
3982 """Split by '_' if found, otherwise split at uppercase/numeric chars.
3984 Will split "some_TEXT" into ["some", "TEXT"], "CamelCase" into ["Camel",
3985 "Case"], and "Vector3" into ["Vector", "3"].
3987 if input_string
.find('_') > -1:
3988 # 'some_TEXT_' -> 'some TEXT'
3989 return input_string
.replace('_', ' ').strip().split()
3991 if re
.search('[A-Z]', input_string
) and re
.search('[a-z]', input_string
):
3993 # look for capitalization to cut input_strings
3994 # 'SomeText' -> 'Some Text'
3995 input_string
= re
.sub('([A-Z])', r
' \1', input_string
).strip()
3996 # 'Vector3' -> 'Vector 3'
3997 input_string
= re
.sub('([^0-9])([0-9])', r
'\1 \2', input_string
)
3998 return input_string
.split()
4000 def ToUnderscore(input_string
):
4001 """converts CamelCase to camel_case."""
4002 words
= SplitWords(input_string
)
4003 return '_'.join([word
.lower() for word
in words
])
4005 def CachedStateName(item
):
4006 if item
.get('cached', False):
4007 return 'cached_' + item
['name']
4010 def ToGLExtensionString(extension_flag
):
4011 """Returns GL-type extension string of a extension flag."""
4012 if extension_flag
== "oes_compressed_etc1_rgb8_texture":
4013 return "OES_compressed_ETC1_RGB8_texture" # Fixup inconsitency with rgb8,
4015 uppercase_words
= [ 'img', 'ext', 'arb', 'chromium', 'oes', 'amd', 'bgra8888',
4016 'egl', 'atc', 'etc1', 'angle']
4017 parts
= extension_flag
.split('_')
4019 [part
.upper() if part
in uppercase_words
else part
for part
in parts
])
4021 def ToCamelCase(input_string
):
4022 """converts ABC_underscore_case to ABCUnderscoreCase."""
4023 return ''.join(w
[0].upper() + w
[1:] for w
in input_string
.split('_'))
4025 def GetGLGetTypeConversion(result_type
, value_type
, value
):
4026 """Makes a gl compatible type conversion string for accessing state variables.
4028 Useful when accessing state variables through glGetXXX calls.
4029 glGet documetation (for example, the manual pages):
4030 [...] If glGetIntegerv is called, [...] most floating-point values are
4031 rounded to the nearest integer value. [...]
4034 result_type: the gl type to be obtained
4035 value_type: the GL type of the state variable
4036 value: the name of the state variable
4039 String that converts the state variable to desired GL type according to GL
4043 if result_type
== 'GLint':
4044 if value_type
== 'GLfloat':
4045 return 'static_cast<GLint>(round(%s))' % value
4046 return 'static_cast<%s>(%s)' % (result_type
, value
)
4048 class CWriter(object):
4049 """Writes to a file formatting it for Google's style guidelines."""
4051 def __init__(self
, filename
):
4052 self
.filename
= filename
4055 def Write(self
, string
):
4056 """Writes a string to a file spliting if it's > 80 characters."""
4057 lines
= string
.splitlines()
4058 num_lines
= len(lines
)
4059 for ii
in range(0, num_lines
):
4060 self
.content
.append(lines
[ii
])
4061 if ii
< (num_lines
- 1) or string
[-1] == '\n':
4062 self
.content
.append('\n')
4065 """Close the file."""
4066 content
= "".join(self
.content
)
4068 if os
.path
.exists(self
.filename
):
4069 old_file
= open(self
.filename
, "rb");
4070 old_content
= old_file
.read()
4072 if content
== old_content
:
4075 file = open(self
.filename
, "wb")
4080 class CHeaderWriter(CWriter
):
4081 """Writes a C Header file."""
4083 _non_alnum_re
= re
.compile(r
'[^a-zA-Z0-9]')
4085 def __init__(self
, filename
, file_comment
= None):
4086 CWriter
.__init
__(self
, filename
)
4088 base
= os
.path
.abspath(filename
)
4089 while os
.path
.basename(base
) != 'src':
4090 new_base
= os
.path
.dirname(base
)
4091 assert new_base
!= base
# Prevent infinite loop.
4094 hpath
= os
.path
.relpath(filename
, base
)
4095 self
.guard
= self
._non
_alnum
_re
.sub('_', hpath
).upper() + '_'
4097 self
.Write(_LICENSE
)
4098 self
.Write(_DO_NOT_EDIT_WARNING
)
4099 if not file_comment
== None:
4100 self
.Write(file_comment
)
4101 self
.Write("#ifndef %s\n" % self
.guard
)
4102 self
.Write("#define %s\n\n" % self
.guard
)
4105 self
.Write("#endif // %s\n\n" % self
.guard
)
4108 class TypeHandler(object):
4109 """This class emits code for a particular type of function."""
4111 _remove_expected_call_re
= re
.compile(r
' EXPECT_CALL.*?;\n', re
.S
)
4116 def InitFunction(self
, func
):
4117 """Add or adjust anything type specific for this function."""
4118 if func
.GetInfo('needs_size') and not func
.name
.endswith('Bucket'):
4119 func
.AddCmdArg(DataSizeArgument('data_size'))
4121 def NeedsDataTransferFunction(self
, func
):
4122 """Overriden from TypeHandler."""
4123 return func
.num_pointer_args
>= 1
4125 def WriteStruct(self
, func
, file):
4126 """Writes a structure that matches the arguments to a function."""
4127 comment
= func
.GetInfo('cmd_comment')
4128 if not comment
== None:
4130 file.Write("struct %s {\n" % func
.name
)
4131 file.Write(" typedef %s ValueType;\n" % func
.name
)
4132 file.Write(" static const CommandId kCmdId = k%s;\n" % func
.name
)
4133 func
.WriteCmdArgFlag(file)
4134 func
.WriteCmdFlag(file)
4136 result
= func
.GetInfo('result')
4137 if not result
== None:
4138 if len(result
) == 1:
4139 file.Write(" typedef %s Result;\n\n" % result
[0])
4141 file.Write(" struct Result {\n")
4143 file.Write(" %s;\n" % line
)
4144 file.Write(" };\n\n")
4146 func
.WriteCmdComputeSize(file)
4147 func
.WriteCmdSetHeader(file)
4148 func
.WriteCmdInit(file)
4149 func
.WriteCmdSet(file)
4151 file.Write(" gpu::CommandHeader header;\n")
4152 args
= func
.GetCmdArgs()
4154 file.Write(" %s %s;\n" % (arg
.cmd_type
, arg
.name
))
4156 consts
= func
.GetCmdConstants()
4157 for const
in consts
:
4158 file.Write(" static const %s %s = %s;\n" %
4159 (const
.cmd_type
, const
.name
, const
.GetConstantValue()))
4164 size
= len(args
) * _SIZE_OF_UINT32
+ _SIZE_OF_COMMAND_HEADER
4165 file.Write("static_assert(sizeof(%s) == %d,\n" % (func
.name
, size
))
4166 file.Write(" \"size of %s should be %d\");\n" %
4168 file.Write("static_assert(offsetof(%s, header) == 0,\n" % func
.name
)
4169 file.Write(" \"offset of %s header should be 0\");\n" %
4171 offset
= _SIZE_OF_COMMAND_HEADER
4173 file.Write("static_assert(offsetof(%s, %s) == %d,\n" %
4174 (func
.name
, arg
.name
, offset
))
4175 file.Write(" \"offset of %s %s should be %d\");\n" %
4176 (func
.name
, arg
.name
, offset
))
4177 offset
+= _SIZE_OF_UINT32
4178 if not result
== None and len(result
) > 1:
4181 parts
= line
.split()
4184 static_assert(offsetof(%(cmd_name)s::Result, %(field_name)s) == %(offset)d,
4185 "offset of %(cmd_name)s Result %(field_name)s should be "
4188 file.Write((check
.strip() + "\n") % {
4189 'cmd_name': func
.name
,
4193 offset
+= _SIZE_OF_UINT32
4196 def WriteHandlerImplementation(self
, func
, file):
4197 """Writes the handler implementation for this command."""
4198 if func
.IsUnsafe() and func
.GetInfo('id_mapping'):
4199 code_no_gen
= """ if (!group_->Get%(type)sServiceId(
4200 %(var)s, &%(service_var)s)) {
4201 LOCAL_SET_GL_ERROR(GL_INVALID_OPERATION, "%(func)s", "invalid %(var)s id");
4202 return error::kNoError;
4205 code_gen
= """ if (!group_->Get%(type)sServiceId(
4206 %(var)s, &%(service_var)s)) {
4207 if (!group_->bind_generates_resource()) {
4209 GL_INVALID_OPERATION, "%(func)s", "invalid %(var)s id");
4210 return error::kNoError;
4212 GLuint client_id = %(var)s;
4213 gl%(gen_func)s(1, &%(service_var)s);
4214 Create%(type)s(client_id, %(service_var)s);
4217 gen_func
= func
.GetInfo('gen_func')
4218 for id_type
in func
.GetInfo('id_mapping'):
4219 service_var
= id_type
.lower()
4220 if id_type
== 'Sync':
4221 service_var
= "service_%s" % service_var
4222 file.Write(" GLsync %s = 0;\n" % service_var
)
4223 if gen_func
and id_type
in gen_func
:
4224 file.Write(code_gen
% { 'type': id_type
,
4225 'var': id_type
.lower(),
4226 'service_var': service_var
,
4227 'func': func
.GetGLFunctionName(),
4228 'gen_func': gen_func
})
4230 file.Write(code_no_gen
% { 'type': id_type
,
4231 'var': id_type
.lower(),
4232 'service_var': service_var
,
4233 'func': func
.GetGLFunctionName() })
4235 for arg
in func
.GetOriginalArgs():
4236 if arg
.type == "GLsync":
4237 args
.append("service_%s" % arg
.name
)
4238 elif arg
.name
.endswith("size") and arg
.type == "GLsizei":
4239 args
.append("num_%s" % func
.GetLastOriginalArg().name
)
4240 elif arg
.name
== "length":
4241 args
.append("nullptr")
4243 args
.append(arg
.name
)
4244 file.Write(" %s(%s);\n" %
4245 (func
.GetGLFunctionName(), ", ".join(args
)))
4247 def WriteCmdSizeTest(self
, func
, file):
4248 """Writes the size test for a command."""
4249 file.Write(" EXPECT_EQ(sizeof(cmd), cmd.header.size * 4u);\n")
4251 def WriteFormatTest(self
, func
, file):
4252 """Writes a format test for a command."""
4253 file.Write("TEST_F(GLES2FormatTest, %s) {\n" % func
.name
)
4254 file.Write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
4255 (func
.name
, func
.name
))
4256 file.Write(" void* next_cmd = cmd.Set(\n")
4258 args
= func
.GetCmdArgs()
4259 for value
, arg
in enumerate(args
):
4260 file.Write(",\n static_cast<%s>(%d)" % (arg
.type, value
+ 11))
4262 file.Write(" EXPECT_EQ(static_cast<uint32_t>(cmds::%s::kCmdId),\n" %
4264 file.Write(" cmd.header.command);\n")
4265 func
.type_handler
.WriteCmdSizeTest(func
, file)
4266 for value
, arg
in enumerate(args
):
4267 file.Write(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);\n" %
4268 (arg
.type, value
+ 11, arg
.name
))
4269 file.Write(" CheckBytesWrittenMatchesExpectedSize(\n")
4270 file.Write(" next_cmd, sizeof(cmd));\n")
4274 def WriteImmediateFormatTest(self
, func
, file):
4275 """Writes a format test for an immediate version of a command."""
4278 def WriteBucketFormatTest(self
, func
, file):
4279 """Writes a format test for a bucket version of a command."""
4282 def WriteGetDataSizeCode(self
, func
, file):
4283 """Writes the code to set data_size used in validation"""
4286 def WriteImmediateCmdSizeTest(self
, func
, file):
4287 """Writes a size test for an immediate version of a command."""
4288 file.Write(" // TODO(gman): Compute correct size.\n")
4289 file.Write(" EXPECT_EQ(sizeof(cmd), cmd.header.size * 4u);\n")
4291 def __WriteIdMapping(self
, func
, file):
4292 """Writes client side / service side ID mapping."""
4293 if not func
.IsUnsafe() or not func
.GetInfo('id_mapping'):
4295 for id_type
in func
.GetInfo('id_mapping'):
4296 file.Write(" group_->Get%sServiceId(%s, &%s);\n" %
4297 (id_type
, id_type
.lower(), id_type
.lower()))
4299 def WriteImmediateHandlerImplementation (self
, func
, file):
4300 """Writes the handler impl for the immediate version of a command."""
4301 self
.__WriteIdMapping
(func
, file)
4302 file.Write(" %s(%s);\n" %
4303 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
4305 def WriteBucketHandlerImplementation (self
, func
, file):
4306 """Writes the handler impl for the bucket version of a command."""
4307 self
.__WriteIdMapping
(func
, file)
4308 file.Write(" %s(%s);\n" %
4309 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
4311 def WriteServiceHandlerFunctionHeader(self
, func
, file):
4312 """Writes function header for service implementation handlers."""
4313 file.Write("""error::Error GLES2DecoderImpl::Handle%(name)s(
4314 uint32_t immediate_data_size, const void* cmd_data) {
4315 """ % {'name': func
.name
})
4317 file.Write("""if (!unsafe_es3_apis_enabled())
4318 return error::kUnknownCommand;
4320 file.Write("""const gles2::cmds::%(name)s& c =
4321 *static_cast<const gles2::cmds::%(name)s*>(cmd_data);
4323 """ % {'name': func
.name
})
4325 def WriteServiceImplementation(self
, func
, file):
4326 """Writes the service implementation for a command."""
4327 self
.WriteServiceHandlerFunctionHeader(func
, file)
4328 self
.WriteHandlerExtensionCheck(func
, file)
4329 self
.WriteHandlerDeferReadWrite(func
, file);
4330 if len(func
.GetOriginalArgs()) > 0:
4331 last_arg
= func
.GetLastOriginalArg()
4332 all_but_last_arg
= func
.GetOriginalArgs()[:-1]
4333 for arg
in all_but_last_arg
:
4334 arg
.WriteGetCode(file)
4335 self
.WriteGetDataSizeCode(func
, file)
4336 last_arg
.WriteGetCode(file)
4337 func
.WriteHandlerValidation(file)
4338 func
.WriteHandlerImplementation(file)
4339 file.Write(" return error::kNoError;\n")
4343 def WriteImmediateServiceImplementation(self
, func
, file):
4344 """Writes the service implementation for an immediate version of command."""
4345 self
.WriteServiceHandlerFunctionHeader(func
, file)
4346 self
.WriteHandlerExtensionCheck(func
, file)
4347 self
.WriteHandlerDeferReadWrite(func
, file);
4348 for arg
in func
.GetOriginalArgs():
4350 self
.WriteGetDataSizeCode(func
, file)
4351 arg
.WriteGetCode(file)
4352 func
.WriteHandlerValidation(file)
4353 func
.WriteHandlerImplementation(file)
4354 file.Write(" return error::kNoError;\n")
4358 def WriteBucketServiceImplementation(self
, func
, file):
4359 """Writes the service implementation for a bucket version of command."""
4360 self
.WriteServiceHandlerFunctionHeader(func
, file)
4361 self
.WriteHandlerExtensionCheck(func
, file)
4362 self
.WriteHandlerDeferReadWrite(func
, file);
4363 for arg
in func
.GetCmdArgs():
4364 arg
.WriteGetCode(file)
4365 func
.WriteHandlerValidation(file)
4366 func
.WriteHandlerImplementation(file)
4367 file.Write(" return error::kNoError;\n")
4371 def WriteHandlerExtensionCheck(self
, func
, file):
4372 if func
.GetInfo('extension_flag'):
4373 file.Write(" if (!features().%s) {\n" % func
.GetInfo('extension_flag'))
4374 file.Write(" LOCAL_SET_GL_ERROR(GL_INVALID_OPERATION, \"gl%s\","
4375 " \"function not available\");\n" % func
.original_name
)
4376 file.Write(" return error::kNoError;")
4377 file.Write(" }\n\n")
4379 def WriteHandlerDeferReadWrite(self
, func
, file):
4380 """Writes the code to handle deferring reads or writes."""
4381 defer_draws
= func
.GetInfo('defer_draws')
4382 defer_reads
= func
.GetInfo('defer_reads')
4383 if defer_draws
or defer_reads
:
4384 file.Write(" error::Error error;\n")
4386 file.Write(" error = WillAccessBoundFramebufferForDraw();\n")
4387 file.Write(" if (error != error::kNoError)\n")
4388 file.Write(" return error;\n")
4390 file.Write(" error = WillAccessBoundFramebufferForRead();\n")
4391 file.Write(" if (error != error::kNoError)\n")
4392 file.Write(" return error;\n")
4394 def WriteValidUnitTest(self
, func
, file, test
, *extras
):
4395 """Writes a valid unit test for the service implementation."""
4396 if func
.GetInfo('expectation') == False:
4397 test
= self
._remove
_expected
_call
_re
.sub('', test
)
4400 arg
.GetValidArg(func
) \
4401 for arg
in func
.GetOriginalArgs() if not arg
.IsConstant()
4404 arg
.GetValidGLArg(func
) \
4405 for arg
in func
.GetOriginalArgs()
4407 gl_func_name
= func
.GetGLTestFunctionName()
4410 'gl_func_name': gl_func_name
,
4411 'args': ", ".join(arg_strings
),
4412 'gl_args': ", ".join(gl_arg_strings
),
4414 for extra
in extras
:
4417 while (old_test
!= test
):
4420 file.Write(test
% vars)
4422 def WriteInvalidUnitTest(self
, func
, file, test
, *extras
):
4423 """Writes an invalid unit test for the service implementation."""
4426 for invalid_arg_index
, invalid_arg
in enumerate(func
.GetOriginalArgs()):
4427 # Service implementation does not test constants, as they are not part of
4428 # the call in the service side.
4429 if invalid_arg
.IsConstant():
4432 num_invalid_values
= invalid_arg
.GetNumInvalidValues(func
)
4433 for value_index
in range(0, num_invalid_values
):
4435 parse_result
= "kNoError"
4437 for arg
in func
.GetOriginalArgs():
4438 if arg
.IsConstant():
4440 if invalid_arg
is arg
:
4441 (arg_string
, parse_result
, gl_error
) = arg
.GetInvalidArg(
4444 arg_string
= arg
.GetValidArg(func
)
4445 arg_strings
.append(arg_string
)
4447 for arg
in func
.GetOriginalArgs():
4448 gl_arg_strings
.append("_")
4449 gl_func_name
= func
.GetGLTestFunctionName()
4451 if not gl_error
== None:
4452 gl_error_test
= '\n EXPECT_EQ(%s, GetGLError());' % gl_error
4456 'arg_index': invalid_arg_index
,
4457 'value_index': value_index
,
4458 'gl_func_name': gl_func_name
,
4459 'args': ", ".join(arg_strings
),
4460 'all_but_last_args': ", ".join(arg_strings
[:-1]),
4461 'gl_args': ", ".join(gl_arg_strings
),
4462 'parse_result': parse_result
,
4463 'gl_error_test': gl_error_test
,
4465 for extra
in extras
:
4467 file.Write(test
% vars)
4469 def WriteServiceUnitTest(self
, func
, file, *extras
):
4470 """Writes the service unit test for a command."""
4472 if func
.name
== 'Enable':
4474 TEST_P(%(test_name)s, %(name)sValidArgs) {
4475 SetupExpectationsForEnableDisable(%(gl_args)s, true);
4476 SpecializedSetup<cmds::%(name)s, 0>(true);
4478 cmd.Init(%(args)s);"""
4479 elif func
.name
== 'Disable':
4481 TEST_P(%(test_name)s, %(name)sValidArgs) {
4482 SetupExpectationsForEnableDisable(%(gl_args)s, false);
4483 SpecializedSetup<cmds::%(name)s, 0>(true);
4485 cmd.Init(%(args)s);"""
4488 TEST_P(%(test_name)s, %(name)sValidArgs) {
4489 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
4490 SpecializedSetup<cmds::%(name)s, 0>(true);
4492 cmd.Init(%(args)s);"""
4495 decoder_->set_unsafe_es3_apis_enabled(true);
4496 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4497 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4498 decoder_->set_unsafe_es3_apis_enabled(false);
4499 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));
4504 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4505 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4508 self
.WriteValidUnitTest(func
, file, valid_test
, *extras
)
4510 if not func
.IsUnsafe():
4512 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
4513 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
4514 SpecializedSetup<cmds::%(name)s, 0>(false);
4517 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
4520 self
.WriteInvalidUnitTest(func
, file, invalid_test
, *extras
)
4522 def WriteImmediateServiceUnitTest(self
, func
, file, *extras
):
4523 """Writes the service unit test for an immediate command."""
4524 file.Write("// TODO(gman): %s\n" % func
.name
)
4526 def WriteImmediateValidationCode(self
, func
, file):
4527 """Writes the validation code for an immediate version of a command."""
4530 def WriteBucketServiceUnitTest(self
, func
, file, *extras
):
4531 """Writes the service unit test for a bucket command."""
4532 file.Write("// TODO(gman): %s\n" % func
.name
)
4534 def WriteBucketValidationCode(self
, func
, file):
4535 """Writes the validation code for a bucket version of a command."""
4536 file.Write("// TODO(gman): %s\n" % func
.name
)
4538 def WriteGLES2ImplementationDeclaration(self
, func
, file):
4539 """Writes the GLES2 Implemention declaration."""
4540 impl_decl
= func
.GetInfo('impl_decl')
4541 if impl_decl
== None or impl_decl
== True:
4542 file.Write("%s %s(%s) override;\n" %
4543 (func
.return_type
, func
.original_name
,
4544 func
.MakeTypedOriginalArgString("")))
4547 def WriteGLES2CLibImplementation(self
, func
, file):
4548 file.Write("%s GLES2%s(%s) {\n" %
4549 (func
.return_type
, func
.name
,
4550 func
.MakeTypedOriginalArgString("")))
4551 result_string
= "return "
4552 if func
.return_type
== "void":
4554 file.Write(" %sgles2::GetGLContext()->%s(%s);\n" %
4555 (result_string
, func
.original_name
,
4556 func
.MakeOriginalArgString("")))
4559 def WriteGLES2Header(self
, func
, file):
4560 """Writes a re-write macro for GLES"""
4561 file.Write("#define gl%s GLES2_GET_FUN(%s)\n" %(func
.name
, func
.name
))
4563 def WriteClientGLCallLog(self
, func
, file):
4564 """Writes a logging macro for the client side code."""
4566 if len(func
.GetOriginalArgs()):
4569 ' GPU_CLIENT_LOG("[" << GetLogPrefix() << "] gl%s("%s%s << ")");\n' %
4570 (func
.original_name
, comma
, func
.MakeLogArgString()))
4572 def WriteClientGLReturnLog(self
, func
, file):
4573 """Writes the return value logging code."""
4574 if func
.return_type
!= "void":
4575 file.Write(' GPU_CLIENT_LOG("return:" << result)\n')
4577 def WriteGLES2ImplementationHeader(self
, func
, file):
4578 """Writes the GLES2 Implemention."""
4579 self
.WriteGLES2ImplementationDeclaration(func
, file)
4581 def WriteGLES2TraceImplementationHeader(self
, func
, file):
4582 """Writes the GLES2 Trace Implemention header."""
4583 file.Write("%s %s(%s) override;\n" %
4584 (func
.return_type
, func
.original_name
,
4585 func
.MakeTypedOriginalArgString("")))
4587 def WriteGLES2TraceImplementation(self
, func
, file):
4588 """Writes the GLES2 Trace Implemention."""
4589 file.Write("%s GLES2TraceImplementation::%s(%s) {\n" %
4590 (func
.return_type
, func
.original_name
,
4591 func
.MakeTypedOriginalArgString("")))
4592 result_string
= "return "
4593 if func
.return_type
== "void":
4595 file.Write(' TRACE_EVENT_BINARY_EFFICIENT0("gpu", "GLES2Trace::%s");\n' %
4597 file.Write(" %sgl_->%s(%s);\n" %
4598 (result_string
, func
.name
, func
.MakeOriginalArgString("")))
4602 def WriteGLES2Implementation(self
, func
, file):
4603 """Writes the GLES2 Implemention."""
4604 impl_func
= func
.GetInfo('impl_func')
4605 impl_decl
= func
.GetInfo('impl_decl')
4606 gen_cmd
= func
.GetInfo('gen_cmd')
4607 if (func
.can_auto_generate
and
4608 (impl_func
== None or impl_func
== True) and
4609 (impl_decl
== None or impl_decl
== True) and
4610 (gen_cmd
== None or gen_cmd
== True)):
4611 file.Write("%s GLES2Implementation::%s(%s) {\n" %
4612 (func
.return_type
, func
.original_name
,
4613 func
.MakeTypedOriginalArgString("")))
4614 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
4615 self
.WriteClientGLCallLog(func
, file)
4616 func
.WriteDestinationInitalizationValidation(file)
4617 for arg
in func
.GetOriginalArgs():
4618 arg
.WriteClientSideValidationCode(file, func
)
4619 file.Write(" helper_->%s(%s);\n" %
4620 (func
.name
, func
.MakeHelperArgString("")))
4621 file.Write(" CheckGLError();\n")
4622 self
.WriteClientGLReturnLog(func
, file)
4626 def WriteGLES2InterfaceHeader(self
, func
, file):
4627 """Writes the GLES2 Interface."""
4628 file.Write("virtual %s %s(%s) = 0;\n" %
4629 (func
.return_type
, func
.original_name
,
4630 func
.MakeTypedOriginalArgString("")))
4632 def WriteMojoGLES2ImplHeader(self
, func
, file):
4633 """Writes the Mojo GLES2 implementation header."""
4634 file.Write("%s %s(%s) override;\n" %
4635 (func
.return_type
, func
.original_name
,
4636 func
.MakeTypedOriginalArgString("")))
4638 def WriteMojoGLES2Impl(self
, func
, file):
4639 """Writes the Mojo GLES2 implementation."""
4640 file.Write("%s MojoGLES2Impl::%s(%s) {\n" %
4641 (func
.return_type
, func
.original_name
,
4642 func
.MakeTypedOriginalArgString("")))
4643 extensions
= ["CHROMIUM_sync_point", "CHROMIUM_texture_mailbox",
4644 "CHROMIUM_sub_image", "CHROMIUM_miscellaneous",
4645 "occlusion_query_EXT", "CHROMIUM_image",
4646 "CHROMIUM_copy_texture",
4647 "CHROMIUM_pixel_transfer_buffer_object"]
4648 if func
.IsCoreGLFunction() or func
.GetInfo("extension") in extensions
:
4649 file.Write("MojoGLES2MakeCurrent(context_);");
4650 func_return
= "gl" + func
.original_name
+ "(" + \
4651 func
.MakeOriginalArgString("") + ");"
4652 if func
.return_type
== "void":
4653 file.Write(func_return
);
4655 file.Write("return " + func_return
);
4657 file.Write("NOTREACHED() << \"Unimplemented %s.\";\n" %
4658 func
.original_name
);
4659 if func
.return_type
!= "void":
4660 file.Write("return 0;")
4663 def WriteGLES2InterfaceStub(self
, func
, file):
4664 """Writes the GLES2 Interface stub declaration."""
4665 file.Write("%s %s(%s) override;\n" %
4666 (func
.return_type
, func
.original_name
,
4667 func
.MakeTypedOriginalArgString("")))
4669 def WriteGLES2InterfaceStubImpl(self
, func
, file):
4670 """Writes the GLES2 Interface stub declaration."""
4671 args
= func
.GetOriginalArgs()
4672 arg_string
= ", ".join(
4673 ["%s /* %s */" % (arg
.type, arg
.name
) for arg
in args
])
4674 file.Write("%s GLES2InterfaceStub::%s(%s) {\n" %
4675 (func
.return_type
, func
.original_name
, arg_string
))
4676 if func
.return_type
!= "void":
4677 file.Write(" return 0;\n")
4680 def WriteGLES2ImplementationUnitTest(self
, func
, file):
4681 """Writes the GLES2 Implemention unit test."""
4682 client_test
= func
.GetInfo('client_test')
4683 if (func
.can_auto_generate
and
4684 (client_test
== None or client_test
== True)):
4686 TEST_F(GLES2ImplementationTest, %(name)s) {
4691 expected.cmd.Init(%(cmd_args)s);
4693 gl_->%(name)s(%(args)s);
4694 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
4698 arg
.GetValidClientSideCmdArg(func
) for arg
in func
.GetCmdArgs()
4702 arg
.GetValidClientSideArg(func
) for arg
in func
.GetOriginalArgs()
4707 'args': ", ".join(gl_arg_strings
),
4708 'cmd_args': ", ".join(cmd_arg_strings
),
4711 # Test constants for invalid values, as they are not tested by the
4713 constants
= [arg
for arg
in func
.GetOriginalArgs() if arg
.IsConstant()]
4716 TEST_F(GLES2ImplementationTest, %(name)sInvalidConstantArg%(invalid_index)d) {
4717 gl_->%(name)s(%(args)s);
4718 EXPECT_TRUE(NoCommandsWritten());
4719 EXPECT_EQ(%(gl_error)s, CheckError());
4722 for invalid_arg
in constants
:
4724 invalid
= invalid_arg
.GetInvalidArg(func
)
4725 for arg
in func
.GetOriginalArgs():
4726 if arg
is invalid_arg
:
4727 gl_arg_strings
.append(invalid
[0])
4729 gl_arg_strings
.append(arg
.GetValidClientSideArg(func
))
4733 'invalid_index': func
.GetOriginalArgs().index(invalid_arg
),
4734 'args': ", ".join(gl_arg_strings
),
4735 'gl_error': invalid
[2],
4738 if client_test
!= False:
4739 file.Write("// TODO(zmo): Implement unit test for %s\n" % func
.name
)
4741 def WriteDestinationInitalizationValidation(self
, func
, file):
4742 """Writes the client side destintion initialization validation."""
4743 for arg
in func
.GetOriginalArgs():
4744 arg
.WriteDestinationInitalizationValidation(file, func
)
4746 def WriteTraceEvent(self
, func
, file):
4747 file.Write(' TRACE_EVENT0("gpu", "GLES2Implementation::%s");\n' %
4750 def WriteImmediateCmdComputeSize(self
, func
, file):
4751 """Writes the size computation code for the immediate version of a cmd."""
4752 file.Write(" static uint32_t ComputeSize(uint32_t size_in_bytes) {\n")
4753 file.Write(" return static_cast<uint32_t>(\n")
4754 file.Write(" sizeof(ValueType) + // NOLINT\n")
4755 file.Write(" RoundSizeToMultipleOfEntries(size_in_bytes));\n")
4759 def WriteImmediateCmdSetHeader(self
, func
, file):
4760 """Writes the SetHeader function for the immediate version of a cmd."""
4761 file.Write(" void SetHeader(uint32_t size_in_bytes) {\n")
4762 file.Write(" header.SetCmdByTotalSize<ValueType>(size_in_bytes);\n")
4766 def WriteImmediateCmdInit(self
, func
, file):
4767 """Writes the Init function for the immediate version of a command."""
4768 raise NotImplementedError(func
.name
)
4770 def WriteImmediateCmdSet(self
, func
, file):
4771 """Writes the Set function for the immediate version of a command."""
4772 raise NotImplementedError(func
.name
)
4774 def WriteCmdHelper(self
, func
, file):
4775 """Writes the cmd helper definition for a cmd."""
4776 code
= """ void %(name)s(%(typed_args)s) {
4777 gles2::cmds::%(name)s* c = GetCmdSpace<gles2::cmds::%(name)s>();
4786 "typed_args": func
.MakeTypedCmdArgString(""),
4787 "args": func
.MakeCmdArgString(""),
4790 def WriteImmediateCmdHelper(self
, func
, file):
4791 """Writes the cmd helper definition for the immediate version of a cmd."""
4792 code
= """ void %(name)s(%(typed_args)s) {
4793 const uint32_t s = 0; // TODO(gman): compute correct size
4794 gles2::cmds::%(name)s* c =
4795 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(s);
4804 "typed_args": func
.MakeTypedCmdArgString(""),
4805 "args": func
.MakeCmdArgString(""),
4809 class StateSetHandler(TypeHandler
):
4810 """Handler for commands that simply set state."""
4813 TypeHandler
.__init
__(self
)
4815 def WriteHandlerImplementation(self
, func
, file):
4816 """Overrriden from TypeHandler."""
4817 state_name
= func
.GetInfo('state')
4818 state
= _STATES
[state_name
]
4819 states
= state
['states']
4820 args
= func
.GetOriginalArgs()
4821 for ndx
,item
in enumerate(states
):
4823 if 'range_checks' in item
:
4824 for range_check
in item
['range_checks']:
4825 code
.append("%s %s" % (args
[ndx
].name
, range_check
['check']))
4826 if 'nan_check' in item
:
4827 # Drivers might generate an INVALID_VALUE error when a value is set
4828 # to NaN. This is allowed behavior under GLES 3.0 section 2.1.1 or
4829 # OpenGL 4.5 section 2.3.4.1 - providing NaN allows undefined results.
4830 # Make this behavior consistent within Chromium, and avoid leaking GL
4831 # errors by generating the error in the command buffer instead of
4832 # letting the GL driver generate it.
4833 code
.append("std::isnan(%s)" % args
[ndx
].name
)
4835 file.Write(" if (%s) {\n" % " ||\n ".join(code
))
4837 ' LOCAL_SET_GL_ERROR(GL_INVALID_VALUE,'
4838 ' "%s", "%s out of range");\n' %
4839 (func
.name
, args
[ndx
].name
))
4840 file.Write(" return error::kNoError;\n")
4843 for ndx
,item
in enumerate(states
):
4844 code
.append("state_.%s != %s" % (item
['name'], args
[ndx
].name
))
4845 file.Write(" if (%s) {\n" % " ||\n ".join(code
))
4846 for ndx
,item
in enumerate(states
):
4847 file.Write(" state_.%s = %s;\n" % (item
['name'], args
[ndx
].name
))
4848 if 'state_flag' in state
:
4849 file.Write(" %s = true;\n" % state
['state_flag'])
4850 if not func
.GetInfo("no_gl"):
4851 for ndx
,item
in enumerate(states
):
4852 if item
.get('cached', False):
4853 file.Write(" state_.%s = %s;\n" %
4854 (CachedStateName(item
), args
[ndx
].name
))
4855 file.Write(" %s(%s);\n" %
4856 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
4859 def WriteServiceUnitTest(self
, func
, file, *extras
):
4860 """Overrriden from TypeHandler."""
4861 TypeHandler
.WriteServiceUnitTest(self
, func
, file, *extras
)
4862 state_name
= func
.GetInfo('state')
4863 state
= _STATES
[state_name
]
4864 states
= state
['states']
4865 for ndx
,item
in enumerate(states
):
4866 if 'range_checks' in item
:
4867 for check_ndx
, range_check
in enumerate(item
['range_checks']):
4869 TEST_P(%(test_name)s, %(name)sInvalidValue%(ndx)d_%(check_ndx)d) {
4870 SpecializedSetup<cmds::%(name)s, 0>(false);
4873 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4874 EXPECT_EQ(GL_INVALID_VALUE, GetGLError());
4879 arg
.GetValidArg(func
) \
4880 for arg
in func
.GetOriginalArgs() if not arg
.IsConstant()
4883 arg_strings
[ndx
] = range_check
['test_value']
4887 'check_ndx': check_ndx
,
4888 'args': ", ".join(arg_strings
),
4890 for extra
in extras
:
4892 file.Write(valid_test
% vars)
4893 if 'nan_check' in item
:
4895 TEST_P(%(test_name)s, %(name)sNaNValue%(ndx)d) {
4896 SpecializedSetup<cmds::%(name)s, 0>(false);
4899 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4900 EXPECT_EQ(GL_INVALID_VALUE, GetGLError());
4905 arg
.GetValidArg(func
) \
4906 for arg
in func
.GetOriginalArgs() if not arg
.IsConstant()
4909 arg_strings
[ndx
] = 'nanf("")'
4913 'args': ", ".join(arg_strings
),
4915 for extra
in extras
:
4917 file.Write(valid_test
% vars)
4920 class StateSetRGBAlphaHandler(TypeHandler
):
4921 """Handler for commands that simply set state that have rgb/alpha."""
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 ndx
,item
in enumerate(states
):
4935 code
.append("state_.%s != %s" % (item
['name'], args
[ndx
% num_args
].name
))
4936 file.Write(" if (%s) {\n" % " ||\n ".join(code
))
4937 for ndx
, item
in enumerate(states
):
4938 file.Write(" state_.%s = %s;\n" %
4939 (item
['name'], args
[ndx
% num_args
].name
))
4940 if 'state_flag' in state
:
4941 file.Write(" %s = true;\n" % state
['state_flag'])
4942 if not func
.GetInfo("no_gl"):
4943 file.Write(" %s(%s);\n" %
4944 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
4948 class StateSetFrontBackSeparateHandler(TypeHandler
):
4949 """Handler for commands that simply set state that have front/back."""
4952 TypeHandler
.__init
__(self
)
4954 def WriteHandlerImplementation(self
, func
, file):
4955 """Overrriden from TypeHandler."""
4956 state_name
= func
.GetInfo('state')
4957 state
= _STATES
[state_name
]
4958 states
= state
['states']
4959 args
= func
.GetOriginalArgs()
4961 num_args
= len(args
)
4962 file.Write(" bool changed = false;\n")
4963 for group_ndx
, group
in enumerate(Grouper(num_args
- 1, states
)):
4964 file.Write(" if (%s == %s || %s == GL_FRONT_AND_BACK) {\n" %
4965 (face
, ('GL_FRONT', 'GL_BACK')[group_ndx
], face
))
4967 for ndx
, item
in enumerate(group
):
4968 code
.append("state_.%s != %s" % (item
['name'], args
[ndx
+ 1].name
))
4969 file.Write(" changed |= %s;\n" % " ||\n ".join(code
))
4971 file.Write(" if (changed) {\n")
4972 for group_ndx
, group
in enumerate(Grouper(num_args
- 1, states
)):
4973 file.Write(" if (%s == %s || %s == GL_FRONT_AND_BACK) {\n" %
4974 (face
, ('GL_FRONT', 'GL_BACK')[group_ndx
], face
))
4975 for ndx
, item
in enumerate(group
):
4976 file.Write(" state_.%s = %s;\n" %
4977 (item
['name'], args
[ndx
+ 1].name
))
4979 if 'state_flag' in state
:
4980 file.Write(" %s = true;\n" % state
['state_flag'])
4981 if not func
.GetInfo("no_gl"):
4982 file.Write(" %s(%s);\n" %
4983 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
4987 class StateSetFrontBackHandler(TypeHandler
):
4988 """Handler for commands that simply set state that set both front/back."""
4991 TypeHandler
.__init
__(self
)
4993 def WriteHandlerImplementation(self
, func
, file):
4994 """Overrriden from TypeHandler."""
4995 state_name
= func
.GetInfo('state')
4996 state
= _STATES
[state_name
]
4997 states
= state
['states']
4998 args
= func
.GetOriginalArgs()
4999 num_args
= len(args
)
5001 for group_ndx
, group
in enumerate(Grouper(num_args
, states
)):
5002 for ndx
, item
in enumerate(group
):
5003 code
.append("state_.%s != %s" % (item
['name'], args
[ndx
].name
))
5004 file.Write(" if (%s) {\n" % " ||\n ".join(code
))
5005 for group_ndx
, group
in enumerate(Grouper(num_args
, states
)):
5006 for ndx
, item
in enumerate(group
):
5007 file.Write(" state_.%s = %s;\n" % (item
['name'], args
[ndx
].name
))
5008 if 'state_flag' in state
:
5009 file.Write(" %s = true;\n" % state
['state_flag'])
5010 if not func
.GetInfo("no_gl"):
5011 file.Write(" %s(%s);\n" %
5012 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
5016 class StateSetNamedParameter(TypeHandler
):
5017 """Handler for commands that set a state chosen with an enum parameter."""
5020 TypeHandler
.__init
__(self
)
5022 def WriteHandlerImplementation(self
, func
, file):
5023 """Overridden from TypeHandler."""
5024 state_name
= func
.GetInfo('state')
5025 state
= _STATES
[state_name
]
5026 states
= state
['states']
5027 args
= func
.GetOriginalArgs()
5028 num_args
= len(args
)
5029 assert num_args
== 2
5030 file.Write(" switch (%s) {\n" % args
[0].name
)
5031 for state
in states
:
5032 file.Write(" case %s:\n" % state
['enum'])
5033 file.Write(" if (state_.%s != %s) {\n" %
5034 (state
['name'], args
[1].name
))
5035 file.Write(" state_.%s = %s;\n" % (state
['name'], args
[1].name
))
5036 if not func
.GetInfo("no_gl"):
5037 file.Write(" %s(%s);\n" %
5038 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
5040 file.Write(" break;\n")
5041 file.Write(" default:\n")
5042 file.Write(" NOTREACHED();\n")
5046 class CustomHandler(TypeHandler
):
5047 """Handler for commands that are auto-generated but require minor tweaks."""
5050 TypeHandler
.__init
__(self
)
5052 def WriteServiceImplementation(self
, func
, file):
5053 """Overrriden from TypeHandler."""
5056 def WriteImmediateServiceImplementation(self
, func
, file):
5057 """Overrriden from TypeHandler."""
5060 def WriteBucketServiceImplementation(self
, func
, file):
5061 """Overrriden from TypeHandler."""
5064 def WriteServiceUnitTest(self
, func
, file, *extras
):
5065 """Overrriden from TypeHandler."""
5066 file.Write("// TODO(gman): %s\n\n" % func
.name
)
5068 def WriteImmediateServiceUnitTest(self
, func
, file, *extras
):
5069 """Overrriden from TypeHandler."""
5070 file.Write("// TODO(gman): %s\n\n" % func
.name
)
5072 def WriteImmediateCmdGetTotalSize(self
, func
, file):
5073 """Overrriden from TypeHandler."""
5075 " uint32_t total_size = 0; // TODO(gman): get correct size.\n")
5077 def WriteImmediateCmdInit(self
, func
, file):
5078 """Overrriden from TypeHandler."""
5079 file.Write(" void Init(%s) {\n" % func
.MakeTypedCmdArgString("_"))
5080 self
.WriteImmediateCmdGetTotalSize(func
, file)
5081 file.Write(" SetHeader(total_size);\n")
5082 args
= func
.GetCmdArgs()
5084 file.Write(" %s = _%s;\n" % (arg
.name
, arg
.name
))
5088 def WriteImmediateCmdSet(self
, func
, file):
5089 """Overrriden from TypeHandler."""
5090 copy_args
= func
.MakeCmdArgString("_", False)
5091 file.Write(" void* Set(void* cmd%s) {\n" %
5092 func
.MakeTypedCmdArgString("_", True))
5093 self
.WriteImmediateCmdGetTotalSize(func
, file)
5094 file.Write(" static_cast<ValueType*>(cmd)->Init(%s);\n" % copy_args
)
5095 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
5096 "cmd, total_size);\n")
5101 class TodoHandler(CustomHandler
):
5102 """Handle for commands that are not yet implemented."""
5104 def NeedsDataTransferFunction(self
, func
):
5105 """Overriden from TypeHandler."""
5108 def WriteImmediateFormatTest(self
, func
, file):
5109 """Overrriden from TypeHandler."""
5112 def WriteGLES2ImplementationUnitTest(self
, func
, file):
5113 """Overrriden from TypeHandler."""
5116 def WriteGLES2Implementation(self
, func
, file):
5117 """Overrriden from TypeHandler."""
5118 file.Write("%s GLES2Implementation::%s(%s) {\n" %
5119 (func
.return_type
, func
.original_name
,
5120 func
.MakeTypedOriginalArgString("")))
5121 file.Write(" // TODO: for now this is a no-op\n")
5124 "GL_INVALID_OPERATION, \"gl%s\", \"not implemented\");\n" %
5126 if func
.return_type
!= "void":
5127 file.Write(" return 0;\n")
5131 def WriteServiceImplementation(self
, func
, file):
5132 """Overrriden from TypeHandler."""
5133 self
.WriteServiceHandlerFunctionHeader(func
, file)
5134 file.Write(" // TODO: for now this is a no-op\n")
5136 " LOCAL_SET_GL_ERROR("
5137 "GL_INVALID_OPERATION, \"gl%s\", \"not implemented\");\n" %
5139 file.Write(" return error::kNoError;\n")
5144 class HandWrittenHandler(CustomHandler
):
5145 """Handler for comands where everything must be written by hand."""
5147 def InitFunction(self
, func
):
5148 """Add or adjust anything type specific for this function."""
5149 CustomHandler
.InitFunction(self
, func
)
5150 func
.can_auto_generate
= False
5152 def NeedsDataTransferFunction(self
, func
):
5153 """Overriden from TypeHandler."""
5154 # If specified explicitly, force the data transfer method.
5155 if func
.GetInfo('data_transfer_methods'):
5159 def WriteStruct(self
, func
, file):
5160 """Overrriden from TypeHandler."""
5163 def WriteDocs(self
, func
, file):
5164 """Overrriden from TypeHandler."""
5167 def WriteServiceUnitTest(self
, func
, file, *extras
):
5168 """Overrriden from TypeHandler."""
5169 file.Write("// TODO(gman): %s\n\n" % func
.name
)
5171 def WriteImmediateServiceUnitTest(self
, func
, file, *extras
):
5172 """Overrriden from TypeHandler."""
5173 file.Write("// TODO(gman): %s\n\n" % func
.name
)
5175 def WriteBucketServiceUnitTest(self
, func
, file, *extras
):
5176 """Overrriden from TypeHandler."""
5177 file.Write("// TODO(gman): %s\n\n" % func
.name
)
5179 def WriteServiceImplementation(self
, func
, file):
5180 """Overrriden from TypeHandler."""
5183 def WriteImmediateServiceImplementation(self
, func
, file):
5184 """Overrriden from TypeHandler."""
5187 def WriteBucketServiceImplementation(self
, func
, file):
5188 """Overrriden from TypeHandler."""
5191 def WriteImmediateCmdHelper(self
, func
, file):
5192 """Overrriden from TypeHandler."""
5195 def WriteCmdHelper(self
, func
, file):
5196 """Overrriden from TypeHandler."""
5199 def WriteFormatTest(self
, func
, file):
5200 """Overrriden from TypeHandler."""
5201 file.Write("// TODO(gman): Write test for %s\n" % func
.name
)
5203 def WriteImmediateFormatTest(self
, func
, file):
5204 """Overrriden from TypeHandler."""
5205 file.Write("// TODO(gman): Write test for %s\n" % func
.name
)
5207 def WriteBucketFormatTest(self
, func
, file):
5208 """Overrriden from TypeHandler."""
5209 file.Write("// TODO(gman): Write test for %s\n" % func
.name
)
5213 class ManualHandler(CustomHandler
):
5214 """Handler for commands who's handlers must be written by hand."""
5217 CustomHandler
.__init
__(self
)
5219 def InitFunction(self
, func
):
5220 """Overrriden from TypeHandler."""
5221 if (func
.name
== 'CompressedTexImage2DBucket' or
5222 func
.name
== 'CompressedTexImage3DBucket'):
5223 func
.cmd_args
= func
.cmd_args
[:-1]
5224 func
.AddCmdArg(Argument('bucket_id', 'GLuint'))
5226 CustomHandler
.InitFunction(self
, func
)
5228 def WriteServiceImplementation(self
, func
, file):
5229 """Overrriden from TypeHandler."""
5232 def WriteBucketServiceImplementation(self
, func
, file):
5233 """Overrriden from TypeHandler."""
5236 def WriteServiceUnitTest(self
, func
, file, *extras
):
5237 """Overrriden from TypeHandler."""
5238 file.Write("// TODO(gman): %s\n\n" % func
.name
)
5240 def WriteImmediateServiceUnitTest(self
, func
, file, *extras
):
5241 """Overrriden from TypeHandler."""
5242 file.Write("// TODO(gman): %s\n\n" % func
.name
)
5244 def WriteImmediateServiceImplementation(self
, func
, file):
5245 """Overrriden from TypeHandler."""
5248 def WriteImmediateFormatTest(self
, func
, file):
5249 """Overrriden from TypeHandler."""
5250 file.Write("// TODO(gman): Implement test for %s\n" % func
.name
)
5252 def WriteGLES2Implementation(self
, func
, file):
5253 """Overrriden from TypeHandler."""
5254 if func
.GetInfo('impl_func'):
5255 super(ManualHandler
, self
).WriteGLES2Implementation(func
, file)
5257 def WriteGLES2ImplementationHeader(self
, func
, file):
5258 """Overrriden from TypeHandler."""
5259 file.Write("%s %s(%s) override;\n" %
5260 (func
.return_type
, func
.original_name
,
5261 func
.MakeTypedOriginalArgString("")))
5264 def WriteImmediateCmdGetTotalSize(self
, func
, file):
5265 """Overrriden from TypeHandler."""
5266 # TODO(gman): Move this data to _FUNCTION_INFO?
5267 CustomHandler
.WriteImmediateCmdGetTotalSize(self
, func
, file)
5270 class DataHandler(TypeHandler
):
5271 """Handler for glBufferData, glBufferSubData, glTexImage*D, glTexSubImage*D,
5272 glCompressedTexImage*D, glCompressedTexImageSub*D."""
5274 TypeHandler
.__init
__(self
)
5276 def InitFunction(self
, func
):
5277 """Overrriden from TypeHandler."""
5278 if (func
.name
== 'CompressedTexSubImage2DBucket' or
5279 func
.name
== 'CompressedTexSubImage3DBucket'):
5280 func
.cmd_args
= func
.cmd_args
[:-1]
5281 func
.AddCmdArg(Argument('bucket_id', 'GLuint'))
5283 def WriteGetDataSizeCode(self
, func
, file):
5284 """Overrriden from TypeHandler."""
5285 # TODO(gman): Move this data to _FUNCTION_INFO?
5287 if name
.endswith("Immediate"):
5289 if name
== 'BufferData' or name
== 'BufferSubData':
5290 file.Write(" uint32_t data_size = size;\n")
5291 elif (name
== 'CompressedTexImage2D' or
5292 name
== 'CompressedTexSubImage2D' or
5293 name
== 'CompressedTexImage3D' or
5294 name
== 'CompressedTexSubImage3D'):
5295 file.Write(" uint32_t data_size = imageSize;\n")
5296 elif (name
== 'CompressedTexSubImage2DBucket' or
5297 name
== 'CompressedTexSubImage3DBucket'):
5298 file.Write(" Bucket* bucket = GetBucket(c.bucket_id);\n")
5299 file.Write(" uint32_t data_size = bucket->size();\n")
5300 file.Write(" GLsizei imageSize = data_size;\n")
5301 elif name
== 'TexImage2D' or name
== 'TexSubImage2D':
5302 code
= """ uint32_t data_size;
5303 if (!GLES2Util::ComputeImageDataSize(
5304 width, height, format, type, unpack_alignment_, &data_size)) {
5305 return error::kOutOfBounds;
5311 "// uint32_t data_size = 0; // TODO(gman): get correct size!\n")
5313 def WriteImmediateCmdGetTotalSize(self
, func
, file):
5314 """Overrriden from TypeHandler."""
5317 def WriteImmediateCmdSizeTest(self
, func
, file):
5318 """Overrriden from TypeHandler."""
5319 file.Write(" EXPECT_EQ(sizeof(cmd), total_size);\n")
5321 def WriteImmediateCmdInit(self
, func
, file):
5322 """Overrriden from TypeHandler."""
5323 file.Write(" void Init(%s) {\n" % func
.MakeTypedCmdArgString("_"))
5324 self
.WriteImmediateCmdGetTotalSize(func
, file)
5325 file.Write(" SetHeader(total_size);\n")
5326 args
= func
.GetCmdArgs()
5328 file.Write(" %s = _%s;\n" % (arg
.name
, arg
.name
))
5332 def WriteImmediateCmdSet(self
, func
, file):
5333 """Overrriden from TypeHandler."""
5334 copy_args
= func
.MakeCmdArgString("_", False)
5335 file.Write(" void* Set(void* cmd%s) {\n" %
5336 func
.MakeTypedCmdArgString("_", True))
5337 self
.WriteImmediateCmdGetTotalSize(func
, file)
5338 file.Write(" static_cast<ValueType*>(cmd)->Init(%s);\n" % copy_args
)
5339 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
5340 "cmd, total_size);\n")
5344 def WriteImmediateFormatTest(self
, func
, file):
5345 """Overrriden from TypeHandler."""
5346 # TODO(gman): Remove this exception.
5347 file.Write("// TODO(gman): Implement test for %s\n" % func
.name
)
5350 def WriteServiceUnitTest(self
, func
, file, *extras
):
5351 """Overrriden from TypeHandler."""
5352 file.Write("// TODO(gman): %s\n\n" % func
.name
)
5354 def WriteImmediateServiceUnitTest(self
, func
, file, *extras
):
5355 """Overrriden from TypeHandler."""
5356 file.Write("// TODO(gman): %s\n\n" % func
.name
)
5358 def WriteBucketServiceImplementation(self
, func
, file):
5359 """Overrriden from TypeHandler."""
5360 if ((not func
.name
== 'CompressedTexSubImage2DBucket') and
5361 (not func
.name
== 'CompressedTexSubImage3DBucket')):
5362 TypeHandler
.WriteBucketServiceImplemenation(self
, func
, file)
5365 class BindHandler(TypeHandler
):
5366 """Handler for glBind___ type functions."""
5369 TypeHandler
.__init
__(self
)
5371 def WriteServiceUnitTest(self
, func
, file, *extras
):
5372 """Overrriden from TypeHandler."""
5374 if len(func
.GetOriginalArgs()) == 1:
5376 TEST_P(%(test_name)s, %(name)sValidArgs) {
5377 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
5378 SpecializedSetup<cmds::%(name)s, 0>(true);
5380 cmd.Init(%(args)s);"""
5383 decoder_->set_unsafe_es3_apis_enabled(true);
5384 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5385 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5386 decoder_->set_unsafe_es3_apis_enabled(false);
5387 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));
5392 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5393 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5396 if func
.GetInfo("gen_func"):
5398 TEST_P(%(test_name)s, %(name)sValidArgsNewId) {
5399 EXPECT_CALL(*gl_, %(gl_func_name)s(kNewServiceId));
5400 EXPECT_CALL(*gl_, %(gl_gen_func_name)s(1, _))
5401 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
5402 SpecializedSetup<cmds::%(name)s, 0>(true);
5404 cmd.Init(kNewClientId);
5405 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5406 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5407 EXPECT_TRUE(Get%(resource_type)s(kNewClientId) != NULL);
5410 self
.WriteValidUnitTest(func
, file, valid_test
, {
5411 'resource_type': func
.GetOriginalArgs()[0].resource_type
,
5412 'gl_gen_func_name': func
.GetInfo("gen_func"),
5416 TEST_P(%(test_name)s, %(name)sValidArgs) {
5417 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
5418 SpecializedSetup<cmds::%(name)s, 0>(true);
5420 cmd.Init(%(args)s);"""
5423 decoder_->set_unsafe_es3_apis_enabled(true);
5424 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5425 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5426 decoder_->set_unsafe_es3_apis_enabled(false);
5427 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));
5432 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5433 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5436 if func
.GetInfo("gen_func"):
5438 TEST_P(%(test_name)s, %(name)sValidArgsNewId) {
5440 %(gl_func_name)s(%(gl_args_with_new_id)s));
5441 EXPECT_CALL(*gl_, %(gl_gen_func_name)s(1, _))
5442 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
5443 SpecializedSetup<cmds::%(name)s, 0>(true);
5445 cmd.Init(%(args_with_new_id)s);"""
5448 decoder_->set_unsafe_es3_apis_enabled(true);
5449 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5450 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5451 EXPECT_TRUE(Get%(resource_type)s(kNewClientId) != NULL);
5452 decoder_->set_unsafe_es3_apis_enabled(false);
5453 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));
5458 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5459 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5460 EXPECT_TRUE(Get%(resource_type)s(kNewClientId) != NULL);
5464 gl_args_with_new_id
= []
5465 args_with_new_id
= []
5466 for arg
in func
.GetOriginalArgs():
5467 if hasattr(arg
, 'resource_type'):
5468 gl_args_with_new_id
.append('kNewServiceId')
5469 args_with_new_id
.append('kNewClientId')
5471 gl_args_with_new_id
.append(arg
.GetValidGLArg(func
))
5472 args_with_new_id
.append(arg
.GetValidArg(func
))
5473 self
.WriteValidUnitTest(func
, file, valid_test
, {
5474 'args_with_new_id': ", ".join(args_with_new_id
),
5475 'gl_args_with_new_id': ", ".join(gl_args_with_new_id
),
5476 'resource_type': func
.GetResourceIdArg().resource_type
,
5477 'gl_gen_func_name': func
.GetInfo("gen_func"),
5481 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
5482 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
5483 SpecializedSetup<cmds::%(name)s, 0>(false);
5486 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
5489 self
.WriteInvalidUnitTest(func
, file, invalid_test
, *extras
)
5491 def WriteGLES2Implementation(self
, func
, file):
5492 """Writes the GLES2 Implemention."""
5494 impl_func
= func
.GetInfo('impl_func')
5495 impl_decl
= func
.GetInfo('impl_decl')
5497 if (func
.can_auto_generate
and
5498 (impl_func
== None or impl_func
== True) and
5499 (impl_decl
== None or impl_decl
== True)):
5501 file.Write("%s GLES2Implementation::%s(%s) {\n" %
5502 (func
.return_type
, func
.original_name
,
5503 func
.MakeTypedOriginalArgString("")))
5504 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
5505 func
.WriteDestinationInitalizationValidation(file)
5506 self
.WriteClientGLCallLog(func
, file)
5507 for arg
in func
.GetOriginalArgs():
5508 arg
.WriteClientSideValidationCode(file, func
)
5510 code
= """ if (Is%(type)sReservedId(%(id)s)) {
5511 SetGLError(GL_INVALID_OPERATION, "%(name)s\", \"%(id)s reserved id");
5514 %(name)sHelper(%(arg_string)s);
5519 name_arg
= func
.GetResourceIdArg()
5522 'arg_string': func
.MakeOriginalArgString(""),
5523 'id': name_arg
.name
,
5524 'type': name_arg
.resource_type
,
5525 'lc_type': name_arg
.resource_type
.lower(),
5528 def WriteGLES2ImplementationUnitTest(self
, func
, file):
5529 """Overrriden from TypeHandler."""
5530 client_test
= func
.GetInfo('client_test')
5531 if client_test
== False:
5534 TEST_F(GLES2ImplementationTest, %(name)s) {
5539 expected.cmd.Init(%(cmd_args)s);
5541 gl_->%(name)s(%(args)s);
5542 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));"""
5543 if not func
.IsUnsafe():
5546 gl_->%(name)s(%(args)s);
5547 EXPECT_TRUE(NoCommandsWritten());"""
5552 arg
.GetValidClientSideCmdArg(func
) for arg
in func
.GetCmdArgs()
5555 arg
.GetValidClientSideArg(func
) for arg
in func
.GetOriginalArgs()
5560 'args': ", ".join(gl_arg_strings
),
5561 'cmd_args': ", ".join(cmd_arg_strings
),
5565 class GENnHandler(TypeHandler
):
5566 """Handler for glGen___ type functions."""
5569 TypeHandler
.__init
__(self
)
5571 def InitFunction(self
, func
):
5572 """Overrriden from TypeHandler."""
5575 def WriteGetDataSizeCode(self
, func
, file):
5576 """Overrriden from TypeHandler."""
5577 code
= """ uint32_t data_size;
5578 if (!SafeMultiplyUint32(n, sizeof(GLuint), &data_size)) {
5579 return error::kOutOfBounds;
5584 def WriteHandlerImplementation (self
, func
, file):
5585 """Overrriden from TypeHandler."""
5586 file.Write(" if (!%sHelper(n, %s)) {\n"
5587 " return error::kInvalidArguments;\n"
5589 (func
.name
, func
.GetLastOriginalArg().name
))
5591 def WriteImmediateHandlerImplementation(self
, func
, file):
5592 """Overrriden from TypeHandler."""
5594 file.Write(""" for (GLsizei ii = 0; ii < n; ++ii) {
5595 if (group_->Get%(resource_name)sServiceId(%(last_arg_name)s[ii], NULL)) {
5596 return error::kInvalidArguments;
5599 scoped_ptr<GLuint[]> service_ids(new GLuint[n]);
5600 gl%(func_name)s(n, service_ids.get());
5601 for (GLsizei ii = 0; ii < n; ++ii) {
5602 group_->Add%(resource_name)sId(%(last_arg_name)s[ii], service_ids[ii]);
5604 """ % { 'func_name': func
.original_name
,
5605 'last_arg_name': func
.GetLastOriginalArg().name
,
5606 'resource_name': func
.GetInfo('resource_type') })
5608 file.Write(" if (!%sHelper(n, %s)) {\n"
5609 " return error::kInvalidArguments;\n"
5611 (func
.original_name
, func
.GetLastOriginalArg().name
))
5613 def WriteGLES2Implementation(self
, func
, file):
5614 """Overrriden from TypeHandler."""
5615 log_code
= (""" GPU_CLIENT_LOG_CODE_BLOCK({
5616 for (GLsizei i = 0; i < n; ++i) {
5617 GPU_CLIENT_LOG(" " << i << ": " << %s[i]);
5619 });""" % func
.GetOriginalArgs()[1].name
)
5621 'log_code': log_code
,
5622 'return_type': func
.return_type
,
5623 'name': func
.original_name
,
5624 'typed_args': func
.MakeTypedOriginalArgString(""),
5625 'args': func
.MakeOriginalArgString(""),
5626 'resource_types': func
.GetInfo('resource_types'),
5627 'count_name': func
.GetOriginalArgs()[0].name
,
5630 "%(return_type)s GLES2Implementation::%(name)s(%(typed_args)s) {\n" %
5632 func
.WriteDestinationInitalizationValidation(file)
5633 self
.WriteClientGLCallLog(func
, file)
5634 for arg
in func
.GetOriginalArgs():
5635 arg
.WriteClientSideValidationCode(file, func
)
5636 not_shared
= func
.GetInfo('not_shared')
5640 """ IdAllocator* id_allocator = GetIdAllocator(id_namespaces::k%s);
5641 for (GLsizei ii = 0; ii < n; ++ii)
5642 %s[ii] = id_allocator->AllocateID();""" %
5643 (func
.GetInfo('resource_types'), func
.GetOriginalArgs()[1].name
))
5645 alloc_code
= (""" GetIdHandler(id_namespaces::k%(resource_types)s)->
5646 MakeIds(this, 0, %(args)s);""" % args
)
5647 args
['alloc_code'] = alloc_code
5649 code
= """ GPU_CLIENT_SINGLE_THREAD_CHECK();
5651 %(name)sHelper(%(args)s);
5652 helper_->%(name)sImmediate(%(args)s);
5653 if (share_group_->bind_generates_resource())
5654 helper_->CommandBufferHelper::Flush();
5660 file.Write(code
% args
)
5662 def WriteGLES2ImplementationUnitTest(self
, func
, file):
5663 """Overrriden from TypeHandler."""
5665 TEST_F(GLES2ImplementationTest, %(name)s) {
5666 GLuint ids[2] = { 0, };
5668 cmds::%(name)sImmediate gen;
5672 expected.gen.Init(arraysize(ids), &ids[0]);
5673 expected.data[0] = k%(types)sStartId;
5674 expected.data[1] = k%(types)sStartId + 1;
5675 gl_->%(name)s(arraysize(ids), &ids[0]);
5676 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
5677 EXPECT_EQ(k%(types)sStartId, ids[0]);
5678 EXPECT_EQ(k%(types)sStartId + 1, ids[1]);
5683 'types': func
.GetInfo('resource_types'),
5686 def WriteServiceUnitTest(self
, func
, file, *extras
):
5687 """Overrriden from TypeHandler."""
5689 TEST_P(%(test_name)s, %(name)sValidArgs) {
5690 EXPECT_CALL(*gl_, %(gl_func_name)s(1, _))
5691 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
5692 GetSharedMemoryAs<GLuint*>()[0] = kNewClientId;
5693 SpecializedSetup<cmds::%(name)s, 0>(true);
5696 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5697 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
5701 EXPECT_TRUE(Get%(resource_name)sServiceId(kNewClientId, &service_id));
5702 EXPECT_EQ(kNewServiceId, service_id)
5707 EXPECT_TRUE(Get%(resource_name)s(kNewClientId, &service_id) != NULL);
5710 self
.WriteValidUnitTest(func
, file, valid_test
, {
5711 'resource_name': func
.GetInfo('resource_type'),
5714 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
5715 EXPECT_CALL(*gl_, %(gl_func_name)s(_, _)).Times(0);
5716 GetSharedMemoryAs<GLuint*>()[0] = client_%(resource_name)s_id_;
5717 SpecializedSetup<cmds::%(name)s, 0>(false);
5720 EXPECT_EQ(error::kInvalidArguments, ExecuteCmd(cmd));
5723 self
.WriteValidUnitTest(func
, file, invalid_test
, {
5724 'resource_name': func
.GetInfo('resource_type').lower(),
5727 def WriteImmediateServiceUnitTest(self
, func
, file, *extras
):
5728 """Overrriden from TypeHandler."""
5730 TEST_P(%(test_name)s, %(name)sValidArgs) {
5731 EXPECT_CALL(*gl_, %(gl_func_name)s(1, _))
5732 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
5733 cmds::%(name)s* cmd = GetImmediateAs<cmds::%(name)s>();
5734 GLuint temp = kNewClientId;
5735 SpecializedSetup<cmds::%(name)s, 0>(true);"""
5738 decoder_->set_unsafe_es3_apis_enabled(true);"""
5740 cmd->Init(1, &temp);
5741 EXPECT_EQ(error::kNoError,
5742 ExecuteImmediateCmd(*cmd, sizeof(temp)));
5743 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
5747 EXPECT_TRUE(Get%(resource_name)sServiceId(kNewClientId, &service_id));
5748 EXPECT_EQ(kNewServiceId, service_id);
5749 decoder_->set_unsafe_es3_apis_enabled(false);
5750 EXPECT_EQ(error::kUnknownCommand,
5751 ExecuteImmediateCmd(*cmd, sizeof(temp)));
5756 EXPECT_TRUE(Get%(resource_name)s(kNewClientId) != NULL);
5759 self
.WriteValidUnitTest(func
, file, valid_test
, {
5760 'resource_name': func
.GetInfo('resource_type'),
5763 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
5764 EXPECT_CALL(*gl_, %(gl_func_name)s(_, _)).Times(0);
5765 cmds::%(name)s* cmd = GetImmediateAs<cmds::%(name)s>();
5766 SpecializedSetup<cmds::%(name)s, 0>(false);
5767 cmd->Init(1, &client_%(resource_name)s_id_);"""
5770 decoder_->set_unsafe_es3_apis_enabled(true);
5771 EXPECT_EQ(error::kInvalidArguments,
5772 ExecuteImmediateCmd(*cmd, sizeof(&client_%(resource_name)s_id_)));
5773 decoder_->set_unsafe_es3_apis_enabled(false);
5778 EXPECT_EQ(error::kInvalidArguments,
5779 ExecuteImmediateCmd(*cmd, sizeof(&client_%(resource_name)s_id_)));
5782 self
.WriteValidUnitTest(func
, file, invalid_test
, {
5783 'resource_name': func
.GetInfo('resource_type').lower(),
5786 def WriteImmediateCmdComputeSize(self
, func
, file):
5787 """Overrriden from TypeHandler."""
5788 file.Write(" static uint32_t ComputeDataSize(GLsizei n) {\n")
5790 " return static_cast<uint32_t>(sizeof(GLuint) * n); // NOLINT\n")
5793 file.Write(" static uint32_t ComputeSize(GLsizei n) {\n")
5794 file.Write(" return static_cast<uint32_t>(\n")
5795 file.Write(" sizeof(ValueType) + ComputeDataSize(n)); // NOLINT\n")
5799 def WriteImmediateCmdSetHeader(self
, func
, file):
5800 """Overrriden from TypeHandler."""
5801 file.Write(" void SetHeader(GLsizei n) {\n")
5802 file.Write(" header.SetCmdByTotalSize<ValueType>(ComputeSize(n));\n")
5806 def WriteImmediateCmdInit(self
, func
, file):
5807 """Overrriden from TypeHandler."""
5808 last_arg
= func
.GetLastOriginalArg()
5809 file.Write(" void Init(%s, %s _%s) {\n" %
5810 (func
.MakeTypedCmdArgString("_"),
5811 last_arg
.type, last_arg
.name
))
5812 file.Write(" SetHeader(_n);\n")
5813 args
= func
.GetCmdArgs()
5815 file.Write(" %s = _%s;\n" % (arg
.name
, arg
.name
))
5816 file.Write(" memcpy(ImmediateDataAddress(this),\n")
5817 file.Write(" _%s, ComputeDataSize(_n));\n" % last_arg
.name
)
5821 def WriteImmediateCmdSet(self
, func
, file):
5822 """Overrriden from TypeHandler."""
5823 last_arg
= func
.GetLastOriginalArg()
5824 copy_args
= func
.MakeCmdArgString("_", False)
5825 file.Write(" void* Set(void* cmd%s, %s _%s) {\n" %
5826 (func
.MakeTypedCmdArgString("_", True),
5827 last_arg
.type, last_arg
.name
))
5828 file.Write(" static_cast<ValueType*>(cmd)->Init(%s, _%s);\n" %
5829 (copy_args
, last_arg
.name
))
5830 file.Write(" const uint32_t size = ComputeSize(_n);\n")
5831 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
5836 def WriteImmediateCmdHelper(self
, func
, file):
5837 """Overrriden from TypeHandler."""
5838 code
= """ void %(name)s(%(typed_args)s) {
5839 const uint32_t size = gles2::cmds::%(name)s::ComputeSize(n);
5840 gles2::cmds::%(name)s* c =
5841 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
5850 "typed_args": func
.MakeTypedOriginalArgString(""),
5851 "args": func
.MakeOriginalArgString(""),
5854 def WriteImmediateFormatTest(self
, func
, file):
5855 """Overrriden from TypeHandler."""
5856 file.Write("TEST_F(GLES2FormatTest, %s) {\n" % func
.name
)
5857 file.Write(" static GLuint ids[] = { 12, 23, 34, };\n")
5858 file.Write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
5859 (func
.name
, func
.name
))
5860 file.Write(" void* next_cmd = cmd.Set(\n")
5861 file.Write(" &cmd, static_cast<GLsizei>(arraysize(ids)), ids);\n")
5862 file.Write(" EXPECT_EQ(static_cast<uint32_t>(cmds::%s::kCmdId),\n" %
5864 file.Write(" cmd.header.command);\n")
5865 file.Write(" EXPECT_EQ(sizeof(cmd) +\n")
5866 file.Write(" RoundSizeToMultipleOfEntries(cmd.n * 4u),\n")
5867 file.Write(" cmd.header.size * 4u);\n")
5868 file.Write(" EXPECT_EQ(static_cast<GLsizei>(arraysize(ids)), cmd.n);\n");
5869 file.Write(" CheckBytesWrittenMatchesExpectedSize(\n")
5870 file.Write(" next_cmd, sizeof(cmd) +\n")
5871 file.Write(" RoundSizeToMultipleOfEntries(arraysize(ids) * 4u));\n")
5872 file.Write(" // TODO(gman): Check that ids were inserted;\n")
5877 class CreateHandler(TypeHandler
):
5878 """Handler for glCreate___ type functions."""
5881 TypeHandler
.__init
__(self
)
5883 def InitFunction(self
, func
):
5884 """Overrriden from TypeHandler."""
5885 func
.AddCmdArg(Argument("client_id", 'uint32_t'))
5887 def __GetResourceType(self
, func
):
5888 if func
.return_type
== "GLsync":
5891 return func
.name
[6:] # Create*
5893 def WriteServiceUnitTest(self
, func
, file, *extras
):
5894 """Overrriden from TypeHandler."""
5896 TEST_P(%(test_name)s, %(name)sValidArgs) {
5897 %(id_type_cast)sEXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s))
5898 .WillOnce(Return(%(const_service_id)s));
5899 SpecializedSetup<cmds::%(name)s, 0>(true);
5901 cmd.Init(%(args)s%(comma)skNewClientId);"""
5904 decoder_->set_unsafe_es3_apis_enabled(true);"""
5906 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5907 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
5910 %(return_type)s service_id = 0;
5911 EXPECT_TRUE(Get%(resource_type)sServiceId(kNewClientId, &service_id));
5912 EXPECT_EQ(%(const_service_id)s, service_id);
5913 decoder_->set_unsafe_es3_apis_enabled(false);
5914 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));
5919 EXPECT_TRUE(Get%(resource_type)s(kNewClientId));
5924 for arg
in func
.GetOriginalArgs():
5925 if not arg
.IsConstant():
5929 if func
.return_type
== 'GLsync':
5930 id_type_cast
= ("const GLsync kNewServiceIdGLuint = reinterpret_cast"
5931 "<GLsync>(kNewServiceId);\n ")
5932 const_service_id
= "kNewServiceIdGLuint"
5935 const_service_id
= "kNewServiceId"
5936 self
.WriteValidUnitTest(func
, file, valid_test
, {
5938 'resource_type': self
.__GetResourceType
(func
),
5939 'return_type': func
.return_type
,
5940 'id_type_cast': id_type_cast
,
5941 'const_service_id': const_service_id
,
5944 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
5945 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
5946 SpecializedSetup<cmds::%(name)s, 0>(false);
5948 cmd.Init(%(args)s%(comma)skNewClientId);
5949 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));%(gl_error_test)s
5952 self
.WriteInvalidUnitTest(func
, file, invalid_test
, {
5956 def WriteHandlerImplementation (self
, func
, file):
5957 """Overrriden from TypeHandler."""
5959 code
= """ uint32_t client_id = c.client_id;
5960 %(return_type)s service_id = 0;
5961 if (group_->Get%(resource_name)sServiceId(client_id, &service_id)) {
5962 return error::kInvalidArguments;
5964 service_id = %(gl_func_name)s(%(gl_args)s);
5966 group_->Add%(resource_name)sId(client_id, service_id);
5970 code
= """ uint32_t client_id = c.client_id;
5971 if (Get%(resource_name)s(client_id)) {
5972 return error::kInvalidArguments;
5974 %(return_type)s service_id = %(gl_func_name)s(%(gl_args)s);
5976 Create%(resource_name)s(client_id, service_id%(gl_args_with_comma)s);
5980 'resource_name': self
.__GetResourceType
(func
),
5981 'return_type': func
.return_type
,
5982 'gl_func_name': func
.GetGLFunctionName(),
5983 'gl_args': func
.MakeOriginalArgString(""),
5984 'gl_args_with_comma': func
.MakeOriginalArgString("", True) })
5986 def WriteGLES2Implementation(self
, func
, file):
5987 """Overrriden from TypeHandler."""
5988 file.Write("%s GLES2Implementation::%s(%s) {\n" %
5989 (func
.return_type
, func
.original_name
,
5990 func
.MakeTypedOriginalArgString("")))
5991 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
5992 func
.WriteDestinationInitalizationValidation(file)
5993 self
.WriteClientGLCallLog(func
, file)
5994 for arg
in func
.GetOriginalArgs():
5995 arg
.WriteClientSideValidationCode(file, func
)
5996 file.Write(" GLuint client_id;\n")
5997 if func
.return_type
== "GLsync":
5999 " GetIdHandler(id_namespaces::kSyncs)->\n")
6002 " GetIdHandler(id_namespaces::kProgramsAndShaders)->\n")
6003 file.Write(" MakeIds(this, 0, 1, &client_id);\n")
6004 file.Write(" helper_->%s(%s);\n" %
6005 (func
.name
, func
.MakeCmdArgString("")))
6006 file.Write(' GPU_CLIENT_LOG("returned " << client_id);\n')
6007 file.Write(" CheckGLError();\n")
6008 if func
.return_type
== "GLsync":
6009 file.Write(" return reinterpret_cast<GLsync>(client_id);\n")
6011 file.Write(" return client_id;\n")
6016 class DeleteHandler(TypeHandler
):
6017 """Handler for glDelete___ single resource type functions."""
6020 TypeHandler
.__init
__(self
)
6022 def WriteServiceImplementation(self
, func
, file):
6023 """Overrriden from TypeHandler."""
6025 TypeHandler
.WriteServiceImplementation(self
, func
, file)
6026 # HandleDeleteShader and HandleDeleteProgram are manually written.
6029 def WriteGLES2Implementation(self
, func
, file):
6030 """Overrriden from TypeHandler."""
6031 file.Write("%s GLES2Implementation::%s(%s) {\n" %
6032 (func
.return_type
, func
.original_name
,
6033 func
.MakeTypedOriginalArgString("")))
6034 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
6035 func
.WriteDestinationInitalizationValidation(file)
6036 self
.WriteClientGLCallLog(func
, file)
6037 for arg
in func
.GetOriginalArgs():
6038 arg
.WriteClientSideValidationCode(file, func
)
6040 " GPU_CLIENT_DCHECK(%s != 0);\n" % func
.GetOriginalArgs()[-1].name
)
6041 file.Write(" %sHelper(%s);\n" %
6042 (func
.original_name
, func
.GetOriginalArgs()[-1].name
))
6043 file.Write(" CheckGLError();\n")
6047 def WriteHandlerImplementation (self
, func
, file):
6048 """Overrriden from TypeHandler."""
6049 assert len(func
.GetOriginalArgs()) == 1
6050 arg
= func
.GetOriginalArgs()[0]
6052 file.Write(""" %(arg_type)s service_id = 0;
6053 if (group_->Get%(resource_type)sServiceId(%(arg_name)s, &service_id)) {
6054 glDelete%(resource_type)s(service_id);
6055 group_->Remove%(resource_type)sId(%(arg_name)s);
6058 GL_INVALID_VALUE, "gl%(func_name)s", "unknown %(arg_name)s");
6060 """ % { 'resource_type': func
.GetInfo('resource_type'),
6061 'arg_name': arg
.name
,
6062 'arg_type': arg
.type,
6063 'func_name': func
.original_name
})
6065 file.Write(" %sHelper(%s);\n" % (func
.original_name
, arg
.name
))
6067 class DELnHandler(TypeHandler
):
6068 """Handler for glDelete___ type functions."""
6071 TypeHandler
.__init
__(self
)
6073 def WriteGetDataSizeCode(self
, func
, file):
6074 """Overrriden from TypeHandler."""
6075 code
= """ uint32_t data_size;
6076 if (!SafeMultiplyUint32(n, sizeof(GLuint), &data_size)) {
6077 return error::kOutOfBounds;
6082 def WriteGLES2ImplementationUnitTest(self
, func
, file):
6083 """Overrriden from TypeHandler."""
6085 TEST_F(GLES2ImplementationTest, %(name)s) {
6086 GLuint ids[2] = { k%(types)sStartId, k%(types)sStartId + 1 };
6088 cmds::%(name)sImmediate del;
6092 expected.del.Init(arraysize(ids), &ids[0]);
6093 expected.data[0] = k%(types)sStartId;
6094 expected.data[1] = k%(types)sStartId + 1;
6095 gl_->%(name)s(arraysize(ids), &ids[0]);
6096 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
6101 'types': func
.GetInfo('resource_types'),
6104 def WriteServiceUnitTest(self
, func
, file, *extras
):
6105 """Overrriden from TypeHandler."""
6107 TEST_P(%(test_name)s, %(name)sValidArgs) {
6110 %(gl_func_name)s(1, Pointee(kService%(upper_resource_name)sId)))
6112 GetSharedMemoryAs<GLuint*>()[0] = client_%(resource_name)s_id_;
6113 SpecializedSetup<cmds::%(name)s, 0>(true);
6116 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
6117 EXPECT_EQ(GL_NO_ERROR, GetGLError());
6119 Get%(upper_resource_name)s(client_%(resource_name)s_id_) == NULL);
6122 self
.WriteValidUnitTest(func
, file, valid_test
, {
6123 'resource_name': func
.GetInfo('resource_type').lower(),
6124 'upper_resource_name': func
.GetInfo('resource_type'),
6127 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
6128 GetSharedMemoryAs<GLuint*>()[0] = kInvalidClientId;
6129 SpecializedSetup<cmds::%(name)s, 0>(false);
6132 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
6135 self
.WriteValidUnitTest(func
, file, invalid_test
, *extras
)
6137 def WriteImmediateServiceUnitTest(self
, func
, file, *extras
):
6138 """Overrriden from TypeHandler."""
6140 TEST_P(%(test_name)s, %(name)sValidArgs) {
6143 %(gl_func_name)s(1, Pointee(kService%(upper_resource_name)sId)))
6145 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
6146 SpecializedSetup<cmds::%(name)s, 0>(true);
6147 cmd.Init(1, &client_%(resource_name)s_id_);"""
6150 decoder_->set_unsafe_es3_apis_enabled(true);"""
6152 EXPECT_EQ(error::kNoError,
6153 ExecuteImmediateCmd(cmd, sizeof(client_%(resource_name)s_id_)));
6154 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
6157 EXPECT_FALSE(Get%(upper_resource_name)sServiceId(
6158 client_%(resource_name)s_id_, NULL));
6159 decoder_->set_unsafe_es3_apis_enabled(false);
6160 EXPECT_EQ(error::kUnknownCommand,
6161 ExecuteImmediateCmd(cmd, sizeof(client_%(resource_name)s_id_)));
6167 Get%(upper_resource_name)s(client_%(resource_name)s_id_) == NULL);
6170 self
.WriteValidUnitTest(func
, file, valid_test
, {
6171 'resource_name': func
.GetInfo('resource_type').lower(),
6172 'upper_resource_name': func
.GetInfo('resource_type'),
6175 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
6176 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
6177 SpecializedSetup<cmds::%(name)s, 0>(false);
6178 GLuint temp = kInvalidClientId;
6179 cmd.Init(1, &temp);"""
6182 decoder_->set_unsafe_es3_apis_enabled(true);
6183 EXPECT_EQ(error::kNoError,
6184 ExecuteImmediateCmd(cmd, sizeof(temp)));
6185 decoder_->set_unsafe_es3_apis_enabled(false);
6186 EXPECT_EQ(error::kUnknownCommand,
6187 ExecuteImmediateCmd(cmd, sizeof(temp)));
6192 EXPECT_EQ(error::kNoError,
6193 ExecuteImmediateCmd(cmd, sizeof(temp)));
6196 self
.WriteValidUnitTest(func
, file, invalid_test
, *extras
)
6198 def WriteHandlerImplementation (self
, func
, file):
6199 """Overrriden from TypeHandler."""
6200 file.Write(" %sHelper(n, %s);\n" %
6201 (func
.name
, func
.GetLastOriginalArg().name
))
6203 def WriteImmediateHandlerImplementation (self
, func
, file):
6204 """Overrriden from TypeHandler."""
6206 file.Write(""" for (GLsizei ii = 0; ii < n; ++ii) {
6207 GLuint service_id = 0;
6208 if (group_->Get%(resource_type)sServiceId(
6209 %(last_arg_name)s[ii], &service_id)) {
6210 glDelete%(resource_type)ss(1, &service_id);
6211 group_->Remove%(resource_type)sId(%(last_arg_name)s[ii]);
6214 """ % { 'resource_type': func
.GetInfo('resource_type'),
6215 'last_arg_name': func
.GetLastOriginalArg().name
})
6217 file.Write(" %sHelper(n, %s);\n" %
6218 (func
.original_name
, func
.GetLastOriginalArg().name
))
6220 def WriteGLES2Implementation(self
, func
, file):
6221 """Overrriden from TypeHandler."""
6222 impl_decl
= func
.GetInfo('impl_decl')
6223 if impl_decl
== None or impl_decl
== True:
6225 'return_type': func
.return_type
,
6226 'name': func
.original_name
,
6227 'typed_args': func
.MakeTypedOriginalArgString(""),
6228 'args': func
.MakeOriginalArgString(""),
6229 'resource_type': func
.GetInfo('resource_type').lower(),
6230 'count_name': func
.GetOriginalArgs()[0].name
,
6233 "%(return_type)s GLES2Implementation::%(name)s(%(typed_args)s) {\n" %
6235 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
6236 func
.WriteDestinationInitalizationValidation(file)
6237 self
.WriteClientGLCallLog(func
, file)
6238 file.Write(""" GPU_CLIENT_LOG_CODE_BLOCK({
6239 for (GLsizei i = 0; i < n; ++i) {
6240 GPU_CLIENT_LOG(" " << i << ": " << %s[i]);
6243 """ % func
.GetOriginalArgs()[1].name
)
6244 file.Write(""" GPU_CLIENT_DCHECK_CODE_BLOCK({
6245 for (GLsizei i = 0; i < n; ++i) {
6249 """ % func
.GetOriginalArgs()[1].name
)
6250 for arg
in func
.GetOriginalArgs():
6251 arg
.WriteClientSideValidationCode(file, func
)
6252 code
= """ %(name)sHelper(%(args)s);
6257 file.Write(code
% args
)
6259 def WriteImmediateCmdComputeSize(self
, func
, file):
6260 """Overrriden from TypeHandler."""
6261 file.Write(" static uint32_t ComputeDataSize(GLsizei n) {\n")
6263 " return static_cast<uint32_t>(sizeof(GLuint) * n); // NOLINT\n")
6266 file.Write(" static uint32_t ComputeSize(GLsizei n) {\n")
6267 file.Write(" return static_cast<uint32_t>(\n")
6268 file.Write(" sizeof(ValueType) + ComputeDataSize(n)); // NOLINT\n")
6272 def WriteImmediateCmdSetHeader(self
, func
, file):
6273 """Overrriden from TypeHandler."""
6274 file.Write(" void SetHeader(GLsizei n) {\n")
6275 file.Write(" header.SetCmdByTotalSize<ValueType>(ComputeSize(n));\n")
6279 def WriteImmediateCmdInit(self
, func
, file):
6280 """Overrriden from TypeHandler."""
6281 last_arg
= func
.GetLastOriginalArg()
6282 file.Write(" void Init(%s, %s _%s) {\n" %
6283 (func
.MakeTypedCmdArgString("_"),
6284 last_arg
.type, last_arg
.name
))
6285 file.Write(" SetHeader(_n);\n")
6286 args
= func
.GetCmdArgs()
6288 file.Write(" %s = _%s;\n" % (arg
.name
, arg
.name
))
6289 file.Write(" memcpy(ImmediateDataAddress(this),\n")
6290 file.Write(" _%s, ComputeDataSize(_n));\n" % last_arg
.name
)
6294 def WriteImmediateCmdSet(self
, func
, file):
6295 """Overrriden from TypeHandler."""
6296 last_arg
= func
.GetLastOriginalArg()
6297 copy_args
= func
.MakeCmdArgString("_", False)
6298 file.Write(" void* Set(void* cmd%s, %s _%s) {\n" %
6299 (func
.MakeTypedCmdArgString("_", True),
6300 last_arg
.type, last_arg
.name
))
6301 file.Write(" static_cast<ValueType*>(cmd)->Init(%s, _%s);\n" %
6302 (copy_args
, last_arg
.name
))
6303 file.Write(" const uint32_t size = ComputeSize(_n);\n")
6304 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
6309 def WriteImmediateCmdHelper(self
, func
, file):
6310 """Overrriden from TypeHandler."""
6311 code
= """ void %(name)s(%(typed_args)s) {
6312 const uint32_t size = gles2::cmds::%(name)s::ComputeSize(n);
6313 gles2::cmds::%(name)s* c =
6314 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
6323 "typed_args": func
.MakeTypedOriginalArgString(""),
6324 "args": func
.MakeOriginalArgString(""),
6327 def WriteImmediateFormatTest(self
, func
, file):
6328 """Overrriden from TypeHandler."""
6329 file.Write("TEST_F(GLES2FormatTest, %s) {\n" % func
.name
)
6330 file.Write(" static GLuint ids[] = { 12, 23, 34, };\n")
6331 file.Write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
6332 (func
.name
, func
.name
))
6333 file.Write(" void* next_cmd = cmd.Set(\n")
6334 file.Write(" &cmd, static_cast<GLsizei>(arraysize(ids)), ids);\n")
6335 file.Write(" EXPECT_EQ(static_cast<uint32_t>(cmds::%s::kCmdId),\n" %
6337 file.Write(" cmd.header.command);\n")
6338 file.Write(" EXPECT_EQ(sizeof(cmd) +\n")
6339 file.Write(" RoundSizeToMultipleOfEntries(cmd.n * 4u),\n")
6340 file.Write(" cmd.header.size * 4u);\n")
6341 file.Write(" EXPECT_EQ(static_cast<GLsizei>(arraysize(ids)), cmd.n);\n");
6342 file.Write(" CheckBytesWrittenMatchesExpectedSize(\n")
6343 file.Write(" next_cmd, sizeof(cmd) +\n")
6344 file.Write(" RoundSizeToMultipleOfEntries(arraysize(ids) * 4u));\n")
6345 file.Write(" // TODO(gman): Check that ids were inserted;\n")
6350 class GETnHandler(TypeHandler
):
6351 """Handler for GETn for glGetBooleanv, glGetFloatv, ... type functions."""
6354 TypeHandler
.__init
__(self
)
6356 def NeedsDataTransferFunction(self
, func
):
6357 """Overriden from TypeHandler."""
6360 def WriteServiceImplementation(self
, func
, file):
6361 """Overrriden from TypeHandler."""
6362 self
.WriteServiceHandlerFunctionHeader(func
, file)
6363 last_arg
= func
.GetLastOriginalArg()
6364 # All except shm_id and shm_offset.
6365 all_but_last_args
= func
.GetCmdArgs()[:-2]
6366 for arg
in all_but_last_args
:
6367 arg
.WriteGetCode(file)
6369 code
= """ typedef cmds::%(func_name)s::Result Result;
6370 GLsizei num_values = 0;
6371 GetNumValuesReturnedForGLGet(pname, &num_values);
6372 Result* result = GetSharedMemoryAs<Result*>(
6373 c.%(last_arg_name)s_shm_id, c.%(last_arg_name)s_shm_offset,
6374 Result::ComputeSize(num_values));
6375 %(last_arg_type)s %(last_arg_name)s = result ? result->GetData() : NULL;
6378 'last_arg_type': last_arg
.type,
6379 'last_arg_name': last_arg
.name
,
6380 'func_name': func
.name
,
6382 func
.WriteHandlerValidation(file)
6383 code
= """ // Check that the client initialized the result.
6384 if (result->size != 0) {
6385 return error::kInvalidArguments;
6388 shadowed
= func
.GetInfo('shadowed')
6390 file.Write(' LOCAL_COPY_REAL_GL_ERRORS_TO_WRAPPER("%s");\n' % func
.name
)
6392 func
.WriteHandlerImplementation(file)
6394 code
= """ result->SetNumResults(num_values);
6395 return error::kNoError;
6399 code
= """ GLenum error = LOCAL_PEEK_GL_ERROR("%(func_name)s");
6400 if (error == GL_NO_ERROR) {
6401 result->SetNumResults(num_values);
6403 return error::kNoError;
6407 file.Write(code
% {'func_name': func
.name
})
6409 def WriteGLES2Implementation(self
, func
, file):
6410 """Overrriden from TypeHandler."""
6411 impl_decl
= func
.GetInfo('impl_decl')
6412 if impl_decl
== None or impl_decl
== True:
6413 file.Write("%s GLES2Implementation::%s(%s) {\n" %
6414 (func
.return_type
, func
.original_name
,
6415 func
.MakeTypedOriginalArgString("")))
6416 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
6417 func
.WriteDestinationInitalizationValidation(file)
6418 self
.WriteClientGLCallLog(func
, file)
6419 for arg
in func
.GetOriginalArgs():
6420 arg
.WriteClientSideValidationCode(file, func
)
6421 all_but_last_args
= func
.GetOriginalArgs()[:-1]
6423 has_length_arg
= False
6424 for arg
in all_but_last_args
:
6425 if arg
.type == 'GLsync':
6426 args
.append('ToGLuint(%s)' % arg
.name
)
6427 elif arg
.name
.endswith('size') and arg
.type == 'GLsizei':
6429 elif arg
.name
== 'length':
6430 has_length_arg
= True
6433 args
.append(arg
.name
)
6434 arg_string
= ", ".join(args
)
6438 for arg
in func
.GetOriginalArgs() if not arg
.IsConstant()]))
6439 self
.WriteTraceEvent(func
, file)
6440 code
= """ if (%(func_name)sHelper(%(all_arg_string)s)) {
6443 typedef cmds::%(func_name)s::Result Result;
6444 Result* result = GetResultAs<Result*>();
6448 result->SetNumResults(0);
6449 helper_->%(func_name)s(%(arg_string)s,
6450 GetResultShmId(), GetResultShmOffset());
6452 result->CopyResult(%(last_arg_name)s);
6453 GPU_CLIENT_LOG_CODE_BLOCK({
6454 for (int32_t i = 0; i < result->GetNumResults(); ++i) {
6455 GPU_CLIENT_LOG(" " << i << ": " << result->GetData()[i]);
6461 *length = result->GetNumResults();
6468 'func_name': func
.name
,
6469 'arg_string': arg_string
,
6470 'all_arg_string': all_arg_string
,
6471 'last_arg_name': func
.GetLastOriginalArg().name
,
6474 def WriteGLES2ImplementationUnitTest(self
, func
, file):
6475 """Writes the GLES2 Implemention unit test."""
6477 TEST_F(GLES2ImplementationTest, %(name)s) {
6481 typedef cmds::%(name)s::Result::Type ResultType;
6482 ResultType result = 0;
6484 ExpectedMemoryInfo result1 = GetExpectedResultMemory(
6485 sizeof(uint32_t) + sizeof(ResultType));
6486 expected.cmd.Init(%(cmd_args)s, result1.id, result1.offset);
6487 EXPECT_CALL(*command_buffer(), OnFlush())
6488 .WillOnce(SetMemory(result1.ptr, SizedResultHelper<ResultType>(1)))
6489 .RetiresOnSaturation();
6490 gl_->%(name)s(%(args)s, &result);
6491 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
6492 EXPECT_EQ(static_cast<ResultType>(1), result);
6495 first_cmd_arg
= func
.GetCmdArgs()[0].GetValidNonCachedClientSideCmdArg(func
)
6496 if not first_cmd_arg
:
6499 first_gl_arg
= func
.GetOriginalArgs()[0].GetValidNonCachedClientSideArg(
6502 cmd_arg_strings
= [first_cmd_arg
]
6503 for arg
in func
.GetCmdArgs()[1:-2]:
6504 cmd_arg_strings
.append(arg
.GetValidClientSideCmdArg(func
))
6505 gl_arg_strings
= [first_gl_arg
]
6506 for arg
in func
.GetOriginalArgs()[1:-1]:
6507 gl_arg_strings
.append(arg
.GetValidClientSideArg(func
))
6511 'args': ", ".join(gl_arg_strings
),
6512 'cmd_args': ", ".join(cmd_arg_strings
),
6515 def WriteServiceUnitTest(self
, func
, file, *extras
):
6516 """Overrriden from TypeHandler."""
6518 TEST_P(%(test_name)s, %(name)sValidArgs) {
6519 EXPECT_CALL(*gl_, GetError())
6520 .WillOnce(Return(GL_NO_ERROR))
6521 .WillOnce(Return(GL_NO_ERROR))
6522 .RetiresOnSaturation();
6523 SpecializedSetup<cmds::%(name)s, 0>(true);
6524 typedef cmds::%(name)s::Result Result;
6525 Result* result = static_cast<Result*>(shared_memory_address_);
6526 EXPECT_CALL(*gl_, %(gl_func_name)s(%(local_gl_args)s));
6529 cmd.Init(%(cmd_args)s);"""
6532 decoder_->set_unsafe_es3_apis_enabled(true);"""
6534 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
6535 EXPECT_EQ(decoder_->GetGLES2Util()->GLGetNumValuesReturned(
6537 result->GetNumResults());
6538 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
6541 decoder_->set_unsafe_es3_apis_enabled(false);
6542 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));"""
6547 cmd_arg_strings
= []
6549 for arg
in func
.GetOriginalArgs()[:-1]:
6550 if arg
.name
== 'length':
6551 gl_arg_value
= 'nullptr'
6552 elif arg
.name
.endswith('size'):
6553 gl_arg_value
= ("decoder_->GetGLES2Util()->GLGetNumValuesReturned(%s)" %
6555 elif arg
.type == 'GLsync':
6556 gl_arg_value
= 'reinterpret_cast<GLsync>(kServiceSyncId)'
6558 gl_arg_value
= arg
.GetValidGLArg(func
)
6559 gl_arg_strings
.append(gl_arg_value
)
6560 if arg
.name
== 'pname':
6561 valid_pname
= gl_arg_value
6562 if arg
.name
.endswith('size') or arg
.name
== 'length':
6564 if arg
.type == 'GLsync':
6565 arg_value
= 'client_sync_id_'
6567 arg_value
= arg
.GetValidArg(func
)
6568 cmd_arg_strings
.append(arg_value
)
6569 if func
.GetInfo('gl_test_func') == 'glGetIntegerv':
6570 gl_arg_strings
.append("_")
6572 gl_arg_strings
.append("result->GetData()")
6573 cmd_arg_strings
.append("shared_memory_id_")
6574 cmd_arg_strings
.append("shared_memory_offset_")
6576 self
.WriteValidUnitTest(func
, file, valid_test
, {
6577 'local_gl_args': ", ".join(gl_arg_strings
),
6578 'cmd_args': ", ".join(cmd_arg_strings
),
6579 'valid_pname': valid_pname
,
6582 if not func
.IsUnsafe():
6584 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
6585 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
6586 SpecializedSetup<cmds::%(name)s, 0>(false);
6587 cmds::%(name)s::Result* result =
6588 static_cast<cmds::%(name)s::Result*>(shared_memory_address_);
6592 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));
6593 EXPECT_EQ(0u, result->size);%(gl_error_test)s
6596 self
.WriteInvalidUnitTest(func
, file, invalid_test
, *extras
)
6598 class ArrayArgTypeHandler(TypeHandler
):
6599 """Base class for type handlers that handle args that are arrays"""
6602 TypeHandler
.__init
__(self
)
6604 def GetArrayType(self
, func
):
6605 """Returns the type of the element in the element array being PUT to."""
6606 for arg
in func
.GetOriginalArgs():
6608 element_type
= arg
.GetPointedType()
6611 # Special case: array type handler is used for a function that is forwarded
6612 # to the actual array type implementation
6613 element_type
= func
.GetOriginalArgs()[-1].type
6614 assert all(arg
.type == element_type \
6615 for arg
in func
.GetOriginalArgs()[-self
.GetArrayCount(func
):])
6618 def GetArrayCount(self
, func
):
6619 """Returns the count of the elements in the array being PUT to."""
6620 return func
.GetInfo('count')
6622 class PUTHandler(ArrayArgTypeHandler
):
6623 """Handler for glTexParameter_v, glVertexAttrib_v functions."""
6626 ArrayArgTypeHandler
.__init
__(self
)
6628 def WriteServiceUnitTest(self
, func
, file, *extras
):
6629 """Writes the service unit test for a command."""
6630 expected_call
= "EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));"
6631 if func
.GetInfo("first_element_only"):
6633 arg
.GetValidGLArg(func
) for arg
in func
.GetOriginalArgs()
6635 gl_arg_strings
[-1] = "*" + gl_arg_strings
[-1]
6636 expected_call
= ("EXPECT_CALL(*gl_, %%(gl_func_name)s(%s));" %
6637 ", ".join(gl_arg_strings
))
6639 TEST_P(%(test_name)s, %(name)sValidArgs) {
6640 SpecializedSetup<cmds::%(name)s, 0>(true);
6643 GetSharedMemoryAs<%(data_type)s*>()[0] = %(data_value)s;
6645 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
6646 EXPECT_EQ(GL_NO_ERROR, GetGLError());
6650 'data_type': self
.GetArrayType(func
),
6651 'data_value': func
.GetInfo('data_value') or '0',
6652 'expected_call': expected_call
,
6654 self
.WriteValidUnitTest(func
, file, valid_test
, extra
, *extras
)
6657 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
6658 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
6659 SpecializedSetup<cmds::%(name)s, 0>(false);
6662 GetSharedMemoryAs<%(data_type)s*>()[0] = %(data_value)s;
6663 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
6666 self
.WriteInvalidUnitTest(func
, file, invalid_test
, extra
, *extras
)
6668 def WriteImmediateServiceUnitTest(self
, func
, file, *extras
):
6669 """Writes the service unit test for a command."""
6671 TEST_P(%(test_name)s, %(name)sValidArgs) {
6672 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
6673 SpecializedSetup<cmds::%(name)s, 0>(true);
6674 %(data_type)s temp[%(data_count)s] = { %(data_value)s, };
6675 cmd.Init(%(gl_args)s, &temp[0]);
6678 %(gl_func_name)s(%(gl_args)s, %(data_ref)sreinterpret_cast<
6679 %(data_type)s*>(ImmediateDataAddress(&cmd))));"""
6682 decoder_->set_unsafe_es3_apis_enabled(true);"""
6684 EXPECT_EQ(error::kNoError,
6685 ExecuteImmediateCmd(cmd, sizeof(temp)));
6686 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
6689 decoder_->set_unsafe_es3_apis_enabled(false);
6690 EXPECT_EQ(error::kUnknownCommand,
6691 ExecuteImmediateCmd(cmd, sizeof(temp)));"""
6696 arg
.GetValidGLArg(func
) for arg
in func
.GetOriginalArgs()[0:-1]
6698 gl_any_strings
= ["_"] * len(gl_arg_strings
)
6701 'data_ref': ("*" if func
.GetInfo('first_element_only') else ""),
6702 'data_type': self
.GetArrayType(func
),
6703 'data_count': self
.GetArrayCount(func
),
6704 'data_value': func
.GetInfo('data_value') or '0',
6705 'gl_args': ", ".join(gl_arg_strings
),
6706 'gl_any_args': ", ".join(gl_any_strings
),
6708 self
.WriteValidUnitTest(func
, file, valid_test
, extra
, *extras
)
6711 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
6712 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();"""
6715 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_any_args)s, _)).Times(1);
6719 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_any_args)s, _)).Times(0);
6722 SpecializedSetup<cmds::%(name)s, 0>(false);
6723 %(data_type)s temp[%(data_count)s] = { %(data_value)s, };
6724 cmd.Init(%(all_but_last_args)s, &temp[0]);"""
6727 decoder_->set_unsafe_es3_apis_enabled(true);
6728 EXPECT_EQ(error::%(parse_result)s,
6729 ExecuteImmediateCmd(cmd, sizeof(temp)));
6730 decoder_->set_unsafe_es3_apis_enabled(false);
6735 EXPECT_EQ(error::%(parse_result)s,
6736 ExecuteImmediateCmd(cmd, sizeof(temp)));
6740 self
.WriteInvalidUnitTest(func
, file, invalid_test
, extra
, *extras
)
6742 def WriteGetDataSizeCode(self
, func
, file):
6743 """Overrriden from TypeHandler."""
6744 code
= """ uint32_t data_size;
6745 if (!ComputeDataSize(1, sizeof(%s), %d, &data_size)) {
6746 return error::kOutOfBounds;
6749 file.Write(code
% (self
.GetArrayType(func
), self
.GetArrayCount(func
)))
6750 if func
.IsImmediate():
6751 file.Write(" if (data_size > immediate_data_size) {\n")
6752 file.Write(" return error::kOutOfBounds;\n")
6755 def __NeedsToCalcDataCount(self
, func
):
6756 use_count_func
= func
.GetInfo('use_count_func')
6757 return use_count_func
!= None and use_count_func
!= False
6759 def WriteGLES2Implementation(self
, func
, file):
6760 """Overrriden from TypeHandler."""
6761 impl_func
= func
.GetInfo('impl_func')
6762 if (impl_func
!= None and impl_func
!= True):
6764 file.Write("%s GLES2Implementation::%s(%s) {\n" %
6765 (func
.return_type
, func
.original_name
,
6766 func
.MakeTypedOriginalArgString("")))
6767 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
6768 func
.WriteDestinationInitalizationValidation(file)
6769 self
.WriteClientGLCallLog(func
, file)
6771 if self
.__NeedsToCalcDataCount
(func
):
6772 file.Write(" size_t count = GLES2Util::Calc%sDataCount(%s);\n" %
6773 (func
.name
, func
.GetOriginalArgs()[0].name
))
6774 file.Write(" DCHECK_LE(count, %du);\n" % self
.GetArrayCount(func
))
6776 file.Write(" size_t count = %d;" % self
.GetArrayCount(func
))
6777 file.Write(" for (size_t ii = 0; ii < count; ++ii)\n")
6778 file.Write(' GPU_CLIENT_LOG("value[" << ii << "]: " << %s[ii]);\n' %
6779 func
.GetLastOriginalArg().name
)
6780 for arg
in func
.GetOriginalArgs():
6781 arg
.WriteClientSideValidationCode(file, func
)
6782 file.Write(" helper_->%sImmediate(%s);\n" %
6783 (func
.name
, func
.MakeOriginalArgString("")))
6784 file.Write(" CheckGLError();\n")
6788 def WriteGLES2ImplementationUnitTest(self
, func
, file):
6789 """Writes the GLES2 Implemention unit test."""
6790 client_test
= func
.GetInfo('client_test')
6791 if (client_test
!= None and client_test
!= True):
6794 TEST_F(GLES2ImplementationTest, %(name)s) {
6795 %(type)s data[%(count)d] = {0};
6797 cmds::%(name)sImmediate cmd;
6798 %(type)s data[%(count)d];
6801 for (int jj = 0; jj < %(count)d; ++jj) {
6802 data[jj] = static_cast<%(type)s>(jj);
6805 expected.cmd.Init(%(cmd_args)s, &data[0]);
6806 gl_->%(name)s(%(args)s, &data[0]);
6807 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
6811 arg
.GetValidClientSideCmdArg(func
) for arg
in func
.GetCmdArgs()[0:-2]
6814 arg
.GetValidClientSideArg(func
) for arg
in func
.GetOriginalArgs()[0:-1]
6819 'type': self
.GetArrayType(func
),
6820 'count': self
.GetArrayCount(func
),
6821 'args': ", ".join(gl_arg_strings
),
6822 'cmd_args': ", ".join(cmd_arg_strings
),
6825 def WriteImmediateCmdComputeSize(self
, func
, file):
6826 """Overrriden from TypeHandler."""
6827 file.Write(" static uint32_t ComputeDataSize() {\n")
6828 file.Write(" return static_cast<uint32_t>(\n")
6829 file.Write(" sizeof(%s) * %d);\n" %
6830 (self
.GetArrayType(func
), self
.GetArrayCount(func
)))
6833 if self
.__NeedsToCalcDataCount
(func
):
6834 file.Write(" static uint32_t ComputeEffectiveDataSize(%s %s) {\n" %
6835 (func
.GetOriginalArgs()[0].type,
6836 func
.GetOriginalArgs()[0].name
))
6837 file.Write(" return static_cast<uint32_t>(\n")
6838 file.Write(" sizeof(%s) * GLES2Util::Calc%sDataCount(%s));\n" %
6839 (self
.GetArrayType(func
), func
.original_name
,
6840 func
.GetOriginalArgs()[0].name
))
6843 file.Write(" static uint32_t ComputeSize() {\n")
6844 file.Write(" return static_cast<uint32_t>(\n")
6846 " sizeof(ValueType) + ComputeDataSize());\n")
6850 def WriteImmediateCmdSetHeader(self
, func
, file):
6851 """Overrriden from TypeHandler."""
6852 file.Write(" void SetHeader() {\n")
6854 " header.SetCmdByTotalSize<ValueType>(ComputeSize());\n")
6858 def WriteImmediateCmdInit(self
, func
, file):
6859 """Overrriden from TypeHandler."""
6860 last_arg
= func
.GetLastOriginalArg()
6861 file.Write(" void Init(%s, %s _%s) {\n" %
6862 (func
.MakeTypedCmdArgString("_"),
6863 last_arg
.type, last_arg
.name
))
6864 file.Write(" SetHeader();\n")
6865 args
= func
.GetCmdArgs()
6867 file.Write(" %s = _%s;\n" % (arg
.name
, arg
.name
))
6868 file.Write(" memcpy(ImmediateDataAddress(this),\n")
6869 if self
.__NeedsToCalcDataCount
(func
):
6870 file.Write(" _%s, ComputeEffectiveDataSize(%s));" %
6871 (last_arg
.name
, func
.GetOriginalArgs()[0].name
))
6873 DCHECK_GE(ComputeDataSize(), ComputeEffectiveDataSize(%(arg)s));
6874 char* pointer = reinterpret_cast<char*>(ImmediateDataAddress(this)) +
6875 ComputeEffectiveDataSize(%(arg)s);
6876 memset(pointer, 0, ComputeDataSize() - ComputeEffectiveDataSize(%(arg)s));
6877 """ % { 'arg': func
.GetOriginalArgs()[0].name
, })
6879 file.Write(" _%s, ComputeDataSize());\n" % last_arg
.name
)
6883 def WriteImmediateCmdSet(self
, func
, file):
6884 """Overrriden from TypeHandler."""
6885 last_arg
= func
.GetLastOriginalArg()
6886 copy_args
= func
.MakeCmdArgString("_", False)
6887 file.Write(" void* Set(void* cmd%s, %s _%s) {\n" %
6888 (func
.MakeTypedCmdArgString("_", True),
6889 last_arg
.type, last_arg
.name
))
6890 file.Write(" static_cast<ValueType*>(cmd)->Init(%s, _%s);\n" %
6891 (copy_args
, last_arg
.name
))
6892 file.Write(" const uint32_t size = ComputeSize();\n")
6893 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
6898 def WriteImmediateCmdHelper(self
, func
, file):
6899 """Overrriden from TypeHandler."""
6900 code
= """ void %(name)s(%(typed_args)s) {
6901 const uint32_t size = gles2::cmds::%(name)s::ComputeSize();
6902 gles2::cmds::%(name)s* c =
6903 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
6912 "typed_args": func
.MakeTypedOriginalArgString(""),
6913 "args": func
.MakeOriginalArgString(""),
6916 def WriteImmediateFormatTest(self
, func
, file):
6917 """Overrriden from TypeHandler."""
6918 file.Write("TEST_F(GLES2FormatTest, %s) {\n" % func
.name
)
6919 file.Write(" const int kSomeBaseValueToTestWith = 51;\n")
6920 file.Write(" static %s data[] = {\n" % self
.GetArrayType(func
))
6921 for v
in range(0, self
.GetArrayCount(func
)):
6922 file.Write(" static_cast<%s>(kSomeBaseValueToTestWith + %d),\n" %
6923 (self
.GetArrayType(func
), v
))
6925 file.Write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
6926 (func
.name
, func
.name
))
6927 file.Write(" void* next_cmd = cmd.Set(\n")
6929 args
= func
.GetCmdArgs()
6930 for value
, arg
in enumerate(args
):
6931 file.Write(",\n static_cast<%s>(%d)" % (arg
.type, value
+ 11))
6932 file.Write(",\n data);\n")
6933 args
= func
.GetCmdArgs()
6934 file.Write(" EXPECT_EQ(static_cast<uint32_t>(cmds::%s::kCmdId),\n"
6936 file.Write(" cmd.header.command);\n")
6937 file.Write(" EXPECT_EQ(sizeof(cmd) +\n")
6938 file.Write(" RoundSizeToMultipleOfEntries(sizeof(data)),\n")
6939 file.Write(" cmd.header.size * 4u);\n")
6940 for value
, arg
in enumerate(args
):
6941 file.Write(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);\n" %
6942 (arg
.type, value
+ 11, arg
.name
))
6943 file.Write(" CheckBytesWrittenMatchesExpectedSize(\n")
6944 file.Write(" next_cmd, sizeof(cmd) +\n")
6945 file.Write(" RoundSizeToMultipleOfEntries(sizeof(data)));\n")
6946 file.Write(" // TODO(gman): Check that data was inserted;\n")
6951 class PUTnHandler(ArrayArgTypeHandler
):
6952 """Handler for PUTn 'glUniform__v' type functions."""
6955 ArrayArgTypeHandler
.__init
__(self
)
6957 def WriteServiceUnitTest(self
, func
, file, *extras
):
6958 """Overridden from TypeHandler."""
6959 ArrayArgTypeHandler
.WriteServiceUnitTest(self
, func
, file, *extras
)
6962 TEST_P(%(test_name)s, %(name)sValidArgsCountTooLarge) {
6963 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
6964 SpecializedSetup<cmds::%(name)s, 0>(true);
6967 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
6968 EXPECT_EQ(GL_NO_ERROR, GetGLError());
6973 for count
, arg
in enumerate(func
.GetOriginalArgs()):
6974 # hardcoded to match unit tests.
6976 # the location of the second element of the 2nd uniform.
6977 # defined in GLES2DecoderBase::SetupShaderForUniform
6978 gl_arg_strings
.append("3")
6979 arg_strings
.append("ProgramManager::MakeFakeLocation(1, 1)")
6981 # the number of elements that gl will be called with.
6982 gl_arg_strings
.append("3")
6983 # the number of elements requested in the command.
6984 arg_strings
.append("5")
6986 gl_arg_strings
.append(arg
.GetValidGLArg(func
))
6987 if not arg
.IsConstant():
6988 arg_strings
.append(arg
.GetValidArg(func
))
6990 'gl_args': ", ".join(gl_arg_strings
),
6991 'args': ", ".join(arg_strings
),
6993 self
.WriteValidUnitTest(func
, file, valid_test
, extra
, *extras
)
6995 def WriteImmediateServiceUnitTest(self
, func
, file, *extras
):
6996 """Overridden from TypeHandler."""
6998 TEST_P(%(test_name)s, %(name)sValidArgs) {
6999 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
7002 %(gl_func_name)s(%(gl_args)s,
7003 reinterpret_cast<%(data_type)s*>(ImmediateDataAddress(&cmd))));
7004 SpecializedSetup<cmds::%(name)s, 0>(true);
7005 %(data_type)s temp[%(data_count)s * 2] = { 0, };
7006 cmd.Init(%(args)s, &temp[0]);"""
7009 decoder_->set_unsafe_es3_apis_enabled(true);"""
7011 EXPECT_EQ(error::kNoError,
7012 ExecuteImmediateCmd(cmd, sizeof(temp)));
7013 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
7016 decoder_->set_unsafe_es3_apis_enabled(false);
7017 EXPECT_EQ(error::kUnknownCommand,
7018 ExecuteImmediateCmd(cmd, sizeof(temp)));"""
7025 for arg
in func
.GetOriginalArgs()[0:-1]:
7026 gl_arg_strings
.append(arg
.GetValidGLArg(func
))
7027 gl_any_strings
.append("_")
7028 if not arg
.IsConstant():
7029 arg_strings
.append(arg
.GetValidArg(func
))
7031 'data_type': self
.GetArrayType(func
),
7032 'data_count': self
.GetArrayCount(func
),
7033 'args': ", ".join(arg_strings
),
7034 'gl_args': ", ".join(gl_arg_strings
),
7035 'gl_any_args': ", ".join(gl_any_strings
),
7037 self
.WriteValidUnitTest(func
, file, valid_test
, extra
, *extras
)
7040 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
7041 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
7042 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_any_args)s, _)).Times(0);
7043 SpecializedSetup<cmds::%(name)s, 0>(false);
7044 %(data_type)s temp[%(data_count)s * 2] = { 0, };
7045 cmd.Init(%(all_but_last_args)s, &temp[0]);
7046 EXPECT_EQ(error::%(parse_result)s,
7047 ExecuteImmediateCmd(cmd, sizeof(temp)));%(gl_error_test)s
7050 self
.WriteInvalidUnitTest(func
, file, invalid_test
, extra
, *extras
)
7052 def WriteGetDataSizeCode(self
, func
, file):
7053 """Overrriden from TypeHandler."""
7054 code
= """ uint32_t data_size;
7055 if (!ComputeDataSize(count, sizeof(%s), %d, &data_size)) {
7056 return error::kOutOfBounds;
7059 file.Write(code
% (self
.GetArrayType(func
), self
.GetArrayCount(func
)))
7060 if func
.IsImmediate():
7061 file.Write(" if (data_size > immediate_data_size) {\n")
7062 file.Write(" return error::kOutOfBounds;\n")
7065 def WriteGLES2Implementation(self
, func
, file):
7066 """Overrriden from TypeHandler."""
7067 file.Write("%s GLES2Implementation::%s(%s) {\n" %
7068 (func
.return_type
, func
.original_name
,
7069 func
.MakeTypedOriginalArgString("")))
7070 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
7071 func
.WriteDestinationInitalizationValidation(file)
7072 self
.WriteClientGLCallLog(func
, file)
7073 last_pointer_name
= func
.GetLastOriginalPointerArg().name
7074 file.Write(""" GPU_CLIENT_LOG_CODE_BLOCK({
7075 for (GLsizei i = 0; i < count; ++i) {
7077 values_str
= ' << ", " << '.join(
7078 ["%s[%d + i * %d]" % (
7079 last_pointer_name
, ndx
, self
.GetArrayCount(func
)) for ndx
in range(
7080 0, self
.GetArrayCount(func
))])
7081 file.Write(' GPU_CLIENT_LOG(" " << i << ": " << %s);\n' % values_str
)
7082 file.Write(" }\n });\n")
7083 for arg
in func
.GetOriginalArgs():
7084 arg
.WriteClientSideValidationCode(file, func
)
7085 file.Write(" helper_->%sImmediate(%s);\n" %
7086 (func
.name
, func
.MakeInitString("")))
7087 file.Write(" CheckGLError();\n")
7091 def WriteGLES2ImplementationUnitTest(self
, func
, file):
7092 """Writes the GLES2 Implemention unit test."""
7094 TEST_F(GLES2ImplementationTest, %(name)s) {
7095 %(type)s data[%(count_param)d][%(count)d] = {{0}};
7097 cmds::%(name)sImmediate cmd;
7098 %(type)s data[%(count_param)d][%(count)d];
7102 for (int ii = 0; ii < %(count_param)d; ++ii) {
7103 for (int jj = 0; jj < %(count)d; ++jj) {
7104 data[ii][jj] = static_cast<%(type)s>(ii * %(count)d + jj);
7107 expected.cmd.Init(%(cmd_args)s);
7108 gl_->%(name)s(%(args)s);
7109 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
7112 cmd_arg_strings
= []
7113 for arg
in func
.GetCmdArgs():
7114 if arg
.name
.endswith("_shm_id"):
7115 cmd_arg_strings
.append("&data[0][0]")
7116 elif arg
.name
.endswith("_shm_offset"):
7119 cmd_arg_strings
.append(arg
.GetValidClientSideCmdArg(func
))
7122 for arg
in func
.GetOriginalArgs():
7124 valid_value
= "&data[0][0]"
7126 valid_value
= arg
.GetValidClientSideArg(func
)
7127 gl_arg_strings
.append(valid_value
)
7128 if arg
.name
== "count":
7129 count_param
= int(valid_value
)
7132 'type': self
.GetArrayType(func
),
7133 'count': self
.GetArrayCount(func
),
7134 'args': ", ".join(gl_arg_strings
),
7135 'cmd_args': ", ".join(cmd_arg_strings
),
7136 'count_param': count_param
,
7139 # Test constants for invalid values, as they are not tested by the
7142 arg
for arg
in func
.GetOriginalArgs()[0:-1] if arg
.IsConstant()
7148 TEST_F(GLES2ImplementationTest, %(name)sInvalidConstantArg%(invalid_index)d) {
7149 %(type)s data[%(count_param)d][%(count)d] = {{0}};
7150 for (int ii = 0; ii < %(count_param)d; ++ii) {
7151 for (int jj = 0; jj < %(count)d; ++jj) {
7152 data[ii][jj] = static_cast<%(type)s>(ii * %(count)d + jj);
7155 gl_->%(name)s(%(args)s);
7156 EXPECT_TRUE(NoCommandsWritten());
7157 EXPECT_EQ(%(gl_error)s, CheckError());
7160 for invalid_arg
in constants
:
7162 invalid
= invalid_arg
.GetInvalidArg(func
)
7163 for arg
in func
.GetOriginalArgs():
7164 if arg
is invalid_arg
:
7165 gl_arg_strings
.append(invalid
[0])
7166 elif arg
.IsPointer():
7167 gl_arg_strings
.append("&data[0][0]")
7169 valid_value
= arg
.GetValidClientSideArg(func
)
7170 gl_arg_strings
.append(valid_value
)
7171 if arg
.name
== "count":
7172 count_param
= int(valid_value
)
7176 'invalid_index': func
.GetOriginalArgs().index(invalid_arg
),
7177 'type': self
.GetArrayType(func
),
7178 'count': self
.GetArrayCount(func
),
7179 'args': ", ".join(gl_arg_strings
),
7180 'gl_error': invalid
[2],
7181 'count_param': count_param
,
7185 def WriteImmediateCmdComputeSize(self
, func
, file):
7186 """Overrriden from TypeHandler."""
7187 file.Write(" static uint32_t ComputeDataSize(GLsizei count) {\n")
7188 file.Write(" return static_cast<uint32_t>(\n")
7189 file.Write(" sizeof(%s) * %d * count); // NOLINT\n" %
7190 (self
.GetArrayType(func
), self
.GetArrayCount(func
)))
7193 file.Write(" static uint32_t ComputeSize(GLsizei count) {\n")
7194 file.Write(" return static_cast<uint32_t>(\n")
7196 " sizeof(ValueType) + ComputeDataSize(count)); // NOLINT\n")
7200 def WriteImmediateCmdSetHeader(self
, func
, file):
7201 """Overrriden from TypeHandler."""
7202 file.Write(" void SetHeader(GLsizei count) {\n")
7204 " header.SetCmdByTotalSize<ValueType>(ComputeSize(count));\n")
7208 def WriteImmediateCmdInit(self
, func
, file):
7209 """Overrriden from TypeHandler."""
7210 file.Write(" void Init(%s) {\n" %
7211 func
.MakeTypedInitString("_"))
7212 file.Write(" SetHeader(_count);\n")
7213 args
= func
.GetCmdArgs()
7215 file.Write(" %s = _%s;\n" % (arg
.name
, arg
.name
))
7216 file.Write(" memcpy(ImmediateDataAddress(this),\n")
7217 pointer_arg
= func
.GetLastOriginalPointerArg()
7218 file.Write(" _%s, ComputeDataSize(_count));\n" % pointer_arg
.name
)
7222 def WriteImmediateCmdSet(self
, func
, file):
7223 """Overrriden from TypeHandler."""
7224 file.Write(" void* Set(void* cmd%s) {\n" %
7225 func
.MakeTypedInitString("_", True))
7226 file.Write(" static_cast<ValueType*>(cmd)->Init(%s);\n" %
7227 func
.MakeInitString("_"))
7228 file.Write(" const uint32_t size = ComputeSize(_count);\n")
7229 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
7234 def WriteImmediateCmdHelper(self
, func
, file):
7235 """Overrriden from TypeHandler."""
7236 code
= """ void %(name)s(%(typed_args)s) {
7237 const uint32_t size = gles2::cmds::%(name)s::ComputeSize(count);
7238 gles2::cmds::%(name)s* c =
7239 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
7248 "typed_args": func
.MakeTypedInitString(""),
7249 "args": func
.MakeInitString("")
7252 def WriteImmediateFormatTest(self
, func
, file):
7253 """Overrriden from TypeHandler."""
7254 args
= func
.GetOriginalArgs()
7257 if arg
.name
== "count":
7258 count_param
= int(arg
.GetValidClientSideCmdArg(func
))
7259 file.Write("TEST_F(GLES2FormatTest, %s) {\n" % func
.name
)
7260 file.Write(" const int kSomeBaseValueToTestWith = 51;\n")
7261 file.Write(" static %s data[] = {\n" % self
.GetArrayType(func
))
7262 for v
in range(0, self
.GetArrayCount(func
) * count_param
):
7263 file.Write(" static_cast<%s>(kSomeBaseValueToTestWith + %d),\n" %
7264 (self
.GetArrayType(func
), v
))
7266 file.Write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
7267 (func
.name
, func
.name
))
7268 file.Write(" const GLsizei kNumElements = %d;\n" % count_param
)
7269 file.Write(" const size_t kExpectedCmdSize =\n")
7270 file.Write(" sizeof(cmd) + kNumElements * sizeof(%s) * %d;\n" %
7271 (self
.GetArrayType(func
), self
.GetArrayCount(func
)))
7272 file.Write(" void* next_cmd = cmd.Set(\n")
7274 for value
, arg
in enumerate(args
):
7276 file.Write(",\n data")
7277 elif arg
.IsConstant():
7280 file.Write(",\n static_cast<%s>(%d)" % (arg
.type, value
+ 1))
7282 file.Write(" EXPECT_EQ(static_cast<uint32_t>(cmds::%s::kCmdId),\n" %
7284 file.Write(" cmd.header.command);\n")
7285 file.Write(" EXPECT_EQ(kExpectedCmdSize, cmd.header.size * 4u);\n")
7286 for value
, arg
in enumerate(args
):
7287 if arg
.IsPointer() or arg
.IsConstant():
7289 file.Write(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);\n" %
7290 (arg
.type, value
+ 1, arg
.name
))
7291 file.Write(" CheckBytesWrittenMatchesExpectedSize(\n")
7292 file.Write(" next_cmd, sizeof(cmd) +\n")
7293 file.Write(" RoundSizeToMultipleOfEntries(sizeof(data)));\n")
7294 file.Write(" // TODO(gman): Check that data was inserted;\n")
7298 class PUTSTRHandler(ArrayArgTypeHandler
):
7299 """Handler for functions that pass a string array."""
7302 ArrayArgTypeHandler
.__init
__(self
)
7304 def __GetDataArg(self
, func
):
7305 """Return the argument that points to the 2D char arrays"""
7306 for arg
in func
.GetOriginalArgs():
7307 if arg
.IsPointer2D():
7311 def __GetLengthArg(self
, func
):
7312 """Return the argument that holds length for each char array"""
7313 for arg
in func
.GetOriginalArgs():
7314 if arg
.IsPointer() and not arg
.IsPointer2D():
7318 def WriteGLES2Implementation(self
, func
, file):
7319 """Overrriden from TypeHandler."""
7320 file.Write("%s GLES2Implementation::%s(%s) {\n" %
7321 (func
.return_type
, func
.original_name
,
7322 func
.MakeTypedOriginalArgString("")))
7323 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
7324 func
.WriteDestinationInitalizationValidation(file)
7325 self
.WriteClientGLCallLog(func
, file)
7326 data_arg
= self
.__GetDataArg
(func
)
7327 length_arg
= self
.__GetLengthArg
(func
)
7328 log_code_block
= """ GPU_CLIENT_LOG_CODE_BLOCK({
7329 for (GLsizei ii = 0; ii < count; ++ii) {
7330 if (%(data)s[ii]) {"""
7331 if length_arg
== None:
7332 log_code_block
+= """
7333 GPU_CLIENT_LOG(" " << ii << ": ---\\n" << %(data)s[ii] << "\\n---");"""
7335 log_code_block
+= """
7336 if (%(length)s && %(length)s[ii] >= 0) {
7337 const std::string my_str(%(data)s[ii], %(length)s[ii]);
7338 GPU_CLIENT_LOG(" " << ii << ": ---\\n" << my_str << "\\n---");
7340 GPU_CLIENT_LOG(" " << ii << ": ---\\n" << %(data)s[ii] << "\\n---");
7342 log_code_block
+= """
7344 GPU_CLIENT_LOG(" " << ii << ": NULL");
7349 file.Write(log_code_block
% {
7350 'data': data_arg
.name
,
7351 'length': length_arg
.name
if not length_arg
== None else ''
7353 for arg
in func
.GetOriginalArgs():
7354 arg
.WriteClientSideValidationCode(file, func
)
7357 for arg
in func
.GetOriginalArgs():
7358 if arg
.name
== 'count' or arg
== self
.__GetLengthArg
(func
):
7360 if arg
== self
.__GetDataArg
(func
):
7361 bucket_args
.append('kResultBucketId')
7363 bucket_args
.append(arg
.name
)
7365 if (!PackStringsToBucket(count, %(data)s, %(length)s, "gl%(func_name)s")) {
7368 helper_->%(func_name)sBucket(%(bucket_args)s);
7369 helper_->SetBucketSize(kResultBucketId, 0);
7374 file.Write(code_block
% {
7375 'data': data_arg
.name
,
7376 'length': length_arg
.name
if not length_arg
== None else 'NULL',
7377 'func_name': func
.name
,
7378 'bucket_args': ', '.join(bucket_args
),
7381 def WriteGLES2ImplementationUnitTest(self
, func
, file):
7382 """Overrriden from TypeHandler."""
7384 TEST_F(GLES2ImplementationTest, %(name)s) {
7385 const uint32 kBucketId = GLES2Implementation::kResultBucketId;
7386 const char* kString1 = "happy";
7387 const char* kString2 = "ending";
7388 const size_t kString1Size = ::strlen(kString1) + 1;
7389 const size_t kString2Size = ::strlen(kString2) + 1;
7390 const size_t kHeaderSize = sizeof(GLint) * 3;
7391 const size_t kSourceSize = kHeaderSize + kString1Size + kString2Size;
7392 const size_t kPaddedHeaderSize =
7393 transfer_buffer_->RoundToAlignment(kHeaderSize);
7394 const size_t kPaddedString1Size =
7395 transfer_buffer_->RoundToAlignment(kString1Size);
7396 const size_t kPaddedString2Size =
7397 transfer_buffer_->RoundToAlignment(kString2Size);
7399 cmd::SetBucketSize set_bucket_size;
7400 cmd::SetBucketData set_bucket_header;
7401 cmd::SetToken set_token1;
7402 cmd::SetBucketData set_bucket_data1;
7403 cmd::SetToken set_token2;
7404 cmd::SetBucketData set_bucket_data2;
7405 cmd::SetToken set_token3;
7406 cmds::%(name)sBucket cmd_bucket;
7407 cmd::SetBucketSize clear_bucket_size;
7410 ExpectedMemoryInfo mem0 = GetExpectedMemory(kPaddedHeaderSize);
7411 ExpectedMemoryInfo mem1 = GetExpectedMemory(kPaddedString1Size);
7412 ExpectedMemoryInfo mem2 = GetExpectedMemory(kPaddedString2Size);
7415 expected.set_bucket_size.Init(kBucketId, kSourceSize);
7416 expected.set_bucket_header.Init(
7417 kBucketId, 0, kHeaderSize, mem0.id, mem0.offset);
7418 expected.set_token1.Init(GetNextToken());
7419 expected.set_bucket_data1.Init(
7420 kBucketId, kHeaderSize, kString1Size, mem1.id, mem1.offset);
7421 expected.set_token2.Init(GetNextToken());
7422 expected.set_bucket_data2.Init(
7423 kBucketId, kHeaderSize + kString1Size, kString2Size, mem2.id,
7425 expected.set_token3.Init(GetNextToken());
7426 expected.cmd_bucket.Init(%(bucket_args)s);
7427 expected.clear_bucket_size.Init(kBucketId, 0);
7428 const char* kStrings[] = { kString1, kString2 };
7429 gl_->%(name)s(%(gl_args)s);
7430 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
7435 for arg
in func
.GetOriginalArgs():
7436 if arg
== self
.__GetDataArg
(func
):
7437 gl_args
.append('kStrings')
7438 bucket_args
.append('kBucketId')
7439 elif arg
== self
.__GetLengthArg
(func
):
7440 gl_args
.append('NULL')
7441 elif arg
.name
== 'count':
7444 gl_args
.append(arg
.GetValidClientSideArg(func
))
7445 bucket_args
.append(arg
.GetValidClientSideArg(func
))
7448 'gl_args': ", ".join(gl_args
),
7449 'bucket_args': ", ".join(bucket_args
),
7452 if self
.__GetLengthArg
(func
) == None:
7455 TEST_F(GLES2ImplementationTest, %(name)sWithLength) {
7456 const uint32 kBucketId = GLES2Implementation::kResultBucketId;
7457 const char* kString = "foobar******";
7458 const size_t kStringSize = 6; // We only need "foobar".
7459 const size_t kHeaderSize = sizeof(GLint) * 2;
7460 const size_t kSourceSize = kHeaderSize + kStringSize + 1;
7461 const size_t kPaddedHeaderSize =
7462 transfer_buffer_->RoundToAlignment(kHeaderSize);
7463 const size_t kPaddedStringSize =
7464 transfer_buffer_->RoundToAlignment(kStringSize + 1);
7466 cmd::SetBucketSize set_bucket_size;
7467 cmd::SetBucketData set_bucket_header;
7468 cmd::SetToken set_token1;
7469 cmd::SetBucketData set_bucket_data;
7470 cmd::SetToken set_token2;
7471 cmds::ShaderSourceBucket shader_source_bucket;
7472 cmd::SetBucketSize clear_bucket_size;
7475 ExpectedMemoryInfo mem0 = GetExpectedMemory(kPaddedHeaderSize);
7476 ExpectedMemoryInfo mem1 = GetExpectedMemory(kPaddedStringSize);
7479 expected.set_bucket_size.Init(kBucketId, kSourceSize);
7480 expected.set_bucket_header.Init(
7481 kBucketId, 0, kHeaderSize, mem0.id, mem0.offset);
7482 expected.set_token1.Init(GetNextToken());
7483 expected.set_bucket_data.Init(
7484 kBucketId, kHeaderSize, kStringSize + 1, mem1.id, mem1.offset);
7485 expected.set_token2.Init(GetNextToken());
7486 expected.shader_source_bucket.Init(%(bucket_args)s);
7487 expected.clear_bucket_size.Init(kBucketId, 0);
7488 const char* kStrings[] = { kString };
7489 const GLint kLength[] = { kStringSize };
7490 gl_->%(name)s(%(gl_args)s);
7491 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
7495 for arg
in func
.GetOriginalArgs():
7496 if arg
== self
.__GetDataArg
(func
):
7497 gl_args
.append('kStrings')
7498 elif arg
== self
.__GetLengthArg
(func
):
7499 gl_args
.append('kLength')
7500 elif arg
.name
== 'count':
7503 gl_args
.append(arg
.GetValidClientSideArg(func
))
7506 'gl_args': ", ".join(gl_args
),
7507 'bucket_args': ", ".join(bucket_args
),
7510 def WriteBucketServiceUnitTest(self
, func
, file, *extras
):
7511 """Overrriden from TypeHandler."""
7513 cmd_args_with_invalid_id
= []
7515 for index
, arg
in enumerate(func
.GetOriginalArgs()):
7516 if arg
== self
.__GetLengthArg
(func
):
7518 elif arg
.name
== 'count':
7520 elif arg
== self
.__GetDataArg
(func
):
7521 cmd_args
.append('kBucketId')
7522 cmd_args_with_invalid_id
.append('kBucketId')
7524 elif index
== 0: # Resource ID arg
7525 cmd_args
.append(arg
.GetValidArg(func
))
7526 cmd_args_with_invalid_id
.append('kInvalidClientId')
7527 gl_args
.append(arg
.GetValidGLArg(func
))
7529 cmd_args
.append(arg
.GetValidArg(func
))
7530 cmd_args_with_invalid_id
.append(arg
.GetValidArg(func
))
7531 gl_args
.append(arg
.GetValidGLArg(func
))
7534 TEST_P(%(test_name)s, %(name)sValidArgs) {
7535 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
7536 const uint32 kBucketId = 123;
7537 const char kSource0[] = "hello";
7538 const char* kSource[] = { kSource0 };
7539 const char kValidStrEnd = 0;
7540 SetBucketAsCStrings(kBucketId, 1, kSource, 1, kValidStrEnd);
7542 cmd.Init(%(cmd_args)s);
7543 decoder_->set_unsafe_es3_apis_enabled(true);
7544 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));"""
7547 decoder_->set_unsafe_es3_apis_enabled(false);
7548 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));
7553 self
.WriteValidUnitTest(func
, file, test
, {
7554 'cmd_args': ", ".join(cmd_args
),
7555 'gl_args': ", ".join(gl_args
),
7559 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
7560 const uint32 kBucketId = 123;
7561 const char kSource0[] = "hello";
7562 const char* kSource[] = { kSource0 };
7563 const char kValidStrEnd = 0;
7564 decoder_->set_unsafe_es3_apis_enabled(true);
7567 cmd.Init(%(cmd_args)s);
7568 EXPECT_NE(error::kNoError, ExecuteCmd(cmd));
7569 // Test invalid client.
7570 SetBucketAsCStrings(kBucketId, 1, kSource, 1, kValidStrEnd);
7571 cmd.Init(%(cmd_args_with_invalid_id)s);
7572 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
7573 EXPECT_EQ(GL_INVALID_VALUE, GetGLError());
7576 self
.WriteValidUnitTest(func
, file, test
, {
7577 'cmd_args': ", ".join(cmd_args
),
7578 'cmd_args_with_invalid_id': ", ".join(cmd_args_with_invalid_id
),
7582 TEST_P(%(test_name)s, %(name)sInvalidHeader) {
7583 const uint32 kBucketId = 123;
7584 const char kSource0[] = "hello";
7585 const char* kSource[] = { kSource0 };
7586 const char kValidStrEnd = 0;
7587 const GLsizei kCount = static_cast<GLsizei>(arraysize(kSource));
7588 const GLsizei kTests[] = {
7591 std::numeric_limits<GLsizei>::max(),
7594 decoder_->set_unsafe_es3_apis_enabled(true);
7595 for (size_t ii = 0; ii < arraysize(kTests); ++ii) {
7596 SetBucketAsCStrings(kBucketId, 1, kSource, kTests[ii], kValidStrEnd);
7598 cmd.Init(%(cmd_args)s);
7599 EXPECT_EQ(error::kInvalidArguments, ExecuteCmd(cmd));
7603 self
.WriteValidUnitTest(func
, file, test
, {
7604 'cmd_args': ", ".join(cmd_args
),
7608 TEST_P(%(test_name)s, %(name)sInvalidStringEnding) {
7609 const uint32 kBucketId = 123;
7610 const char kSource0[] = "hello";
7611 const char* kSource[] = { kSource0 };
7612 const char kInvalidStrEnd = '*';
7613 SetBucketAsCStrings(kBucketId, 1, kSource, 1, kInvalidStrEnd);
7615 cmd.Init(%(cmd_args)s);
7616 decoder_->set_unsafe_es3_apis_enabled(true);
7617 EXPECT_EQ(error::kInvalidArguments, ExecuteCmd(cmd));
7620 self
.WriteValidUnitTest(func
, file, test
, {
7621 'cmd_args': ", ".join(cmd_args
),
7625 class PUTXnHandler(ArrayArgTypeHandler
):
7626 """Handler for glUniform?f functions."""
7628 ArrayArgTypeHandler
.__init
__(self
)
7630 def WriteHandlerImplementation(self
, func
, file):
7631 """Overrriden from TypeHandler."""
7632 code
= """ %(type)s temp[%(count)s] = { %(values)s};"""
7635 gl%(name)sv(%(location)s, 1, &temp[0]);
7639 Do%(name)sv(%(location)s, 1, &temp[0]);
7642 args
= func
.GetOriginalArgs()
7643 count
= int(self
.GetArrayCount(func
))
7644 num_args
= len(args
)
7645 for ii
in range(count
):
7646 values
+= "%s, " % args
[len(args
) - count
+ ii
].name
7650 'count': self
.GetArrayCount(func
),
7651 'type': self
.GetArrayType(func
),
7652 'location': args
[0].name
,
7653 'args': func
.MakeOriginalArgString(""),
7657 def WriteServiceUnitTest(self
, func
, file, *extras
):
7658 """Overrriden from TypeHandler."""
7660 TEST_P(%(test_name)s, %(name)sValidArgs) {
7661 EXPECT_CALL(*gl_, %(name)sv(%(local_args)s));
7662 SpecializedSetup<cmds::%(name)s, 0>(true);
7664 cmd.Init(%(args)s);"""
7667 decoder_->set_unsafe_es3_apis_enabled(true);"""
7669 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
7670 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
7673 decoder_->set_unsafe_es3_apis_enabled(false);
7674 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));"""
7678 args
= func
.GetOriginalArgs()
7679 local_args
= "%s, 1, _" % args
[0].GetValidGLArg(func
)
7680 self
.WriteValidUnitTest(func
, file, valid_test
, {
7682 'count': self
.GetArrayCount(func
),
7683 'local_args': local_args
,
7687 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
7688 EXPECT_CALL(*gl_, %(name)sv(_, _, _).Times(0);
7689 SpecializedSetup<cmds::%(name)s, 0>(false);
7692 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
7695 self
.WriteInvalidUnitTest(func
, file, invalid_test
, {
7696 'name': func
.GetInfo('name'),
7697 'count': self
.GetArrayCount(func
),
7701 class GLcharHandler(CustomHandler
):
7702 """Handler for functions that pass a single string ."""
7705 CustomHandler
.__init
__(self
)
7707 def WriteImmediateCmdComputeSize(self
, func
, file):
7708 """Overrriden from TypeHandler."""
7709 file.Write(" static uint32_t ComputeSize(uint32_t data_size) {\n")
7710 file.Write(" return static_cast<uint32_t>(\n")
7711 file.Write(" sizeof(ValueType) + data_size); // NOLINT\n")
7714 def WriteImmediateCmdSetHeader(self
, func
, file):
7715 """Overrriden from TypeHandler."""
7717 void SetHeader(uint32_t data_size) {
7718 header.SetCmdBySize<ValueType>(data_size);
7723 def WriteImmediateCmdInit(self
, func
, file):
7724 """Overrriden from TypeHandler."""
7725 last_arg
= func
.GetLastOriginalArg()
7726 args
= func
.GetCmdArgs()
7729 set_code
.append(" %s = _%s;" % (arg
.name
, arg
.name
))
7731 void Init(%(typed_args)s, uint32_t _data_size) {
7732 SetHeader(_data_size);
7734 memcpy(ImmediateDataAddress(this), _%(last_arg)s, _data_size);
7739 "typed_args": func
.MakeTypedArgString("_"),
7740 "set_code": "\n".join(set_code
),
7741 "last_arg": last_arg
.name
7744 def WriteImmediateCmdSet(self
, func
, file):
7745 """Overrriden from TypeHandler."""
7746 last_arg
= func
.GetLastOriginalArg()
7747 file.Write(" void* Set(void* cmd%s, uint32_t _data_size) {\n" %
7748 func
.MakeTypedCmdArgString("_", True))
7749 file.Write(" static_cast<ValueType*>(cmd)->Init(%s, _data_size);\n" %
7750 func
.MakeCmdArgString("_"))
7751 file.Write(" return NextImmediateCmdAddress<ValueType>("
7752 "cmd, _data_size);\n")
7756 def WriteImmediateCmdHelper(self
, func
, file):
7757 """Overrriden from TypeHandler."""
7758 code
= """ void %(name)s(%(typed_args)s) {
7759 const uint32_t data_size = strlen(name);
7760 gles2::cmds::%(name)s* c =
7761 GetImmediateCmdSpace<gles2::cmds::%(name)s>(data_size);
7763 c->Init(%(args)s, data_size);
7770 "typed_args": func
.MakeTypedOriginalArgString(""),
7771 "args": func
.MakeOriginalArgString(""),
7775 def WriteImmediateFormatTest(self
, func
, file):
7776 """Overrriden from TypeHandler."""
7779 all_but_last_arg
= func
.GetCmdArgs()[:-1]
7780 for value
, arg
in enumerate(all_but_last_arg
):
7781 init_code
.append(" static_cast<%s>(%d)," % (arg
.type, value
+ 11))
7782 for value
, arg
in enumerate(all_but_last_arg
):
7783 check_code
.append(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);" %
7784 (arg
.type, value
+ 11, arg
.name
))
7786 TEST_F(GLES2FormatTest, %(func_name)s) {
7787 cmds::%(func_name)s& cmd = *GetBufferAs<cmds::%(func_name)s>();
7788 static const char* const test_str = \"test string\";
7789 void* next_cmd = cmd.Set(
7794 EXPECT_EQ(static_cast<uint32_t>(cmds::%(func_name)s::kCmdId),
7795 cmd.header.command);
7796 EXPECT_EQ(sizeof(cmd) +
7797 RoundSizeToMultipleOfEntries(strlen(test_str)),
7798 cmd.header.size * 4u);
7799 EXPECT_EQ(static_cast<char*>(next_cmd),
7800 reinterpret_cast<char*>(&cmd) + sizeof(cmd) +
7801 RoundSizeToMultipleOfEntries(strlen(test_str)));
7803 EXPECT_EQ(static_cast<uint32_t>(strlen(test_str)), cmd.data_size);
7804 EXPECT_EQ(0, memcmp(test_str, ImmediateDataAddress(&cmd), strlen(test_str)));
7807 sizeof(cmd) + RoundSizeToMultipleOfEntries(strlen(test_str)),
7808 sizeof(cmd) + strlen(test_str));
7813 'func_name': func
.name
,
7814 'init_code': "\n".join(init_code
),
7815 'check_code': "\n".join(check_code
),
7819 class GLcharNHandler(CustomHandler
):
7820 """Handler for functions that pass a single string with an optional len."""
7823 CustomHandler
.__init
__(self
)
7825 def InitFunction(self
, func
):
7826 """Overrriden from TypeHandler."""
7828 func
.AddCmdArg(Argument('bucket_id', 'GLuint'))
7830 def NeedsDataTransferFunction(self
, func
):
7831 """Overriden from TypeHandler."""
7834 def AddBucketFunction(self
, generator
, func
):
7835 """Overrriden from TypeHandler."""
7838 def WriteServiceImplementation(self
, func
, file):
7839 """Overrriden from TypeHandler."""
7840 self
.WriteServiceHandlerFunctionHeader(func
, file)
7842 GLuint bucket_id = static_cast<GLuint>(c.%(bucket_id)s);
7843 Bucket* bucket = GetBucket(bucket_id);
7844 if (!bucket || bucket->size() == 0) {
7845 return error::kInvalidArguments;
7848 if (!bucket->GetAsString(&str)) {
7849 return error::kInvalidArguments;
7851 %(gl_func_name)s(0, str.c_str());
7852 return error::kNoError;
7857 'gl_func_name': func
.GetGLFunctionName(),
7858 'bucket_id': func
.cmd_args
[0].name
,
7862 class IsHandler(TypeHandler
):
7863 """Handler for glIs____ type and glGetError functions."""
7866 TypeHandler
.__init
__(self
)
7868 def InitFunction(self
, func
):
7869 """Overrriden from TypeHandler."""
7870 func
.AddCmdArg(Argument("result_shm_id", 'uint32_t'))
7871 func
.AddCmdArg(Argument("result_shm_offset", 'uint32_t'))
7872 if func
.GetInfo('result') == None:
7873 func
.AddInfo('result', ['uint32_t'])
7875 def WriteServiceUnitTest(self
, func
, file, *extras
):
7876 """Overrriden from TypeHandler."""
7878 TEST_P(%(test_name)s, %(name)sValidArgs) {
7879 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
7880 SpecializedSetup<cmds::%(name)s, 0>(true);
7882 cmd.Init(%(args)s%(comma)sshared_memory_id_, shared_memory_offset_);"""
7885 decoder_->set_unsafe_es3_apis_enabled(true);"""
7887 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
7888 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
7891 decoder_->set_unsafe_es3_apis_enabled(false);
7892 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));"""
7897 if len(func
.GetOriginalArgs()):
7899 self
.WriteValidUnitTest(func
, file, valid_test
, {
7904 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
7905 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
7906 SpecializedSetup<cmds::%(name)s, 0>(false);
7908 cmd.Init(%(args)s%(comma)sshared_memory_id_, shared_memory_offset_);
7909 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
7912 self
.WriteInvalidUnitTest(func
, file, invalid_test
, {
7917 TEST_P(%(test_name)s, %(name)sInvalidArgsBadSharedMemoryId) {
7918 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
7919 SpecializedSetup<cmds::%(name)s, 0>(false);"""
7922 decoder_->set_unsafe_es3_apis_enabled(true);"""
7925 cmd.Init(%(args)s%(comma)skInvalidSharedMemoryId, shared_memory_offset_);
7926 EXPECT_EQ(error::kOutOfBounds, ExecuteCmd(cmd));
7927 cmd.Init(%(args)s%(comma)sshared_memory_id_, kInvalidSharedMemoryOffset);
7928 EXPECT_EQ(error::kOutOfBounds, ExecuteCmd(cmd));"""
7931 decoder_->set_unsafe_es3_apis_enabled(true);"""
7935 self
.WriteValidUnitTest(func
, file, invalid_test
, {
7939 def WriteServiceImplementation(self
, func
, file):
7940 """Overrriden from TypeHandler."""
7941 self
.WriteServiceHandlerFunctionHeader(func
, file)
7942 args
= func
.GetOriginalArgs()
7944 arg
.WriteGetCode(file)
7946 code
= """ typedef cmds::%(func_name)s::Result Result;
7947 Result* result_dst = GetSharedMemoryAs<Result*>(
7948 c.result_shm_id, c.result_shm_offset, sizeof(*result_dst));
7950 return error::kOutOfBounds;
7953 file.Write(code
% {'func_name': func
.name
})
7954 func
.WriteHandlerValidation(file)
7956 assert func
.GetInfo('id_mapping')
7957 assert len(func
.GetInfo('id_mapping')) == 1
7958 assert len(args
) == 1
7959 id_type
= func
.GetInfo('id_mapping')[0]
7960 file.Write(" %s service_%s = 0;\n" % (args
[0].type, id_type
.lower()))
7961 file.Write(" *result_dst = group_->Get%sServiceId(%s, &service_%s);\n" %
7962 (id_type
, id_type
.lower(), id_type
.lower()))
7964 file.Write(" *result_dst = %s(%s);\n" %
7965 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
7966 file.Write(" return error::kNoError;\n")
7970 def WriteGLES2Implementation(self
, func
, file):
7971 """Overrriden from TypeHandler."""
7972 impl_func
= func
.GetInfo('impl_func')
7973 if impl_func
== None or impl_func
== True:
7974 error_value
= func
.GetInfo("error_value") or "GL_FALSE"
7975 file.Write("%s GLES2Implementation::%s(%s) {\n" %
7976 (func
.return_type
, func
.original_name
,
7977 func
.MakeTypedOriginalArgString("")))
7978 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
7979 self
.WriteTraceEvent(func
, file)
7980 func
.WriteDestinationInitalizationValidation(file)
7981 self
.WriteClientGLCallLog(func
, file)
7982 file.Write(" typedef cmds::%s::Result Result;\n" % func
.name
)
7983 file.Write(" Result* result = GetResultAs<Result*>();\n")
7984 file.Write(" if (!result) {\n")
7985 file.Write(" return %s;\n" % error_value
)
7987 file.Write(" *result = 0;\n")
7988 assert len(func
.GetOriginalArgs()) == 1
7989 id_arg
= func
.GetOriginalArgs()[0]
7990 if id_arg
.type == 'GLsync':
7991 arg_string
= "ToGLuint(%s)" % func
.MakeOriginalArgString("")
7993 arg_string
= func
.MakeOriginalArgString("")
7995 " helper_->%s(%s, GetResultShmId(), GetResultShmOffset());\n" %
7996 (func
.name
, arg_string
))
7997 file.Write(" WaitForCmd();\n")
7998 file.Write(" %s result_value = *result" % func
.return_type
)
7999 if func
.return_type
== "GLboolean":
8001 file.Write(';\n GPU_CLIENT_LOG("returned " << result_value);\n')
8002 file.Write(" CheckGLError();\n")
8003 file.Write(" return result_value;\n")
8007 def WriteGLES2ImplementationUnitTest(self
, func
, file):
8008 """Overrriden from TypeHandler."""
8009 client_test
= func
.GetInfo('client_test')
8010 if client_test
== None or client_test
== True:
8012 TEST_F(GLES2ImplementationTest, %(name)s) {
8018 ExpectedMemoryInfo result1 =
8019 GetExpectedResultMemory(sizeof(cmds::%(name)s::Result));
8020 expected.cmd.Init(%(cmd_id_value)s, result1.id, result1.offset);
8022 EXPECT_CALL(*command_buffer(), OnFlush())
8023 .WillOnce(SetMemory(result1.ptr, uint32_t(GL_TRUE)))
8024 .RetiresOnSaturation();
8026 GLboolean result = gl_->%(name)s(%(gl_id_value)s);
8027 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
8028 EXPECT_TRUE(result);
8031 args
= func
.GetOriginalArgs()
8032 assert len(args
) == 1
8035 'cmd_id_value': args
[0].GetValidClientSideCmdArg(func
),
8036 'gl_id_value': args
[0].GetValidClientSideArg(func
) })
8039 class STRnHandler(TypeHandler
):
8040 """Handler for GetProgramInfoLog, GetShaderInfoLog, GetShaderSource, and
8041 GetTranslatedShaderSourceANGLE."""
8044 TypeHandler
.__init
__(self
)
8046 def InitFunction(self
, func
):
8047 """Overrriden from TypeHandler."""
8048 # remove all but the first cmd args.
8049 cmd_args
= func
.GetCmdArgs()
8051 func
.AddCmdArg(cmd_args
[0])
8052 # add on a bucket id.
8053 func
.AddCmdArg(Argument('bucket_id', 'uint32_t'))
8055 def WriteGLES2Implementation(self
, func
, file):
8056 """Overrriden from TypeHandler."""
8057 code_1
= """%(return_type)s GLES2Implementation::%(func_name)s(%(args)s) {
8058 GPU_CLIENT_SINGLE_THREAD_CHECK();
8060 code_2
= """ GPU_CLIENT_LOG("[" << GetLogPrefix()
8061 << "] gl%(func_name)s" << "("
8064 << static_cast<void*>(%(arg2)s) << ", "
8065 << static_cast<void*>(%(arg3)s) << ")");
8066 helper_->SetBucketSize(kResultBucketId, 0);
8067 helper_->%(func_name)s(%(id_name)s, kResultBucketId);
8069 GLsizei max_size = 0;
8070 if (GetBucketAsString(kResultBucketId, &str)) {
8073 std::min(static_cast<size_t>(%(bufsize_name)s) - 1, str.size());
8074 memcpy(%(dest_name)s, str.c_str(), max_size);
8075 %(dest_name)s[max_size] = '\\0';
8076 GPU_CLIENT_LOG("------\\n" << %(dest_name)s << "\\n------");
8079 if (%(length_name)s != NULL) {
8080 *%(length_name)s = max_size;
8085 args
= func
.GetOriginalArgs()
8087 'return_type': func
.return_type
,
8088 'func_name': func
.original_name
,
8089 'args': func
.MakeTypedOriginalArgString(""),
8090 'id_name': args
[0].name
,
8091 'bufsize_name': args
[1].name
,
8092 'length_name': args
[2].name
,
8093 'dest_name': args
[3].name
,
8094 'arg0': args
[0].name
,
8095 'arg1': args
[1].name
,
8096 'arg2': args
[2].name
,
8097 'arg3': args
[3].name
,
8099 file.Write(code_1
% str_args
)
8100 func
.WriteDestinationInitalizationValidation(file)
8101 file.Write(code_2
% str_args
)
8103 def WriteServiceUnitTest(self
, func
, file, *extras
):
8104 """Overrriden from TypeHandler."""
8106 TEST_P(%(test_name)s, %(name)sValidArgs) {
8107 const char* kInfo = "hello";
8108 const uint32_t kBucketId = 123;
8109 SpecializedSetup<cmds::%(name)s, 0>(true);
8111 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s))
8112 .WillOnce(DoAll(SetArgumentPointee<2>(strlen(kInfo)),
8113 SetArrayArgument<3>(kInfo, kInfo + strlen(kInfo) + 1)));
8116 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
8117 CommonDecoder::Bucket* bucket = decoder_->GetBucket(kBucketId);
8118 ASSERT_TRUE(bucket != NULL);
8119 EXPECT_EQ(strlen(kInfo) + 1, bucket->size());
8120 EXPECT_EQ(0, memcmp(bucket->GetData(0, bucket->size()), kInfo,
8122 EXPECT_EQ(GL_NO_ERROR, GetGLError());
8125 args
= func
.GetOriginalArgs()
8126 id_name
= args
[0].GetValidGLArg(func
)
8127 get_len_func
= func
.GetInfo('get_len_func')
8128 get_len_enum
= func
.GetInfo('get_len_enum')
8131 'get_len_func': get_len_func
,
8132 'get_len_enum': get_len_enum
,
8133 'gl_args': '%s, strlen(kInfo) + 1, _, _' %
8134 args
[0].GetValidGLArg(func
),
8135 'args': '%s, kBucketId' % args
[0].GetValidArg(func
),
8136 'expect_len_code': '',
8138 if get_len_func
and get_len_func
[0:2] == 'gl':
8139 sub
['expect_len_code'] = (
8140 " EXPECT_CALL(*gl_, %s(%s, %s, _))\n"
8141 " .WillOnce(SetArgumentPointee<2>(strlen(kInfo) + 1));") % (
8142 get_len_func
[2:], id_name
, get_len_enum
)
8143 self
.WriteValidUnitTest(func
, file, valid_test
, sub
, *extras
)
8146 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
8147 const uint32_t kBucketId = 123;
8148 EXPECT_CALL(*gl_, %(gl_func_name)s(_, _, _, _))
8151 cmd.Init(kInvalidClientId, kBucketId);
8152 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
8153 EXPECT_EQ(GL_INVALID_VALUE, GetGLError());
8156 self
.WriteValidUnitTest(func
, file, invalid_test
, *extras
)
8158 def WriteServiceImplementation(self
, func
, file):
8159 """Overrriden from TypeHandler."""
8162 class NamedType(object):
8163 """A class that represents a type of an argument in a client function.
8165 A type of an argument that is to be passed through in the command buffer
8166 command. Currently used only for the arguments that are specificly named in
8167 the 'cmd_buffer_functions.txt' file, mostly enums.
8170 def __init__(self
, info
):
8171 assert not 'is_complete' in info
or info
['is_complete'] == True
8173 self
.valid
= info
['valid']
8174 if 'invalid' in info
:
8175 self
.invalid
= info
['invalid']
8178 if 'valid_es3' in info
:
8179 self
.valid_es3
= info
['valid_es3']
8182 if 'deprecated_es3' in info
:
8183 self
.deprecated_es3
= info
['deprecated_es3']
8185 self
.deprecated_es3
= []
8188 return self
.info
['type']
8190 def GetInvalidValues(self
):
8193 def GetValidValues(self
):
8196 def GetValidValuesES3(self
):
8197 return self
.valid_es3
8199 def GetDeprecatedValuesES3(self
):
8200 return self
.deprecated_es3
8202 def IsConstant(self
):
8203 if not 'is_complete' in self
.info
:
8206 return len(self
.GetValidValues()) == 1
8208 def GetConstantValue(self
):
8209 return self
.GetValidValues()[0]
8211 class Argument(object):
8212 """A class that represents a function argument."""
8215 'GLenum': 'uint32_t',
8217 'GLintptr': 'int32_t',
8218 'GLsizei': 'int32_t',
8219 'GLsizeiptr': 'int32_t',
8221 'GLclampf': 'float',
8223 need_validation_
= ['GLsizei*', 'GLboolean*', 'GLenum*', 'GLint*']
8225 def __init__(self
, name
, type):
8227 self
.optional
= type.endswith("Optional*")
8229 type = type[:-9] + "*"
8232 if type in self
.cmd_type_map_
:
8233 self
.cmd_type
= self
.cmd_type_map_
[type]
8235 self
.cmd_type
= 'uint32_t'
8237 def IsPointer(self
):
8238 """Returns true if argument is a pointer."""
8241 def IsPointer2D(self
):
8242 """Returns true if argument is a 2D pointer."""
8245 def IsConstant(self
):
8246 """Returns true if the argument has only one valid value."""
8249 def AddCmdArgs(self
, args
):
8250 """Adds command arguments for this argument to the given list."""
8251 if not self
.IsConstant():
8252 return args
.append(self
)
8254 def AddInitArgs(self
, args
):
8255 """Adds init arguments for this argument to the given list."""
8256 if not self
.IsConstant():
8257 return args
.append(self
)
8259 def GetValidArg(self
, func
):
8260 """Gets a valid value for this argument."""
8261 valid_arg
= func
.GetValidArg(self
)
8262 if valid_arg
!= None:
8265 index
= func
.GetOriginalArgs().index(self
)
8266 return str(index
+ 1)
8268 def GetValidClientSideArg(self
, func
):
8269 """Gets a valid value for this argument."""
8270 valid_arg
= func
.GetValidArg(self
)
8271 if valid_arg
!= None:
8274 if self
.IsPointer():
8276 index
= func
.GetOriginalArgs().index(self
)
8277 if self
.type == 'GLsync':
8278 return ("reinterpret_cast<GLsync>(%d)" % (index
+ 1))
8279 return str(index
+ 1)
8281 def GetValidClientSideCmdArg(self
, func
):
8282 """Gets a valid value for this argument."""
8283 valid_arg
= func
.GetValidArg(self
)
8284 if valid_arg
!= None:
8287 index
= func
.GetOriginalArgs().index(self
)
8288 return str(index
+ 1)
8291 index
= func
.GetCmdArgs().index(self
)
8292 return str(index
+ 1)
8294 def GetValidGLArg(self
, func
):
8295 """Gets a valid GL value for this argument."""
8296 value
= self
.GetValidArg(func
)
8297 if self
.type == 'GLsync':
8298 return ("reinterpret_cast<GLsync>(%s)" % value
)
8301 def GetValidNonCachedClientSideArg(self
, func
):
8302 """Returns a valid value for this argument in a GL call.
8303 Using the value will produce a command buffer service invocation.
8304 Returns None if there is no such value."""
8306 if self
.type == 'GLsync':
8307 return ("reinterpret_cast<GLsync>(%s)" % value
)
8310 def GetValidNonCachedClientSideCmdArg(self
, func
):
8311 """Returns a valid value for this argument in a command buffer command.
8312 Calling the GL function with the value returned by
8313 GetValidNonCachedClientSideArg will result in a command buffer command
8314 that contains the value returned by this function. """
8317 def GetNumInvalidValues(self
, func
):
8318 """returns the number of invalid values to be tested."""
8321 def GetInvalidArg(self
, index
):
8322 """returns an invalid value and expected parse result by index."""
8323 return ("---ERROR0---", "---ERROR2---", None)
8325 def GetLogArg(self
):
8326 """Get argument appropriate for LOG macro."""
8327 if self
.type == 'GLboolean':
8328 return 'GLES2Util::GetStringBool(%s)' % self
.name
8329 if self
.type == 'GLenum':
8330 return 'GLES2Util::GetStringEnum(%s)' % self
.name
8333 def WriteGetCode(self
, file):
8334 """Writes the code to get an argument from a command structure."""
8335 if self
.type == 'GLsync':
8339 file.Write(" %s %s = static_cast<%s>(c.%s);\n" %
8340 (my_type
, self
.name
, my_type
, self
.name
))
8342 def WriteValidationCode(self
, file, func
):
8343 """Writes the validation code for an argument."""
8346 def WriteClientSideValidationCode(self
, file, func
):
8347 """Writes the validation code for an argument."""
8350 def WriteDestinationInitalizationValidation(self
, file, func
):
8351 """Writes the client side destintion initialization validation."""
8354 def WriteDestinationInitalizationValidatationIfNeeded(self
, file, func
):
8355 """Writes the client side destintion initialization validation if needed."""
8356 parts
= self
.type.split(" ")
8359 if parts
[0] in self
.need_validation_
:
8361 " GPU_CLIENT_VALIDATE_DESTINATION_%sINITALIZATION(%s, %s);\n" %
8362 ("OPTIONAL_" if self
.optional
else "", self
.type[:-1], self
.name
))
8365 def WriteGetAddress(self
, file):
8366 """Writes the code to get the address this argument refers to."""
8369 def GetImmediateVersion(self
):
8370 """Gets the immediate version of this argument."""
8373 def GetBucketVersion(self
):
8374 """Gets the bucket version of this argument."""
8378 class BoolArgument(Argument
):
8379 """class for GLboolean"""
8381 def __init__(self
, name
, type):
8382 Argument
.__init
__(self
, name
, 'GLboolean')
8384 def GetValidArg(self
, func
):
8385 """Gets a valid value for this argument."""
8388 def GetValidClientSideArg(self
, func
):
8389 """Gets a valid value for this argument."""
8392 def GetValidClientSideCmdArg(self
, func
):
8393 """Gets a valid value for this argument."""
8396 def GetValidGLArg(self
, func
):
8397 """Gets a valid GL value for this argument."""
8401 class UniformLocationArgument(Argument
):
8402 """class for uniform locations."""
8404 def __init__(self
, name
):
8405 Argument
.__init
__(self
, name
, "GLint")
8407 def WriteGetCode(self
, file):
8408 """Writes the code to get an argument from a command structure."""
8409 code
= """ %s %s = static_cast<%s>(c.%s);
8411 file.Write(code
% (self
.type, self
.name
, self
.type, self
.name
))
8413 class DataSizeArgument(Argument
):
8414 """class for data_size which Bucket commands do not need."""
8416 def __init__(self
, name
):
8417 Argument
.__init
__(self
, name
, "uint32_t")
8419 def GetBucketVersion(self
):
8423 class SizeArgument(Argument
):
8424 """class for GLsizei and GLsizeiptr."""
8426 def __init__(self
, name
, type):
8427 Argument
.__init
__(self
, name
, type)
8429 def GetNumInvalidValues(self
, func
):
8430 """overridden from Argument."""
8431 if func
.IsImmediate():
8435 def GetInvalidArg(self
, index
):
8436 """overridden from Argument."""
8437 return ("-1", "kNoError", "GL_INVALID_VALUE")
8439 def WriteValidationCode(self
, file, func
):
8440 """overridden from Argument."""
8443 code
= """ if (%(var_name)s < 0) {
8444 LOCAL_SET_GL_ERROR(GL_INVALID_VALUE, "gl%(func_name)s", "%(var_name)s < 0");
8445 return error::kNoError;
8449 "var_name": self
.name
,
8450 "func_name": func
.original_name
,
8453 def WriteClientSideValidationCode(self
, file, func
):
8454 """overridden from Argument."""
8455 code
= """ if (%(var_name)s < 0) {
8456 SetGLError(GL_INVALID_VALUE, "gl%(func_name)s", "%(var_name)s < 0");
8461 "var_name": self
.name
,
8462 "func_name": func
.original_name
,
8466 class SizeNotNegativeArgument(SizeArgument
):
8467 """class for GLsizeiNotNegative. It's NEVER allowed to be negative"""
8469 def __init__(self
, name
, type, gl_type
):
8470 SizeArgument
.__init
__(self
, name
, gl_type
)
8472 def GetInvalidArg(self
, index
):
8473 """overridden from SizeArgument."""
8474 return ("-1", "kOutOfBounds", "GL_NO_ERROR")
8476 def WriteValidationCode(self
, file, func
):
8477 """overridden from SizeArgument."""
8481 class EnumBaseArgument(Argument
):
8482 """Base class for EnumArgument, IntArgument, BitfieldArgument, and
8483 ValidatedBoolArgument."""
8485 def __init__(self
, name
, gl_type
, type, gl_error
):
8486 Argument
.__init
__(self
, name
, gl_type
)
8488 self
.local_type
= type
8489 self
.gl_error
= gl_error
8490 name
= type[len(gl_type
):]
8491 self
.type_name
= name
8492 self
.named_type
= NamedType(_NAMED_TYPE_INFO
[name
])
8494 def IsConstant(self
):
8495 return self
.named_type
.IsConstant()
8497 def GetConstantValue(self
):
8498 return self
.named_type
.GetConstantValue()
8500 def WriteValidationCode(self
, file, func
):
8503 if self
.named_type
.IsConstant():
8505 file.Write(" if (!validators_->%s.IsValid(%s)) {\n" %
8506 (ToUnderscore(self
.type_name
), self
.name
))
8507 if self
.gl_error
== "GL_INVALID_ENUM":
8509 " LOCAL_SET_GL_ERROR_INVALID_ENUM(\"gl%s\", %s, \"%s\");\n" %
8510 (func
.original_name
, self
.name
, self
.name
))
8513 " LOCAL_SET_GL_ERROR(%s, \"gl%s\", \"%s %s\");\n" %
8514 (self
.gl_error
, func
.original_name
, self
.name
, self
.gl_error
))
8515 file.Write(" return error::kNoError;\n")
8518 def WriteClientSideValidationCode(self
, file, func
):
8519 if not self
.named_type
.IsConstant():
8521 file.Write(" if (%s != %s) {" % (self
.name
,
8522 self
.GetConstantValue()))
8524 " SetGLError(%s, \"gl%s\", \"%s %s\");\n" %
8525 (self
.gl_error
, func
.original_name
, self
.name
, self
.gl_error
))
8526 if func
.return_type
== "void":
8527 file.Write(" return;\n")
8529 file.Write(" return %s;\n" % func
.GetErrorReturnString())
8532 def GetValidArg(self
, func
):
8533 valid_arg
= func
.GetValidArg(self
)
8534 if valid_arg
!= None:
8536 valid
= self
.named_type
.GetValidValues()
8538 num_valid
= len(valid
)
8541 index
= func
.GetOriginalArgs().index(self
)
8542 return str(index
+ 1)
8544 def GetValidClientSideArg(self
, func
):
8545 """Gets a valid value for this argument."""
8546 return self
.GetValidArg(func
)
8548 def GetValidClientSideCmdArg(self
, func
):
8549 """Gets a valid value for this argument."""
8550 valid_arg
= func
.GetValidArg(self
)
8551 if valid_arg
!= None:
8554 valid
= self
.named_type
.GetValidValues()
8556 num_valid
= len(valid
)
8560 index
= func
.GetOriginalArgs().index(self
)
8561 return str(index
+ 1)
8564 index
= func
.GetCmdArgs().index(self
)
8565 return str(index
+ 1)
8567 def GetValidGLArg(self
, func
):
8568 """Gets a valid value for this argument."""
8569 return self
.GetValidArg(func
)
8571 def GetNumInvalidValues(self
, func
):
8572 """returns the number of invalid values to be tested."""
8573 return len(self
.named_type
.GetInvalidValues())
8575 def GetInvalidArg(self
, index
):
8576 """returns an invalid value by index."""
8577 invalid
= self
.named_type
.GetInvalidValues()
8579 num_invalid
= len(invalid
)
8580 if index
>= num_invalid
:
8581 index
= num_invalid
- 1
8582 return (invalid
[index
], "kNoError", self
.gl_error
)
8583 return ("---ERROR1---", "kNoError", self
.gl_error
)
8586 class EnumArgument(EnumBaseArgument
):
8587 """A class that represents a GLenum argument"""
8589 def __init__(self
, name
, type):
8590 EnumBaseArgument
.__init
__(self
, name
, "GLenum", type, "GL_INVALID_ENUM")
8592 def GetLogArg(self
):
8593 """Overridden from Argument."""
8594 return ("GLES2Util::GetString%s(%s)" %
8595 (self
.type_name
, self
.name
))
8598 class IntArgument(EnumBaseArgument
):
8599 """A class for a GLint argument that can only accept specific values.
8601 For example glTexImage2D takes a GLint for its internalformat
8602 argument instead of a GLenum.
8605 def __init__(self
, name
, type):
8606 EnumBaseArgument
.__init
__(self
, name
, "GLint", type, "GL_INVALID_VALUE")
8609 class ValidatedBoolArgument(EnumBaseArgument
):
8610 """A class for a GLboolean argument that can only accept specific values.
8612 For example glUniformMatrix takes a GLboolean for it's transpose but it
8616 def __init__(self
, name
, type):
8617 EnumBaseArgument
.__init
__(self
, name
, "GLboolean", type, "GL_INVALID_VALUE")
8619 def GetLogArg(self
):
8620 """Overridden from Argument."""
8621 return 'GLES2Util::GetStringBool(%s)' % self
.name
8624 class BitFieldArgument(EnumBaseArgument
):
8625 """A class for a GLbitfield argument that can only accept specific values.
8627 For example glFenceSync takes a GLbitfield for its flags argument bit it
8631 def __init__(self
, name
, type):
8632 EnumBaseArgument
.__init
__(self
, name
, "GLbitfield", type,
8636 class ImmediatePointerArgument(Argument
):
8637 """A class that represents an immediate argument to a function.
8639 An immediate argument is one where the data follows the command.
8642 def __init__(self
, name
, type):
8643 Argument
.__init
__(self
, name
, type)
8645 def IsPointer(self
):
8648 def GetPointedType(self
):
8649 match
= re
.match('(const\s+)?(?P<element_type>[\w]+)\s*\*', self
.type)
8651 return match
.groupdict()['element_type']
8653 def AddCmdArgs(self
, args
):
8654 """Overridden from Argument."""
8657 def WriteGetCode(self
, file):
8658 """Overridden from Argument."""
8660 " %s %s = GetImmediateDataAs<%s>(\n" %
8661 (self
.type, self
.name
, self
.type))
8662 file.Write(" c, data_size, immediate_data_size);\n")
8664 def WriteValidationCode(self
, file, func
):
8665 """Overridden from Argument."""
8668 file.Write(" if (%s == NULL) {\n" % self
.name
)
8669 file.Write(" return error::kOutOfBounds;\n")
8672 def GetImmediateVersion(self
):
8673 """Overridden from Argument."""
8676 def WriteDestinationInitalizationValidation(self
, file, func
):
8677 """Overridden from Argument."""
8678 self
.WriteDestinationInitalizationValidatationIfNeeded(file, func
)
8680 def GetLogArg(self
):
8681 """Overridden from Argument."""
8682 return "static_cast<const void*>(%s)" % self
.name
8685 class PointerArgument(Argument
):
8686 """A class that represents a pointer argument to a function."""
8688 def __init__(self
, name
, type):
8689 Argument
.__init
__(self
, name
, type)
8691 def IsPointer(self
):
8692 """Overridden from Argument."""
8695 def IsPointer2D(self
):
8696 """Overridden from Argument."""
8697 return self
.type.count('*') == 2
8699 def GetPointedType(self
):
8700 match
= re
.match('(const\s+)?(?P<element_type>[\w]+)\s*\*', self
.type)
8702 return match
.groupdict()['element_type']
8704 def GetValidArg(self
, func
):
8705 """Overridden from Argument."""
8706 return "shared_memory_id_, shared_memory_offset_"
8708 def GetValidGLArg(self
, func
):
8709 """Overridden from Argument."""
8710 return "reinterpret_cast<%s>(shared_memory_address_)" % self
.type
8712 def GetNumInvalidValues(self
, func
):
8713 """Overridden from Argument."""
8716 def GetInvalidArg(self
, index
):
8717 """Overridden from Argument."""
8719 return ("kInvalidSharedMemoryId, 0", "kOutOfBounds", None)
8721 return ("shared_memory_id_, kInvalidSharedMemoryOffset",
8722 "kOutOfBounds", None)
8724 def GetLogArg(self
):
8725 """Overridden from Argument."""
8726 return "static_cast<const void*>(%s)" % self
.name
8728 def AddCmdArgs(self
, args
):
8729 """Overridden from Argument."""
8730 args
.append(Argument("%s_shm_id" % self
.name
, 'uint32_t'))
8731 args
.append(Argument("%s_shm_offset" % self
.name
, 'uint32_t'))
8733 def WriteGetCode(self
, file):
8734 """Overridden from Argument."""
8736 " %s %s = GetSharedMemoryAs<%s>(\n" %
8737 (self
.type, self
.name
, self
.type))
8739 " c.%s_shm_id, c.%s_shm_offset, data_size);\n" %
8740 (self
.name
, self
.name
))
8742 def WriteGetAddress(self
, file):
8743 """Overridden from Argument."""
8745 " %s %s = GetSharedMemoryAs<%s>(\n" %
8746 (self
.type, self
.name
, self
.type))
8748 " %s_shm_id, %s_shm_offset, %s_size);\n" %
8749 (self
.name
, self
.name
, self
.name
))
8751 def WriteValidationCode(self
, file, func
):
8752 """Overridden from Argument."""
8755 file.Write(" if (%s == NULL) {\n" % self
.name
)
8756 file.Write(" return error::kOutOfBounds;\n")
8759 def GetImmediateVersion(self
):
8760 """Overridden from Argument."""
8761 return ImmediatePointerArgument(self
.name
, self
.type)
8763 def GetBucketVersion(self
):
8764 """Overridden from Argument."""
8765 if self
.type.find('char') >= 0:
8766 if self
.IsPointer2D():
8767 return InputStringArrayBucketArgument(self
.name
, self
.type)
8768 return InputStringBucketArgument(self
.name
, self
.type)
8769 return BucketPointerArgument(self
.name
, self
.type)
8771 def WriteDestinationInitalizationValidation(self
, file, func
):
8772 """Overridden from Argument."""
8773 self
.WriteDestinationInitalizationValidatationIfNeeded(file, func
)
8776 class BucketPointerArgument(PointerArgument
):
8777 """A class that represents an bucket argument to a function."""
8779 def __init__(self
, name
, type):
8780 Argument
.__init
__(self
, name
, type)
8782 def AddCmdArgs(self
, args
):
8783 """Overridden from Argument."""
8786 def WriteGetCode(self
, file):
8787 """Overridden from Argument."""
8789 " %s %s = bucket->GetData(0, data_size);\n" %
8790 (self
.type, self
.name
))
8792 def WriteValidationCode(self
, file, func
):
8793 """Overridden from Argument."""
8796 def GetImmediateVersion(self
):
8797 """Overridden from Argument."""
8800 def WriteDestinationInitalizationValidation(self
, file, func
):
8801 """Overridden from Argument."""
8802 self
.WriteDestinationInitalizationValidatationIfNeeded(file, func
)
8804 def GetLogArg(self
):
8805 """Overridden from Argument."""
8806 return "static_cast<const void*>(%s)" % self
.name
8809 class InputStringBucketArgument(Argument
):
8810 """A string input argument where the string is passed in a bucket."""
8812 def __init__(self
, name
, type):
8813 Argument
.__init
__(self
, name
+ "_bucket_id", "uint32_t")
8815 def IsPointer(self
):
8816 """Overridden from Argument."""
8819 def IsPointer2D(self
):
8820 """Overridden from Argument."""
8824 class InputStringArrayBucketArgument(Argument
):
8825 """A string array input argument where the strings are passed in a bucket."""
8827 def __init__(self
, name
, type):
8828 Argument
.__init
__(self
, name
+ "_bucket_id", "uint32_t")
8829 self
._original
_name
= name
8831 def WriteGetCode(self
, file):
8832 """Overridden from Argument."""
8834 Bucket* bucket = GetBucket(c.%(name)s);
8836 return error::kInvalidArguments;
8839 std::vector<char*> strs;
8840 std::vector<GLint> len;
8841 if (!bucket->GetAsStrings(&count, &strs, &len)) {
8842 return error::kInvalidArguments;
8844 const char** %(original_name)s =
8845 strs.size() > 0 ? const_cast<const char**>(&strs[0]) : NULL;
8846 const GLint* length =
8847 len.size() > 0 ? const_cast<const GLint*>(&len[0]) : NULL;
8852 'original_name': self
._original
_name
,
8855 def GetValidArg(self
, func
):
8856 return "kNameBucketId"
8858 def GetValidGLArg(self
, func
):
8861 def IsPointer(self
):
8862 """Overridden from Argument."""
8865 def IsPointer2D(self
):
8866 """Overridden from Argument."""
8870 class ResourceIdArgument(Argument
):
8871 """A class that represents a resource id argument to a function."""
8873 def __init__(self
, name
, type):
8874 match
= re
.match("(GLid\w+)", type)
8875 self
.resource_type
= match
.group(1)[4:]
8876 if self
.resource_type
== "Sync":
8877 type = type.replace(match
.group(1), "GLsync")
8879 type = type.replace(match
.group(1), "GLuint")
8880 Argument
.__init
__(self
, name
, type)
8882 def WriteGetCode(self
, file):
8883 """Overridden from Argument."""
8884 if self
.type == "GLsync":
8888 file.Write(" %s %s = c.%s;\n" % (my_type
, self
.name
, self
.name
))
8890 def GetValidArg(self
, func
):
8891 return "client_%s_id_" % self
.resource_type
.lower()
8893 def GetValidGLArg(self
, func
):
8894 if self
.resource_type
== "Sync":
8895 return "reinterpret_cast<GLsync>(kService%sId)" % self
.resource_type
8896 return "kService%sId" % self
.resource_type
8899 class ResourceIdBindArgument(Argument
):
8900 """Represents a resource id argument to a bind function."""
8902 def __init__(self
, name
, type):
8903 match
= re
.match("(GLidBind\w+)", type)
8904 self
.resource_type
= match
.group(1)[8:]
8905 type = type.replace(match
.group(1), "GLuint")
8906 Argument
.__init
__(self
, name
, type)
8908 def WriteGetCode(self
, file):
8909 """Overridden from Argument."""
8910 code
= """ %(type)s %(name)s = c.%(name)s;
8912 file.Write(code
% {'type': self
.type, 'name': self
.name
})
8914 def GetValidArg(self
, func
):
8915 return "client_%s_id_" % self
.resource_type
.lower()
8917 def GetValidGLArg(self
, func
):
8918 return "kService%sId" % self
.resource_type
8921 class ResourceIdZeroArgument(Argument
):
8922 """Represents a resource id argument to a function that can be zero."""
8924 def __init__(self
, name
, type):
8925 match
= re
.match("(GLidZero\w+)", type)
8926 self
.resource_type
= match
.group(1)[8:]
8927 type = type.replace(match
.group(1), "GLuint")
8928 Argument
.__init
__(self
, name
, type)
8930 def WriteGetCode(self
, file):
8931 """Overridden from Argument."""
8932 file.Write(" %s %s = c.%s;\n" % (self
.type, self
.name
, self
.name
))
8934 def GetValidArg(self
, func
):
8935 return "client_%s_id_" % self
.resource_type
.lower()
8937 def GetValidGLArg(self
, func
):
8938 return "kService%sId" % self
.resource_type
8940 def GetNumInvalidValues(self
, func
):
8941 """returns the number of invalid values to be tested."""
8944 def GetInvalidArg(self
, index
):
8945 """returns an invalid value by index."""
8946 return ("kInvalidClientId", "kNoError", "GL_INVALID_VALUE")
8949 class Function(object):
8950 """A class that represents a function."""
8954 'Bind': BindHandler(),
8955 'Create': CreateHandler(),
8956 'Custom': CustomHandler(),
8957 'Data': DataHandler(),
8958 'Delete': DeleteHandler(),
8959 'DELn': DELnHandler(),
8960 'GENn': GENnHandler(),
8961 'GETn': GETnHandler(),
8962 'GLchar': GLcharHandler(),
8963 'GLcharN': GLcharNHandler(),
8964 'HandWritten': HandWrittenHandler(),
8966 'Manual': ManualHandler(),
8967 'PUT': PUTHandler(),
8968 'PUTn': PUTnHandler(),
8969 'PUTSTR': PUTSTRHandler(),
8970 'PUTXn': PUTXnHandler(),
8971 'StateSet': StateSetHandler(),
8972 'StateSetRGBAlpha': StateSetRGBAlphaHandler(),
8973 'StateSetFrontBack': StateSetFrontBackHandler(),
8974 'StateSetFrontBackSeparate': StateSetFrontBackSeparateHandler(),
8975 'StateSetNamedParameter': StateSetNamedParameter(),
8976 'STRn': STRnHandler(),
8977 'Todo': TodoHandler(),
8980 def __init__(self
, name
, info
):
8982 self
.original_name
= info
['original_name']
8984 self
.original_args
= self
.ParseArgs(info
['original_args'])
8986 if 'cmd_args' in info
:
8987 self
.args_for_cmds
= self
.ParseArgs(info
['cmd_args'])
8989 self
.args_for_cmds
= self
.original_args
[:]
8991 self
.return_type
= info
['return_type']
8992 if self
.return_type
!= 'void':
8993 self
.return_arg
= CreateArg(info
['return_type'] + " result")
8995 self
.return_arg
= None
8997 self
.num_pointer_args
= sum(
8998 [1 for arg
in self
.args_for_cmds
if arg
.IsPointer()])
8999 if self
.num_pointer_args
> 0:
9000 for arg
in reversed(self
.original_args
):
9002 self
.last_original_pointer_arg
= arg
9005 self
.last_original_pointer_arg
= None
9007 self
.type_handler
= self
.type_handlers
[info
['type']]
9008 self
.can_auto_generate
= (self
.num_pointer_args
== 0 and
9009 info
['return_type'] == "void")
9012 def ParseArgs(self
, arg_string
):
9013 """Parses a function arg string."""
9015 parts
= arg_string
.split(',')
9016 for arg_string
in parts
:
9017 arg
= CreateArg(arg_string
)
9022 def IsType(self
, type_name
):
9023 """Returns true if function is a certain type."""
9024 return self
.info
['type'] == type_name
9026 def InitFunction(self
):
9027 """Creates command args and calls the init function for the type handler.
9029 Creates argument lists for command buffer commands, eg. self.cmd_args and
9031 Calls the type function initialization.
9032 Override to create different kind of command buffer command argument lists.
9035 for arg
in self
.args_for_cmds
:
9036 arg
.AddCmdArgs(self
.cmd_args
)
9039 for arg
in self
.args_for_cmds
:
9040 arg
.AddInitArgs(self
.init_args
)
9043 self
.init_args
.append(self
.return_arg
)
9045 self
.type_handler
.InitFunction(self
)
9047 def IsImmediate(self
):
9048 """Returns whether the function is immediate data function or not."""
9052 """Returns whether the function has service side validation or not."""
9053 return self
.GetInfo('unsafe', False)
9055 def GetInfo(self
, name
, default
= None):
9056 """Returns a value from the function info for this function."""
9057 if name
in self
.info
:
9058 return self
.info
[name
]
9061 def GetValidArg(self
, arg
):
9062 """Gets a valid argument value for the parameter arg from the function info
9065 index
= self
.GetOriginalArgs().index(arg
)
9069 valid_args
= self
.GetInfo('valid_args')
9070 if valid_args
and str(index
) in valid_args
:
9071 return valid_args
[str(index
)]
9074 def AddInfo(self
, name
, value
):
9076 self
.info
[name
] = value
9078 def IsExtension(self
):
9079 return self
.GetInfo('extension') or self
.GetInfo('extension_flag')
9081 def IsCoreGLFunction(self
):
9082 return (not self
.IsExtension() and
9083 not self
.GetInfo('pepper_interface') and
9084 not self
.IsUnsafe())
9086 def InPepperInterface(self
, interface
):
9087 ext
= self
.GetInfo('pepper_interface')
9088 if not interface
.GetName():
9089 return self
.IsCoreGLFunction()
9090 return ext
== interface
.GetName()
9092 def InAnyPepperExtension(self
):
9093 return self
.IsCoreGLFunction() or self
.GetInfo('pepper_interface')
9095 def GetErrorReturnString(self
):
9096 if self
.GetInfo("error_return"):
9097 return self
.GetInfo("error_return")
9098 elif self
.return_type
== "GLboolean":
9100 elif "*" in self
.return_type
:
9104 def GetGLFunctionName(self
):
9105 """Gets the function to call to execute GL for this command."""
9106 if self
.GetInfo('decoder_func'):
9107 return self
.GetInfo('decoder_func')
9108 return "gl%s" % self
.original_name
9110 def GetGLTestFunctionName(self
):
9111 gl_func_name
= self
.GetInfo('gl_test_func')
9112 if gl_func_name
== None:
9113 gl_func_name
= self
.GetGLFunctionName()
9114 if gl_func_name
.startswith("gl"):
9115 gl_func_name
= gl_func_name
[2:]
9117 gl_func_name
= self
.original_name
9120 def GetDataTransferMethods(self
):
9121 return self
.GetInfo('data_transfer_methods',
9122 ['immediate' if self
.num_pointer_args
== 1 else 'shm'])
9124 def AddCmdArg(self
, arg
):
9125 """Adds a cmd argument to this function."""
9126 self
.cmd_args
.append(arg
)
9128 def GetCmdArgs(self
):
9129 """Gets the command args for this function."""
9130 return self
.cmd_args
9132 def ClearCmdArgs(self
):
9133 """Clears the command args for this function."""
9136 def GetCmdConstants(self
):
9137 """Gets the constants for this function."""
9138 return [arg
for arg
in self
.args_for_cmds
if arg
.IsConstant()]
9140 def GetInitArgs(self
):
9141 """Gets the init args for this function."""
9142 return self
.init_args
9144 def GetOriginalArgs(self
):
9145 """Gets the original arguments to this function."""
9146 return self
.original_args
9148 def GetLastOriginalArg(self
):
9149 """Gets the last original argument to this function."""
9150 return self
.original_args
[len(self
.original_args
) - 1]
9152 def GetLastOriginalPointerArg(self
):
9153 return self
.last_original_pointer_arg
9155 def GetResourceIdArg(self
):
9156 for arg
in self
.original_args
:
9157 if hasattr(arg
, 'resource_type'):
9161 def _MaybePrependComma(self
, arg_string
, add_comma
):
9162 """Adds a comma if arg_string is not empty and add_comma is true."""
9164 if add_comma
and len(arg_string
):
9166 return "%s%s" % (comma
, arg_string
)
9168 def MakeTypedOriginalArgString(self
, prefix
, add_comma
= False):
9169 """Gets a list of arguments as they are in GL."""
9170 args
= self
.GetOriginalArgs()
9171 arg_string
= ", ".join(
9172 ["%s %s%s" % (arg
.type, prefix
, arg
.name
) for arg
in args
])
9173 return self
._MaybePrependComma
(arg_string
, add_comma
)
9175 def MakeOriginalArgString(self
, prefix
, add_comma
= False, separator
= ", "):
9176 """Gets the list of arguments as they are in GL."""
9177 args
= self
.GetOriginalArgs()
9178 arg_string
= separator
.join(
9179 ["%s%s" % (prefix
, arg
.name
) for arg
in args
])
9180 return self
._MaybePrependComma
(arg_string
, add_comma
)
9182 def MakeTypedHelperArgString(self
, prefix
, add_comma
= False):
9183 """Gets a list of typed GL arguments after removing unneeded arguments."""
9184 args
= self
.GetOriginalArgs()
9185 arg_string
= ", ".join(
9190 ) for arg
in args
if not arg
.IsConstant()])
9191 return self
._MaybePrependComma
(arg_string
, add_comma
)
9193 def MakeHelperArgString(self
, prefix
, add_comma
= False, separator
= ", "):
9194 """Gets a list of GL arguments after removing unneeded arguments."""
9195 args
= self
.GetOriginalArgs()
9196 arg_string
= separator
.join(
9197 ["%s%s" % (prefix
, arg
.name
)
9198 for arg
in args
if not arg
.IsConstant()])
9199 return self
._MaybePrependComma
(arg_string
, add_comma
)
9201 def MakeTypedPepperArgString(self
, prefix
):
9202 """Gets a list of arguments as they need to be for Pepper."""
9203 if self
.GetInfo("pepper_args"):
9204 return self
.GetInfo("pepper_args")
9206 return self
.MakeTypedOriginalArgString(prefix
, False)
9208 def MapCTypeToPepperIdlType(self
, ctype
, is_for_return_type
=False):
9209 """Converts a C type name to the corresponding Pepper IDL type."""
9211 'char*': '[out] str_t',
9212 'const GLchar* const*': '[out] cstr_t',
9213 'const char*': 'cstr_t',
9214 'const void*': 'mem_t',
9215 'void*': '[out] mem_t',
9216 'void**': '[out] mem_ptr_t',
9218 # We use "GLxxx_ptr_t" for "GLxxx*".
9219 matched
= re
.match(r
'(const )?(GL\w+)\*$', ctype
)
9221 idltype
= matched
.group(2) + '_ptr_t'
9222 if not matched
.group(1):
9223 idltype
= '[out] ' + idltype
9224 # If an in/out specifier is not specified yet, prepend [in].
9225 if idltype
[0] != '[':
9226 idltype
= '[in] ' + idltype
9227 # Strip the in/out specifier for a return type.
9228 if is_for_return_type
:
9229 idltype
= re
.sub(r
'\[\w+\] ', '', idltype
)
9232 def MakeTypedPepperIdlArgStrings(self
):
9233 """Gets a list of arguments as they need to be for Pepper IDL."""
9234 args
= self
.GetOriginalArgs()
9235 return ["%s %s" % (self
.MapCTypeToPepperIdlType(arg
.type), arg
.name
)
9238 def GetPepperName(self
):
9239 if self
.GetInfo("pepper_name"):
9240 return self
.GetInfo("pepper_name")
9243 def MakeTypedCmdArgString(self
, prefix
, add_comma
= False):
9244 """Gets a typed list of arguments as they need to be for command buffers."""
9245 args
= self
.GetCmdArgs()
9246 arg_string
= ", ".join(
9247 ["%s %s%s" % (arg
.type, prefix
, arg
.name
) for arg
in args
])
9248 return self
._MaybePrependComma
(arg_string
, add_comma
)
9250 def MakeCmdArgString(self
, prefix
, add_comma
= False):
9251 """Gets the list of arguments as they need to be for command buffers."""
9252 args
= self
.GetCmdArgs()
9253 arg_string
= ", ".join(
9254 ["%s%s" % (prefix
, arg
.name
) for arg
in args
])
9255 return self
._MaybePrependComma
(arg_string
, add_comma
)
9257 def MakeTypedInitString(self
, prefix
, add_comma
= False):
9258 """Gets a typed list of arguments as they need to be for cmd Init/Set."""
9259 args
= self
.GetInitArgs()
9260 arg_string
= ", ".join(
9261 ["%s %s%s" % (arg
.type, prefix
, arg
.name
) for arg
in args
])
9262 return self
._MaybePrependComma
(arg_string
, add_comma
)
9264 def MakeInitString(self
, prefix
, add_comma
= False):
9265 """Gets the list of arguments as they need to be for cmd Init/Set."""
9266 args
= self
.GetInitArgs()
9267 arg_string
= ", ".join(
9268 ["%s%s" % (prefix
, arg
.name
) for arg
in args
])
9269 return self
._MaybePrependComma
(arg_string
, add_comma
)
9271 def MakeLogArgString(self
):
9272 """Makes a string of the arguments for the LOG macros"""
9273 args
= self
.GetOriginalArgs()
9274 return ' << ", " << '.join([arg
.GetLogArg() for arg
in args
])
9276 def WriteCommandDescription(self
, file):
9277 """Writes a description of the command."""
9278 file.Write("//! Command that corresponds to gl%s.\n" % self
.original_name
)
9280 def WriteHandlerValidation(self
, file):
9281 """Writes validation code for the function."""
9282 for arg
in self
.GetOriginalArgs():
9283 arg
.WriteValidationCode(file, self
)
9284 self
.WriteValidationCode(file)
9286 def WriteHandlerImplementation(self
, file):
9287 """Writes the handler implementation for this command."""
9288 self
.type_handler
.WriteHandlerImplementation(self
, file)
9290 def WriteValidationCode(self
, file):
9291 """Writes the validation code for a command."""
9294 def WriteCmdFlag(self
, file):
9295 """Writes the cmd cmd_flags constant."""
9297 # By default trace only at the highest level 3.
9298 trace_level
= int(self
.GetInfo('trace_level', default
= 3))
9299 if trace_level
not in xrange(0, 4):
9300 raise KeyError("Unhandled trace_level: %d" % trace_level
)
9302 flags
.append('CMD_FLAG_SET_TRACE_LEVEL(%d)' % trace_level
)
9305 cmd_flags
= ' | '.join(flags
)
9309 file.Write(" static const uint8 cmd_flags = %s;\n" % cmd_flags
)
9312 def WriteCmdArgFlag(self
, file):
9313 """Writes the cmd kArgFlags constant."""
9314 file.Write(" static const cmd::ArgFlags kArgFlags = cmd::kFixed;\n")
9316 def WriteCmdComputeSize(self
, file):
9317 """Writes the ComputeSize function for the command."""
9318 file.Write(" static uint32_t ComputeSize() {\n")
9320 " return static_cast<uint32_t>(sizeof(ValueType)); // NOLINT\n")
9324 def WriteCmdSetHeader(self
, file):
9325 """Writes the cmd's SetHeader function."""
9326 file.Write(" void SetHeader() {\n")
9327 file.Write(" header.SetCmd<ValueType>();\n")
9331 def WriteCmdInit(self
, file):
9332 """Writes the cmd's Init function."""
9333 file.Write(" void Init(%s) {\n" % self
.MakeTypedCmdArgString("_"))
9334 file.Write(" SetHeader();\n")
9335 args
= self
.GetCmdArgs()
9337 file.Write(" %s = _%s;\n" % (arg
.name
, arg
.name
))
9341 def WriteCmdSet(self
, file):
9342 """Writes the cmd's Set function."""
9343 copy_args
= self
.MakeCmdArgString("_", False)
9344 file.Write(" void* Set(void* cmd%s) {\n" %
9345 self
.MakeTypedCmdArgString("_", True))
9346 file.Write(" static_cast<ValueType*>(cmd)->Init(%s);\n" % copy_args
)
9347 file.Write(" return NextCmdAddress<ValueType>(cmd);\n")
9351 def WriteStruct(self
, file):
9352 self
.type_handler
.WriteStruct(self
, file)
9354 def WriteDocs(self
, file):
9355 self
.type_handler
.WriteDocs(self
, file)
9357 def WriteCmdHelper(self
, file):
9358 """Writes the cmd's helper."""
9359 self
.type_handler
.WriteCmdHelper(self
, file)
9361 def WriteServiceImplementation(self
, file):
9362 """Writes the service implementation for a command."""
9363 self
.type_handler
.WriteServiceImplementation(self
, file)
9365 def WriteServiceUnitTest(self
, file, *extras
):
9366 """Writes the service implementation for a command."""
9367 self
.type_handler
.WriteServiceUnitTest(self
, file, *extras
)
9369 def WriteGLES2CLibImplementation(self
, file):
9370 """Writes the GLES2 C Lib Implemention."""
9371 self
.type_handler
.WriteGLES2CLibImplementation(self
, file)
9373 def WriteGLES2InterfaceHeader(self
, file):
9374 """Writes the GLES2 Interface declaration."""
9375 self
.type_handler
.WriteGLES2InterfaceHeader(self
, file)
9377 def WriteMojoGLES2ImplHeader(self
, file):
9378 """Writes the Mojo GLES2 implementation header declaration."""
9379 self
.type_handler
.WriteMojoGLES2ImplHeader(self
, file)
9381 def WriteMojoGLES2Impl(self
, file):
9382 """Writes the Mojo GLES2 implementation declaration."""
9383 self
.type_handler
.WriteMojoGLES2Impl(self
, file)
9385 def WriteGLES2InterfaceStub(self
, file):
9386 """Writes the GLES2 Interface Stub declaration."""
9387 self
.type_handler
.WriteGLES2InterfaceStub(self
, file)
9389 def WriteGLES2InterfaceStubImpl(self
, file):
9390 """Writes the GLES2 Interface Stub declaration."""
9391 self
.type_handler
.WriteGLES2InterfaceStubImpl(self
, file)
9393 def WriteGLES2ImplementationHeader(self
, file):
9394 """Writes the GLES2 Implemention declaration."""
9395 self
.type_handler
.WriteGLES2ImplementationHeader(self
, file)
9397 def WriteGLES2Implementation(self
, file):
9398 """Writes the GLES2 Implemention definition."""
9399 self
.type_handler
.WriteGLES2Implementation(self
, file)
9401 def WriteGLES2TraceImplementationHeader(self
, file):
9402 """Writes the GLES2 Trace Implemention declaration."""
9403 self
.type_handler
.WriteGLES2TraceImplementationHeader(self
, file)
9405 def WriteGLES2TraceImplementation(self
, file):
9406 """Writes the GLES2 Trace Implemention definition."""
9407 self
.type_handler
.WriteGLES2TraceImplementation(self
, file)
9409 def WriteGLES2Header(self
, file):
9410 """Writes the GLES2 Implemention unit test."""
9411 self
.type_handler
.WriteGLES2Header(self
, file)
9413 def WriteGLES2ImplementationUnitTest(self
, file):
9414 """Writes the GLES2 Implemention unit test."""
9415 self
.type_handler
.WriteGLES2ImplementationUnitTest(self
, file)
9417 def WriteDestinationInitalizationValidation(self
, file):
9418 """Writes the client side destintion initialization validation."""
9419 self
.type_handler
.WriteDestinationInitalizationValidation(self
, file)
9421 def WriteFormatTest(self
, file):
9422 """Writes the cmd's format test."""
9423 self
.type_handler
.WriteFormatTest(self
, file)
9426 class PepperInterface(object):
9427 """A class that represents a function."""
9429 def __init__(self
, info
):
9430 self
.name
= info
["name"]
9431 self
.dev
= info
["dev"]
9436 def GetInterfaceName(self
):
9440 upperint
= "_" + self
.name
.upper()
9443 return "PPB_OPENGLES2%s%s_INTERFACE" % (upperint
, dev
)
9445 def GetInterfaceString(self
):
9449 return "PPB_OpenGLES2%s%s" % (self
.name
, dev
)
9451 def GetStructName(self
):
9455 return "PPB_OpenGLES2%s%s" % (self
.name
, dev
)
9458 class ImmediateFunction(Function
):
9459 """A class that represnets an immediate function command."""
9461 def __init__(self
, func
):
9464 "%sImmediate" % func
.name
,
9467 def InitFunction(self
):
9468 # Override args in original_args and args_for_cmds with immediate versions
9471 new_original_args
= []
9472 for arg
in self
.original_args
:
9473 new_arg
= arg
.GetImmediateVersion()
9475 new_original_args
.append(new_arg
)
9476 self
.original_args
= new_original_args
9478 new_args_for_cmds
= []
9479 for arg
in self
.args_for_cmds
:
9480 new_arg
= arg
.GetImmediateVersion()
9482 new_args_for_cmds
.append(new_arg
)
9484 self
.args_for_cmds
= new_args_for_cmds
9486 Function
.InitFunction(self
)
9488 def IsImmediate(self
):
9491 def WriteCommandDescription(self
, file):
9492 """Overridden from Function"""
9493 file.Write("//! Immediate version of command that corresponds to gl%s.\n" %
9496 def WriteServiceImplementation(self
, file):
9497 """Overridden from Function"""
9498 self
.type_handler
.WriteImmediateServiceImplementation(self
, file)
9500 def WriteHandlerImplementation(self
, file):
9501 """Overridden from Function"""
9502 self
.type_handler
.WriteImmediateHandlerImplementation(self
, file)
9504 def WriteServiceUnitTest(self
, file, *extras
):
9505 """Writes the service implementation for a command."""
9506 self
.type_handler
.WriteImmediateServiceUnitTest(self
, file, *extras
)
9508 def WriteValidationCode(self
, file):
9509 """Overridden from Function"""
9510 self
.type_handler
.WriteImmediateValidationCode(self
, file)
9512 def WriteCmdArgFlag(self
, file):
9513 """Overridden from Function"""
9514 file.Write(" static const cmd::ArgFlags kArgFlags = cmd::kAtLeastN;\n")
9516 def WriteCmdComputeSize(self
, file):
9517 """Overridden from Function"""
9518 self
.type_handler
.WriteImmediateCmdComputeSize(self
, file)
9520 def WriteCmdSetHeader(self
, file):
9521 """Overridden from Function"""
9522 self
.type_handler
.WriteImmediateCmdSetHeader(self
, file)
9524 def WriteCmdInit(self
, file):
9525 """Overridden from Function"""
9526 self
.type_handler
.WriteImmediateCmdInit(self
, file)
9528 def WriteCmdSet(self
, file):
9529 """Overridden from Function"""
9530 self
.type_handler
.WriteImmediateCmdSet(self
, file)
9532 def WriteCmdHelper(self
, file):
9533 """Overridden from Function"""
9534 self
.type_handler
.WriteImmediateCmdHelper(self
, file)
9536 def WriteFormatTest(self
, file):
9537 """Overridden from Function"""
9538 self
.type_handler
.WriteImmediateFormatTest(self
, file)
9541 class BucketFunction(Function
):
9542 """A class that represnets a bucket version of a function command."""
9544 def __init__(self
, func
):
9547 "%sBucket" % func
.name
,
9550 def InitFunction(self
):
9551 # Override args in original_args and args_for_cmds with bucket versions
9554 new_original_args
= []
9555 for arg
in self
.original_args
:
9556 new_arg
= arg
.GetBucketVersion()
9558 new_original_args
.append(new_arg
)
9559 self
.original_args
= new_original_args
9561 new_args_for_cmds
= []
9562 for arg
in self
.args_for_cmds
:
9563 new_arg
= arg
.GetBucketVersion()
9565 new_args_for_cmds
.append(new_arg
)
9567 self
.args_for_cmds
= new_args_for_cmds
9569 Function
.InitFunction(self
)
9571 def WriteCommandDescription(self
, file):
9572 """Overridden from Function"""
9573 file.Write("//! Bucket version of command that corresponds to gl%s.\n" %
9576 def WriteServiceImplementation(self
, file):
9577 """Overridden from Function"""
9578 self
.type_handler
.WriteBucketServiceImplementation(self
, file)
9580 def WriteHandlerImplementation(self
, file):
9581 """Overridden from Function"""
9582 self
.type_handler
.WriteBucketHandlerImplementation(self
, file)
9584 def WriteServiceUnitTest(self
, file, *extras
):
9585 """Overridden from Function"""
9586 self
.type_handler
.WriteBucketServiceUnitTest(self
, file, *extras
)
9588 def MakeOriginalArgString(self
, prefix
, add_comma
= False, separator
= ", "):
9589 """Overridden from Function"""
9590 args
= self
.GetOriginalArgs()
9591 arg_string
= separator
.join(
9592 ["%s%s" % (prefix
, arg
.name
[0:-10] if arg
.name
.endswith("_bucket_id")
9593 else arg
.name
) for arg
in args
])
9594 return super(BucketFunction
, self
)._MaybePrependComma
(arg_string
, add_comma
)
9597 def CreateArg(arg_string
):
9598 """Creates an Argument."""
9599 arg_parts
= arg_string
.split()
9600 if len(arg_parts
) == 1 and arg_parts
[0] == 'void':
9602 # Is this a pointer argument?
9603 elif arg_string
.find('*') >= 0:
9604 return PointerArgument(
9606 " ".join(arg_parts
[0:-1]))
9607 # Is this a resource argument? Must come after pointer check.
9608 elif arg_parts
[0].startswith('GLidBind'):
9609 return ResourceIdBindArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
9610 elif arg_parts
[0].startswith('GLidZero'):
9611 return ResourceIdZeroArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
9612 elif arg_parts
[0].startswith('GLid'):
9613 return ResourceIdArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
9614 elif arg_parts
[0].startswith('GLenum') and len(arg_parts
[0]) > 6:
9615 return EnumArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
9616 elif arg_parts
[0].startswith('GLbitfield') and len(arg_parts
[0]) > 10:
9617 return BitFieldArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
9618 elif arg_parts
[0].startswith('GLboolean') and len(arg_parts
[0]) > 9:
9619 return ValidatedBoolArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
9620 elif arg_parts
[0].startswith('GLboolean'):
9621 return BoolArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
9622 elif arg_parts
[0].startswith('GLintUniformLocation'):
9623 return UniformLocationArgument(arg_parts
[-1])
9624 elif (arg_parts
[0].startswith('GLint') and len(arg_parts
[0]) > 5 and
9625 not arg_parts
[0].startswith('GLintptr')):
9626 return IntArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
9627 elif (arg_parts
[0].startswith('GLsizeiNotNegative') or
9628 arg_parts
[0].startswith('GLintptrNotNegative')):
9629 return SizeNotNegativeArgument(arg_parts
[-1],
9630 " ".join(arg_parts
[0:-1]),
9631 arg_parts
[0][0:-11])
9632 elif arg_parts
[0].startswith('GLsize'):
9633 return SizeArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
9635 return Argument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
9638 class GLGenerator(object):
9639 """A class to generate GL command buffers."""
9641 _function_re
= re
.compile(r
'GL_APICALL(.*?)GL_APIENTRY (.*?) \((.*?)\);')
9643 def __init__(self
, verbose
):
9644 self
.original_functions
= []
9646 self
.verbose
= verbose
9648 self
.pepper_interfaces
= []
9649 self
.interface_info
= {}
9650 self
.generated_cpp_filenames
= []
9652 for interface
in _PEPPER_INTERFACES
:
9653 interface
= PepperInterface(interface
)
9654 self
.pepper_interfaces
.append(interface
)
9655 self
.interface_info
[interface
.GetName()] = interface
9657 def AddFunction(self
, func
):
9658 """Adds a function."""
9659 self
.functions
.append(func
)
9661 def GetFunctionInfo(self
, name
):
9662 """Gets a type info for the given function name."""
9663 if name
in _FUNCTION_INFO
:
9664 func_info
= _FUNCTION_INFO
[name
].copy()
9668 if not 'type' in func_info
:
9669 func_info
['type'] = ''
9674 """Prints something if verbose is true."""
9678 def Error(self
, msg
):
9679 """Prints an error."""
9680 print "Error: %s" % msg
9683 def WriteLicense(self
, file):
9684 """Writes the license."""
9685 file.Write(_LICENSE
)
9687 def WriteNamespaceOpen(self
, file):
9688 """Writes the code for the namespace."""
9689 file.Write("namespace gpu {\n")
9690 file.Write("namespace gles2 {\n")
9693 def WriteNamespaceClose(self
, file):
9694 """Writes the code to close the namespace."""
9695 file.Write("} // namespace gles2\n")
9696 file.Write("} // namespace gpu\n")
9699 def ParseGLH(self
, filename
):
9700 """Parses the cmd_buffer_functions.txt file and extracts the functions"""
9701 f
= open(filename
, "r")
9702 functions
= f
.read()
9704 for line
in functions
.splitlines():
9705 match
= self
._function
_re
.match(line
)
9707 func_name
= match
.group(2)[2:]
9708 func_info
= self
.GetFunctionInfo(func_name
)
9709 if func_info
['type'] == 'Noop':
9712 parsed_func_info
= {
9713 'original_name': func_name
,
9714 'original_args': match
.group(3),
9715 'return_type': match
.group(1).strip(),
9718 for k
in parsed_func_info
.keys():
9719 if not k
in func_info
:
9720 func_info
[k
] = parsed_func_info
[k
]
9722 f
= Function(func_name
, func_info
)
9723 self
.original_functions
.append(f
)
9725 #for arg in f.GetOriginalArgs():
9726 # if not isinstance(arg, EnumArgument) and arg.type == 'GLenum':
9727 # self.Log("%s uses bare GLenum %s." % (func_name, arg.name))
9729 gen_cmd
= f
.GetInfo('gen_cmd')
9730 if gen_cmd
== True or gen_cmd
== None:
9731 if f
.type_handler
.NeedsDataTransferFunction(f
):
9732 methods
= f
.GetDataTransferMethods()
9733 if 'immediate' in methods
:
9734 self
.AddFunction(ImmediateFunction(f
))
9735 if 'bucket' in methods
:
9736 self
.AddFunction(BucketFunction(f
))
9737 if 'shm' in methods
:
9742 self
.Log("Auto Generated Functions : %d" %
9743 len([f
for f
in self
.functions
if f
.can_auto_generate
or
9744 (not f
.IsType('') and not f
.IsType('Custom') and
9745 not f
.IsType('Todo'))]))
9747 funcs
= [f
for f
in self
.functions
if not f
.can_auto_generate
and
9748 (f
.IsType('') or f
.IsType('Custom') or f
.IsType('Todo'))]
9749 self
.Log("Non Auto Generated Functions: %d" % len(funcs
))
9752 self
.Log(" %-10s %-20s gl%s" % (f
.info
['type'], f
.return_type
, f
.name
))
9754 def WriteCommandIds(self
, filename
):
9755 """Writes the command buffer format"""
9756 file = CHeaderWriter(filename
)
9757 file.Write("#define GLES2_COMMAND_LIST(OP) \\\n")
9759 for func
in self
.functions
:
9760 file.Write(" %-60s /* %d */ \\\n" %
9761 ("OP(%s)" % func
.name
, id))
9765 file.Write("enum CommandId {\n")
9766 file.Write(" kStartPoint = cmd::kLastCommonId, "
9767 "// All GLES2 commands start after this.\n")
9768 file.Write("#define GLES2_CMD_OP(name) k ## name,\n")
9769 file.Write(" GLES2_COMMAND_LIST(GLES2_CMD_OP)\n")
9770 file.Write("#undef GLES2_CMD_OP\n")
9771 file.Write(" kNumCommands\n")
9775 self
.generated_cpp_filenames
.append(file.filename
)
9777 def WriteFormat(self
, filename
):
9778 """Writes the command buffer format"""
9779 file = CHeaderWriter(filename
)
9780 # Forward declaration of a few enums used in constant argument
9781 # to avoid including GL header files.
9783 'GL_SYNC_GPU_COMMANDS_COMPLETE': '0x9117',
9784 'GL_SYNC_FLUSH_COMMANDS_BIT': '0x00000001',
9787 for enum
in enum_defines
:
9788 file.Write("#define %s %s\n" % (enum
, enum_defines
[enum
]))
9790 for func
in self
.functions
:
9792 #gen_cmd = func.GetInfo('gen_cmd')
9793 #if gen_cmd == True or gen_cmd == None:
9794 func
.WriteStruct(file)
9797 self
.generated_cpp_filenames
.append(file.filename
)
9799 def WriteDocs(self
, filename
):
9800 """Writes the command buffer doc version of the commands"""
9801 file = CWriter(filename
)
9802 for func
in self
.functions
:
9804 #gen_cmd = func.GetInfo('gen_cmd')
9805 #if gen_cmd == True or gen_cmd == None:
9806 func
.WriteDocs(file)
9809 self
.generated_cpp_filenames
.append(file.filename
)
9811 def WriteFormatTest(self
, filename
):
9812 """Writes the command buffer format test."""
9813 file = CHeaderWriter(
9815 "// This file contains unit tests for gles2 commmands\n"
9816 "// It is included by gles2_cmd_format_test.cc\n"
9819 for func
in self
.functions
:
9821 #gen_cmd = func.GetInfo('gen_cmd')
9822 #if gen_cmd == True or gen_cmd == None:
9823 func
.WriteFormatTest(file)
9826 self
.generated_cpp_filenames
.append(file.filename
)
9828 def WriteCmdHelperHeader(self
, filename
):
9829 """Writes the gles2 command helper."""
9830 file = CHeaderWriter(filename
)
9832 for func
in self
.functions
:
9834 #gen_cmd = func.GetInfo('gen_cmd')
9835 #if gen_cmd == True or gen_cmd == None:
9836 func
.WriteCmdHelper(file)
9839 self
.generated_cpp_filenames
.append(file.filename
)
9841 def WriteServiceContextStateHeader(self
, filename
):
9842 """Writes the service context state header."""
9843 file = CHeaderWriter(
9845 "// It is included by context_state.h\n")
9846 file.Write("struct EnableFlags {\n")
9847 file.Write(" EnableFlags();\n")
9848 for capability
in _CAPABILITY_FLAGS
:
9849 file.Write(" bool %s;\n" % capability
['name'])
9850 file.Write(" bool cached_%s;\n" % capability
['name'])
9851 file.Write("};\n\n")
9853 for state_name
in sorted(_STATES
.keys()):
9854 state
= _STATES
[state_name
]
9855 for item
in state
['states']:
9856 if isinstance(item
['default'], list):
9857 file.Write("%s %s[%d];\n" % (item
['type'], item
['name'],
9858 len(item
['default'])))
9860 file.Write("%s %s;\n" % (item
['type'], item
['name']))
9862 if item
.get('cached', False):
9863 if isinstance(item
['default'], list):
9864 file.Write("%s cached_%s[%d];\n" % (item
['type'], item
['name'],
9865 len(item
['default'])))
9867 file.Write("%s cached_%s;\n" % (item
['type'], item
['name']))
9872 inline void SetDeviceCapabilityState(GLenum cap, bool enable) {
9875 for capability
in _CAPABILITY_FLAGS
:
9878 """ % capability
['name'].upper())
9880 if (enable_flags.cached_%(name)s == enable &&
9881 !ignore_cached_state)
9883 enable_flags.cached_%(name)s = enable;
9900 self
.generated_cpp_filenames
.append(file.filename
)
9902 def WriteClientContextStateHeader(self
, filename
):
9903 """Writes the client context state header."""
9904 file = CHeaderWriter(
9906 "// It is included by client_context_state.h\n")
9907 file.Write("struct EnableFlags {\n")
9908 file.Write(" EnableFlags();\n")
9909 for capability
in _CAPABILITY_FLAGS
:
9910 file.Write(" bool %s;\n" % capability
['name'])
9911 file.Write("};\n\n")
9914 self
.generated_cpp_filenames
.append(file.filename
)
9916 def WriteContextStateGetters(self
, file, class_name
):
9917 """Writes the state getters."""
9918 for gl_type
in ["GLint", "GLfloat"]:
9920 bool %s::GetStateAs%s(
9921 GLenum pname, %s* params, GLsizei* num_written) const {
9923 """ % (class_name
, gl_type
, gl_type
))
9924 for state_name
in sorted(_STATES
.keys()):
9925 state
= _STATES
[state_name
]
9927 file.Write(" case %s:\n" % state
['enum'])
9928 file.Write(" *num_written = %d;\n" % len(state
['states']))
9929 file.Write(" if (params) {\n")
9930 for ndx
,item
in enumerate(state
['states']):
9931 file.Write(" params[%d] = static_cast<%s>(%s);\n" %
9932 (ndx
, gl_type
, item
['name']))
9934 file.Write(" return true;\n")
9936 for item
in state
['states']:
9937 file.Write(" case %s:\n" % item
['enum'])
9938 if isinstance(item
['default'], list):
9939 item_len
= len(item
['default'])
9940 file.Write(" *num_written = %d;\n" % item_len
)
9941 file.Write(" if (params) {\n")
9942 if item
['type'] == gl_type
:
9943 file.Write(" memcpy(params, %s, sizeof(%s) * %d);\n" %
9944 (item
['name'], item
['type'], item_len
))
9946 file.Write(" for (size_t i = 0; i < %s; ++i) {\n" %
9948 file.Write(" params[i] = %s;\n" %
9949 (GetGLGetTypeConversion(gl_type
, item
['type'],
9950 "%s[i]" % item
['name'])))
9953 file.Write(" *num_written = 1;\n")
9954 file.Write(" if (params) {\n")
9955 file.Write(" params[0] = %s;\n" %
9956 (GetGLGetTypeConversion(gl_type
, item
['type'],
9959 file.Write(" return true;\n")
9960 for capability
in _CAPABILITY_FLAGS
:
9961 file.Write(" case GL_%s:\n" % capability
['name'].upper())
9962 file.Write(" *num_written = 1;\n")
9963 file.Write(" if (params) {\n")
9965 " params[0] = static_cast<%s>(enable_flags.%s);\n" %
9966 (gl_type
, capability
['name']))
9968 file.Write(" return true;\n")
9969 file.Write(""" default:
9975 def WriteServiceContextStateImpl(self
, filename
):
9976 """Writes the context state service implementation."""
9977 file = CHeaderWriter(
9979 "// It is included by context_state.cc\n")
9981 for capability
in _CAPABILITY_FLAGS
:
9982 code
.append("%s(%s)" %
9983 (capability
['name'],
9984 ('false', 'true')['default' in capability
]))
9985 code
.append("cached_%s(%s)" %
9986 (capability
['name'],
9987 ('false', 'true')['default' in capability
]))
9988 file.Write("ContextState::EnableFlags::EnableFlags()\n : %s {\n}\n" %
9992 file.Write("void ContextState::Initialize() {\n")
9993 for state_name
in sorted(_STATES
.keys()):
9994 state
= _STATES
[state_name
]
9995 for item
in state
['states']:
9996 if isinstance(item
['default'], list):
9997 for ndx
, value
in enumerate(item
['default']):
9998 file.Write(" %s[%d] = %s;\n" % (item
['name'], ndx
, value
))
10000 file.Write(" %s = %s;\n" % (item
['name'], item
['default']))
10001 if item
.get('cached', False):
10002 if isinstance(item
['default'], list):
10003 for ndx
, value
in enumerate(item
['default']):
10004 file.Write(" cached_%s[%d] = %s;\n" % (item
['name'], ndx
, value
))
10006 file.Write(" cached_%s = %s;\n" % (item
['name'], item
['default']))
10010 void ContextState::InitCapabilities(const ContextState* prev_state) const {
10012 def WriteCapabilities(test_prev
, es3_caps
):
10013 for capability
in _CAPABILITY_FLAGS
:
10014 capability_name
= capability
['name']
10015 capability_es3
= 'es3' in capability
and capability
['es3'] == True
10016 if capability_es3
and not es3_caps
or not capability_es3
and es3_caps
:
10019 file.Write(""" if (prev_state->enable_flags.cached_%s !=
10020 enable_flags.cached_%s) {\n""" %
10021 (capability_name
, capability_name
))
10022 file.Write(" EnableDisable(GL_%s, enable_flags.cached_%s);\n" %
10023 (capability_name
.upper(), capability_name
))
10027 file.Write(" if (prev_state) {")
10028 WriteCapabilities(True, False)
10029 file.Write(" if (feature_info_->IsES3Capable()) {\n")
10030 WriteCapabilities(True, True)
10032 file.Write(" } else {")
10033 WriteCapabilities(False, False)
10034 file.Write(" if (feature_info_->IsES3Capable()) {\n")
10035 WriteCapabilities(False, True)
10041 void ContextState::InitState(const ContextState *prev_state) const {
10044 def WriteStates(test_prev
):
10045 # We need to sort the keys so the expectations match
10046 for state_name
in sorted(_STATES
.keys()):
10047 state
= _STATES
[state_name
]
10048 if state
['type'] == 'FrontBack':
10049 num_states
= len(state
['states'])
10050 for ndx
, group
in enumerate(Grouper(num_states
/ 2, state
['states'])):
10052 file.Write(" if (")
10054 for place
, item
in enumerate(group
):
10055 item_name
= CachedStateName(item
)
10056 args
.append('%s' % item_name
)
10059 file.Write(' ||\n')
10060 file.Write("(%s != prev_state->%s)" % (item_name
, item_name
))
10064 " gl%s(%s, %s);\n" %
10065 (state
['func'], ('GL_FRONT', 'GL_BACK')[ndx
], ", ".join(args
)))
10066 elif state
['type'] == 'NamedParameter':
10067 for item
in state
['states']:
10068 item_name
= CachedStateName(item
)
10070 if 'extension_flag' in item
:
10071 file.Write(" if (feature_info_->feature_flags().%s) {\n " %
10072 item
['extension_flag'])
10074 if isinstance(item
['default'], list):
10075 file.Write(" if (memcmp(prev_state->%s, %s, "
10076 "sizeof(%s) * %d)) {\n" %
10077 (item_name
, item_name
, item
['type'],
10078 len(item
['default'])))
10080 file.Write(" if (prev_state->%s != %s) {\n " %
10081 (item_name
, item_name
))
10082 if 'gl_version_flag' in item
:
10083 item_name
= item
['gl_version_flag']
10085 if item_name
[0] == '!':
10087 item_name
= item_name
[1:]
10088 file.Write(" if (%sfeature_info_->gl_version_info().%s) {\n" %
10089 (inverted
, item_name
))
10090 file.Write(" gl%s(%s, %s);\n" %
10093 if 'enum_set' in item
else item
['enum']),
10095 if 'gl_version_flag' in item
:
10098 if 'extension_flag' in item
:
10101 if 'extension_flag' in item
:
10104 if 'extension_flag' in state
:
10105 file.Write(" if (feature_info_->feature_flags().%s)\n " %
10106 state
['extension_flag'])
10108 file.Write(" if (")
10110 for place
, item
in enumerate(state
['states']):
10111 item_name
= CachedStateName(item
)
10112 args
.append('%s' % item_name
)
10115 file.Write(' ||\n')
10116 file.Write("(%s != prev_state->%s)" %
10117 (item_name
, item_name
))
10120 file.Write(" gl%s(%s);\n" % (state
['func'], ", ".join(args
)))
10122 file.Write(" if (prev_state) {")
10124 file.Write(" } else {")
10129 file.Write("""bool ContextState::GetEnabled(GLenum cap) const {
10132 for capability
in _CAPABILITY_FLAGS
:
10133 file.Write(" case GL_%s:\n" % capability
['name'].upper())
10134 file.Write(" return enable_flags.%s;\n" % capability
['name'])
10135 file.Write(""" default:
10142 self
.WriteContextStateGetters(file, "ContextState")
10144 self
.generated_cpp_filenames
.append(file.filename
)
10146 def WriteClientContextStateImpl(self
, filename
):
10147 """Writes the context state client side implementation."""
10148 file = CHeaderWriter(
10150 "// It is included by client_context_state.cc\n")
10152 for capability
in _CAPABILITY_FLAGS
:
10153 code
.append("%s(%s)" %
10154 (capability
['name'],
10155 ('false', 'true')['default' in capability
]))
10157 "ClientContextState::EnableFlags::EnableFlags()\n : %s {\n}\n" %
10162 bool ClientContextState::SetCapabilityState(
10163 GLenum cap, bool enabled, bool* changed) {
10167 for capability
in _CAPABILITY_FLAGS
:
10168 file.Write(" case GL_%s:\n" % capability
['name'].upper())
10169 file.Write(""" if (enable_flags.%(name)s != enabled) {
10171 enable_flags.%(name)s = enabled;
10175 file.Write(""" default:
10180 file.Write("""bool ClientContextState::GetEnabled(
10181 GLenum cap, bool* enabled) const {
10184 for capability
in _CAPABILITY_FLAGS
:
10185 file.Write(" case GL_%s:\n" % capability
['name'].upper())
10186 file.Write(" *enabled = enable_flags.%s;\n" % capability
['name'])
10187 file.Write(" return true;\n")
10188 file.Write(""" default:
10194 self
.generated_cpp_filenames
.append(file.filename
)
10196 def WriteServiceImplementation(self
, filename
):
10197 """Writes the service decorder implementation."""
10198 file = CHeaderWriter(
10200 "// It is included by gles2_cmd_decoder.cc\n")
10202 for func
in self
.functions
:
10204 #gen_cmd = func.GetInfo('gen_cmd')
10205 #if gen_cmd == True or gen_cmd == None:
10206 func
.WriteServiceImplementation(file)
10209 bool GLES2DecoderImpl::SetCapabilityState(GLenum cap, bool enabled) {
10212 for capability
in _CAPABILITY_FLAGS
:
10213 file.Write(" case GL_%s:\n" % capability
['name'].upper())
10214 if 'state_flag' in capability
:
10217 state_.enable_flags.%(name)s = enabled;
10218 if (state_.enable_flags.cached_%(name)s != enabled
10219 || state_.ignore_cached_state) {
10220 %(state_flag)s = true;
10226 state_.enable_flags.%(name)s = enabled;
10227 if (state_.enable_flags.cached_%(name)s != enabled
10228 || state_.ignore_cached_state) {
10229 state_.enable_flags.cached_%(name)s = enabled;
10234 file.Write(""" default:
10241 self
.generated_cpp_filenames
.append(file.filename
)
10243 def WriteServiceUnitTests(self
, filename
):
10244 """Writes the service decorder unit tests."""
10245 num_tests
= len(self
.functions
)
10246 FUNCTIONS_PER_FILE
= 98 # hard code this so it doesn't change.
10248 for test_num
in range(0, num_tests
, FUNCTIONS_PER_FILE
):
10250 name
= filename
% count
10251 file = CHeaderWriter(
10253 "// It is included by gles2_cmd_decoder_unittest_%d.cc\n" % count
)
10254 test_name
= 'GLES2DecoderTest%d' % count
10255 end
= test_num
+ FUNCTIONS_PER_FILE
10256 if end
> num_tests
:
10258 for idx
in range(test_num
, end
):
10259 func
= self
.functions
[idx
]
10261 # Do any filtering of the functions here, so that the functions
10262 # will not move between the numbered files if filtering properties
10264 if func
.GetInfo('extension_flag'):
10268 #gen_cmd = func.GetInfo('gen_cmd')
10269 #if gen_cmd == True or gen_cmd == None:
10270 if func
.GetInfo('unit_test') == False:
10271 file.Write("// TODO(gman): %s\n" % func
.name
)
10273 func
.WriteServiceUnitTest(file, {
10274 'test_name': test_name
10277 self
.generated_cpp_filenames
.append(file.filename
)
10278 file = CHeaderWriter(
10280 "// It is included by gles2_cmd_decoder_unittest_base.cc\n")
10282 """void GLES2DecoderTestBase::SetupInitCapabilitiesExpectations(
10283 bool es3_capable) {""")
10284 for capability
in _CAPABILITY_FLAGS
:
10285 capability_es3
= 'es3' in capability
and capability
['es3'] == True
10286 if not capability_es3
:
10287 file.Write(" ExpectEnableDisable(GL_%s, %s);\n" %
10288 (capability
['name'].upper(),
10289 ('false', 'true')['default' in capability
]))
10291 file.Write(" if (es3_capable) {")
10292 for capability
in _CAPABILITY_FLAGS
:
10293 capability_es3
= 'es3' in capability
and capability
['es3'] == True
10295 file.Write(" ExpectEnableDisable(GL_%s, %s);\n" %
10296 (capability
['name'].upper(),
10297 ('false', 'true')['default' in capability
]))
10301 void GLES2DecoderTestBase::SetupInitStateExpectations() {
10304 # We need to sort the keys so the expectations match
10305 for state_name
in sorted(_STATES
.keys()):
10306 state
= _STATES
[state_name
]
10307 if state
['type'] == 'FrontBack':
10308 num_states
= len(state
['states'])
10309 for ndx
, group
in enumerate(Grouper(num_states
/ 2, state
['states'])):
10312 if 'expected' in item
:
10313 args
.append(item
['expected'])
10315 args
.append(item
['default'])
10317 " EXPECT_CALL(*gl_, %s(%s, %s))\n" %
10318 (state
['func'], ('GL_FRONT', 'GL_BACK')[ndx
], ", ".join(args
)))
10319 file.Write(" .Times(1)\n")
10320 file.Write(" .RetiresOnSaturation();\n")
10321 elif state
['type'] == 'NamedParameter':
10322 for item
in state
['states']:
10323 if 'extension_flag' in item
:
10324 file.Write(" if (group_->feature_info()->feature_flags().%s) {\n" %
10325 item
['extension_flag'])
10327 expect_value
= item
['default']
10328 if isinstance(expect_value
, list):
10329 # TODO: Currently we do not check array values.
10333 " EXPECT_CALL(*gl_, %s(%s, %s))\n" %
10336 if 'enum_set' in item
else item
['enum']),
10338 file.Write(" .Times(1)\n")
10339 file.Write(" .RetiresOnSaturation();\n")
10340 if 'extension_flag' in item
:
10343 if 'extension_flag' in state
:
10344 file.Write(" if (group_->feature_info()->feature_flags().%s) {\n" %
10345 state
['extension_flag'])
10348 for item
in state
['states']:
10349 if 'expected' in item
:
10350 args
.append(item
['expected'])
10352 args
.append(item
['default'])
10353 # TODO: Currently we do not check array values.
10354 args
= ["_" if isinstance(arg
, list) else arg
for arg
in args
]
10355 file.Write(" EXPECT_CALL(*gl_, %s(%s))\n" %
10356 (state
['func'], ", ".join(args
)))
10357 file.Write(" .Times(1)\n")
10358 file.Write(" .RetiresOnSaturation();\n")
10359 if 'extension_flag' in state
:
10364 self
.generated_cpp_filenames
.append(file.filename
)
10366 def WriteServiceUnitTestsForExtensions(self
, filename
):
10367 """Writes the service decorder unit tests for functions with extension_flag.
10369 The functions are special in that they need a specific unit test
10370 baseclass to turn on the extension.
10372 functions
= [f
for f
in self
.functions
if f
.GetInfo('extension_flag')]
10373 file = CHeaderWriter(
10375 "// It is included by gles2_cmd_decoder_unittest_extensions.cc\n")
10376 for func
in functions
:
10378 if func
.GetInfo('unit_test') == False:
10379 file.Write("// TODO(gman): %s\n" % func
.name
)
10381 extension
= ToCamelCase(
10382 ToGLExtensionString(func
.GetInfo('extension_flag')))
10383 func
.WriteServiceUnitTest(file, {
10384 'test_name': 'GLES2DecoderTestWith%s' % extension
10388 self
.generated_cpp_filenames
.append(file.filename
)
10390 def WriteGLES2Header(self
, filename
):
10391 """Writes the GLES2 header."""
10392 file = CHeaderWriter(
10394 "// This file contains Chromium-specific GLES2 declarations.\n\n")
10396 for func
in self
.original_functions
:
10397 func
.WriteGLES2Header(file)
10401 self
.generated_cpp_filenames
.append(file.filename
)
10403 def WriteGLES2CLibImplementation(self
, filename
):
10404 """Writes the GLES2 c lib implementation."""
10405 file = CHeaderWriter(
10407 "// These functions emulate GLES2 over command buffers.\n")
10409 for func
in self
.original_functions
:
10410 func
.WriteGLES2CLibImplementation(file)
10415 extern const NameToFunc g_gles2_function_table[] = {
10417 for func
in self
.original_functions
:
10419 ' { "gl%s", reinterpret_cast<GLES2FunctionPointer>(gl%s), },\n' %
10420 (func
.name
, func
.name
))
10421 file.Write(""" { NULL, NULL, },
10424 } // namespace gles2
10427 self
.generated_cpp_filenames
.append(file.filename
)
10429 def WriteGLES2InterfaceHeader(self
, filename
):
10430 """Writes the GLES2 interface header."""
10431 file = CHeaderWriter(
10433 "// This file is included by gles2_interface.h to declare the\n"
10434 "// GL api functions.\n")
10435 for func
in self
.original_functions
:
10436 func
.WriteGLES2InterfaceHeader(file)
10438 self
.generated_cpp_filenames
.append(file.filename
)
10440 def WriteMojoGLES2ImplHeader(self
, filename
):
10441 """Writes the Mojo GLES2 implementation header."""
10442 file = CHeaderWriter(
10444 "// This file is included by gles2_interface.h to declare the\n"
10445 "// GL api functions.\n")
10448 #include "gpu/command_buffer/client/gles2_interface.h"
10449 #include "third_party/mojo/src/mojo/public/c/gles2/gles2.h"
10453 class MojoGLES2Impl : public gpu::gles2::GLES2Interface {
10455 explicit MojoGLES2Impl(MojoGLES2Context context) {
10456 context_ = context;
10458 ~MojoGLES2Impl() override {}
10461 for func
in self
.original_functions
:
10462 func
.WriteMojoGLES2ImplHeader(file)
10465 MojoGLES2Context context_;
10468 } // namespace mojo
10472 self
.generated_cpp_filenames
.append(file.filename
)
10474 def WriteMojoGLES2Impl(self
, filename
):
10475 """Writes the Mojo GLES2 implementation."""
10476 file = CWriter(filename
)
10477 file.Write(_LICENSE
)
10478 file.Write(_DO_NOT_EDIT_WARNING
)
10481 #include "mojo/gpu/mojo_gles2_impl_autogen.h"
10483 #include "base/logging.h"
10484 #include "third_party/mojo/src/mojo/public/c/gles2/chromium_copy_texture.h"
10485 #include "third_party/mojo/src/mojo/public/c/gles2/chromium_image.h"
10486 #include "third_party/mojo/src/mojo/public/c/gles2/chromium_miscellaneous.h"
10487 #include "third_party/mojo/src/mojo/public/c/gles2/chromium_pixel_transfer_buffer_object.h"
10488 #include "third_party/mojo/src/mojo/public/c/gles2/chromium_sub_image.h"
10489 #include "third_party/mojo/src/mojo/public/c/gles2/chromium_sync_point.h"
10490 #include "third_party/mojo/src/mojo/public/c/gles2/chromium_texture_mailbox.h"
10491 #include "third_party/mojo/src/mojo/public/c/gles2/gles2.h"
10492 #include "third_party/mojo/src/mojo/public/c/gles2/occlusion_query_ext.h"
10498 for func
in self
.original_functions
:
10499 func
.WriteMojoGLES2Impl(file)
10502 } // namespace mojo
10506 self
.generated_cpp_filenames
.append(file.filename
)
10508 def WriteGLES2InterfaceStub(self
, filename
):
10509 """Writes the GLES2 interface stub header."""
10510 file = CHeaderWriter(
10512 "// This file is included by gles2_interface_stub.h.\n")
10513 for func
in self
.original_functions
:
10514 func
.WriteGLES2InterfaceStub(file)
10516 self
.generated_cpp_filenames
.append(file.filename
)
10518 def WriteGLES2InterfaceStubImpl(self
, filename
):
10519 """Writes the GLES2 interface header."""
10520 file = CHeaderWriter(
10522 "// This file is included by gles2_interface_stub.cc.\n")
10523 for func
in self
.original_functions
:
10524 func
.WriteGLES2InterfaceStubImpl(file)
10526 self
.generated_cpp_filenames
.append(file.filename
)
10528 def WriteGLES2ImplementationHeader(self
, filename
):
10529 """Writes the GLES2 Implementation header."""
10530 file = CHeaderWriter(
10532 "// This file is included by gles2_implementation.h to declare the\n"
10533 "// GL api functions.\n")
10534 for func
in self
.original_functions
:
10535 func
.WriteGLES2ImplementationHeader(file)
10537 self
.generated_cpp_filenames
.append(file.filename
)
10539 def WriteGLES2Implementation(self
, filename
):
10540 """Writes the GLES2 Implementation."""
10541 file = CHeaderWriter(
10543 "// This file is included by gles2_implementation.cc to define the\n"
10544 "// GL api functions.\n")
10545 for func
in self
.original_functions
:
10546 func
.WriteGLES2Implementation(file)
10548 self
.generated_cpp_filenames
.append(file.filename
)
10550 def WriteGLES2TraceImplementationHeader(self
, filename
):
10551 """Writes the GLES2 Trace Implementation header."""
10552 file = CHeaderWriter(
10554 "// This file is included by gles2_trace_implementation.h\n")
10555 for func
in self
.original_functions
:
10556 func
.WriteGLES2TraceImplementationHeader(file)
10558 self
.generated_cpp_filenames
.append(file.filename
)
10560 def WriteGLES2TraceImplementation(self
, filename
):
10561 """Writes the GLES2 Trace Implementation."""
10562 file = CHeaderWriter(
10564 "// This file is included by gles2_trace_implementation.cc\n")
10565 for func
in self
.original_functions
:
10566 func
.WriteGLES2TraceImplementation(file)
10568 self
.generated_cpp_filenames
.append(file.filename
)
10570 def WriteGLES2ImplementationUnitTests(self
, filename
):
10571 """Writes the GLES2 helper header."""
10572 file = CHeaderWriter(
10574 "// This file is included by gles2_implementation.h to declare the\n"
10575 "// GL api functions.\n")
10576 for func
in self
.original_functions
:
10577 func
.WriteGLES2ImplementationUnitTest(file)
10579 self
.generated_cpp_filenames
.append(file.filename
)
10581 def WriteServiceUtilsHeader(self
, filename
):
10582 """Writes the gles2 auto generated utility header."""
10583 file = CHeaderWriter(filename
)
10584 for name
in sorted(_NAMED_TYPE_INFO
.keys()):
10585 named_type
= NamedType(_NAMED_TYPE_INFO
[name
])
10586 if named_type
.IsConstant():
10588 file.Write("ValueValidator<%s> %s;\n" %
10589 (named_type
.GetType(), ToUnderscore(name
)))
10592 self
.generated_cpp_filenames
.append(file.filename
)
10594 def WriteServiceUtilsImplementation(self
, filename
):
10595 """Writes the gles2 auto generated utility implementation."""
10596 file = CHeaderWriter(filename
)
10597 names
= sorted(_NAMED_TYPE_INFO
.keys())
10599 named_type
= NamedType(_NAMED_TYPE_INFO
[name
])
10600 if named_type
.IsConstant():
10602 if named_type
.GetValidValues():
10603 file.Write("static const %s valid_%s_table[] = {\n" %
10604 (named_type
.GetType(), ToUnderscore(name
)))
10605 for value
in named_type
.GetValidValues():
10606 file.Write(" %s,\n" % value
)
10609 if named_type
.GetValidValuesES3():
10610 file.Write("static const %s valid_%s_table_es3[] = {\n" %
10611 (named_type
.GetType(), ToUnderscore(name
)))
10612 for value
in named_type
.GetValidValuesES3():
10613 file.Write(" %s,\n" % value
)
10616 if named_type
.GetDeprecatedValuesES3():
10617 file.Write("static const %s deprecated_%s_table_es3[] = {\n" %
10618 (named_type
.GetType(), ToUnderscore(name
)))
10619 for value
in named_type
.GetDeprecatedValuesES3():
10620 file.Write(" %s,\n" % value
)
10623 file.Write("Validators::Validators()")
10625 for count
, name
in enumerate(names
):
10626 named_type
= NamedType(_NAMED_TYPE_INFO
[name
])
10627 if named_type
.IsConstant():
10629 if named_type
.GetValidValues():
10630 code
= """%(pre)s%(name)s(
10631 valid_%(name)s_table, arraysize(valid_%(name)s_table))"""
10633 code
= "%(pre)s%(name)s()"
10634 file.Write(code
% {
10635 'name': ToUnderscore(name
),
10639 file.Write(" {\n");
10640 file.Write("}\n\n");
10642 file.Write("void Validators::UpdateValuesES3() {\n")
10644 named_type
= NamedType(_NAMED_TYPE_INFO
[name
])
10645 if named_type
.GetDeprecatedValuesES3():
10646 code
= """ %(name)s.RemoveValues(
10647 deprecated_%(name)s_table_es3, arraysize(deprecated_%(name)s_table_es3));
10649 file.Write(code
% {
10650 'name': ToUnderscore(name
),
10652 if named_type
.GetValidValuesES3():
10653 code
= """ %(name)s.AddValues(
10654 valid_%(name)s_table_es3, arraysize(valid_%(name)s_table_es3));
10656 file.Write(code
% {
10657 'name': ToUnderscore(name
),
10659 file.Write("}\n\n");
10661 self
.generated_cpp_filenames
.append(file.filename
)
10663 def WriteCommonUtilsHeader(self
, filename
):
10664 """Writes the gles2 common utility header."""
10665 file = CHeaderWriter(filename
)
10666 type_infos
= sorted(_NAMED_TYPE_INFO
.keys())
10667 for type_info
in type_infos
:
10668 if _NAMED_TYPE_INFO
[type_info
]['type'] == 'GLenum':
10669 file.Write("static std::string GetString%s(uint32_t value);\n" %
10673 self
.generated_cpp_filenames
.append(file.filename
)
10675 def WriteCommonUtilsImpl(self
, filename
):
10676 """Writes the gles2 common utility header."""
10677 enum_re
= re
.compile(r
'\#define\s+(GL_[a-zA-Z0-9_]+)\s+([0-9A-Fa-fx]+)')
10679 for fname
in ['third_party/khronos/GLES2/gl2.h',
10680 'third_party/khronos/GLES2/gl2ext.h',
10681 'third_party/khronos/GLES3/gl3.h',
10682 'gpu/GLES2/gl2chromium.h',
10683 'gpu/GLES2/gl2extchromium.h']:
10684 lines
= open(fname
).readlines()
10686 m
= enum_re
.match(line
)
10690 if len(value
) <= 10:
10691 if not value
in dict:
10693 # check our own _CHROMIUM macro conflicts with khronos GL headers.
10694 elif dict[value
] != name
and (name
.endswith('_CHROMIUM') or
10695 dict[value
].endswith('_CHROMIUM')):
10696 self
.Error("code collision: %s and %s have the same code %s" %
10697 (dict[value
], name
, value
))
10699 file = CHeaderWriter(filename
)
10700 file.Write("static const GLES2Util::EnumToString "
10701 "enum_to_string_table[] = {\n")
10703 file.Write(' { %s, "%s", },\n' % (value
, dict[value
]))
10706 const GLES2Util::EnumToString* const GLES2Util::enum_to_string_table_ =
10707 enum_to_string_table;
10708 const size_t GLES2Util::enum_to_string_table_len_ =
10709 sizeof(enum_to_string_table) / sizeof(enum_to_string_table[0]);
10713 enums
= sorted(_NAMED_TYPE_INFO
.keys())
10715 if _NAMED_TYPE_INFO
[enum
]['type'] == 'GLenum':
10716 file.Write("std::string GLES2Util::GetString%s(uint32_t value) {\n" %
10718 valid_list
= _NAMED_TYPE_INFO
[enum
]['valid']
10719 if 'valid_es3' in _NAMED_TYPE_INFO
[enum
]:
10720 valid_list
= valid_list
+ _NAMED_TYPE_INFO
[enum
]['valid_es3']
10721 assert len(valid_list
) == len(set(valid_list
))
10722 if len(valid_list
) > 0:
10723 file.Write(" static const EnumToString string_table[] = {\n")
10724 for value
in valid_list
:
10725 file.Write(' { %s, "%s" },\n' % (value
, value
))
10727 return GLES2Util::GetQualifiedEnumString(
10728 string_table, arraysize(string_table), value);
10733 file.Write(""" return GLES2Util::GetQualifiedEnumString(
10739 self
.generated_cpp_filenames
.append(file.filename
)
10741 def WritePepperGLES2Interface(self
, filename
, dev
):
10742 """Writes the Pepper OpenGLES interface definition."""
10743 file = CWriter(filename
)
10744 file.Write(_LICENSE
)
10745 file.Write(_DO_NOT_EDIT_WARNING
)
10747 file.Write("label Chrome {\n")
10748 file.Write(" M39 = 1.0\n")
10749 file.Write("};\n\n")
10752 # Declare GL types.
10753 file.Write("[version=1.0]\n")
10754 file.Write("describe {\n")
10755 for gltype
in ['GLbitfield', 'GLboolean', 'GLbyte', 'GLclampf',
10756 'GLclampx', 'GLenum', 'GLfixed', 'GLfloat', 'GLint',
10757 'GLintptr', 'GLshort', 'GLsizei', 'GLsizeiptr',
10758 'GLubyte', 'GLuint', 'GLushort']:
10759 file.Write(" %s;\n" % gltype
)
10760 file.Write(" %s_ptr_t;\n" % gltype
)
10761 file.Write("};\n\n")
10763 # C level typedefs.
10764 file.Write("#inline c\n")
10765 file.Write("#include \"ppapi/c/pp_resource.h\"\n")
10767 file.Write("#include \"ppapi/c/ppb_opengles2.h\"\n\n")
10769 file.Write("\n#ifndef __gl2_h_\n")
10770 for (k
, v
) in _GL_TYPES
.iteritems():
10771 file.Write("typedef %s %s;\n" % (v
, k
))
10772 file.Write("#ifdef _WIN64\n")
10773 for (k
, v
) in _GL_TYPES_64
.iteritems():
10774 file.Write("typedef %s %s;\n" % (v
, k
))
10775 file.Write("#else\n")
10776 for (k
, v
) in _GL_TYPES_32
.iteritems():
10777 file.Write("typedef %s %s;\n" % (v
, k
))
10778 file.Write("#endif // _WIN64\n")
10779 file.Write("#endif // __gl2_h_\n\n")
10780 file.Write("#endinl\n")
10782 for interface
in self
.pepper_interfaces
:
10783 if interface
.dev
!= dev
:
10785 # Historically, we provide OpenGLES2 interfaces with struct
10786 # namespace. Not to break code which uses the interface as
10787 # "struct OpenGLES2", we put it in struct namespace.
10788 file.Write('\n[macro="%s", force_struct_namespace]\n' %
10789 interface
.GetInterfaceName())
10790 file.Write("interface %s {\n" % interface
.GetStructName())
10791 for func
in self
.original_functions
:
10792 if not func
.InPepperInterface(interface
):
10795 ret_type
= func
.MapCTypeToPepperIdlType(func
.return_type
,
10796 is_for_return_type
=True)
10797 func_prefix
= " %s %s(" % (ret_type
, func
.GetPepperName())
10798 file.Write(func_prefix
)
10799 file.Write("[in] PP_Resource context")
10800 for arg
in func
.MakeTypedPepperIdlArgStrings():
10801 file.Write(",\n" + " " * len(func_prefix
) + arg
)
10803 file.Write("};\n\n")
10808 def WritePepperGLES2Implementation(self
, filename
):
10809 """Writes the Pepper OpenGLES interface implementation."""
10811 file = CWriter(filename
)
10812 file.Write(_LICENSE
)
10813 file.Write(_DO_NOT_EDIT_WARNING
)
10815 file.Write("#include \"ppapi/shared_impl/ppb_opengles2_shared.h\"\n\n")
10816 file.Write("#include \"base/logging.h\"\n")
10817 file.Write("#include \"gpu/command_buffer/client/gles2_implementation.h\"\n")
10818 file.Write("#include \"ppapi/shared_impl/ppb_graphics_3d_shared.h\"\n")
10819 file.Write("#include \"ppapi/thunk/enter.h\"\n\n")
10821 file.Write("namespace ppapi {\n\n")
10822 file.Write("namespace {\n\n")
10824 file.Write("typedef thunk::EnterResource<thunk::PPB_Graphics3D_API>"
10827 file.Write("gpu::gles2::GLES2Implementation* ToGles2Impl(Enter3D*"
10829 file.Write(" DCHECK(enter);\n")
10830 file.Write(" DCHECK(enter->succeeded());\n")
10831 file.Write(" return static_cast<PPB_Graphics3D_Shared*>(enter->object())->"
10832 "gles2_impl();\n");
10833 file.Write("}\n\n");
10835 for func
in self
.original_functions
:
10836 if not func
.InAnyPepperExtension():
10839 original_arg
= func
.MakeTypedPepperArgString("")
10840 context_arg
= "PP_Resource context_id"
10841 if len(original_arg
):
10842 arg
= context_arg
+ ", " + original_arg
10845 file.Write("%s %s(%s) {\n" %
10846 (func
.return_type
, func
.GetPepperName(), arg
))
10847 file.Write(" Enter3D enter(context_id, true);\n")
10848 file.Write(" if (enter.succeeded()) {\n")
10850 return_str
= "" if func
.return_type
== "void" else "return "
10851 file.Write(" %sToGles2Impl(&enter)->%s(%s);\n" %
10852 (return_str
, func
.original_name
,
10853 func
.MakeOriginalArgString("")))
10855 if func
.return_type
== "void":
10858 file.Write(" else {\n")
10859 file.Write(" return %s;\n" % func
.GetErrorReturnString())
10861 file.Write("}\n\n")
10863 file.Write("} // namespace\n")
10865 for interface
in self
.pepper_interfaces
:
10866 file.Write("const %s* PPB_OpenGLES2_Shared::Get%sInterface() {\n" %
10867 (interface
.GetStructName(), interface
.GetName()))
10868 file.Write(" static const struct %s "
10869 "ppb_opengles2 = {\n" % interface
.GetStructName())
10871 file.Write(",\n &".join(
10872 f
.GetPepperName() for f
in self
.original_functions
10873 if f
.InPepperInterface(interface
)))
10876 file.Write(" };\n")
10877 file.Write(" return &ppb_opengles2;\n")
10880 file.Write("} // namespace ppapi\n")
10882 self
.generated_cpp_filenames
.append(file.filename
)
10884 def WriteGLES2ToPPAPIBridge(self
, filename
):
10885 """Connects GLES2 helper library to PPB_OpenGLES2 interface"""
10887 file = CWriter(filename
)
10888 file.Write(_LICENSE
)
10889 file.Write(_DO_NOT_EDIT_WARNING
)
10891 file.Write("#ifndef GL_GLEXT_PROTOTYPES\n")
10892 file.Write("#define GL_GLEXT_PROTOTYPES\n")
10893 file.Write("#endif\n")
10894 file.Write("#include <GLES2/gl2.h>\n")
10895 file.Write("#include <GLES2/gl2ext.h>\n")
10896 file.Write("#include \"ppapi/lib/gl/gles2/gl2ext_ppapi.h\"\n\n")
10898 for func
in self
.original_functions
:
10899 if not func
.InAnyPepperExtension():
10902 interface
= self
.interface_info
[func
.GetInfo('pepper_interface') or '']
10904 file.Write("%s GL_APIENTRY gl%s(%s) {\n" %
10905 (func
.return_type
, func
.GetPepperName(),
10906 func
.MakeTypedPepperArgString("")))
10907 return_str
= "" if func
.return_type
== "void" else "return "
10908 interface_str
= "glGet%sInterfacePPAPI()" % interface
.GetName()
10909 original_arg
= func
.MakeOriginalArgString("")
10910 context_arg
= "glGetCurrentContextPPAPI()"
10911 if len(original_arg
):
10912 arg
= context_arg
+ ", " + original_arg
10915 if interface
.GetName():
10916 file.Write(" const struct %s* ext = %s;\n" %
10917 (interface
.GetStructName(), interface_str
))
10918 file.Write(" if (ext)\n")
10919 file.Write(" %sext->%s(%s);\n" %
10920 (return_str
, func
.GetPepperName(), arg
))
10922 file.Write(" %s0;\n" % return_str
)
10924 file.Write(" %s%s->%s(%s);\n" %
10925 (return_str
, interface_str
, func
.GetPepperName(), arg
))
10926 file.Write("}\n\n")
10928 self
.generated_cpp_filenames
.append(file.filename
)
10930 def WriteMojoGLCallVisitor(self
, filename
):
10931 """Provides the GL implementation for mojo"""
10932 file = CWriter(filename
)
10933 file.Write(_LICENSE
)
10934 file.Write(_DO_NOT_EDIT_WARNING
)
10936 for func
in self
.original_functions
:
10937 if not func
.IsCoreGLFunction():
10939 file.Write("VISIT_GL_CALL(%s, %s, (%s), (%s))\n" %
10940 (func
.name
, func
.return_type
,
10941 func
.MakeTypedOriginalArgString(""),
10942 func
.MakeOriginalArgString("")))
10945 self
.generated_cpp_filenames
.append(file.filename
)
10947 def WriteMojoGLCallVisitorForExtension(self
, filename
, extension
):
10948 """Provides the GL implementation for mojo for a particular extension"""
10949 file = CWriter(filename
)
10950 file.Write(_LICENSE
)
10951 file.Write(_DO_NOT_EDIT_WARNING
)
10953 for func
in self
.original_functions
:
10954 if func
.GetInfo("extension") != extension
:
10956 file.Write("VISIT_GL_CALL(%s, %s, (%s), (%s))\n" %
10957 (func
.name
, func
.return_type
,
10958 func
.MakeTypedOriginalArgString(""),
10959 func
.MakeOriginalArgString("")))
10962 self
.generated_cpp_filenames
.append(file.filename
)
10964 def Format(generated_files
):
10965 formatter
= "clang-format"
10966 if platform
.system() == "Windows":
10967 formatter
+= ".bat"
10968 for filename
in generated_files
:
10969 call([formatter
, "-i", "-style=chromium", filename
])
10972 """This is the main function."""
10973 parser
= OptionParser()
10976 help="base directory for resulting files, under chrome/src. default is "
10977 "empty. Use this if you want the result stored under gen.")
10979 "-v", "--verbose", action
="store_true",
10980 help="prints more output.")
10982 (options
, args
) = parser
.parse_args(args
=argv
)
10984 # Add in states and capabilites to GLState
10985 gl_state_valid
= _NAMED_TYPE_INFO
['GLState']['valid']
10986 for state_name
in sorted(_STATES
.keys()):
10987 state
= _STATES
[state_name
]
10988 if 'extension_flag' in state
:
10990 if 'enum' in state
:
10991 if not state
['enum'] in gl_state_valid
:
10992 gl_state_valid
.append(state
['enum'])
10994 for item
in state
['states']:
10995 if 'extension_flag' in item
:
10997 if not item
['enum'] in gl_state_valid
:
10998 gl_state_valid
.append(item
['enum'])
10999 for capability
in _CAPABILITY_FLAGS
:
11000 valid_value
= "GL_%s" % capability
['name'].upper()
11001 if not valid_value
in gl_state_valid
:
11002 gl_state_valid
.append(valid_value
)
11004 # This script lives under gpu/command_buffer, cd to base directory.
11005 os
.chdir(os
.path
.dirname(__file__
) + "/../..")
11006 base_dir
= os
.getcwd()
11007 gen
= GLGenerator(options
.verbose
)
11008 gen
.ParseGLH("gpu/command_buffer/cmd_buffer_functions.txt")
11010 # Support generating files under gen/
11011 if options
.output_dir
!= None:
11012 os
.chdir(options
.output_dir
)
11014 gen
.WritePepperGLES2Interface("ppapi/api/ppb_opengles2.idl", False)
11015 gen
.WritePepperGLES2Interface("ppapi/api/dev/ppb_opengles2ext_dev.idl", True)
11016 gen
.WriteGLES2ToPPAPIBridge("ppapi/lib/gl/gles2/gles2.c")
11017 gen
.WritePepperGLES2Implementation(
11018 "ppapi/shared_impl/ppb_opengles2_shared.cc")
11020 gen
.WriteCommandIds("gpu/command_buffer/common/gles2_cmd_ids_autogen.h")
11021 gen
.WriteFormat("gpu/command_buffer/common/gles2_cmd_format_autogen.h")
11022 gen
.WriteFormatTest(
11023 "gpu/command_buffer/common/gles2_cmd_format_test_autogen.h")
11024 gen
.WriteGLES2InterfaceHeader(
11025 "gpu/command_buffer/client/gles2_interface_autogen.h")
11026 gen
.WriteMojoGLES2ImplHeader(
11027 "mojo/gpu/mojo_gles2_impl_autogen.h")
11028 gen
.WriteMojoGLES2Impl(
11029 "mojo/gpu/mojo_gles2_impl_autogen.cc")
11030 gen
.WriteGLES2InterfaceStub(
11031 "gpu/command_buffer/client/gles2_interface_stub_autogen.h")
11032 gen
.WriteGLES2InterfaceStubImpl(
11033 "gpu/command_buffer/client/gles2_interface_stub_impl_autogen.h")
11034 gen
.WriteGLES2ImplementationHeader(
11035 "gpu/command_buffer/client/gles2_implementation_autogen.h")
11036 gen
.WriteGLES2Implementation(
11037 "gpu/command_buffer/client/gles2_implementation_impl_autogen.h")
11038 gen
.WriteGLES2ImplementationUnitTests(
11039 "gpu/command_buffer/client/gles2_implementation_unittest_autogen.h")
11040 gen
.WriteGLES2TraceImplementationHeader(
11041 "gpu/command_buffer/client/gles2_trace_implementation_autogen.h")
11042 gen
.WriteGLES2TraceImplementation(
11043 "gpu/command_buffer/client/gles2_trace_implementation_impl_autogen.h")
11044 gen
.WriteGLES2CLibImplementation(
11045 "gpu/command_buffer/client/gles2_c_lib_autogen.h")
11046 gen
.WriteCmdHelperHeader(
11047 "gpu/command_buffer/client/gles2_cmd_helper_autogen.h")
11048 gen
.WriteServiceImplementation(
11049 "gpu/command_buffer/service/gles2_cmd_decoder_autogen.h")
11050 gen
.WriteServiceContextStateHeader(
11051 "gpu/command_buffer/service/context_state_autogen.h")
11052 gen
.WriteServiceContextStateImpl(
11053 "gpu/command_buffer/service/context_state_impl_autogen.h")
11054 gen
.WriteClientContextStateHeader(
11055 "gpu/command_buffer/client/client_context_state_autogen.h")
11056 gen
.WriteClientContextStateImpl(
11057 "gpu/command_buffer/client/client_context_state_impl_autogen.h")
11058 gen
.WriteServiceUnitTests(
11059 "gpu/command_buffer/service/gles2_cmd_decoder_unittest_%d_autogen.h")
11060 gen
.WriteServiceUnitTestsForExtensions(
11061 "gpu/command_buffer/service/"
11062 "gles2_cmd_decoder_unittest_extensions_autogen.h")
11063 gen
.WriteServiceUtilsHeader(
11064 "gpu/command_buffer/service/gles2_cmd_validation_autogen.h")
11065 gen
.WriteServiceUtilsImplementation(
11066 "gpu/command_buffer/service/"
11067 "gles2_cmd_validation_implementation_autogen.h")
11068 gen
.WriteCommonUtilsHeader(
11069 "gpu/command_buffer/common/gles2_cmd_utils_autogen.h")
11070 gen
.WriteCommonUtilsImpl(
11071 "gpu/command_buffer/common/gles2_cmd_utils_implementation_autogen.h")
11072 gen
.WriteGLES2Header("gpu/GLES2/gl2chromium_autogen.h")
11073 mojo_gles2_prefix
= ("third_party/mojo/src/mojo/public/c/gles2/"
11074 "gles2_call_visitor")
11075 gen
.WriteMojoGLCallVisitor(mojo_gles2_prefix
+ "_autogen.h")
11076 gen
.WriteMojoGLCallVisitorForExtension(
11077 mojo_gles2_prefix
+ "_chromium_texture_mailbox_autogen.h",
11078 "CHROMIUM_texture_mailbox")
11079 gen
.WriteMojoGLCallVisitorForExtension(
11080 mojo_gles2_prefix
+ "_chromium_sync_point_autogen.h",
11081 "CHROMIUM_sync_point")
11082 gen
.WriteMojoGLCallVisitorForExtension(
11083 mojo_gles2_prefix
+ "_chromium_sub_image_autogen.h",
11084 "CHROMIUM_sub_image")
11085 gen
.WriteMojoGLCallVisitorForExtension(
11086 mojo_gles2_prefix
+ "_chromium_miscellaneous_autogen.h",
11087 "CHROMIUM_miscellaneous")
11088 gen
.WriteMojoGLCallVisitorForExtension(
11089 mojo_gles2_prefix
+ "_occlusion_query_ext_autogen.h",
11090 "occlusion_query_EXT")
11091 gen
.WriteMojoGLCallVisitorForExtension(
11092 mojo_gles2_prefix
+ "_chromium_image_autogen.h",
11094 gen
.WriteMojoGLCallVisitorForExtension(
11095 mojo_gles2_prefix
+ "_chromium_copy_texture_autogen.h",
11096 "CHROMIUM_copy_texture")
11097 gen
.WriteMojoGLCallVisitorForExtension(
11098 mojo_gles2_prefix
+ "_chromium_pixel_transfer_buffer_object_autogen.h",
11099 "CHROMIUM_pixel_transfer_buffer_object")
11101 Format(gen
.generated_cpp_filenames
)
11104 print "%d errors" % gen
.errors
11109 if __name__
== '__main__':
11110 sys
.exit(main(sys
.argv
[1:]))