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."""
13 from optparse
import OptionParser
14 from subprocess
import call
17 _SIZE_OF_COMMAND_HEADER
= 4
18 _FIRST_SPECIFIC_COMMAND_ID
= 256
20 _LICENSE
= """// Copyright 2014 The Chromium Authors. All rights reserved.
21 // Use of this source code is governed by a BSD-style license that can be
22 // found in the LICENSE file.
26 _DO_NOT_EDIT_WARNING
= """// This file is auto-generated from
27 // gpu/command_buffer/build_gles2_cmd_buffer.py
28 // It's formatted by clang-format using chromium coding style:
29 // clang-format -i -style=chromium filename
34 # This string is copied directly out of the gl2.h file from GLES2.0
38 # *) Any argument that is a resourceID has been changed to GLid<Type>.
39 # (not pointer arguments) and if it's allowed to be zero it's GLidZero<Type>
40 # If it's allowed to not exist it's GLidBind<Type>
42 # *) All GLenums have been changed to GLenumTypeOfEnum
45 'GLenum': 'unsigned int',
46 'GLboolean': 'unsigned char',
47 'GLbitfield': 'unsigned int',
48 'GLbyte': 'signed char',
52 'GLubyte': 'unsigned char',
53 'GLushort': 'unsigned short',
54 'GLuint': 'unsigned int',
63 'GLintptr': 'long int',
64 'GLsizeiptr': 'long int'
68 'GLintptr': 'long long int',
69 'GLsizeiptr': 'long long int'
72 # Capabilites selected with glEnable
75 {'name': 'cull_face'},
76 {'name': 'depth_test', 'state_flag': 'framebuffer_state_.clear_state_dirty'},
77 {'name': 'dither', 'default': True},
78 {'name': 'polygon_offset_fill'},
79 {'name': 'sample_alpha_to_coverage'},
80 {'name': 'sample_coverage'},
81 {'name': 'scissor_test'},
82 {'name': 'stencil_test',
83 'state_flag': 'framebuffer_state_.clear_state_dirty'},
90 'enum': 'GL_COLOR_CLEAR_VALUE',
92 {'name': 'color_clear_red', 'type': 'GLfloat', 'default': '0.0f'},
93 {'name': 'color_clear_green', 'type': 'GLfloat', 'default': '0.0f'},
94 {'name': 'color_clear_blue', 'type': 'GLfloat', 'default': '0.0f'},
95 {'name': 'color_clear_alpha', 'type': 'GLfloat', 'default': '0.0f'},
100 'func': 'ClearDepth',
101 'enum': 'GL_DEPTH_CLEAR_VALUE',
103 {'name': 'depth_clear', 'type': 'GLclampf', 'default': '1.0f'},
109 'enum': 'GL_COLOR_WRITEMASK',
112 'name': 'color_mask_red',
118 'name': 'color_mask_green',
124 'name': 'color_mask_blue',
130 'name': 'color_mask_alpha',
136 'state_flag': 'framebuffer_state_.clear_state_dirty',
140 'func': 'ClearStencil',
141 'enum': 'GL_STENCIL_CLEAR_VALUE',
143 {'name': 'stencil_clear', 'type': 'GLint', 'default': '0'},
148 'func': 'BlendColor',
149 'enum': 'GL_BLEND_COLOR',
151 {'name': 'blend_color_red', 'type': 'GLfloat', 'default': '0.0f'},
152 {'name': 'blend_color_green', 'type': 'GLfloat', 'default': '0.0f'},
153 {'name': 'blend_color_blue', 'type': 'GLfloat', 'default': '0.0f'},
154 {'name': 'blend_color_alpha', 'type': 'GLfloat', 'default': '0.0f'},
159 'func': 'BlendEquationSeparate',
162 'name': 'blend_equation_rgb',
164 'enum': 'GL_BLEND_EQUATION_RGB',
165 'default': 'GL_FUNC_ADD',
168 'name': 'blend_equation_alpha',
170 'enum': 'GL_BLEND_EQUATION_ALPHA',
171 'default': 'GL_FUNC_ADD',
177 'func': 'BlendFuncSeparate',
180 'name': 'blend_source_rgb',
182 'enum': 'GL_BLEND_SRC_RGB',
186 'name': 'blend_dest_rgb',
188 'enum': 'GL_BLEND_DST_RGB',
189 'default': 'GL_ZERO',
192 'name': 'blend_source_alpha',
194 'enum': 'GL_BLEND_SRC_ALPHA',
198 'name': 'blend_dest_alpha',
200 'enum': 'GL_BLEND_DST_ALPHA',
201 'default': 'GL_ZERO',
207 'func': 'PolygonOffset',
210 'name': 'polygon_offset_factor',
212 'enum': 'GL_POLYGON_OFFSET_FACTOR',
216 'name': 'polygon_offset_units',
218 'enum': 'GL_POLYGON_OFFSET_UNITS',
226 'enum': 'GL_CULL_FACE_MODE',
231 'default': 'GL_BACK',
238 'enum': 'GL_FRONT_FACE',
239 'states': [{'name': 'front_face', 'type': 'GLenum', 'default': 'GL_CCW'}],
244 'enum': 'GL_DEPTH_FUNC',
245 'states': [{'name': 'depth_func', 'type': 'GLenum', 'default': 'GL_LESS'}],
249 'func': 'DepthRange',
250 'enum': 'GL_DEPTH_RANGE',
252 {'name': 'z_near', 'type': 'GLclampf', 'default': '0.0f'},
253 {'name': 'z_far', 'type': 'GLclampf', 'default': '1.0f'},
258 'func': 'SampleCoverage',
261 'name': 'sample_coverage_value',
263 'enum': 'GL_SAMPLE_COVERAGE_VALUE',
267 'name': 'sample_coverage_invert',
269 'enum': 'GL_SAMPLE_COVERAGE_INVERT',
276 'func': 'StencilMaskSeparate',
277 'state_flag': 'framebuffer_state_.clear_state_dirty',
280 'name': 'stencil_front_writemask',
282 'enum': 'GL_STENCIL_WRITEMASK',
283 'default': '0xFFFFFFFFU',
287 'name': 'stencil_back_writemask',
289 'enum': 'GL_STENCIL_BACK_WRITEMASK',
290 'default': '0xFFFFFFFFU',
297 'func': 'StencilOpSeparate',
300 'name': 'stencil_front_fail_op',
302 'enum': 'GL_STENCIL_FAIL',
303 'default': 'GL_KEEP',
306 'name': 'stencil_front_z_fail_op',
308 'enum': 'GL_STENCIL_PASS_DEPTH_FAIL',
309 'default': 'GL_KEEP',
312 'name': 'stencil_front_z_pass_op',
314 'enum': 'GL_STENCIL_PASS_DEPTH_PASS',
315 'default': 'GL_KEEP',
318 'name': 'stencil_back_fail_op',
320 'enum': 'GL_STENCIL_BACK_FAIL',
321 'default': 'GL_KEEP',
324 'name': 'stencil_back_z_fail_op',
326 'enum': 'GL_STENCIL_BACK_PASS_DEPTH_FAIL',
327 'default': 'GL_KEEP',
330 'name': 'stencil_back_z_pass_op',
332 'enum': 'GL_STENCIL_BACK_PASS_DEPTH_PASS',
333 'default': 'GL_KEEP',
339 'func': 'StencilFuncSeparate',
342 'name': 'stencil_front_func',
344 'enum': 'GL_STENCIL_FUNC',
345 'default': 'GL_ALWAYS',
348 'name': 'stencil_front_ref',
350 'enum': 'GL_STENCIL_REF',
354 'name': 'stencil_front_mask',
356 'enum': 'GL_STENCIL_VALUE_MASK',
357 'default': '0xFFFFFFFFU',
360 'name': 'stencil_back_func',
362 'enum': 'GL_STENCIL_BACK_FUNC',
363 'default': 'GL_ALWAYS',
366 'name': 'stencil_back_ref',
368 'enum': 'GL_STENCIL_BACK_REF',
372 'name': 'stencil_back_mask',
374 'enum': 'GL_STENCIL_BACK_VALUE_MASK',
375 'default': '0xFFFFFFFFU',
380 'type': 'NamedParameter',
384 'name': 'hint_generate_mipmap',
386 'enum': 'GL_GENERATE_MIPMAP_HINT',
387 'default': 'GL_DONT_CARE'
390 'name': 'hint_fragment_shader_derivative',
392 'enum': 'GL_FRAGMENT_SHADER_DERIVATIVE_HINT_OES',
393 'default': 'GL_DONT_CARE',
394 'extension_flag': 'oes_standard_derivatives'
399 'type': 'NamedParameter',
400 'func': 'PixelStorei',
403 'name': 'pack_alignment',
405 'enum': 'GL_PACK_ALIGNMENT',
409 'name': 'unpack_alignment',
411 'enum': 'GL_UNPACK_ALIGNMENT',
416 # TODO: Consider implemenenting these states
421 'enum': 'GL_LINE_WIDTH',
424 'name': 'line_width',
427 'range_checks': [{'check': "<= 0.0f", 'test_value': "0.0f"}],
434 'enum': 'GL_DEPTH_WRITEMASK',
437 'name': 'depth_mask',
443 'state_flag': 'framebuffer_state_.clear_state_dirty',
448 'enum': 'GL_SCISSOR_BOX',
450 # NOTE: These defaults reset at GLES2DecoderImpl::Initialization.
455 'expected': 'kViewportX',
461 'expected': 'kViewportY',
464 'name': 'scissor_width',
467 'expected': 'kViewportWidth',
470 'name': 'scissor_height',
473 'expected': 'kViewportHeight',
480 'enum': 'GL_VIEWPORT',
482 # NOTE: These defaults reset at GLES2DecoderImpl::Initialization.
484 'name': 'viewport_x',
487 'expected': 'kViewportX',
490 'name': 'viewport_y',
493 'expected': 'kViewportY',
496 'name': 'viewport_width',
499 'expected': 'kViewportWidth',
502 'name': 'viewport_height',
505 'expected': 'kViewportHeight',
509 'MatrixValuesCHROMIUM': {
510 'type': 'NamedParameter',
511 'func': 'MatrixLoadfEXT',
513 { 'enum': 'GL_PATH_MODELVIEW_MATRIX_CHROMIUM',
514 'enum_set': 'GL_PATH_MODELVIEW_CHROMIUM',
515 'name': 'modelview_matrix',
518 '1.0f', '0.0f','0.0f','0.0f',
519 '0.0f', '1.0f','0.0f','0.0f',
520 '0.0f', '0.0f','1.0f','0.0f',
521 '0.0f', '0.0f','0.0f','1.0f',
523 'extension_flag': 'chromium_path_rendering',
525 { 'enum': 'GL_PATH_PROJECTION_MATRIX_CHROMIUM',
526 'enum_set': 'GL_PATH_PROJECTION_CHROMIUM',
527 'name': 'projection_matrix',
530 '1.0f', '0.0f','0.0f','0.0f',
531 '0.0f', '1.0f','0.0f','0.0f',
532 '0.0f', '0.0f','1.0f','0.0f',
533 '0.0f', '0.0f','0.0f','1.0f',
535 'extension_flag': 'chromium_path_rendering',
541 # Named type info object represents a named type that is used in OpenGL call
542 # arguments. Each named type defines a set of valid OpenGL call arguments. The
543 # named types are used in 'cmd_buffer_functions.txt'.
544 # type: The actual GL type of the named type.
545 # valid: The list of values that are valid for both the client and the service.
546 # invalid: Examples of invalid values for the type. At least these values
547 # should be tested to be invalid.
548 # is_complete: The list of valid values of type are final and will not be
549 # modified during runtime.
558 'GL_LINEAR_MIPMAP_LINEAR',
561 'FrameBufferTarget': {
567 'GL_DRAW_FRAMEBUFFER' ,
568 'GL_READ_FRAMEBUFFER' ,
571 'RenderBufferTarget': {
584 'GL_ELEMENT_ARRAY_BUFFER',
601 'CompressedTextureFormat': {
609 # NOTE: State an Capability entries added later.
611 'GL_ALIASED_LINE_WIDTH_RANGE',
612 'GL_ALIASED_POINT_SIZE_RANGE',
614 'GL_ARRAY_BUFFER_BINDING',
616 'GL_COMPRESSED_TEXTURE_FORMATS',
617 'GL_CURRENT_PROGRAM',
620 'GL_ELEMENT_ARRAY_BUFFER_BINDING',
621 'GL_FRAMEBUFFER_BINDING',
622 'GL_GENERATE_MIPMAP_HINT',
624 'GL_IMPLEMENTATION_COLOR_READ_FORMAT',
625 'GL_IMPLEMENTATION_COLOR_READ_TYPE',
626 'GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS',
627 'GL_MAX_CUBE_MAP_TEXTURE_SIZE',
628 'GL_MAX_FRAGMENT_UNIFORM_VECTORS',
629 'GL_MAX_RENDERBUFFER_SIZE',
630 'GL_MAX_TEXTURE_IMAGE_UNITS',
631 'GL_MAX_TEXTURE_SIZE',
632 'GL_MAX_VARYING_VECTORS',
633 'GL_MAX_VERTEX_ATTRIBS',
634 'GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS',
635 'GL_MAX_VERTEX_UNIFORM_VECTORS',
636 'GL_MAX_VIEWPORT_DIMS',
637 'GL_NUM_COMPRESSED_TEXTURE_FORMATS',
638 'GL_NUM_SHADER_BINARY_FORMATS',
641 'GL_RENDERBUFFER_BINDING',
643 'GL_SAMPLE_COVERAGE_INVERT',
644 'GL_SAMPLE_COVERAGE_VALUE',
647 'GL_SHADER_BINARY_FORMATS',
648 'GL_SHADER_COMPILER',
651 'GL_TEXTURE_BINDING_2D',
652 'GL_TEXTURE_BINDING_CUBE_MAP',
653 'GL_UNPACK_ALIGNMENT',
654 'GL_UNPACK_FLIP_Y_CHROMIUM',
655 'GL_UNPACK_PREMULTIPLY_ALPHA_CHROMIUM',
656 'GL_UNPACK_UNPREMULTIPLY_ALPHA_CHROMIUM',
657 'GL_BIND_GENERATES_RESOURCE_CHROMIUM',
658 # we can add this because we emulate it if the driver does not support it.
659 'GL_VERTEX_ARRAY_BINDING_OES',
666 'GetTexParamTarget': {
670 'GL_TEXTURE_CUBE_MAP',
673 'GL_PROXY_TEXTURE_CUBE_MAP',
680 'GL_TEXTURE_CUBE_MAP_POSITIVE_X',
681 'GL_TEXTURE_CUBE_MAP_NEGATIVE_X',
682 'GL_TEXTURE_CUBE_MAP_POSITIVE_Y',
683 'GL_TEXTURE_CUBE_MAP_NEGATIVE_Y',
684 'GL_TEXTURE_CUBE_MAP_POSITIVE_Z',
685 'GL_TEXTURE_CUBE_MAP_NEGATIVE_Z',
688 'GL_PROXY_TEXTURE_CUBE_MAP',
691 'TextureBindTarget': {
695 'GL_TEXTURE_CUBE_MAP',
706 'GL_FRAGMENT_SHADER',
709 'GL_GEOMETRY_SHADER',
745 'GL_FUNC_REVERSE_SUBTRACT',
758 'GL_ONE_MINUS_SRC_COLOR',
760 'GL_ONE_MINUS_DST_COLOR',
762 'GL_ONE_MINUS_SRC_ALPHA',
764 'GL_ONE_MINUS_DST_ALPHA',
766 'GL_ONE_MINUS_CONSTANT_COLOR',
768 'GL_ONE_MINUS_CONSTANT_ALPHA',
769 'GL_SRC_ALPHA_SATURATE',
778 'GL_ONE_MINUS_SRC_COLOR',
780 'GL_ONE_MINUS_DST_COLOR',
782 'GL_ONE_MINUS_SRC_ALPHA',
784 'GL_ONE_MINUS_DST_ALPHA',
786 'GL_ONE_MINUS_CONSTANT_COLOR',
788 'GL_ONE_MINUS_CONSTANT_ALPHA',
793 'valid': ["GL_%s" % cap
['name'].upper() for cap
in _CAPABILITY_FLAGS
],
840 'GL_COLOR_ATTACHMENT0',
841 'GL_DEPTH_ATTACHMENT',
842 'GL_STENCIL_ATTACHMENT',
845 'BackbufferAttachment': {
860 'GL_PIXEL_PACK_BUFFER',
863 'FrameBufferParameter': {
866 'GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE',
867 'GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME',
868 'GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL',
869 'GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE',
875 'GL_PATH_PROJECTION_CHROMIUM',
876 'GL_PATH_MODELVIEW_CHROMIUM',
879 'ProgramParameter': {
884 'GL_VALIDATE_STATUS',
885 'GL_INFO_LOG_LENGTH',
886 'GL_ATTACHED_SHADERS',
887 'GL_ACTIVE_ATTRIBUTES',
888 'GL_ACTIVE_ATTRIBUTE_MAX_LENGTH',
889 'GL_ACTIVE_UNIFORMS',
890 'GL_ACTIVE_UNIFORM_MAX_LENGTH',
893 'QueryObjectParameter': {
896 'GL_QUERY_RESULT_EXT',
897 'GL_QUERY_RESULT_AVAILABLE_EXT',
903 'GL_CURRENT_QUERY_EXT',
909 'GL_ANY_SAMPLES_PASSED_EXT',
910 'GL_ANY_SAMPLES_PASSED_CONSERVATIVE_EXT',
911 'GL_COMMANDS_ISSUED_CHROMIUM',
912 'GL_LATENCY_QUERY_CHROMIUM',
913 'GL_ASYNC_PIXEL_UNPACK_COMPLETED_CHROMIUM',
914 'GL_ASYNC_PIXEL_PACK_COMPLETED_CHROMIUM',
915 'GL_COMMANDS_COMPLETED_CHROMIUM',
918 'RenderBufferParameter': {
921 'GL_RENDERBUFFER_RED_SIZE',
922 'GL_RENDERBUFFER_GREEN_SIZE',
923 'GL_RENDERBUFFER_BLUE_SIZE',
924 'GL_RENDERBUFFER_ALPHA_SIZE',
925 'GL_RENDERBUFFER_DEPTH_SIZE',
926 'GL_RENDERBUFFER_STENCIL_SIZE',
927 'GL_RENDERBUFFER_WIDTH',
928 'GL_RENDERBUFFER_HEIGHT',
929 'GL_RENDERBUFFER_INTERNAL_FORMAT',
938 'GL_INFO_LOG_LENGTH',
939 'GL_SHADER_SOURCE_LENGTH',
940 'GL_TRANSLATED_SHADER_SOURCE_LENGTH_ANGLE',
960 'GL_SHADING_LANGUAGE_VERSION',
964 'TextureParameter': {
967 'GL_TEXTURE_MAG_FILTER',
968 'GL_TEXTURE_MIN_FILTER',
969 'GL_TEXTURE_POOL_CHROMIUM',
974 'GL_GENERATE_MIPMAP',
980 'GL_TEXTURE_POOL_MANAGED_CHROMIUM',
981 'GL_TEXTURE_POOL_UNMANAGED_CHROMIUM',
988 'GL_MIRRORED_REPEAT',
992 'TextureMinFilterMode': {
997 'GL_NEAREST_MIPMAP_NEAREST',
998 'GL_LINEAR_MIPMAP_NEAREST',
999 'GL_NEAREST_MIPMAP_LINEAR',
1000 'GL_LINEAR_MIPMAP_LINEAR',
1003 'TextureMagFilterMode': {
1014 'GL_FRAMEBUFFER_ATTACHMENT_ANGLE',
1017 'VertexAttribute': {
1020 # some enum that the decoder actually passes through to GL needs
1021 # to be the first listed here since it's used in unit tests.
1022 'GL_VERTEX_ATTRIB_ARRAY_NORMALIZED',
1023 'GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING',
1024 'GL_VERTEX_ATTRIB_ARRAY_ENABLED',
1025 'GL_VERTEX_ATTRIB_ARRAY_SIZE',
1026 'GL_VERTEX_ATTRIB_ARRAY_STRIDE',
1027 'GL_VERTEX_ATTRIB_ARRAY_TYPE',
1028 'GL_CURRENT_VERTEX_ATTRIB',
1034 'GL_VERTEX_ATTRIB_ARRAY_POINTER',
1040 'GL_GENERATE_MIPMAP_HINT',
1043 'GL_PERSPECTIVE_CORRECTION_HINT',
1057 'GL_PACK_ALIGNMENT',
1058 'GL_UNPACK_ALIGNMENT',
1059 'GL_UNPACK_FLIP_Y_CHROMIUM',
1060 'GL_UNPACK_PREMULTIPLY_ALPHA_CHROMIUM',
1061 'GL_UNPACK_UNPREMULTIPLY_ALPHA_CHROMIUM',
1064 'GL_PACK_SWAP_BYTES',
1065 'GL_UNPACK_SWAP_BYTES',
1068 'PixelStoreAlignment': {
1081 'ReadPixelFormat': {
1093 'GL_UNSIGNED_SHORT_5_6_5',
1094 'GL_UNSIGNED_SHORT_4_4_4_4',
1095 'GL_UNSIGNED_SHORT_5_5_5_1',
1106 'GL_UNSIGNED_SHORT_5_6_5',
1107 'GL_UNSIGNED_SHORT_4_4_4_4',
1108 'GL_UNSIGNED_SHORT_5_5_5_1',
1115 'RenderBufferFormat': {
1121 'GL_DEPTH_COMPONENT16',
1122 'GL_STENCIL_INDEX8',
1125 'ShaderBinaryFormat': {
1148 'GL_LUMINANCE_ALPHA',
1157 'TextureInternalFormat': {
1162 'GL_LUMINANCE_ALPHA',
1171 'TextureInternalFormatStorage': {
1178 'GL_LUMINANCE8_EXT',
1179 'GL_LUMINANCE8_ALPHA8_EXT',
1184 'ImageInternalFormat': {
1195 'GL_SCANOUT_CHROMIUM'
1198 'VertexAttribType': {
1204 'GL_UNSIGNED_SHORT',
1205 # 'GL_FIXED', // This is not available on Desktop GL.
1214 'is_complete': True,
1222 'VertexAttribSize': {
1237 'is_complete': True,
1246 'type': 'GLboolean',
1247 'is_complete': True,
1258 'GL_GUILTY_CONTEXT_RESET_ARB',
1259 'GL_INNOCENT_CONTEXT_RESET_ARB',
1260 'GL_UNKNOWN_CONTEXT_RESET_ARB',
1265 # This table specifies the different pepper interfaces that are supported for
1266 # GL commands. 'dev' is true if it's a dev interface.
1267 _PEPPER_INTERFACES
= [
1268 {'name': '', 'dev': False},
1269 {'name': 'InstancedArrays', 'dev': False},
1270 {'name': 'FramebufferBlit', 'dev': False},
1271 {'name': 'FramebufferMultisample', 'dev': False},
1272 {'name': 'ChromiumEnableFeature', 'dev': False},
1273 {'name': 'ChromiumMapSub', 'dev': False},
1274 {'name': 'Query', 'dev': False},
1275 {'name': 'VertexArrayObject', 'dev': False},
1276 {'name': 'DrawBuffers', 'dev': True},
1279 # A function info object specifies the type and other special data for the
1280 # command that will be generated. A base function info object is generated by
1281 # parsing the "cmd_buffer_functions.txt", one for each function in the
1282 # file. These function info objects can be augmented and their values can be
1283 # overridden by adding an object to the table below.
1285 # Must match function names specified in "cmd_buffer_functions.txt".
1287 # cmd_comment: A comment added to the cmd format.
1288 # type: defines which handler will be used to generate code.
1289 # decoder_func: defines which function to call in the decoder to execute the
1290 # corresponding GL command. If not specified the GL command will
1291 # be called directly.
1292 # gl_test_func: GL function that is expected to be called when testing.
1293 # cmd_args: The arguments to use for the command. This overrides generating
1294 # them based on the GL function arguments.
1295 # gen_cmd: Whether or not this function geneates a command. Default = True.
1296 # data_transfer_methods: Array of methods that are used for transfering the
1297 # pointer data. Possible values: 'immediate', 'shm', 'bucket'.
1298 # The default is 'immediate' if the command has one pointer
1299 # argument, otherwise 'shm'. One command is generated for each
1300 # transfer method. Affects only commands which are not of type
1301 # 'HandWritten', 'GETn' or 'GLcharN'.
1302 # Note: the command arguments that affect this are the final args,
1303 # taking cmd_args override into consideration.
1304 # impl_func: Whether or not to generate the GLES2Implementation part of this
1306 # impl_decl: Whether or not to generate the GLES2Implementation declaration
1308 # needs_size: If true a data_size field is added to the command.
1309 # count: The number of units per element. For PUTn or PUT types.
1310 # unit_test: If False no service side unit test will be generated.
1311 # client_test: If False no client side unit test will be generated.
1312 # expectation: If False the unit test will have no expected calls.
1313 # gen_func: Name of function that generates GL resource for corresponding
1315 # states: array of states that get set by this function corresponding to
1316 # the given arguments
1317 # state_flag: name of flag that is set to true when function is called.
1318 # no_gl: no GL function is called.
1319 # valid_args: A dictionary of argument indices to args to use in unit tests
1320 # when they can not be automatically determined.
1321 # pepper_interface: The pepper interface that is used for this extension
1322 # pepper_name: The name of the function as exposed to pepper.
1323 # pepper_args: A string representing the argument list (what would appear in
1324 # C/C++ between the parentheses for the function declaration)
1325 # that the Pepper API expects for this function. Use this only if
1326 # the stable Pepper API differs from the GLES2 argument list.
1327 # invalid_test: False if no invalid test needed.
1328 # shadowed: True = the value is shadowed so no glGetXXX call will be made.
1329 # first_element_only: For PUT types, True if only the first element of an
1330 # array is used and we end up calling the single value
1331 # corresponding function. eg. TexParameteriv -> TexParameteri
1332 # extension: Function is an extension to GL and should not be exposed to
1333 # pepper unless pepper_interface is defined.
1334 # extension_flag: Function is an extension and should be enabled only when
1335 # the corresponding feature info flag is enabled. Implies
1336 # 'extension': True.
1337 # not_shared: For GENn types, True if objects can't be shared between contexts
1341 'decoder_func': 'DoActiveTexture',
1344 'client_test': False,
1346 'AttachShader': {'decoder_func': 'DoAttachShader'},
1347 'BindAttribLocation': {
1349 'data_transfer_methods': ['bucket'],
1354 'decoder_func': 'DoBindBuffer',
1355 'gen_func': 'GenBuffersARB',
1357 'BindFramebuffer': {
1359 'decoder_func': 'DoBindFramebuffer',
1360 'gl_test_func': 'glBindFramebufferEXT',
1361 'gen_func': 'GenFramebuffersEXT',
1364 'BindRenderbuffer': {
1366 'decoder_func': 'DoBindRenderbuffer',
1367 'gl_test_func': 'glBindRenderbufferEXT',
1368 'gen_func': 'GenRenderbuffersEXT',
1372 'decoder_func': 'DoBindTexture',
1373 'gen_func': 'GenTextures',
1374 # TODO(gman): remove this once client side caching works.
1375 'client_test': False,
1378 'BlitFramebufferCHROMIUM': {
1379 'decoder_func': 'DoBlitFramebufferCHROMIUM',
1381 'extension_flag': 'chromium_framebuffer_multisample',
1382 'pepper_interface': 'FramebufferBlit',
1383 'pepper_name': 'BlitFramebufferEXT',
1384 'defer_reads': True,
1385 'defer_draws': True,
1390 'data_transfer_methods': ['shm'],
1391 'client_test': False,
1395 'client_test': False,
1396 'decoder_func': 'DoBufferSubData',
1397 'data_transfer_methods': ['shm'],
1399 'CheckFramebufferStatus': {
1401 'decoder_func': 'DoCheckFramebufferStatus',
1402 'gl_test_func': 'glCheckFramebufferStatusEXT',
1403 'error_value': 'GL_FRAMEBUFFER_UNSUPPORTED',
1404 'result': ['GLenum'],
1407 'decoder_func': 'DoClear',
1408 'defer_draws': True,
1413 'state': 'ClearColor',
1417 'state': 'ClearDepthf',
1418 'decoder_func': 'glClearDepth',
1419 'gl_test_func': 'glClearDepth',
1426 'state': 'ColorMask',
1428 'expectation': False,
1430 'ConsumeTextureCHROMIUM': {
1431 'decoder_func': 'DoConsumeTextureCHROMIUM',
1434 'count': 64, # GL_MAILBOX_SIZE_CHROMIUM
1436 'client_test': False,
1437 'extension': "CHROMIUM_texture_mailbox",
1441 'CreateAndConsumeTextureCHROMIUM': {
1442 'decoder_func': 'DoCreateAndConsumeTextureCHROMIUM',
1444 'type': 'HandWritten',
1445 'data_transfer_methods': ['immediate'],
1447 'client_test': False,
1448 'extension': "CHROMIUM_texture_mailbox",
1453 'state': 'ClearStencil',
1455 'EnableFeatureCHROMIUM': {
1457 'data_transfer_methods': ['shm'],
1458 'decoder_func': 'DoEnableFeatureCHROMIUM',
1459 'expectation': False,
1460 'cmd_args': 'GLuint bucket_id, GLint* result',
1461 'result': ['GLint'],
1464 'pepper_interface': 'ChromiumEnableFeature',
1466 'CompileShader': {'decoder_func': 'DoCompileShader', 'unit_test': False},
1467 'CompressedTexImage2D': {
1469 'data_transfer_methods': ['bucket', 'shm'],
1471 'CompressedTexSubImage2D': {
1473 'data_transfer_methods': ['bucket', 'shm'],
1474 'decoder_func': 'DoCompressedTexSubImage2D',
1477 'decoder_func': 'DoCopyTexImage2D',
1479 'defer_reads': True,
1481 'CopyTexSubImage2D': {
1482 'decoder_func': 'DoCopyTexSubImage2D',
1483 'defer_reads': True,
1485 'CreateImageCHROMIUM': {
1488 'ClientBuffer buffer, GLsizei width, GLsizei height, '
1489 'GLenum internalformat',
1490 'result': ['GLuint'],
1491 'client_test': False,
1493 'expectation': False,
1497 'DestroyImageCHROMIUM': {
1499 'client_test': False,
1504 'CreateGpuMemoryBufferImageCHROMIUM': {
1507 'GLsizei width, GLsizei height, GLenum internalformat, GLenum usage',
1508 'result': ['GLuint'],
1509 'client_test': False,
1511 'expectation': False,
1517 'client_test': False,
1521 'client_test': False,
1525 'state': 'BlendColor',
1528 'type': 'StateSetRGBAlpha',
1529 'state': 'BlendEquation',
1531 '0': 'GL_FUNC_SUBTRACT'
1534 'BlendEquationSeparate': {
1536 'state': 'BlendEquation',
1538 '0': 'GL_FUNC_SUBTRACT'
1542 'type': 'StateSetRGBAlpha',
1543 'state': 'BlendFunc',
1545 'BlendFuncSeparate': {
1547 'state': 'BlendFunc',
1549 'SampleCoverage': {'decoder_func': 'DoSampleCoverage'},
1551 'type': 'StateSetFrontBack',
1552 'state': 'StencilFunc',
1554 'StencilFuncSeparate': {
1555 'type': 'StateSetFrontBackSeparate',
1556 'state': 'StencilFunc',
1559 'type': 'StateSetFrontBack',
1560 'state': 'StencilOp',
1565 'StencilOpSeparate': {
1566 'type': 'StateSetFrontBackSeparate',
1567 'state': 'StencilOp',
1573 'type': 'StateSetNamedParameter',
1576 'CullFace': {'type': 'StateSet', 'state': 'CullFace'},
1577 'FrontFace': {'type': 'StateSet', 'state': 'FrontFace'},
1578 'DepthFunc': {'type': 'StateSet', 'state': 'DepthFunc'},
1581 'state': 'LineWidth',
1588 'state': 'PolygonOffset',
1592 'gl_test_func': 'glDeleteBuffersARB',
1593 'resource_type': 'Buffer',
1594 'resource_types': 'Buffers',
1596 'DeleteFramebuffers': {
1598 'gl_test_func': 'glDeleteFramebuffersEXT',
1599 'resource_type': 'Framebuffer',
1600 'resource_types': 'Framebuffers',
1602 'DeleteProgram': {'type': 'Delete', 'decoder_func': 'DoDeleteProgram'},
1603 'DeleteRenderbuffers': {
1605 'gl_test_func': 'glDeleteRenderbuffersEXT',
1606 'resource_type': 'Renderbuffer',
1607 'resource_types': 'Renderbuffers',
1609 'DeleteShader': {'type': 'Delete', 'decoder_func': 'DoDeleteShader'},
1612 'resource_type': 'Texture',
1613 'resource_types': 'Textures',
1616 'decoder_func': 'DoDepthRangef',
1617 'gl_test_func': 'glDepthRange',
1621 'state': 'DepthMask',
1623 'expectation': False,
1625 'DetachShader': {'decoder_func': 'DoDetachShader'},
1627 'decoder_func': 'DoDisable',
1629 'client_test': False,
1631 'DisableVertexAttribArray': {
1632 'decoder_func': 'DoDisableVertexAttribArray',
1637 'cmd_args': 'GLenumDrawMode mode, GLint first, GLsizei count',
1638 'defer_draws': True,
1643 'cmd_args': 'GLenumDrawMode mode, GLsizei count, '
1644 'GLenumIndexType type, GLuint index_offset',
1645 'client_test': False,
1646 'defer_draws': True,
1650 'decoder_func': 'DoEnable',
1652 'client_test': False,
1654 'EnableVertexAttribArray': {
1655 'decoder_func': 'DoEnableVertexAttribArray',
1660 'client_test': False,
1661 'decoder_func': 'DoFinish',
1662 'defer_reads': True,
1666 'decoder_func': 'DoFlush',
1668 'FramebufferRenderbuffer': {
1669 'decoder_func': 'DoFramebufferRenderbuffer',
1670 'gl_test_func': 'glFramebufferRenderbufferEXT',
1672 'FramebufferTexture2D': {
1673 'decoder_func': 'DoFramebufferTexture2D',
1674 'gl_test_func': 'glFramebufferTexture2DEXT',
1677 'FramebufferTexture2DMultisampleEXT': {
1678 'decoder_func': 'DoFramebufferTexture2DMultisample',
1679 'gl_test_func': 'glFramebufferTexture2DMultisampleEXT',
1680 'expectation': False,
1682 'extension_flag': 'multisampled_render_to_texture',
1686 'decoder_func': 'DoGenerateMipmap',
1687 'gl_test_func': 'glGenerateMipmapEXT',
1691 'gl_test_func': 'glGenBuffersARB',
1692 'resource_type': 'Buffer',
1693 'resource_types': 'Buffers',
1695 'GenMailboxCHROMIUM': {
1696 'type': 'HandWritten',
1698 'extension': "CHROMIUM_texture_mailbox",
1701 'GenFramebuffers': {
1703 'gl_test_func': 'glGenFramebuffersEXT',
1704 'resource_type': 'Framebuffer',
1705 'resource_types': 'Framebuffers',
1707 'GenRenderbuffers': {
1708 'type': 'GENn', 'gl_test_func': 'glGenRenderbuffersEXT',
1709 'resource_type': 'Renderbuffer',
1710 'resource_types': 'Renderbuffers',
1714 'gl_test_func': 'glGenTextures',
1715 'resource_type': 'Texture',
1716 'resource_types': 'Textures',
1718 'GetActiveAttrib': {
1720 'data_transfer_methods': ['shm'],
1722 'GLidProgram program, GLuint index, uint32_t name_bucket_id, '
1730 'GetActiveUniform': {
1732 'data_transfer_methods': ['shm'],
1734 'GLidProgram program, GLuint index, uint32_t name_bucket_id, '
1742 'GetAttachedShaders': {
1744 'data_transfer_methods': ['shm'],
1745 'cmd_args': 'GLidProgram program, void* result, uint32_t result_size',
1746 'result': ['SizedResult<GLuint>'],
1748 'GetAttribLocation': {
1750 'data_transfer_methods': ['shm'],
1752 'GLidProgram program, uint32_t name_bucket_id, GLint* location',
1753 'result': ['GLint'],
1754 'error_return': -1, # http://www.opengl.org/sdk/docs/man/xhtml/glGetAttribLocation.xml
1758 'result': ['SizedResult<GLboolean>'],
1759 'decoder_func': 'DoGetBooleanv',
1760 'gl_test_func': 'glGetBooleanv',
1762 'GetBufferParameteriv': {
1764 'result': ['SizedResult<GLint>'],
1765 'decoder_func': 'DoGetBufferParameteriv',
1766 'expectation': False,
1771 'decoder_func': 'GetErrorState()->GetGLError',
1773 'result': ['GLenum'],
1774 'client_test': False,
1778 'result': ['SizedResult<GLfloat>'],
1779 'decoder_func': 'DoGetFloatv',
1780 'gl_test_func': 'glGetFloatv',
1782 'GetFramebufferAttachmentParameteriv': {
1784 'decoder_func': 'DoGetFramebufferAttachmentParameteriv',
1785 'gl_test_func': 'glGetFramebufferAttachmentParameterivEXT',
1786 'result': ['SizedResult<GLint>'],
1790 'result': ['SizedResult<GLint>'],
1791 'decoder_func': 'DoGetIntegerv',
1792 'client_test': False,
1794 'GetMaxValueInBufferCHROMIUM': {
1796 'decoder_func': 'DoGetMaxValueInBufferCHROMIUM',
1797 'result': ['GLuint'],
1799 'client_test': False,
1804 'GetMultipleIntegervCHROMIUM': {
1806 'data_transfer_methods': ['shm'],
1807 'expectation': False,
1810 'client_test': False,
1814 'decoder_func': 'DoGetProgramiv',
1815 'result': ['SizedResult<GLint>'],
1816 'expectation': False,
1818 'GetProgramInfoCHROMIUM': {
1820 'expectation': False,
1824 'client_test': False,
1825 'cmd_args': 'GLidProgram program, uint32_t bucket_id',
1827 'uint32_t link_status',
1828 'uint32_t num_attribs',
1829 'uint32_t num_uniforms',
1832 'GetProgramInfoLog': {
1834 'expectation': False,
1836 'GetRenderbufferParameteriv': {
1838 'decoder_func': 'DoGetRenderbufferParameteriv',
1839 'gl_test_func': 'glGetRenderbufferParameterivEXT',
1840 'result': ['SizedResult<GLint>'],
1844 'decoder_func': 'DoGetShaderiv',
1845 'result': ['SizedResult<GLint>'],
1847 'GetShaderInfoLog': {
1849 'get_len_func': 'glGetShaderiv',
1850 'get_len_enum': 'GL_INFO_LOG_LENGTH',
1853 'GetShaderPrecisionFormat': {
1855 'data_transfer_methods': ['shm'],
1857 'GLenumShaderType shadertype, GLenumShaderPrecision precisiontype, '
1861 'int32_t min_range',
1862 'int32_t max_range',
1863 'int32_t precision',
1866 'GetShaderSource': {
1868 'get_len_func': 'DoGetShaderiv',
1869 'get_len_enum': 'GL_SHADER_SOURCE_LENGTH',
1871 'client_test': False,
1875 'client_test': False,
1876 'cmd_args': 'GLenumStringType name, uint32_t bucket_id',
1878 'GetTexParameterfv': {
1880 'decoder_func': 'DoGetTexParameterfv',
1881 'result': ['SizedResult<GLfloat>']
1883 'GetTexParameteriv': {
1885 'decoder_func': 'DoGetTexParameteriv',
1886 'result': ['SizedResult<GLint>']
1888 'GetTranslatedShaderSourceANGLE': {
1890 'get_len_func': 'DoGetShaderiv',
1891 'get_len_enum': 'GL_TRANSLATED_SHADER_SOURCE_LENGTH_ANGLE',
1897 'data_transfer_methods': ['shm'],
1898 'result': ['SizedResult<GLfloat>'],
1902 'data_transfer_methods': ['shm'],
1903 'result': ['SizedResult<GLint>'],
1905 'GetUniformLocation': {
1907 'data_transfer_methods': ['shm'],
1909 'GLidProgram program, uint32_t name_bucket_id, GLint* location',
1910 'result': ['GLint'],
1911 'error_return': -1, # http://www.opengl.org/sdk/docs/man/xhtml/glGetUniformLocation.xml
1913 'GetVertexAttribfv': {
1915 'result': ['SizedResult<GLfloat>'],
1917 'decoder_func': 'DoGetVertexAttribfv',
1918 'expectation': False,
1919 'client_test': False,
1921 'GetVertexAttribiv': {
1923 'result': ['SizedResult<GLint>'],
1925 'decoder_func': 'DoGetVertexAttribiv',
1926 'expectation': False,
1927 'client_test': False,
1929 'GetVertexAttribPointerv': {
1931 'data_transfer_methods': ['shm'],
1932 'result': ['SizedResult<GLuint>'],
1933 'client_test': False,
1937 'decoder_func': 'DoIsBuffer',
1938 'expectation': False,
1942 'decoder_func': 'DoIsEnabled',
1944 'expectation': False,
1948 'decoder_func': 'DoIsFramebuffer',
1949 'expectation': False,
1953 'decoder_func': 'DoIsProgram',
1954 'expectation': False,
1958 'decoder_func': 'DoIsRenderbuffer',
1959 'expectation': False,
1963 'decoder_func': 'DoIsShader',
1964 'expectation': False,
1968 'decoder_func': 'DoIsTexture',
1969 'expectation': False,
1972 'decoder_func': 'DoLinkProgram',
1975 'MapBufferCHROMIUM': {
1979 'client_test': False,
1981 'MapBufferSubDataCHROMIUM': {
1985 'client_test': False,
1986 'pepper_interface': 'ChromiumMapSub',
1988 'MapTexSubImage2DCHROMIUM': {
1992 'client_test': False,
1993 'pepper_interface': 'ChromiumMapSub',
1995 'PixelStorei': {'type': 'Manual'},
1996 'PostSubBufferCHROMIUM': {
2000 'client_test': False,
2004 'ProduceTextureCHROMIUM': {
2005 'decoder_func': 'DoProduceTextureCHROMIUM',
2008 'count': 64, # GL_MAILBOX_SIZE_CHROMIUM
2010 'client_test': False,
2011 'extension': "CHROMIUM_texture_mailbox",
2015 'ProduceTextureDirectCHROMIUM': {
2016 'decoder_func': 'DoProduceTextureDirectCHROMIUM',
2019 'count': 64, # GL_MAILBOX_SIZE_CHROMIUM
2021 'client_test': False,
2022 'extension': "CHROMIUM_texture_mailbox",
2026 'RenderbufferStorage': {
2027 'decoder_func': 'DoRenderbufferStorage',
2028 'gl_test_func': 'glRenderbufferStorageEXT',
2029 'expectation': False,
2031 'RenderbufferStorageMultisampleCHROMIUM': {
2033 '// GL_CHROMIUM_framebuffer_multisample\n',
2034 'decoder_func': 'DoRenderbufferStorageMultisampleCHROMIUM',
2035 'gl_test_func': 'glRenderbufferStorageMultisampleCHROMIUM',
2036 'expectation': False,
2038 'extension_flag': 'chromium_framebuffer_multisample',
2039 'pepper_interface': 'FramebufferMultisample',
2040 'pepper_name': 'RenderbufferStorageMultisampleEXT',
2042 'RenderbufferStorageMultisampleEXT': {
2044 '// GL_EXT_multisampled_render_to_texture\n',
2045 'decoder_func': 'DoRenderbufferStorageMultisampleEXT',
2046 'gl_test_func': 'glRenderbufferStorageMultisampleEXT',
2047 'expectation': False,
2049 'extension_flag': 'multisampled_render_to_texture',
2053 '// ReadPixels has the result separated from the pixel buffer so that\n'
2054 '// it is easier to specify the result going to some specific place\n'
2055 '// that exactly fits the rectangle of pixels.\n',
2057 'data_transfer_methods': ['shm'],
2059 'client_test': False,
2061 'GLint x, GLint y, GLsizei width, GLsizei height, '
2062 'GLenumReadPixelFormat format, GLenumReadPixelType type, '
2063 'uint32_t pixels_shm_id, uint32_t pixels_shm_offset, '
2064 'uint32_t result_shm_id, uint32_t result_shm_offset, '
2066 'result': ['uint32_t'],
2067 'defer_reads': True,
2069 'ReleaseShaderCompiler': {
2070 'decoder_func': 'DoReleaseShaderCompiler',
2075 'client_test': False,
2079 'data_transfer_methods': ['bucket'],
2081 'client_test': False,
2083 'GLuint shader, const char* data',
2085 'GLuint shader, GLsizei count, const char** str, const GLint* length',
2088 'type': 'StateSetFrontBack',
2089 'state': 'StencilMask',
2091 'expectation': False,
2093 'StencilMaskSeparate': {
2094 'type': 'StateSetFrontBackSeparate',
2095 'state': 'StencilMask',
2097 'expectation': False,
2101 'decoder_func': 'DoSwapBuffers',
2103 'client_test': False,
2109 'data_transfer_methods': ['shm'],
2110 'client_test': False,
2113 'decoder_func': 'DoTexParameterf',
2119 'decoder_func': 'DoTexParameteri',
2126 'data_value': 'GL_NEAREST',
2128 'decoder_func': 'DoTexParameterfv',
2129 'gl_test_func': 'glTexParameterf',
2130 'first_element_only': True,
2134 'data_value': 'GL_NEAREST',
2136 'decoder_func': 'DoTexParameteriv',
2137 'gl_test_func': 'glTexParameteri',
2138 'first_element_only': True,
2142 'data_transfer_methods': ['shm'],
2143 'client_test': False,
2144 'cmd_args': 'GLenumTextureTarget target, GLint level, '
2145 'GLint xoffset, GLint yoffset, '
2146 'GLsizei width, GLsizei height, '
2147 'GLenumTextureFormat format, GLenumPixelType type, '
2148 'const void* pixels, GLboolean internal'
2150 'Uniform1f': {'type': 'PUTXn', 'count': 1},
2154 'decoder_func': 'DoUniform1fv',
2156 'Uniform1i': {'decoder_func': 'DoUniform1i', 'unit_test': False},
2160 'decoder_func': 'DoUniform1iv',
2163 'Uniform2i': {'type': 'PUTXn', 'count': 2},
2164 'Uniform2f': {'type': 'PUTXn', 'count': 2},
2168 'decoder_func': 'DoUniform2fv',
2173 'decoder_func': 'DoUniform2iv',
2175 'Uniform3i': {'type': 'PUTXn', 'count': 3},
2176 'Uniform3f': {'type': 'PUTXn', 'count': 3},
2180 'decoder_func': 'DoUniform3fv',
2185 'decoder_func': 'DoUniform3iv',
2187 'Uniform4i': {'type': 'PUTXn', 'count': 4},
2188 'Uniform4f': {'type': 'PUTXn', 'count': 4},
2192 'decoder_func': 'DoUniform4fv',
2197 'decoder_func': 'DoUniform4iv',
2199 'UniformMatrix2fv': {
2202 'decoder_func': 'DoUniformMatrix2fv',
2204 'UniformMatrix3fv': {
2207 'decoder_func': 'DoUniformMatrix3fv',
2209 'UniformMatrix4fv': {
2212 'decoder_func': 'DoUniformMatrix4fv',
2214 'UnmapBufferCHROMIUM': {
2218 'client_test': False,
2220 'UnmapBufferSubDataCHROMIUM': {
2224 'client_test': False,
2225 'pepper_interface': 'ChromiumMapSub',
2227 'UnmapTexSubImage2DCHROMIUM': {
2231 'client_test': False,
2232 'pepper_interface': 'ChromiumMapSub',
2236 'decoder_func': 'DoUseProgram',
2238 'ValidateProgram': {'decoder_func': 'DoValidateProgram'},
2239 'VertexAttrib1f': {'decoder_func': 'DoVertexAttrib1f'},
2240 'VertexAttrib1fv': {
2243 'decoder_func': 'DoVertexAttrib1fv',
2245 'VertexAttrib2f': {'decoder_func': 'DoVertexAttrib2f'},
2246 'VertexAttrib2fv': {
2249 'decoder_func': 'DoVertexAttrib2fv',
2251 'VertexAttrib3f': {'decoder_func': 'DoVertexAttrib3f'},
2252 'VertexAttrib3fv': {
2255 'decoder_func': 'DoVertexAttrib3fv',
2257 'VertexAttrib4f': {'decoder_func': 'DoVertexAttrib4f'},
2258 'VertexAttrib4fv': {
2261 'decoder_func': 'DoVertexAttrib4fv',
2263 'VertexAttribPointer': {
2265 'cmd_args': 'GLuint indx, GLintVertexAttribSize size, '
2266 'GLenumVertexAttribType type, GLboolean normalized, '
2267 'GLsizei stride, GLuint offset',
2268 'client_test': False,
2275 'decoder_func': 'DoViewport',
2284 'GetRequestableExtensionsCHROMIUM': {
2287 'cmd_args': 'uint32_t bucket_id',
2291 'RequestExtensionCHROMIUM': {
2294 'client_test': False,
2295 'cmd_args': 'uint32_t bucket_id',
2299 'RateLimitOffscreenContextCHROMIUM': {
2303 'client_test': False,
2305 'CreateStreamTextureCHROMIUM': {
2306 'type': 'HandWritten',
2312 'TexImageIOSurface2DCHROMIUM': {
2313 'decoder_func': 'DoTexImageIOSurface2DCHROMIUM',
2318 'CopyTextureCHROMIUM': {
2319 'decoder_func': 'DoCopyTextureCHROMIUM',
2324 'TexStorage2DEXT': {
2327 'decoder_func': 'DoTexStorage2DEXT',
2329 'DrawArraysInstancedANGLE': {
2331 'cmd_args': 'GLenumDrawMode mode, GLint first, GLsizei count, '
2332 'GLsizei primcount',
2335 'pepper_interface': 'InstancedArrays',
2336 'defer_draws': True,
2340 'decoder_func': 'DoDrawBuffersEXT',
2342 'client_test': False,
2344 # could use 'extension_flag': 'ext_draw_buffers' but currently expected to
2347 'pepper_interface': 'DrawBuffers',
2349 'DrawElementsInstancedANGLE': {
2351 'cmd_args': 'GLenumDrawMode mode, GLsizei count, '
2352 'GLenumIndexType type, GLuint index_offset, GLsizei primcount',
2355 'client_test': False,
2356 'pepper_interface': 'InstancedArrays',
2357 'defer_draws': True,
2359 'VertexAttribDivisorANGLE': {
2361 'cmd_args': 'GLuint index, GLuint divisor',
2364 'pepper_interface': 'InstancedArrays',
2368 'gl_test_func': 'glGenQueriesARB',
2369 'resource_type': 'Query',
2370 'resource_types': 'Queries',
2372 'pepper_interface': 'Query',
2373 'not_shared': 'True',
2375 'DeleteQueriesEXT': {
2377 'gl_test_func': 'glDeleteQueriesARB',
2378 'resource_type': 'Query',
2379 'resource_types': 'Queries',
2381 'pepper_interface': 'Query',
2385 'client_test': False,
2386 'pepper_interface': 'Query',
2390 'cmd_args': 'GLenumQueryTarget target, GLidQuery id, void* sync_data',
2391 'data_transfer_methods': ['shm'],
2392 'gl_test_func': 'glBeginQuery',
2393 'pepper_interface': 'Query',
2397 'cmd_args': 'GLenumQueryTarget target, GLuint submit_count',
2398 'gl_test_func': 'glEndnQuery',
2399 'client_test': False,
2400 'pepper_interface': 'Query',
2404 'client_test': False,
2405 'gl_test_func': 'glGetQueryiv',
2406 'pepper_interface': 'Query',
2408 'GetQueryObjectuivEXT': {
2410 'client_test': False,
2411 'gl_test_func': 'glGetQueryObjectuiv',
2412 'pepper_interface': 'Query',
2414 'BindUniformLocationCHROMIUM': {
2417 'data_transfer_methods': ['bucket'],
2419 'gl_test_func': 'DoBindUniformLocationCHROMIUM',
2421 'InsertEventMarkerEXT': {
2423 'decoder_func': 'DoInsertEventMarkerEXT',
2424 'expectation': False,
2427 'PushGroupMarkerEXT': {
2429 'decoder_func': 'DoPushGroupMarkerEXT',
2430 'expectation': False,
2433 'PopGroupMarkerEXT': {
2434 'decoder_func': 'DoPopGroupMarkerEXT',
2435 'expectation': False,
2440 'GenVertexArraysOES': {
2443 'gl_test_func': 'glGenVertexArraysOES',
2444 'resource_type': 'VertexArray',
2445 'resource_types': 'VertexArrays',
2447 'pepper_interface': 'VertexArrayObject',
2449 'BindVertexArrayOES': {
2452 'gl_test_func': 'glBindVertexArrayOES',
2453 'decoder_func': 'DoBindVertexArrayOES',
2454 'gen_func': 'GenVertexArraysOES',
2456 'client_test': False,
2457 'pepper_interface': 'VertexArrayObject',
2459 'DeleteVertexArraysOES': {
2462 'gl_test_func': 'glDeleteVertexArraysOES',
2463 'resource_type': 'VertexArray',
2464 'resource_types': 'VertexArrays',
2466 'pepper_interface': 'VertexArrayObject',
2468 'IsVertexArrayOES': {
2471 'gl_test_func': 'glIsVertexArrayOES',
2472 'decoder_func': 'DoIsVertexArrayOES',
2473 'expectation': False,
2475 'pepper_interface': 'VertexArrayObject',
2477 'BindTexImage2DCHROMIUM': {
2478 'decoder_func': 'DoBindTexImage2DCHROMIUM',
2483 'ReleaseTexImage2DCHROMIUM': {
2484 'decoder_func': 'DoReleaseTexImage2DCHROMIUM',
2489 'ShallowFinishCHROMIUM': {
2494 'client_test': False,
2496 'ShallowFlushCHROMIUM': {
2501 'client_test': False,
2503 'TraceBeginCHROMIUM': {
2506 'client_test': False,
2507 'cmd_args': 'GLuint bucket_id',
2511 'TraceEndCHROMIUM': {
2513 'client_test': False,
2514 'decoder_func': 'DoTraceEndCHROMIUM',
2519 'AsyncTexImage2DCHROMIUM': {
2521 'data_transfer_methods': ['shm'],
2522 'client_test': False,
2523 'cmd_args': 'GLenumTextureTarget target, GLint level, '
2524 'GLintTextureInternalFormat internalformat, '
2525 'GLsizei width, GLsizei height, '
2526 'GLintTextureBorder border, '
2527 'GLenumTextureFormat format, GLenumPixelType type, '
2528 'const void* pixels, '
2529 'uint32_t async_upload_token, '
2534 'AsyncTexSubImage2DCHROMIUM': {
2536 'data_transfer_methods': ['shm'],
2537 'client_test': False,
2538 'cmd_args': 'GLenumTextureTarget target, GLint level, '
2539 'GLint xoffset, GLint yoffset, '
2540 'GLsizei width, GLsizei height, '
2541 'GLenumTextureFormat format, GLenumPixelType type, '
2542 'const void* data, '
2543 'uint32_t async_upload_token, '
2548 'WaitAsyncTexImage2DCHROMIUM': {
2550 'client_test': False,
2554 'WaitAllAsyncTexImage2DCHROMIUM': {
2556 'client_test': False,
2560 'DiscardFramebufferEXT': {
2563 'cmd_args': 'GLenum target, GLsizei count, '
2564 'const GLenum* attachments',
2565 'decoder_func': 'DoDiscardFramebufferEXT',
2567 'client_test': False,
2568 'extension_flag': 'ext_discard_framebuffer',
2570 'LoseContextCHROMIUM': {
2571 'decoder_func': 'DoLoseContextCHROMIUM',
2576 'InsertSyncPointCHROMIUM': {
2577 'type': 'HandWritten',
2579 'extension': "CHROMIUM_sync_point",
2582 'WaitSyncPointCHROMIUM': {
2585 'extension': "CHROMIUM_sync_point",
2589 'DiscardBackbufferCHROMIUM': {
2595 'ScheduleOverlayPlaneCHROMIUM': {
2599 'client_test': False,
2603 'MatrixLoadfCHROMIUM': {
2606 'data_type': 'GLfloat',
2607 'decoder_func': 'DoMatrixLoadfCHROMIUM',
2608 'gl_test_func': 'glMatrixLoadfEXT',
2611 'extension_flag': 'chromium_path_rendering',
2613 'MatrixLoadIdentityCHROMIUM': {
2614 'decoder_func': 'DoMatrixLoadIdentityCHROMIUM',
2615 'gl_test_func': 'glMatrixLoadIdentityEXT',
2618 'extension_flag': 'chromium_path_rendering',
2623 def Grouper(n
, iterable
, fillvalue
=None):
2624 """Collect data into fixed-length chunks or blocks"""
2625 args
= [iter(iterable
)] * n
2626 return itertools
.izip_longest(fillvalue
=fillvalue
, *args
)
2629 def SplitWords(input_string
):
2630 """Transforms a input_string into a list of lower-case components.
2633 input_string: the input string.
2636 a list of lower-case words.
2638 if input_string
.find('_') > -1:
2639 # 'some_TEXT_' -> 'some text'
2640 return input_string
.replace('_', ' ').strip().lower().split()
2642 if re
.search('[A-Z]', input_string
) and re
.search('[a-z]', input_string
):
2644 # look for capitalization to cut input_strings
2645 # 'SomeText' -> 'Some Text'
2646 input_string
= re
.sub('([A-Z])', r
' \1', input_string
).strip()
2647 # 'Vector3' -> 'Vector 3'
2648 input_string
= re
.sub('([^0-9])([0-9])', r
'\1 \2', input_string
)
2649 return input_string
.lower().split()
2653 """Makes a lower-case identifier from words.
2656 words: a list of lower-case words.
2659 the lower-case identifier.
2661 return '_'.join(words
)
2664 def ToUnderscore(input_string
):
2665 """converts CamelCase to camel_case."""
2666 words
= SplitWords(input_string
)
2669 def CachedStateName(item
):
2670 if item
.get('cached', False):
2671 return 'cached_' + item
['name']
2674 def ToGLExtensionString(extension_flag
):
2675 """Returns GL-type extension string of a extension flag."""
2676 if extension_flag
== "oes_compressed_etc1_rgb8_texture":
2677 return "OES_compressed_ETC1_RGB8_texture" # Fixup inconsitency with rgb8,
2679 uppercase_words
= [ 'img', 'ext', 'arb', 'chromium', 'oes', 'amd', 'bgra8888',
2680 'egl', 'atc', 'etc1', 'angle']
2681 parts
= extension_flag
.split('_')
2683 [part
.upper() if part
in uppercase_words
else part
for part
in parts
])
2685 def ToCamelCase(input_string
):
2686 """converts ABC_underscore_case to ABCUnderscoreCase."""
2687 return ''.join(w
[0].upper() + w
[1:] for w
in input_string
.split('_'))
2689 def GetGLGetTypeConversion(result_type
, value_type
, value
):
2690 """Makes a gl compatible type conversion string for accessing state variables.
2692 Useful when accessing state variables through glGetXXX calls.
2693 glGet documetation (for example, the manual pages):
2694 [...] If glGetIntegerv is called, [...] most floating-point values are
2695 rounded to the nearest integer value. [...]
2698 result_type: the gl type to be obtained
2699 value_type: the GL type of the state variable
2700 value: the name of the state variable
2703 String that converts the state variable to desired GL type according to GL
2707 if result_type
== 'GLint':
2708 if value_type
== 'GLfloat':
2709 return 'static_cast<GLint>(round(%s))' % value
2710 return 'static_cast<%s>(%s)' % (result_type
, value
)
2712 class CWriter(object):
2713 """Writes to a file formatting it for Google's style guidelines."""
2715 def __init__(self
, filename
):
2716 self
.filename
= filename
2719 def Write(self
, string
):
2720 """Writes a string to a file spliting if it's > 80 characters."""
2721 lines
= string
.splitlines()
2722 num_lines
= len(lines
)
2723 for ii
in range(0, num_lines
):
2724 self
.content
.append(lines
[ii
])
2725 if ii
< (num_lines
- 1) or string
[-1] == '\n':
2726 self
.content
.append('\n')
2729 """Close the file."""
2730 content
= "".join(self
.content
)
2732 if os
.path
.exists(self
.filename
):
2733 old_file
= open(self
.filename
, "rb");
2734 old_content
= old_file
.read()
2736 if content
== old_content
:
2739 file = open(self
.filename
, "wb")
2744 class CHeaderWriter(CWriter
):
2745 """Writes a C Header file."""
2747 _non_alnum_re
= re
.compile(r
'[^a-zA-Z0-9]')
2749 def __init__(self
, filename
, file_comment
= None):
2750 CWriter
.__init
__(self
, filename
)
2752 base
= os
.path
.abspath(filename
)
2753 while os
.path
.basename(base
) != 'src':
2754 new_base
= os
.path
.dirname(base
)
2755 assert new_base
!= base
# Prevent infinite loop.
2758 hpath
= os
.path
.relpath(filename
, base
)
2759 self
.guard
= self
._non
_alnum
_re
.sub('_', hpath
).upper() + '_'
2761 self
.Write(_LICENSE
)
2762 self
.Write(_DO_NOT_EDIT_WARNING
)
2763 if not file_comment
== None:
2764 self
.Write(file_comment
)
2765 self
.Write("#ifndef %s\n" % self
.guard
)
2766 self
.Write("#define %s\n\n" % self
.guard
)
2769 self
.Write("#endif // %s\n\n" % self
.guard
)
2772 class TypeHandler(object):
2773 """This class emits code for a particular type of function."""
2775 _remove_expected_call_re
= re
.compile(r
' EXPECT_CALL.*?;\n', re
.S
)
2780 def InitFunction(self
, func
):
2781 """Add or adjust anything type specific for this function."""
2782 if func
.GetInfo('needs_size') and not func
.name
.endswith('Bucket'):
2783 func
.AddCmdArg(DataSizeArgument('data_size'))
2785 def NeedsDataTransferFunction(self
, func
):
2786 """Overriden from TypeHandler."""
2787 return func
.num_pointer_args
>= 1
2789 def WriteStruct(self
, func
, file):
2790 """Writes a structure that matches the arguments to a function."""
2791 comment
= func
.GetInfo('cmd_comment')
2792 if not comment
== None:
2794 file.Write("struct %s {\n" % func
.name
)
2795 file.Write(" typedef %s ValueType;\n" % func
.name
)
2796 file.Write(" static const CommandId kCmdId = k%s;\n" % func
.name
)
2797 func
.WriteCmdArgFlag(file)
2798 func
.WriteCmdFlag(file)
2800 result
= func
.GetInfo('result')
2801 if not result
== None:
2802 if len(result
) == 1:
2803 file.Write(" typedef %s Result;\n\n" % result
[0])
2805 file.Write(" struct Result {\n")
2807 file.Write(" %s;\n" % line
)
2808 file.Write(" };\n\n")
2810 func
.WriteCmdComputeSize(file)
2811 func
.WriteCmdSetHeader(file)
2812 func
.WriteCmdInit(file)
2813 func
.WriteCmdSet(file)
2815 file.Write(" gpu::CommandHeader header;\n")
2816 args
= func
.GetCmdArgs()
2818 file.Write(" %s %s;\n" % (arg
.cmd_type
, arg
.name
))
2820 consts
= func
.GetCmdConstants()
2821 for const
in consts
:
2822 file.Write(" static const %s %s = %s;\n" %
2823 (const
.cmd_type
, const
.name
, const
.GetConstantValue()))
2828 size
= len(args
) * _SIZE_OF_UINT32
+ _SIZE_OF_COMMAND_HEADER
2829 file.Write("COMPILE_ASSERT(sizeof(%s) == %d,\n" % (func
.name
, size
))
2830 file.Write(" Sizeof_%s_is_not_%d);\n" % (func
.name
, size
))
2831 file.Write("COMPILE_ASSERT(offsetof(%s, header) == 0,\n" % func
.name
)
2832 file.Write(" OffsetOf_%s_header_not_0);\n" % func
.name
)
2833 offset
= _SIZE_OF_COMMAND_HEADER
2835 file.Write("COMPILE_ASSERT(offsetof(%s, %s) == %d,\n" %
2836 (func
.name
, arg
.name
, offset
))
2837 file.Write(" OffsetOf_%s_%s_not_%d);\n" %
2838 (func
.name
, arg
.name
, offset
))
2839 offset
+= _SIZE_OF_UINT32
2840 if not result
== None and len(result
) > 1:
2843 parts
= line
.split()
2846 COMPILE_ASSERT(offsetof(%(cmd_name)s::Result, %(field_name)s) == %(offset)d,
2847 OffsetOf_%(cmd_name)s_Result_%(field_name)s_not_%(offset)d);
2849 file.Write((check
.strip() + "\n") % {
2850 'cmd_name': func
.name
,
2854 offset
+= _SIZE_OF_UINT32
2857 def WriteHandlerImplementation(self
, func
, file):
2858 """Writes the handler implementation for this command."""
2859 file.Write(" %s(%s);\n" %
2860 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
2862 def WriteCmdSizeTest(self
, func
, file):
2863 """Writes the size test for a command."""
2864 file.Write(" EXPECT_EQ(sizeof(cmd), cmd.header.size * 4u);\n")
2866 def WriteFormatTest(self
, func
, file):
2867 """Writes a format test for a command."""
2868 file.Write("TEST_F(GLES2FormatTest, %s) {\n" % func
.name
)
2869 file.Write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
2870 (func
.name
, func
.name
))
2871 file.Write(" void* next_cmd = cmd.Set(\n")
2873 args
= func
.GetCmdArgs()
2874 for value
, arg
in enumerate(args
):
2875 file.Write(",\n static_cast<%s>(%d)" % (arg
.type, value
+ 11))
2877 file.Write(" EXPECT_EQ(static_cast<uint32_t>(cmds::%s::kCmdId),\n" %
2879 file.Write(" cmd.header.command);\n")
2880 func
.type_handler
.WriteCmdSizeTest(func
, file)
2881 for value
, arg
in enumerate(args
):
2882 file.Write(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);\n" %
2883 (arg
.type, value
+ 11, arg
.name
))
2884 file.Write(" CheckBytesWrittenMatchesExpectedSize(\n")
2885 file.Write(" next_cmd, sizeof(cmd));\n")
2889 def WriteImmediateFormatTest(self
, func
, file):
2890 """Writes a format test for an immediate version of a command."""
2893 def WriteBucketFormatTest(self
, func
, file):
2894 """Writes a format test for a bucket version of a command."""
2897 def WriteGetDataSizeCode(self
, func
, file):
2898 """Writes the code to set data_size used in validation"""
2901 def WriteImmediateCmdSizeTest(self
, func
, file):
2902 """Writes a size test for an immediate version of a command."""
2903 file.Write(" // TODO(gman): Compute correct size.\n")
2904 file.Write(" EXPECT_EQ(sizeof(cmd), cmd.header.size * 4u);\n")
2906 def WriteImmediateHandlerImplementation (self
, func
, file):
2907 """Writes the handler impl for the immediate version of a command."""
2908 file.Write(" %s(%s);\n" %
2909 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
2911 def WriteBucketHandlerImplementation (self
, func
, file):
2912 """Writes the handler impl for the bucket version of a command."""
2913 file.Write(" %s(%s);\n" %
2914 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
2916 def WriteServiceHandlerFunctionHeader(self
, func
, file):
2917 """Writes function header for service implementation handlers."""
2918 file.Write("""error::Error GLES2DecoderImpl::Handle%(name)s(
2919 uint32_t immediate_data_size, const void* cmd_data) {
2920 const gles2::cmds::%(name)s& c =
2921 *static_cast<const gles2::cmds::%(name)s*>(cmd_data);
2923 """ % {'name': func
.name
})
2925 def WriteServiceImplementation(self
, func
, file):
2926 """Writes the service implementation for a command."""
2927 self
.WriteServiceHandlerFunctionHeader(func
, file)
2928 self
.WriteHandlerExtensionCheck(func
, file)
2929 self
.WriteHandlerDeferReadWrite(func
, file);
2930 if len(func
.GetOriginalArgs()) > 0:
2931 last_arg
= func
.GetLastOriginalArg()
2932 all_but_last_arg
= func
.GetOriginalArgs()[:-1]
2933 for arg
in all_but_last_arg
:
2934 arg
.WriteGetCode(file)
2935 self
.WriteGetDataSizeCode(func
, file)
2936 last_arg
.WriteGetCode(file)
2937 func
.WriteHandlerValidation(file)
2938 func
.WriteHandlerImplementation(file)
2939 file.Write(" return error::kNoError;\n")
2943 def WriteImmediateServiceImplementation(self
, func
, file):
2944 """Writes the service implementation for an immediate version of command."""
2945 self
.WriteServiceHandlerFunctionHeader(func
, file)
2946 self
.WriteHandlerExtensionCheck(func
, file)
2947 self
.WriteHandlerDeferReadWrite(func
, file);
2948 last_arg
= func
.GetLastOriginalArg()
2949 all_but_last_arg
= func
.GetOriginalArgs()[:-1]
2950 for arg
in all_but_last_arg
:
2951 arg
.WriteGetCode(file)
2952 self
.WriteGetDataSizeCode(func
, file)
2953 last_arg
.WriteGetCode(file)
2954 func
.WriteHandlerValidation(file)
2955 func
.WriteHandlerImplementation(file)
2956 file.Write(" return error::kNoError;\n")
2960 def WriteBucketServiceImplementation(self
, func
, file):
2961 """Writes the service implementation for a bucket version of command."""
2962 self
.WriteServiceHandlerFunctionHeader(func
, file)
2963 self
.WriteHandlerExtensionCheck(func
, file)
2964 self
.WriteHandlerDeferReadWrite(func
, file);
2965 last_arg
= func
.GetLastOriginalArg()
2966 all_but_last_arg
= func
.GetOriginalArgs()[:-1]
2967 for arg
in all_but_last_arg
:
2968 arg
.WriteGetCode(file)
2969 self
.WriteGetDataSizeCode(func
, file)
2970 last_arg
.WriteGetCode(file)
2971 func
.WriteHandlerValidation(file)
2972 func
.WriteHandlerImplementation(file)
2973 file.Write(" return error::kNoError;\n")
2977 def WriteHandlerExtensionCheck(self
, func
, file):
2978 if func
.GetInfo('extension_flag'):
2979 file.Write(" if (!features().%s) {\n" % func
.GetInfo('extension_flag'))
2980 file.Write(" LOCAL_SET_GL_ERROR(GL_INVALID_OPERATION, \"gl%s\","
2981 " \"function not available\");\n" % func
.original_name
)
2982 file.Write(" return error::kNoError;")
2983 file.Write(" }\n\n")
2985 def WriteHandlerDeferReadWrite(self
, func
, file):
2986 """Writes the code to handle deferring reads or writes."""
2987 defer_draws
= func
.GetInfo('defer_draws')
2988 defer_reads
= func
.GetInfo('defer_reads')
2989 if defer_draws
or defer_reads
:
2990 file.Write(" error::Error error;\n")
2992 file.Write(" error = WillAccessBoundFramebufferForDraw();\n")
2993 file.Write(" if (error != error::kNoError)\n")
2994 file.Write(" return error;\n")
2996 file.Write(" error = WillAccessBoundFramebufferForRead();\n")
2997 file.Write(" if (error != error::kNoError)\n")
2998 file.Write(" return error;\n")
3000 def WriteValidUnitTest(self
, func
, file, test
, *extras
):
3001 """Writes a valid unit test for the service implementation."""
3002 if func
.GetInfo('expectation') == False:
3003 test
= self
._remove
_expected
_call
_re
.sub('', test
)
3006 arg
.GetValidArg(func
) \
3007 for arg
in func
.GetOriginalArgs() if not arg
.IsConstant()
3010 arg
.GetValidGLArg(func
) \
3011 for arg
in func
.GetOriginalArgs()
3013 gl_func_name
= func
.GetGLTestFunctionName()
3016 'gl_func_name': gl_func_name
,
3017 'args': ", ".join(arg_strings
),
3018 'gl_args': ", ".join(gl_arg_strings
),
3020 for extra
in extras
:
3023 while (old_test
!= test
):
3026 file.Write(test
% vars)
3028 def WriteInvalidUnitTest(self
, func
, file, test
, *extras
):
3029 """Writes an invalid unit test for the service implementation."""
3030 for invalid_arg_index
, invalid_arg
in enumerate(func
.GetOriginalArgs()):
3031 # Service implementation does not test constants, as they are not part of
3032 # the call in the service side.
3033 if invalid_arg
.IsConstant():
3036 num_invalid_values
= invalid_arg
.GetNumInvalidValues(func
)
3037 for value_index
in range(0, num_invalid_values
):
3039 parse_result
= "kNoError"
3041 for arg
in func
.GetOriginalArgs():
3042 if arg
.IsConstant():
3044 if invalid_arg
is arg
:
3045 (arg_string
, parse_result
, gl_error
) = arg
.GetInvalidArg(
3048 arg_string
= arg
.GetValidArg(func
)
3049 arg_strings
.append(arg_string
)
3051 for arg
in func
.GetOriginalArgs():
3052 gl_arg_strings
.append("_")
3053 gl_func_name
= func
.GetGLTestFunctionName()
3055 if not gl_error
== None:
3056 gl_error_test
= '\n EXPECT_EQ(%s, GetGLError());' % gl_error
3060 'arg_index': invalid_arg_index
,
3061 'value_index': value_index
,
3062 'gl_func_name': gl_func_name
,
3063 'args': ", ".join(arg_strings
),
3064 'all_but_last_args': ", ".join(arg_strings
[:-1]),
3065 'gl_args': ", ".join(gl_arg_strings
),
3066 'parse_result': parse_result
,
3067 'gl_error_test': gl_error_test
,
3069 for extra
in extras
:
3071 file.Write(test
% vars)
3073 def WriteServiceUnitTest(self
, func
, file, *extras
):
3074 """Writes the service unit test for a command."""
3076 if func
.name
== 'Enable':
3078 TEST_P(%(test_name)s, %(name)sValidArgs) {
3079 SetupExpectationsForEnableDisable(%(gl_args)s, true);
3080 SpecializedSetup<cmds::%(name)s, 0>(true);
3083 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
3084 EXPECT_EQ(GL_NO_ERROR, GetGLError());
3087 elif func
.name
== 'Disable':
3089 TEST_P(%(test_name)s, %(name)sValidArgs) {
3090 SetupExpectationsForEnableDisable(%(gl_args)s, false);
3091 SpecializedSetup<cmds::%(name)s, 0>(true);
3094 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
3095 EXPECT_EQ(GL_NO_ERROR, GetGLError());
3100 TEST_P(%(test_name)s, %(name)sValidArgs) {
3101 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
3102 SpecializedSetup<cmds::%(name)s, 0>(true);
3105 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
3106 EXPECT_EQ(GL_NO_ERROR, GetGLError());
3109 self
.WriteValidUnitTest(func
, file, valid_test
, *extras
)
3112 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
3113 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
3114 SpecializedSetup<cmds::%(name)s, 0>(false);
3117 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
3120 self
.WriteInvalidUnitTest(func
, file, invalid_test
, *extras
)
3122 def WriteImmediateServiceUnitTest(self
, func
, file, *extras
):
3123 """Writes the service unit test for an immediate command."""
3124 file.Write("// TODO(gman): %s\n" % func
.name
)
3126 def WriteImmediateValidationCode(self
, func
, file):
3127 """Writes the validation code for an immediate version of a command."""
3130 def WriteBucketServiceUnitTest(self
, func
, file, *extras
):
3131 """Writes the service unit test for a bucket command."""
3132 file.Write("// TODO(gman): %s\n" % func
.name
)
3134 def WriteBucketValidationCode(self
, func
, file):
3135 """Writes the validation code for a bucket version of a command."""
3136 file.Write("// TODO(gman): %s\n" % func
.name
)
3138 def WriteGLES2ImplementationDeclaration(self
, func
, file):
3139 """Writes the GLES2 Implemention declaration."""
3140 impl_decl
= func
.GetInfo('impl_decl')
3141 if impl_decl
== None or impl_decl
== True:
3142 file.Write("virtual %s %s(%s) override;\n" %
3143 (func
.return_type
, func
.original_name
,
3144 func
.MakeTypedOriginalArgString("")))
3147 def WriteGLES2CLibImplementation(self
, func
, file):
3148 file.Write("%s GLES2%s(%s) {\n" %
3149 (func
.return_type
, func
.name
,
3150 func
.MakeTypedOriginalArgString("")))
3151 result_string
= "return "
3152 if func
.return_type
== "void":
3154 file.Write(" %sgles2::GetGLContext()->%s(%s);\n" %
3155 (result_string
, func
.original_name
,
3156 func
.MakeOriginalArgString("")))
3159 def WriteGLES2Header(self
, func
, file):
3160 """Writes a re-write macro for GLES"""
3161 file.Write("#define gl%s GLES2_GET_FUN(%s)\n" %(func
.name
, func
.name
))
3163 def WriteClientGLCallLog(self
, func
, file):
3164 """Writes a logging macro for the client side code."""
3166 if len(func
.GetOriginalArgs()):
3169 ' GPU_CLIENT_LOG("[" << GetLogPrefix() << "] gl%s("%s%s << ")");\n' %
3170 (func
.original_name
, comma
, func
.MakeLogArgString()))
3172 def WriteClientGLReturnLog(self
, func
, file):
3173 """Writes the return value logging code."""
3174 if func
.return_type
!= "void":
3175 file.Write(' GPU_CLIENT_LOG("return:" << result)\n')
3177 def WriteGLES2ImplementationHeader(self
, func
, file):
3178 """Writes the GLES2 Implemention."""
3179 self
.WriteGLES2ImplementationDeclaration(func
, file)
3181 def WriteGLES2TraceImplementationHeader(self
, func
, file):
3182 """Writes the GLES2 Trace Implemention header."""
3183 file.Write("virtual %s %s(%s) override;\n" %
3184 (func
.return_type
, func
.original_name
,
3185 func
.MakeTypedOriginalArgString("")))
3187 def WriteGLES2TraceImplementation(self
, func
, file):
3188 """Writes the GLES2 Trace Implemention."""
3189 file.Write("%s GLES2TraceImplementation::%s(%s) {\n" %
3190 (func
.return_type
, func
.original_name
,
3191 func
.MakeTypedOriginalArgString("")))
3192 result_string
= "return "
3193 if func
.return_type
== "void":
3195 file.Write(' TRACE_EVENT_BINARY_EFFICIENT0("gpu", "GLES2Trace::%s");\n' %
3197 file.Write(" %sgl_->%s(%s);\n" %
3198 (result_string
, func
.name
, func
.MakeOriginalArgString("")))
3202 def WriteGLES2Implementation(self
, func
, file):
3203 """Writes the GLES2 Implemention."""
3204 impl_func
= func
.GetInfo('impl_func')
3205 impl_decl
= func
.GetInfo('impl_decl')
3206 gen_cmd
= func
.GetInfo('gen_cmd')
3207 if (func
.can_auto_generate
and
3208 (impl_func
== None or impl_func
== True) and
3209 (impl_decl
== None or impl_decl
== True) and
3210 (gen_cmd
== None or gen_cmd
== True)):
3211 file.Write("%s GLES2Implementation::%s(%s) {\n" %
3212 (func
.return_type
, func
.original_name
,
3213 func
.MakeTypedOriginalArgString("")))
3214 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
3215 self
.WriteClientGLCallLog(func
, file)
3216 func
.WriteDestinationInitalizationValidation(file)
3217 for arg
in func
.GetOriginalArgs():
3218 arg
.WriteClientSideValidationCode(file, func
)
3219 file.Write(" helper_->%s(%s);\n" %
3220 (func
.name
, func
.MakeHelperArgString("")))
3221 file.Write(" CheckGLError();\n")
3222 self
.WriteClientGLReturnLog(func
, file)
3226 def WriteGLES2InterfaceHeader(self
, func
, file):
3227 """Writes the GLES2 Interface."""
3228 file.Write("virtual %s %s(%s) = 0;\n" %
3229 (func
.return_type
, func
.original_name
,
3230 func
.MakeTypedOriginalArgString("")))
3232 def WriteGLES2InterfaceStub(self
, func
, file):
3233 """Writes the GLES2 Interface stub declaration."""
3234 file.Write("virtual %s %s(%s) override;\n" %
3235 (func
.return_type
, func
.original_name
,
3236 func
.MakeTypedOriginalArgString("")))
3238 def WriteGLES2InterfaceStubImpl(self
, func
, file):
3239 """Writes the GLES2 Interface stub declaration."""
3240 args
= func
.GetOriginalArgs()
3241 arg_string
= ", ".join(
3242 ["%s /* %s */" % (arg
.type, arg
.name
) for arg
in args
])
3243 file.Write("%s GLES2InterfaceStub::%s(%s) {\n" %
3244 (func
.return_type
, func
.original_name
, arg_string
))
3245 if func
.return_type
!= "void":
3246 file.Write(" return 0;\n")
3249 def WriteGLES2ImplementationUnitTest(self
, func
, file):
3250 """Writes the GLES2 Implemention unit test."""
3251 client_test
= func
.GetInfo('client_test')
3252 if (func
.can_auto_generate
and
3253 (client_test
== None or client_test
== True)):
3255 TEST_F(GLES2ImplementationTest, %(name)s) {
3260 expected.cmd.Init(%(cmd_args)s);
3262 gl_->%(name)s(%(args)s);
3263 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
3267 arg
.GetValidClientSideCmdArg(func
) for arg
in func
.GetCmdArgs()
3271 arg
.GetValidClientSideArg(func
) for arg
in func
.GetOriginalArgs()
3276 'args': ", ".join(gl_arg_strings
),
3277 'cmd_args': ", ".join(cmd_arg_strings
),
3280 # Test constants for invalid values, as they are not tested by the
3282 constants
= [arg
for arg
in func
.GetOriginalArgs() if arg
.IsConstant()]
3285 TEST_F(GLES2ImplementationTest, %(name)sInvalidConstantArg%(invalid_index)d) {
3286 gl_->%(name)s(%(args)s);
3287 EXPECT_TRUE(NoCommandsWritten());
3288 EXPECT_EQ(%(gl_error)s, CheckError());
3291 for invalid_arg
in constants
:
3293 invalid
= invalid_arg
.GetInvalidArg(func
)
3294 for arg
in func
.GetOriginalArgs():
3295 if arg
is invalid_arg
:
3296 gl_arg_strings
.append(invalid
[0])
3298 gl_arg_strings
.append(arg
.GetValidClientSideArg(func
))
3302 'invalid_index': func
.GetOriginalArgs().index(invalid_arg
),
3303 'args': ", ".join(gl_arg_strings
),
3304 'gl_error': invalid
[2],
3307 if client_test
!= False:
3308 file.Write("// TODO: Implement unit test for %s\n" % func
.name
)
3310 def WriteDestinationInitalizationValidation(self
, func
, file):
3311 """Writes the client side destintion initialization validation."""
3312 for arg
in func
.GetOriginalArgs():
3313 arg
.WriteDestinationInitalizationValidation(file, func
)
3315 def WriteTraceEvent(self
, func
, file):
3316 file.Write(' TRACE_EVENT0("gpu", "GLES2Implementation::%s");\n' %
3319 def WriteImmediateCmdComputeSize(self
, func
, file):
3320 """Writes the size computation code for the immediate version of a cmd."""
3321 file.Write(" static uint32_t ComputeSize(uint32_t size_in_bytes) {\n")
3322 file.Write(" return static_cast<uint32_t>(\n")
3323 file.Write(" sizeof(ValueType) + // NOLINT\n")
3324 file.Write(" RoundSizeToMultipleOfEntries(size_in_bytes));\n")
3328 def WriteImmediateCmdSetHeader(self
, func
, file):
3329 """Writes the SetHeader function for the immediate version of a cmd."""
3330 file.Write(" void SetHeader(uint32_t size_in_bytes) {\n")
3331 file.Write(" header.SetCmdByTotalSize<ValueType>(size_in_bytes);\n")
3335 def WriteImmediateCmdInit(self
, func
, file):
3336 """Writes the Init function for the immediate version of a command."""
3337 raise NotImplementedError(func
.name
)
3339 def WriteImmediateCmdSet(self
, func
, file):
3340 """Writes the Set function for the immediate version of a command."""
3341 raise NotImplementedError(func
.name
)
3343 def WriteCmdHelper(self
, func
, file):
3344 """Writes the cmd helper definition for a cmd."""
3345 code
= """ void %(name)s(%(typed_args)s) {
3346 gles2::cmds::%(name)s* c = GetCmdSpace<gles2::cmds::%(name)s>();
3355 "typed_args": func
.MakeTypedCmdArgString(""),
3356 "args": func
.MakeCmdArgString(""),
3359 def WriteImmediateCmdHelper(self
, func
, file):
3360 """Writes the cmd helper definition for the immediate version of a cmd."""
3361 code
= """ void %(name)s(%(typed_args)s) {
3362 const uint32_t s = 0; // TODO(gman): compute correct size
3363 gles2::cmds::%(name)s* c =
3364 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(s);
3373 "typed_args": func
.MakeTypedCmdArgString(""),
3374 "args": func
.MakeCmdArgString(""),
3378 class StateSetHandler(TypeHandler
):
3379 """Handler for commands that simply set state."""
3382 TypeHandler
.__init
__(self
)
3384 def WriteHandlerImplementation(self
, func
, file):
3385 """Overrriden from TypeHandler."""
3386 state_name
= func
.GetInfo('state')
3387 state
= _STATES
[state_name
]
3388 states
= state
['states']
3389 args
= func
.GetOriginalArgs()
3390 for ndx
,item
in enumerate(states
):
3392 if 'range_checks' in item
:
3393 for range_check
in item
['range_checks']:
3394 code
.append("%s %s" % (args
[ndx
].name
, range_check
['check']))
3395 if 'nan_check' in item
:
3396 # Drivers might generate an INVALID_VALUE error when a value is set
3397 # to NaN. This is allowed behavior under GLES 3.0 section 2.1.1 or
3398 # OpenGL 4.5 section 2.3.4.1 - providing NaN allows undefined results.
3399 # Make this behavior consistent within Chromium, and avoid leaking GL
3400 # errors by generating the error in the command buffer instead of
3401 # letting the GL driver generate it.
3402 code
.append("base::IsNaN(%s)" % args
[ndx
].name
)
3404 file.Write(" if (%s) {\n" % " ||\n ".join(code
))
3406 ' LOCAL_SET_GL_ERROR(GL_INVALID_VALUE,'
3407 ' "%s", "%s out of range");\n' %
3408 (func
.name
, args
[ndx
].name
))
3409 file.Write(" return error::kNoError;\n")
3412 for ndx
,item
in enumerate(states
):
3413 code
.append("state_.%s != %s" % (item
['name'], args
[ndx
].name
))
3414 file.Write(" if (%s) {\n" % " ||\n ".join(code
))
3415 for ndx
,item
in enumerate(states
):
3416 file.Write(" state_.%s = %s;\n" % (item
['name'], args
[ndx
].name
))
3417 if 'state_flag' in state
:
3418 file.Write(" %s = true;\n" % state
['state_flag'])
3419 if not func
.GetInfo("no_gl"):
3420 for ndx
,item
in enumerate(states
):
3421 if item
.get('cached', False):
3422 file.Write(" state_.%s = %s;\n" %
3423 (CachedStateName(item
), args
[ndx
].name
))
3424 file.Write(" %s(%s);\n" %
3425 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
3428 def WriteServiceUnitTest(self
, func
, file, *extras
):
3429 """Overrriden from TypeHandler."""
3430 TypeHandler
.WriteServiceUnitTest(self
, func
, file, *extras
)
3431 state_name
= func
.GetInfo('state')
3432 state
= _STATES
[state_name
]
3433 states
= state
['states']
3434 for ndx
,item
in enumerate(states
):
3435 if 'range_checks' in item
:
3436 for check_ndx
, range_check
in enumerate(item
['range_checks']):
3438 TEST_P(%(test_name)s, %(name)sInvalidValue%(ndx)d_%(check_ndx)d) {
3439 SpecializedSetup<cmds::%(name)s, 0>(false);
3442 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
3443 EXPECT_EQ(GL_INVALID_VALUE, GetGLError());
3448 arg
.GetValidArg(func
) \
3449 for arg
in func
.GetOriginalArgs() if not arg
.IsConstant()
3452 arg_strings
[ndx
] = range_check
['test_value']
3456 'check_ndx': check_ndx
,
3457 'args': ", ".join(arg_strings
),
3459 for extra
in extras
:
3461 file.Write(valid_test
% vars)
3462 if 'nan_check' in item
:
3464 TEST_P(%(test_name)s, %(name)sNaNValue%(ndx)d) {
3465 SpecializedSetup<cmds::%(name)s, 0>(false);
3468 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
3469 EXPECT_EQ(GL_INVALID_VALUE, GetGLError());
3474 arg
.GetValidArg(func
) \
3475 for arg
in func
.GetOriginalArgs() if not arg
.IsConstant()
3478 arg_strings
[ndx
] = 'nanf("")'
3482 'args': ", ".join(arg_strings
),
3484 for extra
in extras
:
3486 file.Write(valid_test
% vars)
3489 class StateSetRGBAlphaHandler(TypeHandler
):
3490 """Handler for commands that simply set state that have rgb/alpha."""
3493 TypeHandler
.__init
__(self
)
3495 def WriteHandlerImplementation(self
, func
, file):
3496 """Overrriden from TypeHandler."""
3497 state_name
= func
.GetInfo('state')
3498 state
= _STATES
[state_name
]
3499 states
= state
['states']
3500 args
= func
.GetOriginalArgs()
3501 num_args
= len(args
)
3503 for ndx
,item
in enumerate(states
):
3504 code
.append("state_.%s != %s" % (item
['name'], args
[ndx
% num_args
].name
))
3505 file.Write(" if (%s) {\n" % " ||\n ".join(code
))
3506 for ndx
, item
in enumerate(states
):
3507 file.Write(" state_.%s = %s;\n" %
3508 (item
['name'], args
[ndx
% num_args
].name
))
3509 if 'state_flag' in state
:
3510 file.Write(" %s = true;\n" % state
['state_flag'])
3511 if not func
.GetInfo("no_gl"):
3512 file.Write(" %s(%s);\n" %
3513 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
3517 class StateSetFrontBackSeparateHandler(TypeHandler
):
3518 """Handler for commands that simply set state that have front/back."""
3521 TypeHandler
.__init
__(self
)
3523 def WriteHandlerImplementation(self
, func
, file):
3524 """Overrriden from TypeHandler."""
3525 state_name
= func
.GetInfo('state')
3526 state
= _STATES
[state_name
]
3527 states
= state
['states']
3528 args
= func
.GetOriginalArgs()
3530 num_args
= len(args
)
3531 file.Write(" bool changed = false;\n")
3532 for group_ndx
, group
in enumerate(Grouper(num_args
- 1, states
)):
3533 file.Write(" if (%s == %s || %s == GL_FRONT_AND_BACK) {\n" %
3534 (face
, ('GL_FRONT', 'GL_BACK')[group_ndx
], face
))
3536 for ndx
, item
in enumerate(group
):
3537 code
.append("state_.%s != %s" % (item
['name'], args
[ndx
+ 1].name
))
3538 file.Write(" changed |= %s;\n" % " ||\n ".join(code
))
3540 file.Write(" if (changed) {\n")
3541 for group_ndx
, group
in enumerate(Grouper(num_args
- 1, states
)):
3542 file.Write(" if (%s == %s || %s == GL_FRONT_AND_BACK) {\n" %
3543 (face
, ('GL_FRONT', 'GL_BACK')[group_ndx
], face
))
3544 for ndx
, item
in enumerate(group
):
3545 file.Write(" state_.%s = %s;\n" %
3546 (item
['name'], args
[ndx
+ 1].name
))
3548 if 'state_flag' in state
:
3549 file.Write(" %s = true;\n" % state
['state_flag'])
3550 if not func
.GetInfo("no_gl"):
3551 file.Write(" %s(%s);\n" %
3552 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
3556 class StateSetFrontBackHandler(TypeHandler
):
3557 """Handler for commands that simply set state that set both front/back."""
3560 TypeHandler
.__init
__(self
)
3562 def WriteHandlerImplementation(self
, func
, file):
3563 """Overrriden from TypeHandler."""
3564 state_name
= func
.GetInfo('state')
3565 state
= _STATES
[state_name
]
3566 states
= state
['states']
3567 args
= func
.GetOriginalArgs()
3568 num_args
= len(args
)
3570 for group_ndx
, group
in enumerate(Grouper(num_args
, states
)):
3571 for ndx
, item
in enumerate(group
):
3572 code
.append("state_.%s != %s" % (item
['name'], args
[ndx
].name
))
3573 file.Write(" if (%s) {\n" % " ||\n ".join(code
))
3574 for group_ndx
, group
in enumerate(Grouper(num_args
, states
)):
3575 for ndx
, item
in enumerate(group
):
3576 file.Write(" state_.%s = %s;\n" % (item
['name'], args
[ndx
].name
))
3577 if 'state_flag' in state
:
3578 file.Write(" %s = true;\n" % state
['state_flag'])
3579 if not func
.GetInfo("no_gl"):
3580 file.Write(" %s(%s);\n" %
3581 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
3585 class StateSetNamedParameter(TypeHandler
):
3586 """Handler for commands that set a state chosen with an enum parameter."""
3589 TypeHandler
.__init
__(self
)
3591 def WriteHandlerImplementation(self
, func
, file):
3592 """Overridden from TypeHandler."""
3593 state_name
= func
.GetInfo('state')
3594 state
= _STATES
[state_name
]
3595 states
= state
['states']
3596 args
= func
.GetOriginalArgs()
3597 num_args
= len(args
)
3598 assert num_args
== 2
3599 file.Write(" switch (%s) {\n" % args
[0].name
)
3600 for state
in states
:
3601 file.Write(" case %s:\n" % state
['enum'])
3602 file.Write(" if (state_.%s != %s) {\n" %
3603 (state
['name'], args
[1].name
))
3604 file.Write(" state_.%s = %s;\n" % (state
['name'], args
[1].name
))
3605 if not func
.GetInfo("no_gl"):
3606 file.Write(" %s(%s);\n" %
3607 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
3609 file.Write(" break;\n")
3610 file.Write(" default:\n")
3611 file.Write(" NOTREACHED();\n")
3615 class CustomHandler(TypeHandler
):
3616 """Handler for commands that are auto-generated but require minor tweaks."""
3619 TypeHandler
.__init
__(self
)
3621 def WriteServiceImplementation(self
, func
, file):
3622 """Overrriden from TypeHandler."""
3625 def WriteImmediateServiceImplementation(self
, func
, file):
3626 """Overrriden from TypeHandler."""
3629 def WriteBucketServiceImplementation(self
, func
, file):
3630 """Overrriden from TypeHandler."""
3633 def WriteServiceUnitTest(self
, func
, file, *extras
):
3634 """Overrriden from TypeHandler."""
3635 file.Write("// TODO(gman): %s\n\n" % func
.name
)
3637 def WriteImmediateServiceUnitTest(self
, func
, file, *extras
):
3638 """Overrriden from TypeHandler."""
3639 file.Write("// TODO(gman): %s\n\n" % func
.name
)
3641 def WriteImmediateCmdGetTotalSize(self
, func
, file):
3642 """Overrriden from TypeHandler."""
3644 " uint32_t total_size = 0; // TODO(gman): get correct size.\n")
3646 def WriteImmediateCmdInit(self
, func
, file):
3647 """Overrriden from TypeHandler."""
3648 file.Write(" void Init(%s) {\n" % func
.MakeTypedCmdArgString("_"))
3649 self
.WriteImmediateCmdGetTotalSize(func
, file)
3650 file.Write(" SetHeader(total_size);\n")
3651 args
= func
.GetCmdArgs()
3653 file.Write(" %s = _%s;\n" % (arg
.name
, arg
.name
))
3657 def WriteImmediateCmdSet(self
, func
, file):
3658 """Overrriden from TypeHandler."""
3659 copy_args
= func
.MakeCmdArgString("_", False)
3660 file.Write(" void* Set(void* cmd%s) {\n" %
3661 func
.MakeTypedCmdArgString("_", True))
3662 self
.WriteImmediateCmdGetTotalSize(func
, file)
3663 file.Write(" static_cast<ValueType*>(cmd)->Init(%s);\n" % copy_args
)
3664 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
3665 "cmd, total_size);\n")
3670 class TodoHandler(CustomHandler
):
3671 """Handle for commands that are not yet implemented."""
3673 def NeedsDataTransferFunction(self
, func
):
3674 """Overriden from TypeHandler."""
3677 def WriteImmediateFormatTest(self
, func
, file):
3678 """Overrriden from TypeHandler."""
3681 def WriteGLES2ImplementationUnitTest(self
, func
, file):
3682 """Overrriden from TypeHandler."""
3685 def WriteGLES2Implementation(self
, func
, file):
3686 """Overrriden from TypeHandler."""
3687 file.Write("%s GLES2Implementation::%s(%s) {\n" %
3688 (func
.return_type
, func
.original_name
,
3689 func
.MakeTypedOriginalArgString("")))
3690 file.Write(" // TODO: for now this is a no-op\n")
3693 "GL_INVALID_OPERATION, \"gl%s\", \"not implemented\");\n" %
3695 if func
.return_type
!= "void":
3696 file.Write(" return 0;\n")
3700 def WriteServiceImplementation(self
, func
, file):
3701 """Overrriden from TypeHandler."""
3702 self
.WriteServiceHandlerFunctionHeader(func
, file)
3703 file.Write(" // TODO: for now this is a no-op\n")
3705 " LOCAL_SET_GL_ERROR("
3706 "GL_INVALID_OPERATION, \"gl%s\", \"not implemented\");\n" %
3708 file.Write(" return error::kNoError;\n")
3713 class HandWrittenHandler(CustomHandler
):
3714 """Handler for comands where everything must be written by hand."""
3716 def InitFunction(self
, func
):
3717 """Add or adjust anything type specific for this function."""
3718 CustomHandler
.InitFunction(self
, func
)
3719 func
.can_auto_generate
= False
3721 def NeedsDataTransferFunction(self
, func
):
3722 """Overriden from TypeHandler."""
3723 # If specified explicitly, force the data transfer method.
3724 if func
.GetInfo('data_transfer_methods'):
3728 def WriteStruct(self
, func
, file):
3729 """Overrriden from TypeHandler."""
3732 def WriteDocs(self
, func
, file):
3733 """Overrriden from TypeHandler."""
3736 def WriteServiceUnitTest(self
, func
, file, *extras
):
3737 """Overrriden from TypeHandler."""
3738 file.Write("// TODO(gman): %s\n\n" % func
.name
)
3740 def WriteImmediateServiceUnitTest(self
, func
, file, *extras
):
3741 """Overrriden from TypeHandler."""
3742 file.Write("// TODO(gman): %s\n\n" % func
.name
)
3744 def WriteBucketServiceUnitTest(self
, func
, file, *extras
):
3745 """Overrriden from TypeHandler."""
3746 file.Write("// TODO(gman): %s\n\n" % func
.name
)
3748 def WriteServiceImplementation(self
, func
, file):
3749 """Overrriden from TypeHandler."""
3752 def WriteImmediateServiceImplementation(self
, func
, file):
3753 """Overrriden from TypeHandler."""
3756 def WriteBucketServiceImplementation(self
, func
, file):
3757 """Overrriden from TypeHandler."""
3760 def WriteImmediateCmdHelper(self
, func
, file):
3761 """Overrriden from TypeHandler."""
3764 def WriteBucketCmdHelper(self
, func
, file):
3765 """Overrriden from TypeHandler."""
3768 def WriteCmdHelper(self
, func
, file):
3769 """Overrriden from TypeHandler."""
3772 def WriteFormatTest(self
, func
, file):
3773 """Overrriden from TypeHandler."""
3774 file.Write("// TODO(gman): Write test for %s\n" % func
.name
)
3776 def WriteImmediateFormatTest(self
, func
, file):
3777 """Overrriden from TypeHandler."""
3778 file.Write("// TODO(gman): Write test for %s\n" % func
.name
)
3780 def WriteBucketFormatTest(self
, func
, file):
3781 """Overrriden from TypeHandler."""
3782 file.Write("// TODO(gman): Write test for %s\n" % func
.name
)
3786 class ManualHandler(CustomHandler
):
3787 """Handler for commands who's handlers must be written by hand."""
3790 CustomHandler
.__init
__(self
)
3792 def InitFunction(self
, func
):
3793 """Overrriden from TypeHandler."""
3794 if (func
.name
== 'CompressedTexImage2DBucket'):
3795 func
.cmd_args
= func
.cmd_args
[:-1]
3796 func
.AddCmdArg(Argument('bucket_id', 'GLuint'))
3798 CustomHandler
.InitFunction(self
, func
)
3800 def WriteServiceImplementation(self
, func
, file):
3801 """Overrriden from TypeHandler."""
3804 def WriteBucketServiceImplementation(self
, func
, file):
3805 """Overrriden from TypeHandler."""
3808 def WriteServiceUnitTest(self
, func
, file, *extras
):
3809 """Overrriden from TypeHandler."""
3810 file.Write("// TODO(gman): %s\n\n" % func
.name
)
3812 def WriteImmediateServiceUnitTest(self
, func
, file, *extras
):
3813 """Overrriden from TypeHandler."""
3814 file.Write("// TODO(gman): %s\n\n" % func
.name
)
3816 def WriteImmediateServiceImplementation(self
, func
, file):
3817 """Overrriden from TypeHandler."""
3820 def WriteImmediateFormatTest(self
, func
, file):
3821 """Overrriden from TypeHandler."""
3822 file.Write("// TODO(gman): Implement test for %s\n" % func
.name
)
3824 def WriteGLES2Implementation(self
, func
, file):
3825 """Overrriden from TypeHandler."""
3826 if func
.GetInfo('impl_func'):
3827 super(ManualHandler
, self
).WriteGLES2Implementation(func
, file)
3829 def WriteGLES2ImplementationHeader(self
, func
, file):
3830 """Overrriden from TypeHandler."""
3831 file.Write("virtual %s %s(%s) override;\n" %
3832 (func
.return_type
, func
.original_name
,
3833 func
.MakeTypedOriginalArgString("")))
3836 def WriteImmediateCmdGetTotalSize(self
, func
, file):
3837 """Overrriden from TypeHandler."""
3838 # TODO(gman): Move this data to _FUNCTION_INFO?
3839 CustomHandler
.WriteImmediateCmdGetTotalSize(self
, func
, file)
3842 class DataHandler(TypeHandler
):
3843 """Handler for glBufferData, glBufferSubData, glTexImage2D, glTexSubImage2D,
3844 glCompressedTexImage2D, glCompressedTexImageSub2D."""
3846 TypeHandler
.__init
__(self
)
3848 def InitFunction(self
, func
):
3849 """Overrriden from TypeHandler."""
3850 if func
.name
== 'CompressedTexSubImage2DBucket':
3851 func
.cmd_args
= func
.cmd_args
[:-1]
3852 func
.AddCmdArg(Argument('bucket_id', 'GLuint'))
3854 def WriteGetDataSizeCode(self
, func
, file):
3855 """Overrriden from TypeHandler."""
3856 # TODO(gman): Move this data to _FUNCTION_INFO?
3858 if name
.endswith("Immediate"):
3860 if name
== 'BufferData' or name
== 'BufferSubData':
3861 file.Write(" uint32_t data_size = size;\n")
3862 elif (name
== 'CompressedTexImage2D' or
3863 name
== 'CompressedTexSubImage2D'):
3864 file.Write(" uint32_t data_size = imageSize;\n")
3865 elif (name
== 'CompressedTexSubImage2DBucket'):
3866 file.Write(" Bucket* bucket = GetBucket(c.bucket_id);\n")
3867 file.Write(" uint32_t data_size = bucket->size();\n")
3868 file.Write(" GLsizei imageSize = data_size;\n")
3869 elif name
== 'TexImage2D' or name
== 'TexSubImage2D':
3870 code
= """ uint32_t data_size;
3871 if (!GLES2Util::ComputeImageDataSize(
3872 width, height, format, type, unpack_alignment_, &data_size)) {
3873 return error::kOutOfBounds;
3879 "// uint32_t data_size = 0; // TODO(gman): get correct size!\n")
3881 def WriteImmediateCmdGetTotalSize(self
, func
, file):
3882 """Overrriden from TypeHandler."""
3885 def WriteImmediateCmdSizeTest(self
, func
, file):
3886 """Overrriden from TypeHandler."""
3887 file.Write(" EXPECT_EQ(sizeof(cmd), total_size);\n")
3889 def WriteImmediateCmdInit(self
, func
, file):
3890 """Overrriden from TypeHandler."""
3891 file.Write(" void Init(%s) {\n" % func
.MakeTypedCmdArgString("_"))
3892 self
.WriteImmediateCmdGetTotalSize(func
, file)
3893 file.Write(" SetHeader(total_size);\n")
3894 args
= func
.GetCmdArgs()
3896 file.Write(" %s = _%s;\n" % (arg
.name
, arg
.name
))
3900 def WriteImmediateCmdSet(self
, func
, file):
3901 """Overrriden from TypeHandler."""
3902 copy_args
= func
.MakeCmdArgString("_", False)
3903 file.Write(" void* Set(void* cmd%s) {\n" %
3904 func
.MakeTypedCmdArgString("_", True))
3905 self
.WriteImmediateCmdGetTotalSize(func
, file)
3906 file.Write(" static_cast<ValueType*>(cmd)->Init(%s);\n" % copy_args
)
3907 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
3908 "cmd, total_size);\n")
3912 def WriteImmediateFormatTest(self
, func
, file):
3913 """Overrriden from TypeHandler."""
3914 # TODO(gman): Remove this exception.
3915 file.Write("// TODO(gman): Implement test for %s\n" % func
.name
)
3918 def WriteServiceUnitTest(self
, func
, file, *extras
):
3919 """Overrriden from TypeHandler."""
3920 file.Write("// TODO(gman): %s\n\n" % func
.name
)
3922 def WriteImmediateServiceUnitTest(self
, func
, file, *extras
):
3923 """Overrriden from TypeHandler."""
3924 file.Write("// TODO(gman): %s\n\n" % func
.name
)
3926 def WriteBucketServiceImplementation(self
, func
, file):
3927 """Overrriden from TypeHandler."""
3928 if not func
.name
== 'CompressedTexSubImage2DBucket':
3929 TypeHandler
.WriteBucketServiceImplemenation(self
, func
, file)
3932 class BindHandler(TypeHandler
):
3933 """Handler for glBind___ type functions."""
3936 TypeHandler
.__init
__(self
)
3938 def WriteServiceUnitTest(self
, func
, file, *extras
):
3939 """Overrriden from TypeHandler."""
3941 if len(func
.GetOriginalArgs()) == 1:
3943 TEST_P(%(test_name)s, %(name)sValidArgs) {
3944 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
3945 SpecializedSetup<cmds::%(name)s, 0>(true);
3948 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
3949 EXPECT_EQ(GL_NO_ERROR, GetGLError());
3952 if func
.GetInfo("gen_func"):
3954 TEST_P(%(test_name)s, %(name)sValidArgsNewId) {
3955 EXPECT_CALL(*gl_, %(gl_func_name)s(kNewServiceId));
3956 EXPECT_CALL(*gl_, %(gl_gen_func_name)s(1, _))
3957 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
3958 SpecializedSetup<cmds::%(name)s, 0>(true);
3960 cmd.Init(kNewClientId);
3961 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
3962 EXPECT_EQ(GL_NO_ERROR, GetGLError());
3963 EXPECT_TRUE(Get%(resource_type)s(kNewClientId) != NULL);
3966 self
.WriteValidUnitTest(func
, file, valid_test
, {
3967 'resource_type': func
.GetOriginalArgs()[0].resource_type
,
3968 'gl_gen_func_name': func
.GetInfo("gen_func"),
3972 TEST_P(%(test_name)s, %(name)sValidArgs) {
3973 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
3974 SpecializedSetup<cmds::%(name)s, 0>(true);
3977 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
3978 EXPECT_EQ(GL_NO_ERROR, GetGLError());
3981 if func
.GetInfo("gen_func"):
3983 TEST_P(%(test_name)s, %(name)sValidArgsNewId) {
3984 EXPECT_CALL(*gl_, %(gl_func_name)s(%(first_gl_arg)s, kNewServiceId));
3985 EXPECT_CALL(*gl_, %(gl_gen_func_name)s(1, _))
3986 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
3987 SpecializedSetup<cmds::%(name)s, 0>(true);
3989 cmd.Init(%(first_arg)s, kNewClientId);
3990 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
3991 EXPECT_EQ(GL_NO_ERROR, GetGLError());
3992 EXPECT_TRUE(Get%(resource_type)s(kNewClientId) != NULL);
3995 self
.WriteValidUnitTest(func
, file, valid_test
, {
3996 'first_arg': func
.GetOriginalArgs()[0].GetValidArg(func
),
3997 'first_gl_arg': func
.GetOriginalArgs()[0].GetValidGLArg(func
),
3998 'resource_type': func
.GetOriginalArgs()[1].resource_type
,
3999 'gl_gen_func_name': func
.GetInfo("gen_func"),
4003 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
4004 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
4005 SpecializedSetup<cmds::%(name)s, 0>(false);
4008 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
4011 self
.WriteInvalidUnitTest(func
, file, invalid_test
, *extras
)
4013 def WriteGLES2Implementation(self
, func
, file):
4014 """Writes the GLES2 Implemention."""
4016 impl_func
= func
.GetInfo('impl_func')
4017 impl_decl
= func
.GetInfo('impl_decl')
4019 if (func
.can_auto_generate
and
4020 (impl_func
== None or impl_func
== True) and
4021 (impl_decl
== None or impl_decl
== True)):
4023 file.Write("%s GLES2Implementation::%s(%s) {\n" %
4024 (func
.return_type
, func
.original_name
,
4025 func
.MakeTypedOriginalArgString("")))
4026 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
4027 func
.WriteDestinationInitalizationValidation(file)
4028 self
.WriteClientGLCallLog(func
, file)
4029 for arg
in func
.GetOriginalArgs():
4030 arg
.WriteClientSideValidationCode(file, func
)
4032 code
= """ if (Is%(type)sReservedId(%(id)s)) {
4033 SetGLError(GL_INVALID_OPERATION, "%(name)s\", \"%(id)s reserved id");
4036 if (%(name)sHelper(%(arg_string)s)) {
4037 helper_->%(name)s(%(arg_string)s);
4044 if len(func
.GetOriginalArgs()) == 1:
4045 # Bind functions that have no target (like BindVertexArrayOES)
4046 name_arg
= func
.GetOriginalArgs()[0]
4048 # Bind functions that have both a target and a name (like BindTexture)
4049 name_arg
= func
.GetOriginalArgs()[1]
4053 'arg_string': func
.MakeOriginalArgString(""),
4054 'id': name_arg
.name
,
4055 'type': name_arg
.resource_type
,
4056 'lc_type': name_arg
.resource_type
.lower(),
4059 def WriteGLES2ImplementationUnitTest(self
, func
, file):
4060 """Overrriden from TypeHandler."""
4061 client_test
= func
.GetInfo('client_test')
4062 if client_test
== False:
4065 TEST_F(GLES2ImplementationTest, %(name)s) {
4070 expected.cmd.Init(%(cmd_args)s);
4072 gl_->%(name)s(%(args)s);
4073 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
4075 gl_->%(name)s(%(args)s);
4076 EXPECT_TRUE(NoCommandsWritten());
4080 arg
.GetValidClientSideCmdArg(func
) for arg
in func
.GetCmdArgs()
4083 arg
.GetValidClientSideArg(func
) for arg
in func
.GetOriginalArgs()
4088 'args': ", ".join(gl_arg_strings
),
4089 'cmd_args': ", ".join(cmd_arg_strings
),
4093 class GENnHandler(TypeHandler
):
4094 """Handler for glGen___ type functions."""
4097 TypeHandler
.__init
__(self
)
4099 def InitFunction(self
, func
):
4100 """Overrriden from TypeHandler."""
4103 def WriteGetDataSizeCode(self
, func
, file):
4104 """Overrriden from TypeHandler."""
4105 code
= """ uint32_t data_size;
4106 if (!SafeMultiplyUint32(n, sizeof(GLuint), &data_size)) {
4107 return error::kOutOfBounds;
4112 def WriteHandlerImplementation (self
, func
, file):
4113 """Overrriden from TypeHandler."""
4114 file.Write(" if (!%sHelper(n, %s)) {\n"
4115 " return error::kInvalidArguments;\n"
4117 (func
.name
, func
.GetLastOriginalArg().name
))
4119 def WriteImmediateHandlerImplementation(self
, func
, file):
4120 """Overrriden from TypeHandler."""
4121 file.Write(" if (!%sHelper(n, %s)) {\n"
4122 " return error::kInvalidArguments;\n"
4124 (func
.original_name
, func
.GetLastOriginalArg().name
))
4126 def WriteGLES2Implementation(self
, func
, file):
4127 """Overrriden from TypeHandler."""
4128 log_code
= (""" GPU_CLIENT_LOG_CODE_BLOCK({
4129 for (GLsizei i = 0; i < n; ++i) {
4130 GPU_CLIENT_LOG(" " << i << ": " << %s[i]);
4132 });""" % func
.GetOriginalArgs()[1].name
)
4134 'log_code': log_code
,
4135 'return_type': func
.return_type
,
4136 'name': func
.original_name
,
4137 'typed_args': func
.MakeTypedOriginalArgString(""),
4138 'args': func
.MakeOriginalArgString(""),
4139 'resource_types': func
.GetInfo('resource_types'),
4140 'count_name': func
.GetOriginalArgs()[0].name
,
4143 "%(return_type)s GLES2Implementation::%(name)s(%(typed_args)s) {\n" %
4145 func
.WriteDestinationInitalizationValidation(file)
4146 self
.WriteClientGLCallLog(func
, file)
4147 for arg
in func
.GetOriginalArgs():
4148 arg
.WriteClientSideValidationCode(file, func
)
4149 not_shared
= func
.GetInfo('not_shared')
4153 """ IdAllocator* id_allocator = GetIdAllocator(id_namespaces::k%s);
4154 for (GLsizei ii = 0; ii < n; ++ii)
4155 %s[ii] = id_allocator->AllocateID();""" %
4156 (func
.GetInfo('resource_types'), func
.GetOriginalArgs()[1].name
))
4158 alloc_code
= (""" GetIdHandler(id_namespaces::k%(resource_types)s)->
4159 MakeIds(this, 0, %(args)s);""" % args
)
4160 args
['alloc_code'] = alloc_code
4162 code
= """ GPU_CLIENT_SINGLE_THREAD_CHECK();
4164 %(name)sHelper(%(args)s);
4165 helper_->%(name)sImmediate(%(args)s);
4166 if (share_group_->bind_generates_resource())
4167 helper_->CommandBufferHelper::Flush();
4173 file.Write(code
% args
)
4175 def WriteGLES2ImplementationUnitTest(self
, func
, file):
4176 """Overrriden from TypeHandler."""
4178 TEST_F(GLES2ImplementationTest, %(name)s) {
4179 GLuint ids[2] = { 0, };
4181 cmds::%(name)sImmediate gen;
4185 expected.gen.Init(arraysize(ids), &ids[0]);
4186 expected.data[0] = k%(types)sStartId;
4187 expected.data[1] = k%(types)sStartId + 1;
4188 gl_->%(name)s(arraysize(ids), &ids[0]);
4189 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
4190 EXPECT_EQ(k%(types)sStartId, ids[0]);
4191 EXPECT_EQ(k%(types)sStartId + 1, ids[1]);
4196 'types': func
.GetInfo('resource_types'),
4199 def WriteServiceUnitTest(self
, func
, file, *extras
):
4200 """Overrriden from TypeHandler."""
4202 TEST_P(%(test_name)s, %(name)sValidArgs) {
4203 EXPECT_CALL(*gl_, %(gl_func_name)s(1, _))
4204 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
4205 GetSharedMemoryAs<GLuint*>()[0] = kNewClientId;
4206 SpecializedSetup<cmds::%(name)s, 0>(true);
4209 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4210 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4211 EXPECT_TRUE(Get%(resource_name)s(kNewClientId) != NULL);
4214 self
.WriteValidUnitTest(func
, file, valid_test
, {
4215 'resource_name': func
.GetInfo('resource_type'),
4218 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
4219 EXPECT_CALL(*gl_, %(gl_func_name)s(_, _)).Times(0);
4220 GetSharedMemoryAs<GLuint*>()[0] = client_%(resource_name)s_id_;
4221 SpecializedSetup<cmds::%(name)s, 0>(false);
4224 EXPECT_EQ(error::kInvalidArguments, ExecuteCmd(cmd));
4227 self
.WriteValidUnitTest(func
, file, invalid_test
, {
4228 'resource_name': func
.GetInfo('resource_type').lower(),
4231 def WriteImmediateServiceUnitTest(self
, func
, file, *extras
):
4232 """Overrriden from TypeHandler."""
4234 TEST_P(%(test_name)s, %(name)sValidArgs) {
4235 EXPECT_CALL(*gl_, %(gl_func_name)s(1, _))
4236 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
4237 cmds::%(name)s* cmd = GetImmediateAs<cmds::%(name)s>();
4238 GLuint temp = kNewClientId;
4239 SpecializedSetup<cmds::%(name)s, 0>(true);
4240 cmd->Init(1, &temp);
4241 EXPECT_EQ(error::kNoError,
4242 ExecuteImmediateCmd(*cmd, sizeof(temp)));
4243 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4244 EXPECT_TRUE(Get%(resource_name)s(kNewClientId) != NULL);
4247 self
.WriteValidUnitTest(func
, file, valid_test
, {
4248 'resource_name': func
.GetInfo('resource_type'),
4251 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
4252 EXPECT_CALL(*gl_, %(gl_func_name)s(_, _)).Times(0);
4253 cmds::%(name)s* cmd = GetImmediateAs<cmds::%(name)s>();
4254 SpecializedSetup<cmds::%(name)s, 0>(false);
4255 cmd->Init(1, &client_%(resource_name)s_id_);
4256 EXPECT_EQ(error::kInvalidArguments,
4257 ExecuteImmediateCmd(*cmd, sizeof(&client_%(resource_name)s_id_)));
4260 self
.WriteValidUnitTest(func
, file, invalid_test
, {
4261 'resource_name': func
.GetInfo('resource_type').lower(),
4264 def WriteImmediateCmdComputeSize(self
, func
, file):
4265 """Overrriden from TypeHandler."""
4266 file.Write(" static uint32_t ComputeDataSize(GLsizei n) {\n")
4268 " return static_cast<uint32_t>(sizeof(GLuint) * n); // NOLINT\n")
4271 file.Write(" static uint32_t ComputeSize(GLsizei n) {\n")
4272 file.Write(" return static_cast<uint32_t>(\n")
4273 file.Write(" sizeof(ValueType) + ComputeDataSize(n)); // NOLINT\n")
4277 def WriteImmediateCmdSetHeader(self
, func
, file):
4278 """Overrriden from TypeHandler."""
4279 file.Write(" void SetHeader(GLsizei n) {\n")
4280 file.Write(" header.SetCmdByTotalSize<ValueType>(ComputeSize(n));\n")
4284 def WriteImmediateCmdInit(self
, func
, file):
4285 """Overrriden from TypeHandler."""
4286 last_arg
= func
.GetLastOriginalArg()
4287 file.Write(" void Init(%s, %s _%s) {\n" %
4288 (func
.MakeTypedCmdArgString("_"),
4289 last_arg
.type, last_arg
.name
))
4290 file.Write(" SetHeader(_n);\n")
4291 args
= func
.GetCmdArgs()
4293 file.Write(" %s = _%s;\n" % (arg
.name
, arg
.name
))
4294 file.Write(" memcpy(ImmediateDataAddress(this),\n")
4295 file.Write(" _%s, ComputeDataSize(_n));\n" % last_arg
.name
)
4299 def WriteImmediateCmdSet(self
, func
, file):
4300 """Overrriden from TypeHandler."""
4301 last_arg
= func
.GetLastOriginalArg()
4302 copy_args
= func
.MakeCmdArgString("_", False)
4303 file.Write(" void* Set(void* cmd%s, %s _%s) {\n" %
4304 (func
.MakeTypedCmdArgString("_", True),
4305 last_arg
.type, last_arg
.name
))
4306 file.Write(" static_cast<ValueType*>(cmd)->Init(%s, _%s);\n" %
4307 (copy_args
, last_arg
.name
))
4308 file.Write(" const uint32_t size = ComputeSize(_n);\n")
4309 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
4314 def WriteImmediateCmdHelper(self
, func
, file):
4315 """Overrriden from TypeHandler."""
4316 code
= """ void %(name)s(%(typed_args)s) {
4317 const uint32_t size = gles2::cmds::%(name)s::ComputeSize(n);
4318 gles2::cmds::%(name)s* c =
4319 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
4328 "typed_args": func
.MakeTypedOriginalArgString(""),
4329 "args": func
.MakeOriginalArgString(""),
4332 def WriteImmediateFormatTest(self
, func
, file):
4333 """Overrriden from TypeHandler."""
4334 file.Write("TEST_F(GLES2FormatTest, %s) {\n" % func
.name
)
4335 file.Write(" static GLuint ids[] = { 12, 23, 34, };\n")
4336 file.Write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
4337 (func
.name
, func
.name
))
4338 file.Write(" void* next_cmd = cmd.Set(\n")
4339 file.Write(" &cmd, static_cast<GLsizei>(arraysize(ids)), ids);\n")
4340 file.Write(" EXPECT_EQ(static_cast<uint32_t>(cmds::%s::kCmdId),\n" %
4342 file.Write(" cmd.header.command);\n")
4343 file.Write(" EXPECT_EQ(sizeof(cmd) +\n")
4344 file.Write(" RoundSizeToMultipleOfEntries(cmd.n * 4u),\n")
4345 file.Write(" cmd.header.size * 4u);\n")
4346 file.Write(" EXPECT_EQ(static_cast<GLsizei>(arraysize(ids)), cmd.n);\n");
4347 file.Write(" CheckBytesWrittenMatchesExpectedSize(\n")
4348 file.Write(" next_cmd, sizeof(cmd) +\n")
4349 file.Write(" RoundSizeToMultipleOfEntries(arraysize(ids) * 4u));\n")
4350 file.Write(" // TODO(gman): Check that ids were inserted;\n")
4355 class CreateHandler(TypeHandler
):
4356 """Handler for glCreate___ type functions."""
4359 TypeHandler
.__init
__(self
)
4361 def InitFunction(self
, func
):
4362 """Overrriden from TypeHandler."""
4363 func
.AddCmdArg(Argument("client_id", 'uint32_t'))
4365 def WriteServiceUnitTest(self
, func
, file, *extras
):
4366 """Overrriden from TypeHandler."""
4368 TEST_P(%(test_name)s, %(name)sValidArgs) {
4369 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s))
4370 .WillOnce(Return(kNewServiceId));
4371 SpecializedSetup<cmds::%(name)s, 0>(true);
4373 cmd.Init(%(args)s%(comma)skNewClientId);
4374 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4375 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4376 EXPECT_TRUE(Get%(resource_type)s(kNewClientId) != NULL);
4380 if len(func
.GetOriginalArgs()):
4382 self
.WriteValidUnitTest(func
, file, valid_test
, {
4384 'resource_type': func
.name
[6:],
4387 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
4388 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
4389 SpecializedSetup<cmds::%(name)s, 0>(false);
4391 cmd.Init(%(args)s%(comma)skNewClientId);
4392 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));%(gl_error_test)s
4395 self
.WriteInvalidUnitTest(func
, file, invalid_test
, {
4399 def WriteHandlerImplementation (self
, func
, file):
4400 """Overrriden from TypeHandler."""
4401 file.Write(" uint32_t client_id = c.client_id;\n")
4402 file.Write(" if (!%sHelper(%s)) {\n" %
4403 (func
.name
, func
.MakeCmdArgString("")))
4404 file.Write(" return error::kInvalidArguments;\n")
4407 def WriteGLES2Implementation(self
, func
, file):
4408 """Overrriden from TypeHandler."""
4409 file.Write("%s GLES2Implementation::%s(%s) {\n" %
4410 (func
.return_type
, func
.original_name
,
4411 func
.MakeTypedOriginalArgString("")))
4412 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
4413 func
.WriteDestinationInitalizationValidation(file)
4414 self
.WriteClientGLCallLog(func
, file)
4415 for arg
in func
.GetOriginalArgs():
4416 arg
.WriteClientSideValidationCode(file, func
)
4417 file.Write(" GLuint client_id;\n")
4419 " GetIdHandler(id_namespaces::kProgramsAndShaders)->\n")
4420 file.Write(" MakeIds(this, 0, 1, &client_id);\n")
4421 file.Write(" helper_->%s(%s);\n" %
4422 (func
.name
, func
.MakeCmdArgString("")))
4423 file.Write(' GPU_CLIENT_LOG("returned " << client_id);\n')
4424 file.Write(" CheckGLError();\n")
4425 file.Write(" return client_id;\n")
4430 class DeleteHandler(TypeHandler
):
4431 """Handler for glDelete___ single resource type functions."""
4434 TypeHandler
.__init
__(self
)
4436 def WriteServiceImplementation(self
, func
, file):
4437 """Overrriden from TypeHandler."""
4440 def WriteGLES2Implementation(self
, func
, file):
4441 """Overrriden from TypeHandler."""
4442 file.Write("%s GLES2Implementation::%s(%s) {\n" %
4443 (func
.return_type
, func
.original_name
,
4444 func
.MakeTypedOriginalArgString("")))
4445 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
4446 func
.WriteDestinationInitalizationValidation(file)
4447 self
.WriteClientGLCallLog(func
, file)
4448 for arg
in func
.GetOriginalArgs():
4449 arg
.WriteClientSideValidationCode(file, func
)
4451 " GPU_CLIENT_DCHECK(%s != 0);\n" % func
.GetOriginalArgs()[-1].name
)
4452 file.Write(" %sHelper(%s);\n" %
4453 (func
.original_name
, func
.GetOriginalArgs()[-1].name
))
4454 file.Write(" CheckGLError();\n")
4459 class DELnHandler(TypeHandler
):
4460 """Handler for glDelete___ type functions."""
4463 TypeHandler
.__init
__(self
)
4465 def WriteGetDataSizeCode(self
, func
, file):
4466 """Overrriden from TypeHandler."""
4467 code
= """ uint32_t data_size;
4468 if (!SafeMultiplyUint32(n, sizeof(GLuint), &data_size)) {
4469 return error::kOutOfBounds;
4474 def WriteGLES2ImplementationUnitTest(self
, func
, file):
4475 """Overrriden from TypeHandler."""
4477 TEST_F(GLES2ImplementationTest, %(name)s) {
4478 GLuint ids[2] = { k%(types)sStartId, k%(types)sStartId + 1 };
4480 cmds::%(name)sImmediate del;
4484 expected.del.Init(arraysize(ids), &ids[0]);
4485 expected.data[0] = k%(types)sStartId;
4486 expected.data[1] = k%(types)sStartId + 1;
4487 gl_->%(name)s(arraysize(ids), &ids[0]);
4488 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
4493 'types': func
.GetInfo('resource_types'),
4496 def WriteServiceUnitTest(self
, func
, file, *extras
):
4497 """Overrriden from TypeHandler."""
4499 TEST_P(%(test_name)s, %(name)sValidArgs) {
4502 %(gl_func_name)s(1, Pointee(kService%(upper_resource_name)sId)))
4504 GetSharedMemoryAs<GLuint*>()[0] = client_%(resource_name)s_id_;
4505 SpecializedSetup<cmds::%(name)s, 0>(true);
4508 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4509 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4511 Get%(upper_resource_name)s(client_%(resource_name)s_id_) == NULL);
4514 self
.WriteValidUnitTest(func
, file, valid_test
, {
4515 'resource_name': func
.GetInfo('resource_type').lower(),
4516 'upper_resource_name': func
.GetInfo('resource_type'),
4519 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
4520 GetSharedMemoryAs<GLuint*>()[0] = kInvalidClientId;
4521 SpecializedSetup<cmds::%(name)s, 0>(false);
4524 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4527 self
.WriteValidUnitTest(func
, file, invalid_test
, *extras
)
4529 def WriteImmediateServiceUnitTest(self
, func
, file, *extras
):
4530 """Overrriden from TypeHandler."""
4532 TEST_P(%(test_name)s, %(name)sValidArgs) {
4535 %(gl_func_name)s(1, Pointee(kService%(upper_resource_name)sId)))
4537 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
4538 SpecializedSetup<cmds::%(name)s, 0>(true);
4539 cmd.Init(1, &client_%(resource_name)s_id_);
4540 EXPECT_EQ(error::kNoError,
4541 ExecuteImmediateCmd(cmd, sizeof(client_%(resource_name)s_id_)));
4542 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4544 Get%(upper_resource_name)s(client_%(resource_name)s_id_) == NULL);
4547 self
.WriteValidUnitTest(func
, file, valid_test
, {
4548 'resource_name': func
.GetInfo('resource_type').lower(),
4549 'upper_resource_name': func
.GetInfo('resource_type'),
4552 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
4553 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
4554 SpecializedSetup<cmds::%(name)s, 0>(false);
4555 GLuint temp = kInvalidClientId;
4557 EXPECT_EQ(error::kNoError,
4558 ExecuteImmediateCmd(cmd, sizeof(temp)));
4561 self
.WriteValidUnitTest(func
, file, invalid_test
, *extras
)
4563 def WriteHandlerImplementation (self
, func
, file):
4564 """Overrriden from TypeHandler."""
4565 file.Write(" %sHelper(n, %s);\n" %
4566 (func
.name
, func
.GetLastOriginalArg().name
))
4568 def WriteImmediateHandlerImplementation (self
, func
, file):
4569 """Overrriden from TypeHandler."""
4570 file.Write(" %sHelper(n, %s);\n" %
4571 (func
.original_name
, func
.GetLastOriginalArg().name
))
4573 def WriteGLES2Implementation(self
, func
, file):
4574 """Overrriden from TypeHandler."""
4575 impl_decl
= func
.GetInfo('impl_decl')
4576 if impl_decl
== None or impl_decl
== True:
4578 'return_type': func
.return_type
,
4579 'name': func
.original_name
,
4580 'typed_args': func
.MakeTypedOriginalArgString(""),
4581 'args': func
.MakeOriginalArgString(""),
4582 'resource_type': func
.GetInfo('resource_type').lower(),
4583 'count_name': func
.GetOriginalArgs()[0].name
,
4586 "%(return_type)s GLES2Implementation::%(name)s(%(typed_args)s) {\n" %
4588 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
4589 func
.WriteDestinationInitalizationValidation(file)
4590 self
.WriteClientGLCallLog(func
, file)
4591 file.Write(""" GPU_CLIENT_LOG_CODE_BLOCK({
4592 for (GLsizei i = 0; i < n; ++i) {
4593 GPU_CLIENT_LOG(" " << i << ": " << %s[i]);
4596 """ % func
.GetOriginalArgs()[1].name
)
4597 file.Write(""" GPU_CLIENT_DCHECK_CODE_BLOCK({
4598 for (GLsizei i = 0; i < n; ++i) {
4602 """ % func
.GetOriginalArgs()[1].name
)
4603 for arg
in func
.GetOriginalArgs():
4604 arg
.WriteClientSideValidationCode(file, func
)
4605 code
= """ %(name)sHelper(%(args)s);
4610 file.Write(code
% args
)
4612 def WriteImmediateCmdComputeSize(self
, func
, file):
4613 """Overrriden from TypeHandler."""
4614 file.Write(" static uint32_t ComputeDataSize(GLsizei n) {\n")
4616 " return static_cast<uint32_t>(sizeof(GLuint) * n); // NOLINT\n")
4619 file.Write(" static uint32_t ComputeSize(GLsizei n) {\n")
4620 file.Write(" return static_cast<uint32_t>(\n")
4621 file.Write(" sizeof(ValueType) + ComputeDataSize(n)); // NOLINT\n")
4625 def WriteImmediateCmdSetHeader(self
, func
, file):
4626 """Overrriden from TypeHandler."""
4627 file.Write(" void SetHeader(GLsizei n) {\n")
4628 file.Write(" header.SetCmdByTotalSize<ValueType>(ComputeSize(n));\n")
4632 def WriteImmediateCmdInit(self
, func
, file):
4633 """Overrriden from TypeHandler."""
4634 last_arg
= func
.GetLastOriginalArg()
4635 file.Write(" void Init(%s, %s _%s) {\n" %
4636 (func
.MakeTypedCmdArgString("_"),
4637 last_arg
.type, last_arg
.name
))
4638 file.Write(" SetHeader(_n);\n")
4639 args
= func
.GetCmdArgs()
4641 file.Write(" %s = _%s;\n" % (arg
.name
, arg
.name
))
4642 file.Write(" memcpy(ImmediateDataAddress(this),\n")
4643 file.Write(" _%s, ComputeDataSize(_n));\n" % last_arg
.name
)
4647 def WriteImmediateCmdSet(self
, func
, file):
4648 """Overrriden from TypeHandler."""
4649 last_arg
= func
.GetLastOriginalArg()
4650 copy_args
= func
.MakeCmdArgString("_", False)
4651 file.Write(" void* Set(void* cmd%s, %s _%s) {\n" %
4652 (func
.MakeTypedCmdArgString("_", True),
4653 last_arg
.type, last_arg
.name
))
4654 file.Write(" static_cast<ValueType*>(cmd)->Init(%s, _%s);\n" %
4655 (copy_args
, last_arg
.name
))
4656 file.Write(" const uint32_t size = ComputeSize(_n);\n")
4657 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
4662 def WriteImmediateCmdHelper(self
, func
, file):
4663 """Overrriden from TypeHandler."""
4664 code
= """ void %(name)s(%(typed_args)s) {
4665 const uint32_t size = gles2::cmds::%(name)s::ComputeSize(n);
4666 gles2::cmds::%(name)s* c =
4667 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
4676 "typed_args": func
.MakeTypedOriginalArgString(""),
4677 "args": func
.MakeOriginalArgString(""),
4680 def WriteImmediateFormatTest(self
, func
, file):
4681 """Overrriden from TypeHandler."""
4682 file.Write("TEST_F(GLES2FormatTest, %s) {\n" % func
.name
)
4683 file.Write(" static GLuint ids[] = { 12, 23, 34, };\n")
4684 file.Write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
4685 (func
.name
, func
.name
))
4686 file.Write(" void* next_cmd = cmd.Set(\n")
4687 file.Write(" &cmd, static_cast<GLsizei>(arraysize(ids)), ids);\n")
4688 file.Write(" EXPECT_EQ(static_cast<uint32_t>(cmds::%s::kCmdId),\n" %
4690 file.Write(" cmd.header.command);\n")
4691 file.Write(" EXPECT_EQ(sizeof(cmd) +\n")
4692 file.Write(" RoundSizeToMultipleOfEntries(cmd.n * 4u),\n")
4693 file.Write(" cmd.header.size * 4u);\n")
4694 file.Write(" EXPECT_EQ(static_cast<GLsizei>(arraysize(ids)), cmd.n);\n");
4695 file.Write(" CheckBytesWrittenMatchesExpectedSize(\n")
4696 file.Write(" next_cmd, sizeof(cmd) +\n")
4697 file.Write(" RoundSizeToMultipleOfEntries(arraysize(ids) * 4u));\n")
4698 file.Write(" // TODO(gman): Check that ids were inserted;\n")
4703 class GETnHandler(TypeHandler
):
4704 """Handler for GETn for glGetBooleanv, glGetFloatv, ... type functions."""
4707 TypeHandler
.__init
__(self
)
4709 def NeedsDataTransferFunction(self
, func
):
4710 """Overriden from TypeHandler."""
4713 def WriteServiceImplementation(self
, func
, file):
4714 """Overrriden from TypeHandler."""
4715 self
.WriteServiceHandlerFunctionHeader(func
, file)
4716 last_arg
= func
.GetLastOriginalArg()
4718 all_but_last_args
= func
.GetOriginalArgs()[:-1]
4719 for arg
in all_but_last_args
:
4720 arg
.WriteGetCode(file)
4722 code
= """ typedef cmds::%(func_name)s::Result Result;
4723 GLsizei num_values = 0;
4724 GetNumValuesReturnedForGLGet(pname, &num_values);
4725 Result* result = GetSharedMemoryAs<Result*>(
4726 c.params_shm_id, c.params_shm_offset, Result::ComputeSize(num_values));
4727 %(last_arg_type)s params = result ? result->GetData() : NULL;
4730 'last_arg_type': last_arg
.type,
4731 'func_name': func
.name
,
4733 func
.WriteHandlerValidation(file)
4734 code
= """ // Check that the client initialized the result.
4735 if (result->size != 0) {
4736 return error::kInvalidArguments;
4739 shadowed
= func
.GetInfo('shadowed')
4741 file.Write(' LOCAL_COPY_REAL_GL_ERRORS_TO_WRAPPER("%s");\n' % func
.name
)
4743 func
.WriteHandlerImplementation(file)
4745 code
= """ result->SetNumResults(num_values);
4746 return error::kNoError;
4750 code
= """ GLenum error = glGetError();
4751 if (error == GL_NO_ERROR) {
4752 result->SetNumResults(num_values);
4754 LOCAL_SET_GL_ERROR(error, "%(func_name)s", "");
4756 return error::kNoError;
4760 file.Write(code
% {'func_name': func
.name
})
4762 def WriteGLES2Implementation(self
, func
, file):
4763 """Overrriden from TypeHandler."""
4764 impl_decl
= func
.GetInfo('impl_decl')
4765 if impl_decl
== None or impl_decl
== True:
4766 file.Write("%s GLES2Implementation::%s(%s) {\n" %
4767 (func
.return_type
, func
.original_name
,
4768 func
.MakeTypedOriginalArgString("")))
4769 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
4770 func
.WriteDestinationInitalizationValidation(file)
4771 self
.WriteClientGLCallLog(func
, file)
4772 for arg
in func
.GetOriginalArgs():
4773 arg
.WriteClientSideValidationCode(file, func
)
4774 all_but_last_args
= func
.GetOriginalArgs()[:-1]
4776 ", ".join(["%s" % arg
.name
for arg
in all_but_last_args
]))
4780 for arg
in func
.GetOriginalArgs() if not arg
.IsConstant()]))
4781 self
.WriteTraceEvent(func
, file)
4782 code
= """ if (%(func_name)sHelper(%(all_arg_string)s)) {
4785 typedef cmds::%(func_name)s::Result Result;
4786 Result* result = GetResultAs<Result*>();
4790 result->SetNumResults(0);
4791 helper_->%(func_name)s(%(arg_string)s,
4792 GetResultShmId(), GetResultShmOffset());
4794 result->CopyResult(params);
4795 GPU_CLIENT_LOG_CODE_BLOCK({
4796 for (int32_t i = 0; i < result->GetNumResults(); ++i) {
4797 GPU_CLIENT_LOG(" " << i << ": " << result->GetData()[i]);
4804 'func_name': func
.name
,
4805 'arg_string': arg_string
,
4806 'all_arg_string': all_arg_string
,
4809 def WriteGLES2ImplementationUnitTest(self
, func
, file):
4810 """Writes the GLES2 Implemention unit test."""
4812 TEST_F(GLES2ImplementationTest, %(name)s) {
4816 typedef cmds::%(name)s::Result Result;
4817 Result::Type result = 0;
4819 ExpectedMemoryInfo result1 = GetExpectedResultMemory(4);
4820 expected.cmd.Init(%(cmd_args)s, result1.id, result1.offset);
4821 EXPECT_CALL(*command_buffer(), OnFlush())
4822 .WillOnce(SetMemory(result1.ptr, SizedResultHelper<Result::Type>(1)))
4823 .RetiresOnSaturation();
4824 gl_->%(name)s(%(args)s, &result);
4825 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
4826 EXPECT_EQ(static_cast<Result::Type>(1), result);
4829 first_cmd_arg
= func
.GetCmdArgs()[0].GetValidNonCachedClientSideCmdArg(func
)
4830 if not first_cmd_arg
:
4833 first_gl_arg
= func
.GetCmdArgs()[0].GetValidNonCachedClientSideArg(func
)
4834 cmd_arg_strings
= [first_cmd_arg
]
4835 for arg
in func
.GetCmdArgs()[1:-2]:
4836 cmd_arg_strings
.append(arg
.GetValidClientSideCmdArg(func
))
4837 gl_arg_strings
= [first_gl_arg
]
4838 for arg
in func
.GetOriginalArgs()[1:-1]:
4839 gl_arg_strings
.append(arg
.GetValidClientSideArg(func
))
4843 'args': ", ".join(gl_arg_strings
),
4844 'cmd_args': ", ".join(cmd_arg_strings
),
4847 def WriteServiceUnitTest(self
, func
, file, *extras
):
4848 """Overrriden from TypeHandler."""
4850 TEST_P(%(test_name)s, %(name)sValidArgs) {
4851 EXPECT_CALL(*gl_, GetError())
4852 .WillOnce(Return(GL_NO_ERROR))
4853 .WillOnce(Return(GL_NO_ERROR))
4854 .RetiresOnSaturation();
4855 SpecializedSetup<cmds::%(name)s, 0>(true);
4856 typedef cmds::%(name)s::Result Result;
4857 Result* result = static_cast<Result*>(shared_memory_address_);
4858 EXPECT_CALL(*gl_, %(gl_func_name)s(%(local_gl_args)s));
4862 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4863 EXPECT_EQ(decoder_->GetGLES2Util()->GLGetNumValuesReturned(
4865 result->GetNumResults());
4866 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4871 for arg
in func
.GetOriginalArgs()[:-1]:
4872 arg_value
= arg
.GetValidGLArg(func
)
4873 gl_arg_strings
.append(arg_value
)
4874 if arg
.name
== 'pname':
4875 valid_pname
= arg_value
4876 if func
.GetInfo('gl_test_func') == 'glGetIntegerv':
4877 gl_arg_strings
.append("_")
4879 gl_arg_strings
.append("result->GetData()")
4881 self
.WriteValidUnitTest(func
, file, valid_test
, {
4882 'local_gl_args': ", ".join(gl_arg_strings
),
4883 'valid_pname': valid_pname
,
4887 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
4888 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
4889 SpecializedSetup<cmds::%(name)s, 0>(false);
4890 cmds::%(name)s::Result* result =
4891 static_cast<cmds::%(name)s::Result*>(shared_memory_address_);
4895 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));
4896 EXPECT_EQ(0u, result->size);%(gl_error_test)s
4899 self
.WriteInvalidUnitTest(func
, file, invalid_test
, *extras
)
4901 class ArrayArgTypeHandler(TypeHandler
):
4902 """Base class for type handlers that handle args that are arrays"""
4905 TypeHandler
.__init
__(self
)
4907 def GetArrayType(self
, func
):
4908 """Returns the type of the element in the element array being PUT to."""
4909 for arg
in func
.GetOriginalArgs():
4911 element_type
= arg
.GetPointedType()
4914 # Special case: array type handler is used for a function that is forwarded
4915 # to the actual array type implementation
4916 element_type
= func
.GetOriginalArgs()[-1].type
4917 assert all(arg
.type == element_type \
4918 for arg
in func
.GetOriginalArgs()[-self
.GetArrayCount(func
):])
4921 def GetArrayCount(self
, func
):
4922 """Returns the count of the elements in the array being PUT to."""
4923 return func
.GetInfo('count')
4925 class PUTHandler(ArrayArgTypeHandler
):
4926 """Handler for glTexParameter_v, glVertexAttrib_v functions."""
4929 ArrayArgTypeHandler
.__init
__(self
)
4931 def WriteServiceUnitTest(self
, func
, file, *extras
):
4932 """Writes the service unit test for a command."""
4933 expected_call
= "EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));"
4934 if func
.GetInfo("first_element_only"):
4936 arg
.GetValidGLArg(func
) for arg
in func
.GetOriginalArgs()
4938 gl_arg_strings
[-1] = "*" + gl_arg_strings
[-1]
4939 expected_call
= ("EXPECT_CALL(*gl_, %%(gl_func_name)s(%s));" %
4940 ", ".join(gl_arg_strings
))
4942 TEST_P(%(test_name)s, %(name)sValidArgs) {
4943 SpecializedSetup<cmds::%(name)s, 0>(true);
4946 GetSharedMemoryAs<%(data_type)s*>()[0] = %(data_value)s;
4948 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4949 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4953 'data_type': self
.GetArrayType(func
),
4954 'data_value': func
.GetInfo('data_value') or '0',
4955 'expected_call': expected_call
,
4957 self
.WriteValidUnitTest(func
, file, valid_test
, extra
, *extras
)
4960 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
4961 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
4962 SpecializedSetup<cmds::%(name)s, 0>(false);
4965 GetSharedMemoryAs<%(data_type)s*>()[0] = %(data_value)s;
4966 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
4969 self
.WriteInvalidUnitTest(func
, file, invalid_test
, extra
, *extras
)
4971 def WriteImmediateServiceUnitTest(self
, func
, file, *extras
):
4972 """Writes the service unit test for a command."""
4974 TEST_P(%(test_name)s, %(name)sValidArgs) {
4975 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
4976 SpecializedSetup<cmds::%(name)s, 0>(true);
4977 %(data_type)s temp[%(data_count)s] = { %(data_value)s, };
4978 cmd.Init(%(gl_args)s, &temp[0]);
4981 %(gl_func_name)s(%(gl_args)s, %(data_ref)sreinterpret_cast<
4982 %(data_type)s*>(ImmediateDataAddress(&cmd))));
4983 EXPECT_EQ(error::kNoError,
4984 ExecuteImmediateCmd(cmd, sizeof(temp)));
4985 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4989 arg
.GetValidGLArg(func
) for arg
in func
.GetOriginalArgs()[0:-1]
4991 gl_any_strings
= ["_"] * len(gl_arg_strings
)
4994 'data_ref': ("*" if func
.GetInfo('first_element_only') else ""),
4995 'data_type': self
.GetArrayType(func
),
4996 'data_count': self
.GetArrayCount(func
),
4997 'data_value': func
.GetInfo('data_value') or '0',
4998 'gl_args': ", ".join(gl_arg_strings
),
4999 'gl_any_args': ", ".join(gl_any_strings
),
5001 self
.WriteValidUnitTest(func
, file, valid_test
, extra
, *extras
)
5004 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
5005 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
5006 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_any_args)s, _)).Times(0);
5007 SpecializedSetup<cmds::%(name)s, 0>(false);
5008 %(data_type)s temp[%(data_count)s] = { %(data_value)s, };
5009 cmd.Init(%(all_but_last_args)s, &temp[0]);
5010 EXPECT_EQ(error::%(parse_result)s,
5011 ExecuteImmediateCmd(cmd, sizeof(temp)));%(gl_error_test)s
5014 self
.WriteInvalidUnitTest(func
, file, invalid_test
, extra
, *extras
)
5016 def WriteGetDataSizeCode(self
, func
, file):
5017 """Overrriden from TypeHandler."""
5018 code
= """ uint32_t data_size;
5019 if (!ComputeDataSize(1, sizeof(%s), %d, &data_size)) {
5020 return error::kOutOfBounds;
5023 file.Write(code
% (self
.GetArrayType(func
), self
.GetArrayCount(func
)))
5024 if func
.IsImmediate():
5025 file.Write(" if (data_size > immediate_data_size) {\n")
5026 file.Write(" return error::kOutOfBounds;\n")
5029 def WriteGLES2Implementation(self
, func
, file):
5030 """Overrriden from TypeHandler."""
5031 impl_func
= func
.GetInfo('impl_func')
5032 if (impl_func
!= None and impl_func
!= True):
5034 file.Write("%s GLES2Implementation::%s(%s) {\n" %
5035 (func
.return_type
, func
.original_name
,
5036 func
.MakeTypedOriginalArgString("")))
5037 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
5038 func
.WriteDestinationInitalizationValidation(file)
5039 self
.WriteClientGLCallLog(func
, file)
5040 last_arg_name
= func
.GetLastOriginalArg().name
5041 values_str
= ' << ", " << '.join(
5042 ["%s[%d]" % (last_arg_name
, ndx
) \
5043 for ndx
in range(0, self
.GetArrayCount(func
))])
5044 file.Write(' GPU_CLIENT_LOG("values: " << %s);\n' % values_str
)
5045 for arg
in func
.GetOriginalArgs():
5046 arg
.WriteClientSideValidationCode(file, func
)
5047 file.Write(" helper_->%sImmediate(%s);\n" %
5048 (func
.name
, func
.MakeOriginalArgString("")))
5049 file.Write(" CheckGLError();\n")
5053 def WriteGLES2ImplementationUnitTest(self
, func
, file):
5054 """Writes the GLES2 Implemention unit test."""
5055 client_test
= func
.GetInfo('client_test')
5056 if (client_test
!= None and client_test
!= True):
5059 TEST_F(GLES2ImplementationTest, %(name)s) {
5060 %(type)s data[%(count)d] = {0};
5062 cmds::%(name)sImmediate cmd;
5063 %(type)s data[%(count)d];
5066 for (int jj = 0; jj < %(count)d; ++jj) {
5067 data[jj] = static_cast<%(type)s>(jj);
5070 expected.cmd.Init(%(cmd_args)s, &data[0]);
5071 gl_->%(name)s(%(args)s, &data[0]);
5072 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
5076 arg
.GetValidClientSideCmdArg(func
) for arg
in func
.GetCmdArgs()[0:-2]
5079 arg
.GetValidClientSideArg(func
) for arg
in func
.GetOriginalArgs()[0:-1]
5084 'type': self
.GetArrayType(func
),
5085 'count': self
.GetArrayCount(func
),
5086 'args': ", ".join(gl_arg_strings
),
5087 'cmd_args': ", ".join(cmd_arg_strings
),
5090 def WriteImmediateCmdComputeSize(self
, func
, file):
5091 """Overrriden from TypeHandler."""
5092 file.Write(" static uint32_t ComputeDataSize() {\n")
5093 file.Write(" return static_cast<uint32_t>(\n")
5094 file.Write(" sizeof(%s) * %d); // NOLINT\n" %
5095 (self
.GetArrayType(func
), self
.GetArrayCount(func
)))
5098 file.Write(" static uint32_t ComputeSize() {\n")
5099 file.Write(" return static_cast<uint32_t>(\n")
5101 " sizeof(ValueType) + ComputeDataSize()); // NOLINT\n")
5105 def WriteImmediateCmdSetHeader(self
, func
, file):
5106 """Overrriden from TypeHandler."""
5107 file.Write(" void SetHeader() {\n")
5109 " header.SetCmdByTotalSize<ValueType>(ComputeSize());\n")
5113 def WriteImmediateCmdInit(self
, func
, file):
5114 """Overrriden from TypeHandler."""
5115 last_arg
= func
.GetLastOriginalArg()
5116 file.Write(" void Init(%s, %s _%s) {\n" %
5117 (func
.MakeTypedCmdArgString("_"),
5118 last_arg
.type, last_arg
.name
))
5119 file.Write(" SetHeader();\n")
5120 args
= func
.GetCmdArgs()
5122 file.Write(" %s = _%s;\n" % (arg
.name
, arg
.name
))
5123 file.Write(" memcpy(ImmediateDataAddress(this),\n")
5124 file.Write(" _%s, ComputeDataSize());\n" % last_arg
.name
)
5128 def WriteImmediateCmdSet(self
, func
, file):
5129 """Overrriden from TypeHandler."""
5130 last_arg
= func
.GetLastOriginalArg()
5131 copy_args
= func
.MakeCmdArgString("_", False)
5132 file.Write(" void* Set(void* cmd%s, %s _%s) {\n" %
5133 (func
.MakeTypedCmdArgString("_", True),
5134 last_arg
.type, last_arg
.name
))
5135 file.Write(" static_cast<ValueType*>(cmd)->Init(%s, _%s);\n" %
5136 (copy_args
, last_arg
.name
))
5137 file.Write(" const uint32_t size = ComputeSize();\n")
5138 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
5143 def WriteImmediateCmdHelper(self
, func
, file):
5144 """Overrriden from TypeHandler."""
5145 code
= """ void %(name)s(%(typed_args)s) {
5146 const uint32_t size = gles2::cmds::%(name)s::ComputeSize();
5147 gles2::cmds::%(name)s* c =
5148 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
5157 "typed_args": func
.MakeTypedOriginalArgString(""),
5158 "args": func
.MakeOriginalArgString(""),
5161 def WriteImmediateFormatTest(self
, func
, file):
5162 """Overrriden from TypeHandler."""
5163 file.Write("TEST_F(GLES2FormatTest, %s) {\n" % func
.name
)
5164 file.Write(" const int kSomeBaseValueToTestWith = 51;\n")
5165 file.Write(" static %s data[] = {\n" % self
.GetArrayType(func
))
5166 for v
in range(0, self
.GetArrayCount(func
)):
5167 file.Write(" static_cast<%s>(kSomeBaseValueToTestWith + %d),\n" %
5168 (self
.GetArrayType(func
), v
))
5170 file.Write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
5171 (func
.name
, func
.name
))
5172 file.Write(" void* next_cmd = cmd.Set(\n")
5174 args
= func
.GetCmdArgs()
5175 for value
, arg
in enumerate(args
):
5176 file.Write(",\n static_cast<%s>(%d)" % (arg
.type, value
+ 11))
5177 file.Write(",\n data);\n")
5178 args
= func
.GetCmdArgs()
5179 file.Write(" EXPECT_EQ(static_cast<uint32_t>(cmds::%s::kCmdId),\n"
5181 file.Write(" cmd.header.command);\n")
5182 file.Write(" EXPECT_EQ(sizeof(cmd) +\n")
5183 file.Write(" RoundSizeToMultipleOfEntries(sizeof(data)),\n")
5184 file.Write(" cmd.header.size * 4u);\n")
5185 for value
, arg
in enumerate(args
):
5186 file.Write(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);\n" %
5187 (arg
.type, value
+ 11, arg
.name
))
5188 file.Write(" CheckBytesWrittenMatchesExpectedSize(\n")
5189 file.Write(" next_cmd, sizeof(cmd) +\n")
5190 file.Write(" RoundSizeToMultipleOfEntries(sizeof(data)));\n")
5191 file.Write(" // TODO(gman): Check that data was inserted;\n")
5196 class PUTnHandler(ArrayArgTypeHandler
):
5197 """Handler for PUTn 'glUniform__v' type functions."""
5200 ArrayArgTypeHandler
.__init
__(self
)
5202 def WriteServiceUnitTest(self
, func
, file, *extras
):
5203 """Overridden from TypeHandler."""
5204 ArrayArgTypeHandler
.WriteServiceUnitTest(self
, func
, file, *extras
)
5207 TEST_P(%(test_name)s, %(name)sValidArgsCountTooLarge) {
5208 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
5209 SpecializedSetup<cmds::%(name)s, 0>(true);
5212 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5213 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5218 for count
, arg
in enumerate(func
.GetOriginalArgs()):
5219 # hardcoded to match unit tests.
5221 # the location of the second element of the 2nd uniform.
5222 # defined in GLES2DecoderBase::SetupShaderForUniform
5223 gl_arg_strings
.append("3")
5224 arg_strings
.append("ProgramManager::MakeFakeLocation(1, 1)")
5226 # the number of elements that gl will be called with.
5227 gl_arg_strings
.append("3")
5228 # the number of elements requested in the command.
5229 arg_strings
.append("5")
5231 gl_arg_strings
.append(arg
.GetValidGLArg(func
))
5232 if not arg
.IsConstant():
5233 arg_strings
.append(arg
.GetValidArg(func
))
5235 'gl_args': ", ".join(gl_arg_strings
),
5236 'args': ", ".join(arg_strings
),
5238 self
.WriteValidUnitTest(func
, file, valid_test
, extra
, *extras
)
5240 def WriteImmediateServiceUnitTest(self
, func
, file, *extras
):
5241 """Overridden from TypeHandler."""
5243 TEST_P(%(test_name)s, %(name)sValidArgs) {
5244 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
5247 %(gl_func_name)s(%(gl_args)s,
5248 reinterpret_cast<%(data_type)s*>(ImmediateDataAddress(&cmd))));
5249 SpecializedSetup<cmds::%(name)s, 0>(true);
5250 %(data_type)s temp[%(data_count)s * 2] = { 0, };
5251 cmd.Init(%(args)s, &temp[0]);
5252 EXPECT_EQ(error::kNoError,
5253 ExecuteImmediateCmd(cmd, sizeof(temp)));
5254 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5260 for arg
in func
.GetOriginalArgs()[0:-1]:
5261 gl_arg_strings
.append(arg
.GetValidGLArg(func
))
5262 gl_any_strings
.append("_")
5263 if not arg
.IsConstant():
5264 arg_strings
.append(arg
.GetValidArg(func
))
5266 'data_type': self
.GetArrayType(func
),
5267 'data_count': self
.GetArrayCount(func
),
5268 'args': ", ".join(arg_strings
),
5269 'gl_args': ", ".join(gl_arg_strings
),
5270 'gl_any_args': ", ".join(gl_any_strings
),
5272 self
.WriteValidUnitTest(func
, file, valid_test
, extra
, *extras
)
5275 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
5276 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
5277 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_any_args)s, _)).Times(0);
5278 SpecializedSetup<cmds::%(name)s, 0>(false);
5279 %(data_type)s temp[%(data_count)s * 2] = { 0, };
5280 cmd.Init(%(all_but_last_args)s, &temp[0]);
5281 EXPECT_EQ(error::%(parse_result)s,
5282 ExecuteImmediateCmd(cmd, sizeof(temp)));%(gl_error_test)s
5285 self
.WriteInvalidUnitTest(func
, file, invalid_test
, extra
, *extras
)
5287 def WriteGetDataSizeCode(self
, func
, file):
5288 """Overrriden from TypeHandler."""
5289 code
= """ uint32_t data_size;
5290 if (!ComputeDataSize(count, sizeof(%s), %d, &data_size)) {
5291 return error::kOutOfBounds;
5294 file.Write(code
% (self
.GetArrayType(func
), self
.GetArrayCount(func
)))
5295 if func
.IsImmediate():
5296 file.Write(" if (data_size > immediate_data_size) {\n")
5297 file.Write(" return error::kOutOfBounds;\n")
5300 def WriteGLES2Implementation(self
, func
, file):
5301 """Overrriden from TypeHandler."""
5302 file.Write("%s GLES2Implementation::%s(%s) {\n" %
5303 (func
.return_type
, func
.original_name
,
5304 func
.MakeTypedOriginalArgString("")))
5305 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
5306 func
.WriteDestinationInitalizationValidation(file)
5307 self
.WriteClientGLCallLog(func
, file)
5308 last_arg_name
= func
.GetLastOriginalArg().name
5309 file.Write(""" GPU_CLIENT_LOG_CODE_BLOCK({
5310 for (GLsizei i = 0; i < count; ++i) {
5312 values_str
= ' << ", " << '.join(
5313 ["%s[%d + i * %d]" % (
5314 last_arg_name
, ndx
, self
.GetArrayCount(func
)) for ndx
in range(
5315 0, self
.GetArrayCount(func
))])
5316 file.Write(' GPU_CLIENT_LOG(" " << i << ": " << %s);\n' % values_str
)
5317 file.Write(" }\n });\n")
5318 for arg
in func
.GetOriginalArgs():
5319 arg
.WriteClientSideValidationCode(file, func
)
5320 file.Write(" helper_->%sImmediate(%s);\n" %
5321 (func
.name
, func
.MakeInitString("")))
5322 file.Write(" CheckGLError();\n")
5326 def WriteGLES2ImplementationUnitTest(self
, func
, file):
5327 """Writes the GLES2 Implemention unit test."""
5329 TEST_F(GLES2ImplementationTest, %(name)s) {
5330 %(type)s data[%(count_param)d][%(count)d] = {{0}};
5332 cmds::%(name)sImmediate cmd;
5333 %(type)s data[%(count_param)d][%(count)d];
5337 for (int ii = 0; ii < %(count_param)d; ++ii) {
5338 for (int jj = 0; jj < %(count)d; ++jj) {
5339 data[ii][jj] = static_cast<%(type)s>(ii * %(count)d + jj);
5342 expected.cmd.Init(%(cmd_args)s, &data[0][0]);
5343 gl_->%(name)s(%(args)s, &data[0][0]);
5344 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
5348 arg
.GetValidClientSideCmdArg(func
) for arg
in func
.GetCmdArgs()[0:-2]
5352 for arg
in func
.GetOriginalArgs()[0:-1]:
5353 valid_value
= arg
.GetValidClientSideArg(func
)
5354 gl_arg_strings
.append(valid_value
)
5355 if arg
.name
== "count":
5356 count_param
= int(valid_value
)
5359 'type': self
.GetArrayType(func
),
5360 'count': self
.GetArrayCount(func
),
5361 'args': ", ".join(gl_arg_strings
),
5362 'cmd_args': ", ".join(cmd_arg_strings
),
5363 'count_param': count_param
,
5366 # Test constants for invalid values, as they are not tested by the
5369 arg
for arg
in func
.GetOriginalArgs()[0:-1] if arg
.IsConstant()
5375 TEST_F(GLES2ImplementationTest, %(name)sInvalidConstantArg%(invalid_index)d) {
5376 %(type)s data[%(count_param)d][%(count)d] = {{0}};
5377 for (int ii = 0; ii < %(count_param)d; ++ii) {
5378 for (int jj = 0; jj < %(count)d; ++jj) {
5379 data[ii][jj] = static_cast<%(type)s>(ii * %(count)d + jj);
5382 gl_->%(name)s(%(args)s, &data[0][0]);
5383 EXPECT_TRUE(NoCommandsWritten());
5384 EXPECT_EQ(%(gl_error)s, CheckError());
5387 for invalid_arg
in constants
:
5389 invalid
= invalid_arg
.GetInvalidArg(func
)
5390 for arg
in func
.GetOriginalArgs()[0:-1]:
5391 if arg
is invalid_arg
:
5392 gl_arg_strings
.append(invalid
[0])
5394 valid_value
= arg
.GetValidClientSideArg(func
)
5395 gl_arg_strings
.append(valid_value
)
5396 if arg
.name
== "count":
5397 count_param
= int(valid_value
)
5401 'invalid_index': func
.GetOriginalArgs().index(invalid_arg
),
5402 'type': self
.GetArrayType(func
),
5403 'count': self
.GetArrayCount(func
),
5404 'args': ", ".join(gl_arg_strings
),
5405 'gl_error': invalid
[2],
5406 'count_param': count_param
,
5410 def WriteImmediateCmdComputeSize(self
, func
, file):
5411 """Overrriden from TypeHandler."""
5412 file.Write(" static uint32_t ComputeDataSize(GLsizei count) {\n")
5413 file.Write(" return static_cast<uint32_t>(\n")
5414 file.Write(" sizeof(%s) * %d * count); // NOLINT\n" %
5415 (self
.GetArrayType(func
), self
.GetArrayCount(func
)))
5418 file.Write(" static uint32_t ComputeSize(GLsizei count) {\n")
5419 file.Write(" return static_cast<uint32_t>(\n")
5421 " sizeof(ValueType) + ComputeDataSize(count)); // NOLINT\n")
5425 def WriteImmediateCmdSetHeader(self
, func
, file):
5426 """Overrriden from TypeHandler."""
5427 file.Write(" void SetHeader(GLsizei count) {\n")
5429 " header.SetCmdByTotalSize<ValueType>(ComputeSize(count));\n")
5433 def WriteImmediateCmdInit(self
, func
, file):
5434 """Overrriden from TypeHandler."""
5435 last_arg
= func
.GetLastOriginalArg()
5436 file.Write(" void Init(%s, %s _%s) {\n" %
5437 (func
.MakeTypedCmdArgString("_"),
5438 last_arg
.type, last_arg
.name
))
5439 file.Write(" SetHeader(_count);\n")
5440 args
= func
.GetCmdArgs()
5442 file.Write(" %s = _%s;\n" % (arg
.name
, arg
.name
))
5443 file.Write(" memcpy(ImmediateDataAddress(this),\n")
5444 file.Write(" _%s, ComputeDataSize(_count));\n" % last_arg
.name
)
5448 def WriteImmediateCmdSet(self
, func
, file):
5449 """Overrriden from TypeHandler."""
5450 last_arg
= func
.GetLastOriginalArg()
5451 copy_args
= func
.MakeCmdArgString("_", False)
5452 file.Write(" void* Set(void* cmd%s, %s _%s) {\n" %
5453 (func
.MakeTypedCmdArgString("_", True),
5454 last_arg
.type, last_arg
.name
))
5455 file.Write(" static_cast<ValueType*>(cmd)->Init(%s, _%s);\n" %
5456 (copy_args
, last_arg
.name
))
5457 file.Write(" const uint32_t size = ComputeSize(_count);\n")
5458 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
5463 def WriteImmediateCmdHelper(self
, func
, file):
5464 """Overrriden from TypeHandler."""
5465 code
= """ void %(name)s(%(typed_args)s) {
5466 const uint32_t size = gles2::cmds::%(name)s::ComputeSize(count);
5467 gles2::cmds::%(name)s* c =
5468 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
5477 "typed_args": func
.MakeTypedInitString(""),
5478 "args": func
.MakeInitString("")
5481 def WriteImmediateFormatTest(self
, func
, file):
5482 """Overrriden from TypeHandler."""
5483 args
= func
.GetCmdArgs()
5486 if arg
.name
== "count":
5487 count_param
= int(arg
.GetValidClientSideCmdArg(func
))
5488 file.Write("TEST_F(GLES2FormatTest, %s) {\n" % func
.name
)
5489 file.Write(" const int kSomeBaseValueToTestWith = 51;\n")
5490 file.Write(" static %s data[] = {\n" % self
.GetArrayType(func
))
5491 for v
in range(0, self
.GetArrayCount(func
) * count_param
):
5492 file.Write(" static_cast<%s>(kSomeBaseValueToTestWith + %d),\n" %
5493 (self
.GetArrayType(func
), v
))
5495 file.Write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
5496 (func
.name
, func
.name
))
5497 file.Write(" const GLsizei kNumElements = %d;\n" % count_param
)
5498 file.Write(" const size_t kExpectedCmdSize =\n")
5499 file.Write(" sizeof(cmd) + kNumElements * sizeof(%s) * %d;\n" %
5500 (self
.GetArrayType(func
), self
.GetArrayCount(func
)))
5501 file.Write(" void* next_cmd = cmd.Set(\n")
5503 for value
, arg
in enumerate(args
):
5504 file.Write(",\n static_cast<%s>(%d)" % (arg
.type, value
+ 1))
5505 file.Write(",\n data);\n")
5506 file.Write(" EXPECT_EQ(static_cast<uint32_t>(cmds::%s::kCmdId),\n" %
5508 file.Write(" cmd.header.command);\n")
5509 file.Write(" EXPECT_EQ(kExpectedCmdSize, cmd.header.size * 4u);\n")
5510 for value
, arg
in enumerate(args
):
5511 file.Write(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);\n" %
5512 (arg
.type, value
+ 1, arg
.name
))
5513 file.Write(" CheckBytesWrittenMatchesExpectedSize(\n")
5514 file.Write(" next_cmd, sizeof(cmd) +\n")
5515 file.Write(" RoundSizeToMultipleOfEntries(sizeof(data)));\n")
5516 file.Write(" // TODO(gman): Check that data was inserted;\n")
5521 class PUTXnHandler(ArrayArgTypeHandler
):
5522 """Handler for glUniform?f functions."""
5524 ArrayArgTypeHandler
.__init
__(self
)
5526 def WriteHandlerImplementation(self
, func
, file):
5527 """Overrriden from TypeHandler."""
5528 code
= """ %(type)s temp[%(count)s] = { %(values)s};
5529 Do%(name)sv(%(location)s, 1, &temp[0]);
5532 args
= func
.GetOriginalArgs()
5533 count
= int(self
.GetArrayCount(func
))
5534 num_args
= len(args
)
5535 for ii
in range(count
):
5536 values
+= "%s, " % args
[len(args
) - count
+ ii
].name
5540 'count': self
.GetArrayCount(func
),
5541 'type': self
.GetArrayType(func
),
5542 'location': args
[0].name
,
5543 'args': func
.MakeOriginalArgString(""),
5547 def WriteServiceUnitTest(self
, func
, file, *extras
):
5548 """Overrriden from TypeHandler."""
5550 TEST_P(%(test_name)s, %(name)sValidArgs) {
5551 EXPECT_CALL(*gl_, %(name)sv(%(local_args)s));
5552 SpecializedSetup<cmds::%(name)s, 0>(true);
5555 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5556 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5559 args
= func
.GetOriginalArgs()
5560 local_args
= "%s, 1, _" % args
[0].GetValidGLArg(func
)
5561 self
.WriteValidUnitTest(func
, file, valid_test
, {
5563 'count': self
.GetArrayCount(func
),
5564 'local_args': local_args
,
5568 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
5569 EXPECT_CALL(*gl_, %(name)sv(_, _, _).Times(0);
5570 SpecializedSetup<cmds::%(name)s, 0>(false);
5573 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
5576 self
.WriteInvalidUnitTest(func
, file, invalid_test
, {
5577 'name': func
.GetInfo('name'),
5578 'count': self
.GetArrayCount(func
),
5582 class GLcharHandler(CustomHandler
):
5583 """Handler for functions that pass a single string ."""
5586 CustomHandler
.__init
__(self
)
5588 def WriteImmediateCmdComputeSize(self
, func
, file):
5589 """Overrriden from TypeHandler."""
5590 file.Write(" static uint32_t ComputeSize(uint32_t data_size) {\n")
5591 file.Write(" return static_cast<uint32_t>(\n")
5592 file.Write(" sizeof(ValueType) + data_size); // NOLINT\n")
5595 def WriteImmediateCmdSetHeader(self
, func
, file):
5596 """Overrriden from TypeHandler."""
5598 void SetHeader(uint32_t data_size) {
5599 header.SetCmdBySize<ValueType>(data_size);
5604 def WriteImmediateCmdInit(self
, func
, file):
5605 """Overrriden from TypeHandler."""
5606 last_arg
= func
.GetLastOriginalArg()
5607 args
= func
.GetCmdArgs()
5610 set_code
.append(" %s = _%s;" % (arg
.name
, arg
.name
))
5612 void Init(%(typed_args)s, uint32_t _data_size) {
5613 SetHeader(_data_size);
5615 memcpy(ImmediateDataAddress(this), _%(last_arg)s, _data_size);
5620 "typed_args": func
.MakeTypedArgString("_"),
5621 "set_code": "\n".join(set_code
),
5622 "last_arg": last_arg
.name
5625 def WriteImmediateCmdSet(self
, func
, file):
5626 """Overrriden from TypeHandler."""
5627 last_arg
= func
.GetLastOriginalArg()
5628 file.Write(" void* Set(void* cmd%s, uint32_t _data_size) {\n" %
5629 func
.MakeTypedCmdArgString("_", True))
5630 file.Write(" static_cast<ValueType*>(cmd)->Init(%s, _data_size);\n" %
5631 func
.MakeCmdArgString("_"))
5632 file.Write(" return NextImmediateCmdAddress<ValueType>("
5633 "cmd, _data_size);\n")
5637 def WriteImmediateCmdHelper(self
, func
, file):
5638 """Overrriden from TypeHandler."""
5639 code
= """ void %(name)s(%(typed_args)s) {
5640 const uint32_t data_size = strlen(name);
5641 gles2::cmds::%(name)s* c =
5642 GetImmediateCmdSpace<gles2::cmds::%(name)s>(data_size);
5644 c->Init(%(args)s, data_size);
5651 "typed_args": func
.MakeTypedOriginalArgString(""),
5652 "args": func
.MakeOriginalArgString(""),
5656 def WriteImmediateFormatTest(self
, func
, file):
5657 """Overrriden from TypeHandler."""
5660 all_but_last_arg
= func
.GetCmdArgs()[:-1]
5661 for value
, arg
in enumerate(all_but_last_arg
):
5662 init_code
.append(" static_cast<%s>(%d)," % (arg
.type, value
+ 11))
5663 for value
, arg
in enumerate(all_but_last_arg
):
5664 check_code
.append(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);" %
5665 (arg
.type, value
+ 11, arg
.name
))
5667 TEST_F(GLES2FormatTest, %(func_name)s) {
5668 cmds::%(func_name)s& cmd = *GetBufferAs<cmds::%(func_name)s>();
5669 static const char* const test_str = \"test string\";
5670 void* next_cmd = cmd.Set(
5675 EXPECT_EQ(static_cast<uint32_t>(cmds::%(func_name)s::kCmdId),
5676 cmd.header.command);
5677 EXPECT_EQ(sizeof(cmd) +
5678 RoundSizeToMultipleOfEntries(strlen(test_str)),
5679 cmd.header.size * 4u);
5680 EXPECT_EQ(static_cast<char*>(next_cmd),
5681 reinterpret_cast<char*>(&cmd) + sizeof(cmd) +
5682 RoundSizeToMultipleOfEntries(strlen(test_str)));
5684 EXPECT_EQ(static_cast<uint32_t>(strlen(test_str)), cmd.data_size);
5685 EXPECT_EQ(0, memcmp(test_str, ImmediateDataAddress(&cmd), strlen(test_str)));
5688 sizeof(cmd) + RoundSizeToMultipleOfEntries(strlen(test_str)),
5689 sizeof(cmd) + strlen(test_str));
5694 'func_name': func
.name
,
5695 'init_code': "\n".join(init_code
),
5696 'check_code': "\n".join(check_code
),
5700 class GLcharNHandler(CustomHandler
):
5701 """Handler for functions that pass a single string with an optional len."""
5704 CustomHandler
.__init
__(self
)
5706 def InitFunction(self
, func
):
5707 """Overrriden from TypeHandler."""
5709 func
.AddCmdArg(Argument('bucket_id', 'GLuint'))
5711 def NeedsDataTransferFunction(self
, func
):
5712 """Overriden from TypeHandler."""
5715 def AddBucketFunction(self
, generator
, func
):
5716 """Overrriden from TypeHandler."""
5719 def WriteServiceImplementation(self
, func
, file):
5720 """Overrriden from TypeHandler."""
5721 self
.WriteServiceHandlerFunctionHeader(func
, file)
5723 GLuint bucket_id = static_cast<GLuint>(c.%(bucket_id)s);
5724 Bucket* bucket = GetBucket(bucket_id);
5725 if (!bucket || bucket->size() == 0) {
5726 return error::kInvalidArguments;
5729 if (!bucket->GetAsString(&str)) {
5730 return error::kInvalidArguments;
5732 %(gl_func_name)s(0, str.c_str());
5733 return error::kNoError;
5738 'gl_func_name': func
.GetGLFunctionName(),
5739 'bucket_id': func
.cmd_args
[0].name
,
5743 class IsHandler(TypeHandler
):
5744 """Handler for glIs____ type and glGetError functions."""
5747 TypeHandler
.__init
__(self
)
5749 def InitFunction(self
, func
):
5750 """Overrriden from TypeHandler."""
5751 func
.AddCmdArg(Argument("result_shm_id", 'uint32_t'))
5752 func
.AddCmdArg(Argument("result_shm_offset", 'uint32_t'))
5753 if func
.GetInfo('result') == None:
5754 func
.AddInfo('result', ['uint32_t'])
5756 def WriteServiceUnitTest(self
, func
, file, *extras
):
5757 """Overrriden from TypeHandler."""
5759 TEST_P(%(test_name)s, %(name)sValidArgs) {
5760 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
5761 SpecializedSetup<cmds::%(name)s, 0>(true);
5763 cmd.Init(%(args)s%(comma)sshared_memory_id_, shared_memory_offset_);
5764 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5765 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5769 if len(func
.GetOriginalArgs()):
5771 self
.WriteValidUnitTest(func
, file, valid_test
, {
5776 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
5777 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
5778 SpecializedSetup<cmds::%(name)s, 0>(false);
5780 cmd.Init(%(args)s%(comma)sshared_memory_id_, shared_memory_offset_);
5781 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
5784 self
.WriteInvalidUnitTest(func
, file, invalid_test
, {
5789 TEST_P(%(test_name)s, %(name)sInvalidArgsBadSharedMemoryId) {
5790 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
5791 SpecializedSetup<cmds::%(name)s, 0>(false);
5793 cmd.Init(%(args)s%(comma)skInvalidSharedMemoryId, shared_memory_offset_);
5794 EXPECT_EQ(error::kOutOfBounds, ExecuteCmd(cmd));
5795 cmd.Init(%(args)s%(comma)sshared_memory_id_, kInvalidSharedMemoryOffset);
5796 EXPECT_EQ(error::kOutOfBounds, ExecuteCmd(cmd));
5799 self
.WriteValidUnitTest(func
, file, invalid_test
, {
5803 def WriteServiceImplementation(self
, func
, file):
5804 """Overrriden from TypeHandler."""
5805 self
.WriteServiceHandlerFunctionHeader(func
, file)
5806 args
= func
.GetOriginalArgs()
5808 arg
.WriteGetCode(file)
5810 code
= """ typedef cmds::%(func_name)s::Result Result;
5811 Result* result_dst = GetSharedMemoryAs<Result*>(
5812 c.result_shm_id, c.result_shm_offset, sizeof(*result_dst));
5814 return error::kOutOfBounds;
5817 file.Write(code
% {'func_name': func
.name
})
5818 func
.WriteHandlerValidation(file)
5819 file.Write(" *result_dst = %s(%s);\n" %
5820 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
5821 file.Write(" return error::kNoError;\n")
5825 def WriteGLES2Implementation(self
, func
, file):
5826 """Overrriden from TypeHandler."""
5827 impl_func
= func
.GetInfo('impl_func')
5828 if impl_func
== None or impl_func
== True:
5829 error_value
= func
.GetInfo("error_value") or "GL_FALSE"
5830 file.Write("%s GLES2Implementation::%s(%s) {\n" %
5831 (func
.return_type
, func
.original_name
,
5832 func
.MakeTypedOriginalArgString("")))
5833 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
5834 self
.WriteTraceEvent(func
, file)
5835 func
.WriteDestinationInitalizationValidation(file)
5836 self
.WriteClientGLCallLog(func
, file)
5837 file.Write(" typedef cmds::%s::Result Result;\n" % func
.name
)
5838 file.Write(" Result* result = GetResultAs<Result*>();\n")
5839 file.Write(" if (!result) {\n")
5840 file.Write(" return %s;\n" % error_value
)
5842 file.Write(" *result = 0;\n")
5843 arg_string
= func
.MakeOriginalArgString("")
5845 if len(arg_string
) > 0:
5848 " helper_->%s(%s%sGetResultShmId(), GetResultShmOffset());\n" %
5849 (func
.name
, arg_string
, comma
))
5850 file.Write(" WaitForCmd();\n")
5851 file.Write(" %s result_value = *result" % func
.return_type
)
5852 if func
.return_type
== "GLboolean":
5854 file.Write(';\n GPU_CLIENT_LOG("returned " << result_value);\n')
5855 file.Write(" CheckGLError();\n")
5856 file.Write(" return result_value;\n")
5860 def WriteGLES2ImplementationUnitTest(self
, func
, file):
5861 """Overrriden from TypeHandler."""
5862 client_test
= func
.GetInfo('client_test')
5863 if client_test
== None or client_test
== True:
5865 TEST_F(GLES2ImplementationTest, %(name)s) {
5871 ExpectedMemoryInfo result1 =
5872 GetExpectedResultMemory(sizeof(cmds::%(name)s::Result));
5873 expected.cmd.Init(1, result1.id, result1.offset);
5875 EXPECT_CALL(*command_buffer(), OnFlush())
5876 .WillOnce(SetMemory(result1.ptr, uint32_t(1)))
5877 .RetiresOnSaturation();
5879 GLboolean result = gl_->%(name)s(1);
5880 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
5881 EXPECT_TRUE(result);
5889 class STRnHandler(TypeHandler
):
5890 """Handler for GetProgramInfoLog, GetShaderInfoLog, GetShaderSource, and
5891 GetTranslatedShaderSourceANGLE."""
5894 TypeHandler
.__init
__(self
)
5896 def InitFunction(self
, func
):
5897 """Overrriden from TypeHandler."""
5898 # remove all but the first cmd args.
5899 cmd_args
= func
.GetCmdArgs()
5901 func
.AddCmdArg(cmd_args
[0])
5902 # add on a bucket id.
5903 func
.AddCmdArg(Argument('bucket_id', 'uint32_t'))
5905 def WriteGLES2Implementation(self
, func
, file):
5906 """Overrriden from TypeHandler."""
5907 code_1
= """%(return_type)s GLES2Implementation::%(func_name)s(%(args)s) {
5908 GPU_CLIENT_SINGLE_THREAD_CHECK();
5910 code_2
= """ GPU_CLIENT_LOG("[" << GetLogPrefix()
5911 << "] gl%(func_name)s" << "("
5914 << static_cast<void*>(%(arg2)s) << ", "
5915 << static_cast<void*>(%(arg3)s) << ")");
5916 helper_->SetBucketSize(kResultBucketId, 0);
5917 helper_->%(func_name)s(%(id_name)s, kResultBucketId);
5919 GLsizei max_size = 0;
5920 if (GetBucketAsString(kResultBucketId, &str)) {
5923 std::min(static_cast<size_t>(%(bufsize_name)s) - 1, str.size());
5924 memcpy(%(dest_name)s, str.c_str(), max_size);
5925 %(dest_name)s[max_size] = '\\0';
5926 GPU_CLIENT_LOG("------\\n" << %(dest_name)s << "\\n------");
5929 if (%(length_name)s != NULL) {
5930 *%(length_name)s = max_size;
5935 args
= func
.GetOriginalArgs()
5937 'return_type': func
.return_type
,
5938 'func_name': func
.original_name
,
5939 'args': func
.MakeTypedOriginalArgString(""),
5940 'id_name': args
[0].name
,
5941 'bufsize_name': args
[1].name
,
5942 'length_name': args
[2].name
,
5943 'dest_name': args
[3].name
,
5944 'arg0': args
[0].name
,
5945 'arg1': args
[1].name
,
5946 'arg2': args
[2].name
,
5947 'arg3': args
[3].name
,
5949 file.Write(code_1
% str_args
)
5950 func
.WriteDestinationInitalizationValidation(file)
5951 file.Write(code_2
% str_args
)
5953 def WriteServiceUnitTest(self
, func
, file, *extras
):
5954 """Overrriden from TypeHandler."""
5956 TEST_P(%(test_name)s, %(name)sValidArgs) {
5957 const char* kInfo = "hello";
5958 const uint32_t kBucketId = 123;
5959 SpecializedSetup<cmds::%(name)s, 0>(true);
5961 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s))
5962 .WillOnce(DoAll(SetArgumentPointee<2>(strlen(kInfo)),
5963 SetArrayArgument<3>(kInfo, kInfo + strlen(kInfo) + 1)));
5966 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5967 CommonDecoder::Bucket* bucket = decoder_->GetBucket(kBucketId);
5968 ASSERT_TRUE(bucket != NULL);
5969 EXPECT_EQ(strlen(kInfo) + 1, bucket->size());
5970 EXPECT_EQ(0, memcmp(bucket->GetData(0, bucket->size()), kInfo,
5972 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5975 args
= func
.GetOriginalArgs()
5976 id_name
= args
[0].GetValidGLArg(func
)
5977 get_len_func
= func
.GetInfo('get_len_func')
5978 get_len_enum
= func
.GetInfo('get_len_enum')
5981 'get_len_func': get_len_func
,
5982 'get_len_enum': get_len_enum
,
5983 'gl_args': '%s, strlen(kInfo) + 1, _, _' %
5984 args
[0].GetValidGLArg(func
),
5985 'args': '%s, kBucketId' % args
[0].GetValidArg(func
),
5986 'expect_len_code': '',
5988 if get_len_func
and get_len_func
[0:2] == 'gl':
5989 sub
['expect_len_code'] = (
5990 " EXPECT_CALL(*gl_, %s(%s, %s, _))\n"
5991 " .WillOnce(SetArgumentPointee<2>(strlen(kInfo) + 1));") % (
5992 get_len_func
[2:], id_name
, get_len_enum
)
5993 self
.WriteValidUnitTest(func
, file, valid_test
, sub
, *extras
)
5996 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
5997 const uint32_t kBucketId = 123;
5998 EXPECT_CALL(*gl_, %(gl_func_name)s(_, _, _, _))
6001 cmd.Init(kInvalidClientId, kBucketId);
6002 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
6003 EXPECT_EQ(GL_INVALID_VALUE, GetGLError());
6006 self
.WriteValidUnitTest(func
, file, invalid_test
, *extras
)
6008 def WriteServiceImplementation(self
, func
, file):
6009 """Overrriden from TypeHandler."""
6012 class NamedType(object):
6013 """A class that represents a type of an argument in a client function.
6015 A type of an argument that is to be passed through in the command buffer
6016 command. Currently used only for the arguments that are specificly named in
6017 the 'cmd_buffer_functions.txt' file, mostly enums.
6020 def __init__(self
, info
):
6021 assert not 'is_complete' in info
or info
['is_complete'] == True
6023 self
.valid
= info
['valid']
6024 if 'invalid' in info
:
6025 self
.invalid
= info
['invalid']
6030 return self
.info
['type']
6032 def GetInvalidValues(self
):
6035 def GetValidValues(self
):
6038 def IsConstant(self
):
6039 if not 'is_complete' in self
.info
:
6042 return len(self
.GetValidValues()) == 1
6044 def GetConstantValue(self
):
6045 return self
.GetValidValues()[0]
6047 class Argument(object):
6048 """A class that represents a function argument."""
6051 'GLenum': 'uint32_t',
6053 'GLintptr': 'int32_t',
6054 'GLsizei': 'int32_t',
6055 'GLsizeiptr': 'int32_t',
6057 'GLclampf': 'float',
6059 need_validation_
= ['GLsizei*', 'GLboolean*', 'GLenum*', 'GLint*']
6061 def __init__(self
, name
, type):
6063 self
.optional
= type.endswith("Optional*")
6065 type = type[:-9] + "*"
6068 if type in self
.cmd_type_map_
:
6069 self
.cmd_type
= self
.cmd_type_map_
[type]
6071 self
.cmd_type
= 'uint32_t'
6073 def IsPointer(self
):
6074 """Returns true if argument is a pointer."""
6077 def IsConstant(self
):
6078 """Returns true if the argument has only one valid value."""
6081 def AddCmdArgs(self
, args
):
6082 """Adds command arguments for this argument to the given list."""
6083 if not self
.IsConstant():
6084 return args
.append(self
)
6086 def AddInitArgs(self
, args
):
6087 """Adds init arguments for this argument to the given list."""
6088 if not self
.IsConstant():
6089 return args
.append(self
)
6091 def GetValidArg(self
, func
):
6092 """Gets a valid value for this argument."""
6093 valid_arg
= func
.GetValidArg(self
)
6094 if valid_arg
!= None:
6097 index
= func
.GetOriginalArgs().index(self
)
6098 return str(index
+ 1)
6100 def GetValidClientSideArg(self
, func
):
6101 """Gets a valid value for this argument."""
6102 valid_arg
= func
.GetValidArg(self
)
6103 if valid_arg
!= None:
6106 index
= func
.GetOriginalArgs().index(self
)
6107 return str(index
+ 1)
6109 def GetValidClientSideCmdArg(self
, func
):
6110 """Gets a valid value for this argument."""
6111 valid_arg
= func
.GetValidArg(self
)
6112 if valid_arg
!= None:
6115 index
= func
.GetOriginalArgs().index(self
)
6116 return str(index
+ 1)
6119 index
= func
.GetCmdArgs().index(self
)
6120 return str(index
+ 1)
6122 def GetValidGLArg(self
, func
):
6123 """Gets a valid GL value for this argument."""
6124 return self
.GetValidArg(func
)
6126 def GetValidNonCachedClientSideArg(self
, func
):
6127 """Returns a valid value for this argument in a GL call.
6128 Using the value will produce a command buffer service invocation.
6129 Returns None if there is no such value."""
6132 def GetValidNonCachedClientSideCmdArg(self
, func
):
6133 """Returns a valid value for this argument in a command buffer command.
6134 Calling the GL function with the value returned by
6135 GetValidNonCachedClientSideArg will result in a command buffer command
6136 that contains the value returned by this function. """
6139 def GetNumInvalidValues(self
, func
):
6140 """returns the number of invalid values to be tested."""
6143 def GetInvalidArg(self
, index
):
6144 """returns an invalid value and expected parse result by index."""
6145 return ("---ERROR0---", "---ERROR2---", None)
6147 def GetLogArg(self
):
6148 """Get argument appropriate for LOG macro."""
6149 if self
.type == 'GLboolean':
6150 return 'GLES2Util::GetStringBool(%s)' % self
.name
6151 if self
.type == 'GLenum':
6152 return 'GLES2Util::GetStringEnum(%s)' % self
.name
6155 def WriteGetCode(self
, file):
6156 """Writes the code to get an argument from a command structure."""
6157 file.Write(" %s %s = static_cast<%s>(c.%s);\n" %
6158 (self
.type, self
.name
, self
.type, self
.name
))
6160 def WriteValidationCode(self
, file, func
):
6161 """Writes the validation code for an argument."""
6164 def WriteClientSideValidationCode(self
, file, func
):
6165 """Writes the validation code for an argument."""
6168 def WriteDestinationInitalizationValidation(self
, file, func
):
6169 """Writes the client side destintion initialization validation."""
6172 def WriteDestinationInitalizationValidatationIfNeeded(self
, file, func
):
6173 """Writes the client side destintion initialization validation if needed."""
6174 parts
= self
.type.split(" ")
6177 if parts
[0] in self
.need_validation_
:
6179 " GPU_CLIENT_VALIDATE_DESTINATION_%sINITALIZATION(%s, %s);\n" %
6180 ("OPTIONAL_" if self
.optional
else "", self
.type[:-1], self
.name
))
6183 def WriteGetAddress(self
, file):
6184 """Writes the code to get the address this argument refers to."""
6187 def GetImmediateVersion(self
):
6188 """Gets the immediate version of this argument."""
6191 def GetBucketVersion(self
):
6192 """Gets the bucket version of this argument."""
6196 class BoolArgument(Argument
):
6197 """class for GLboolean"""
6199 def __init__(self
, name
, type):
6200 Argument
.__init
__(self
, name
, 'GLboolean')
6202 def GetValidArg(self
, func
):
6203 """Gets a valid value for this argument."""
6206 def GetValidClientSideArg(self
, func
):
6207 """Gets a valid value for this argument."""
6210 def GetValidClientSideCmdArg(self
, func
):
6211 """Gets a valid value for this argument."""
6214 def GetValidGLArg(self
, func
):
6215 """Gets a valid GL value for this argument."""
6219 class UniformLocationArgument(Argument
):
6220 """class for uniform locations."""
6222 def __init__(self
, name
):
6223 Argument
.__init
__(self
, name
, "GLint")
6225 def WriteGetCode(self
, file):
6226 """Writes the code to get an argument from a command structure."""
6227 code
= """ %s %s = static_cast<%s>(c.%s);
6229 file.Write(code
% (self
.type, self
.name
, self
.type, self
.name
))
6231 class DataSizeArgument(Argument
):
6232 """class for data_size which Bucket commands do not need."""
6234 def __init__(self
, name
):
6235 Argument
.__init
__(self
, name
, "uint32_t")
6237 def GetBucketVersion(self
):
6241 class SizeArgument(Argument
):
6242 """class for GLsizei and GLsizeiptr."""
6244 def __init__(self
, name
, type):
6245 Argument
.__init
__(self
, name
, type)
6247 def GetNumInvalidValues(self
, func
):
6248 """overridden from Argument."""
6249 if func
.IsImmediate():
6253 def GetInvalidArg(self
, index
):
6254 """overridden from Argument."""
6255 return ("-1", "kNoError", "GL_INVALID_VALUE")
6257 def WriteValidationCode(self
, file, func
):
6258 """overridden from Argument."""
6259 file.Write(" if (%s < 0) {\n" % self
.name
)
6261 " LOCAL_SET_GL_ERROR(GL_INVALID_VALUE, \"gl%s\", \"%s < 0\");\n" %
6262 (func
.original_name
, self
.name
))
6263 file.Write(" return error::kNoError;\n")
6266 def WriteClientSideValidationCode(self
, file, func
):
6267 """overridden from Argument."""
6268 file.Write(" if (%s < 0) {\n" % self
.name
)
6270 " SetGLError(GL_INVALID_VALUE, \"gl%s\", \"%s < 0\");\n" %
6271 (func
.original_name
, self
.name
))
6272 file.Write(" return;\n")
6276 class SizeNotNegativeArgument(SizeArgument
):
6277 """class for GLsizeiNotNegative. It's NEVER allowed to be negative"""
6279 def __init__(self
, name
, type, gl_type
):
6280 SizeArgument
.__init
__(self
, name
, gl_type
)
6282 def GetInvalidArg(self
, index
):
6283 """overridden from SizeArgument."""
6284 return ("-1", "kOutOfBounds", "GL_NO_ERROR")
6286 def WriteValidationCode(self
, file, func
):
6287 """overridden from SizeArgument."""
6291 class EnumBaseArgument(Argument
):
6292 """Base class for EnumArgument, IntArgument and ValidatedBoolArgument"""
6294 def __init__(self
, name
, gl_type
, type, gl_error
):
6295 Argument
.__init
__(self
, name
, gl_type
)
6297 self
.local_type
= type
6298 self
.gl_error
= gl_error
6299 name
= type[len(gl_type
):]
6300 self
.type_name
= name
6301 self
.named_type
= NamedType(_NAMED_TYPE_INFO
[name
])
6303 def IsConstant(self
):
6304 return self
.named_type
.IsConstant()
6306 def GetConstantValue(self
):
6307 return self
.named_type
.GetConstantValue()
6309 def WriteValidationCode(self
, file, func
):
6310 if self
.named_type
.IsConstant():
6312 file.Write(" if (!validators_->%s.IsValid(%s)) {\n" %
6313 (ToUnderscore(self
.type_name
), self
.name
))
6314 if self
.gl_error
== "GL_INVALID_ENUM":
6316 " LOCAL_SET_GL_ERROR_INVALID_ENUM(\"gl%s\", %s, \"%s\");\n" %
6317 (func
.original_name
, self
.name
, self
.name
))
6320 " LOCAL_SET_GL_ERROR(%s, \"gl%s\", \"%s %s\");\n" %
6321 (self
.gl_error
, func
.original_name
, self
.name
, self
.gl_error
))
6322 file.Write(" return error::kNoError;\n")
6325 def WriteClientSideValidationCode(self
, file, func
):
6326 if not self
.named_type
.IsConstant():
6328 file.Write(" if (%s != %s) {" % (self
.name
,
6329 self
.GetConstantValue()))
6331 " SetGLError(%s, \"gl%s\", \"%s %s\");\n" %
6332 (self
.gl_error
, func
.original_name
, self
.name
, self
.gl_error
))
6333 if func
.return_type
== "void":
6334 file.Write(" return;\n")
6336 file.Write(" return %s;\n" % func
.GetErrorReturnString())
6339 def GetValidArg(self
, func
):
6340 valid_arg
= func
.GetValidArg(self
)
6341 if valid_arg
!= None:
6343 valid
= self
.named_type
.GetValidValues()
6345 num_valid
= len(valid
)
6348 index
= func
.GetOriginalArgs().index(self
)
6349 return str(index
+ 1)
6351 def GetValidClientSideArg(self
, func
):
6352 """Gets a valid value for this argument."""
6353 return self
.GetValidArg(func
)
6355 def GetValidClientSideCmdArg(self
, func
):
6356 """Gets a valid value for this argument."""
6357 valid_arg
= func
.GetValidArg(self
)
6358 if valid_arg
!= None:
6361 valid
= self
.named_type
.GetValidValues()
6363 num_valid
= len(valid
)
6367 index
= func
.GetOriginalArgs().index(self
)
6368 return str(index
+ 1)
6371 index
= func
.GetCmdArgs().index(self
)
6372 return str(index
+ 1)
6374 def GetValidGLArg(self
, func
):
6375 """Gets a valid value for this argument."""
6376 return self
.GetValidArg(func
)
6378 def GetNumInvalidValues(self
, func
):
6379 """returns the number of invalid values to be tested."""
6380 return len(self
.named_type
.GetInvalidValues())
6382 def GetInvalidArg(self
, index
):
6383 """returns an invalid value by index."""
6384 invalid
= self
.named_type
.GetInvalidValues()
6386 num_invalid
= len(invalid
)
6387 if index
>= num_invalid
:
6388 index
= num_invalid
- 1
6389 return (invalid
[index
], "kNoError", self
.gl_error
)
6390 return ("---ERROR1---", "kNoError", self
.gl_error
)
6393 class EnumArgument(EnumBaseArgument
):
6394 """A class that represents a GLenum argument"""
6396 def __init__(self
, name
, type):
6397 EnumBaseArgument
.__init
__(self
, name
, "GLenum", type, "GL_INVALID_ENUM")
6399 def GetLogArg(self
):
6400 """Overridden from Argument."""
6401 return ("GLES2Util::GetString%s(%s)" %
6402 (self
.type_name
, self
.name
))
6405 class IntArgument(EnumBaseArgument
):
6406 """A class for a GLint argument that can only except specific values.
6408 For example glTexImage2D takes a GLint for its internalformat
6409 argument instead of a GLenum.
6412 def __init__(self
, name
, type):
6413 EnumBaseArgument
.__init
__(self
, name
, "GLint", type, "GL_INVALID_VALUE")
6416 class ValidatedBoolArgument(EnumBaseArgument
):
6417 """A class for a GLboolean argument that can only except specific values.
6419 For example glUniformMatrix takes a GLboolean for it's transpose but it
6423 def __init__(self
, name
, type):
6424 EnumBaseArgument
.__init
__(self
, name
, "GLboolean", type, "GL_INVALID_VALUE")
6426 def GetLogArg(self
):
6427 """Overridden from Argument."""
6428 return 'GLES2Util::GetStringBool(%s)' % self
.name
6431 class ImmediatePointerArgument(Argument
):
6432 """A class that represents an immediate argument to a function.
6434 An immediate argument is one where the data follows the command.
6437 def __init__(self
, name
, type):
6438 Argument
.__init
__(self
, name
, type)
6440 def IsPointer(self
):
6443 def GetPointedType(self
):
6444 match
= re
.match('(const\s+)?(?P<element_type>[\w]+)\s*\*', self
.type)
6446 return match
.groupdict()['element_type']
6448 def AddCmdArgs(self
, args
):
6449 """Overridden from Argument."""
6452 def WriteGetCode(self
, file):
6453 """Overridden from Argument."""
6455 " %s %s = GetImmediateDataAs<%s>(\n" %
6456 (self
.type, self
.name
, self
.type))
6457 file.Write(" c, data_size, immediate_data_size);\n")
6459 def WriteValidationCode(self
, file, func
):
6460 """Overridden from Argument."""
6461 file.Write(" if (%s == NULL) {\n" % self
.name
)
6462 file.Write(" return error::kOutOfBounds;\n")
6465 def GetImmediateVersion(self
):
6466 """Overridden from Argument."""
6469 def WriteDestinationInitalizationValidation(self
, file, func
):
6470 """Overridden from Argument."""
6471 self
.WriteDestinationInitalizationValidatationIfNeeded(file, func
)
6473 def GetLogArg(self
):
6474 """Overridden from Argument."""
6475 return "static_cast<const void*>(%s)" % self
.name
6478 class BucketPointerArgument(Argument
):
6479 """A class that represents an bucket argument to a function."""
6481 def __init__(self
, name
, type):
6482 Argument
.__init
__(self
, name
, type)
6484 def AddCmdArgs(self
, args
):
6485 """Overridden from Argument."""
6488 def WriteGetCode(self
, file):
6489 """Overridden from Argument."""
6491 " %s %s = bucket->GetData(0, data_size);\n" %
6492 (self
.type, self
.name
))
6494 def WriteValidationCode(self
, file, func
):
6495 """Overridden from Argument."""
6498 def GetImmediateVersion(self
):
6499 """Overridden from Argument."""
6502 def WriteDestinationInitalizationValidation(self
, file, func
):
6503 """Overridden from Argument."""
6504 self
.WriteDestinationInitalizationValidatationIfNeeded(file, func
)
6506 def GetLogArg(self
):
6507 """Overridden from Argument."""
6508 return "static_cast<const void*>(%s)" % self
.name
6511 class PointerArgument(Argument
):
6512 """A class that represents a pointer argument to a function."""
6514 def __init__(self
, name
, type):
6515 Argument
.__init
__(self
, name
, type)
6517 def IsPointer(self
):
6518 """Returns true if argument is a pointer."""
6521 def GetPointedType(self
):
6522 match
= re
.match('(const\s+)?(?P<element_type>[\w]+)\s*\*', self
.type)
6524 return match
.groupdict()['element_type']
6526 def GetValidArg(self
, func
):
6527 """Overridden from Argument."""
6528 return "shared_memory_id_, shared_memory_offset_"
6530 def GetValidGLArg(self
, func
):
6531 """Overridden from Argument."""
6532 return "reinterpret_cast<%s>(shared_memory_address_)" % self
.type
6534 def GetNumInvalidValues(self
, func
):
6535 """Overridden from Argument."""
6538 def GetInvalidArg(self
, index
):
6539 """Overridden from Argument."""
6541 return ("kInvalidSharedMemoryId, 0", "kOutOfBounds", None)
6543 return ("shared_memory_id_, kInvalidSharedMemoryOffset",
6544 "kOutOfBounds", None)
6546 def GetLogArg(self
):
6547 """Overridden from Argument."""
6548 return "static_cast<const void*>(%s)" % self
.name
6550 def AddCmdArgs(self
, args
):
6551 """Overridden from Argument."""
6552 args
.append(Argument("%s_shm_id" % self
.name
, 'uint32_t'))
6553 args
.append(Argument("%s_shm_offset" % self
.name
, 'uint32_t'))
6555 def WriteGetCode(self
, file):
6556 """Overridden from Argument."""
6558 " %s %s = GetSharedMemoryAs<%s>(\n" %
6559 (self
.type, self
.name
, self
.type))
6561 " c.%s_shm_id, c.%s_shm_offset, data_size);\n" %
6562 (self
.name
, self
.name
))
6564 def WriteGetAddress(self
, file):
6565 """Overridden from Argument."""
6567 " %s %s = GetSharedMemoryAs<%s>(\n" %
6568 (self
.type, self
.name
, self
.type))
6570 " %s_shm_id, %s_shm_offset, %s_size);\n" %
6571 (self
.name
, self
.name
, self
.name
))
6573 def WriteValidationCode(self
, file, func
):
6574 """Overridden from Argument."""
6575 file.Write(" if (%s == NULL) {\n" % self
.name
)
6576 file.Write(" return error::kOutOfBounds;\n")
6579 def GetImmediateVersion(self
):
6580 """Overridden from Argument."""
6581 return ImmediatePointerArgument(self
.name
, self
.type)
6583 def GetBucketVersion(self
):
6584 """Overridden from Argument."""
6585 if self
.type == "const char*":
6586 return InputStringBucketArgument(self
.name
, self
.type)
6587 return BucketPointerArgument(self
.name
, self
.type)
6589 def WriteDestinationInitalizationValidation(self
, file, func
):
6590 """Overridden from Argument."""
6591 self
.WriteDestinationInitalizationValidatationIfNeeded(file, func
)
6594 class InputStringBucketArgument(Argument
):
6595 """An string input argument where the string is passed in a bucket."""
6597 def __init__(self
, name
, type):
6598 Argument
.__init
__(self
, name
+ "_bucket_id", "uint32_t")
6600 def WriteGetCode(self
, file):
6601 """Overridden from Argument."""
6603 Bucket* %(name)s_bucket = GetBucket(c.%(name)s);
6604 if (!%(name)s_bucket) {
6605 return error::kInvalidArguments;
6607 std::string %(name)s_str;
6608 if (!%(name)s_bucket->GetAsString(&%(name)s_str)) {
6609 return error::kInvalidArguments;
6611 const char* %(name)s = %(name)s_str.c_str();
6617 def GetValidArg(self
, func
):
6618 return "kNameBucketId"
6620 def GetValidGLArg(self
, func
):
6624 class ResourceIdArgument(Argument
):
6625 """A class that represents a resource id argument to a function."""
6627 def __init__(self
, name
, type):
6628 match
= re
.match("(GLid\w+)", type)
6629 self
.resource_type
= match
.group(1)[4:]
6630 type = type.replace(match
.group(1), "GLuint")
6631 Argument
.__init
__(self
, name
, type)
6633 def WriteGetCode(self
, file):
6634 """Overridden from Argument."""
6635 file.Write(" %s %s = c.%s;\n" % (self
.type, self
.name
, self
.name
))
6637 def GetValidArg(self
, func
):
6638 return "client_%s_id_" % self
.resource_type
.lower()
6640 def GetValidGLArg(self
, func
):
6641 return "kService%sId" % self
.resource_type
6644 class ResourceIdBindArgument(Argument
):
6645 """Represents a resource id argument to a bind function."""
6647 def __init__(self
, name
, type):
6648 match
= re
.match("(GLidBind\w+)", type)
6649 self
.resource_type
= match
.group(1)[8:]
6650 type = type.replace(match
.group(1), "GLuint")
6651 Argument
.__init
__(self
, name
, type)
6653 def WriteGetCode(self
, file):
6654 """Overridden from Argument."""
6655 code
= """ %(type)s %(name)s = c.%(name)s;
6657 file.Write(code
% {'type': self
.type, 'name': self
.name
})
6659 def GetValidArg(self
, func
):
6660 return "client_%s_id_" % self
.resource_type
.lower()
6662 def GetValidGLArg(self
, func
):
6663 return "kService%sId" % self
.resource_type
6666 class ResourceIdZeroArgument(Argument
):
6667 """Represents a resource id argument to a function that can be zero."""
6669 def __init__(self
, name
, type):
6670 match
= re
.match("(GLidZero\w+)", type)
6671 self
.resource_type
= match
.group(1)[8:]
6672 type = type.replace(match
.group(1), "GLuint")
6673 Argument
.__init
__(self
, name
, type)
6675 def WriteGetCode(self
, file):
6676 """Overridden from Argument."""
6677 file.Write(" %s %s = c.%s;\n" % (self
.type, self
.name
, self
.name
))
6679 def GetValidArg(self
, func
):
6680 return "client_%s_id_" % self
.resource_type
.lower()
6682 def GetValidGLArg(self
, func
):
6683 return "kService%sId" % self
.resource_type
6685 def GetNumInvalidValues(self
, func
):
6686 """returns the number of invalid values to be tested."""
6689 def GetInvalidArg(self
, index
):
6690 """returns an invalid value by index."""
6691 return ("kInvalidClientId", "kNoError", "GL_INVALID_VALUE")
6694 class Function(object):
6695 """A class that represents a function."""
6699 'Bind': BindHandler(),
6700 'Create': CreateHandler(),
6701 'Custom': CustomHandler(),
6702 'Data': DataHandler(),
6703 'Delete': DeleteHandler(),
6704 'DELn': DELnHandler(),
6705 'GENn': GENnHandler(),
6706 'GETn': GETnHandler(),
6707 'GLchar': GLcharHandler(),
6708 'GLcharN': GLcharNHandler(),
6709 'HandWritten': HandWrittenHandler(),
6711 'Manual': ManualHandler(),
6712 'PUT': PUTHandler(),
6713 'PUTn': PUTnHandler(),
6714 'PUTXn': PUTXnHandler(),
6715 'StateSet': StateSetHandler(),
6716 'StateSetRGBAlpha': StateSetRGBAlphaHandler(),
6717 'StateSetFrontBack': StateSetFrontBackHandler(),
6718 'StateSetFrontBackSeparate': StateSetFrontBackSeparateHandler(),
6719 'StateSetNamedParameter': StateSetNamedParameter(),
6720 'STRn': STRnHandler(),
6721 'Todo': TodoHandler(),
6724 def __init__(self
, name
, info
):
6726 self
.original_name
= info
['original_name']
6728 self
.original_args
= self
.ParseArgs(info
['original_args'])
6730 if 'cmd_args' in info
:
6731 self
.args_for_cmds
= self
.ParseArgs(info
['cmd_args'])
6733 self
.args_for_cmds
= self
.original_args
[:]
6735 self
.return_type
= info
['return_type']
6736 if self
.return_type
!= 'void':
6737 self
.return_arg
= CreateArg(info
['return_type'] + " result")
6739 self
.return_arg
= None
6741 self
.num_pointer_args
= sum(
6742 [1 for arg
in self
.args_for_cmds
if arg
.IsPointer()])
6744 self
.type_handler
= self
.type_handlers
[info
['type']]
6745 self
.can_auto_generate
= (self
.num_pointer_args
== 0 and
6746 info
['return_type'] == "void")
6749 def ParseArgs(self
, arg_string
):
6750 """Parses a function arg string."""
6752 parts
= arg_string
.split(',')
6753 for arg_string
in parts
:
6754 arg
= CreateArg(arg_string
)
6759 def IsType(self
, type_name
):
6760 """Returns true if function is a certain type."""
6761 return self
.info
['type'] == type_name
6763 def InitFunction(self
):
6764 """Creates command args and calls the init function for the type handler.
6766 Creates argument lists for command buffer commands, eg. self.cmd_args and
6768 Calls the type function initialization.
6769 Override to create different kind of command buffer command argument lists.
6772 for arg
in self
.args_for_cmds
:
6773 arg
.AddCmdArgs(self
.cmd_args
)
6776 for arg
in self
.args_for_cmds
:
6777 arg
.AddInitArgs(self
.init_args
)
6780 self
.init_args
.append(self
.return_arg
)
6782 self
.type_handler
.InitFunction(self
)
6784 def IsImmediate(self
):
6785 """Returns whether the function is immediate data function or not."""
6788 def GetInfo(self
, name
, default
= None):
6789 """Returns a value from the function info for this function."""
6790 if name
in self
.info
:
6791 return self
.info
[name
]
6794 def GetValidArg(self
, arg
):
6795 """Gets a valid argument value for the parameter arg from the function info
6798 index
= self
.GetOriginalArgs().index(arg
)
6802 valid_args
= self
.GetInfo('valid_args')
6803 if valid_args
and str(index
) in valid_args
:
6804 return valid_args
[str(index
)]
6807 def AddInfo(self
, name
, value
):
6809 self
.info
[name
] = value
6811 def IsExtension(self
):
6812 return self
.GetInfo('extension') or self
.GetInfo('extension_flag')
6814 def IsCoreGLFunction(self
):
6815 return (not self
.IsExtension() and
6816 not self
.GetInfo('pepper_interface'))
6818 def InPepperInterface(self
, interface
):
6819 ext
= self
.GetInfo('pepper_interface')
6820 if not interface
.GetName():
6821 return self
.IsCoreGLFunction()
6822 return ext
== interface
.GetName()
6824 def InAnyPepperExtension(self
):
6825 return self
.IsCoreGLFunction() or self
.GetInfo('pepper_interface')
6827 def GetErrorReturnString(self
):
6828 if self
.GetInfo("error_return"):
6829 return self
.GetInfo("error_return")
6830 elif self
.return_type
== "GLboolean":
6832 elif "*" in self
.return_type
:
6836 def GetGLFunctionName(self
):
6837 """Gets the function to call to execute GL for this command."""
6838 if self
.GetInfo('decoder_func'):
6839 return self
.GetInfo('decoder_func')
6840 return "gl%s" % self
.original_name
6842 def GetGLTestFunctionName(self
):
6843 gl_func_name
= self
.GetInfo('gl_test_func')
6844 if gl_func_name
== None:
6845 gl_func_name
= self
.GetGLFunctionName()
6846 if gl_func_name
.startswith("gl"):
6847 gl_func_name
= gl_func_name
[2:]
6849 gl_func_name
= self
.original_name
6852 def GetDataTransferMethods(self
):
6853 return self
.GetInfo('data_transfer_methods',
6854 ['immediate' if self
.num_pointer_args
== 1 else 'shm'])
6856 def AddCmdArg(self
, arg
):
6857 """Adds a cmd argument to this function."""
6858 self
.cmd_args
.append(arg
)
6860 def GetCmdArgs(self
):
6861 """Gets the command args for this function."""
6862 return self
.cmd_args
6864 def ClearCmdArgs(self
):
6865 """Clears the command args for this function."""
6868 def GetCmdConstants(self
):
6869 """Gets the constants for this function."""
6870 return [arg
for arg
in self
.args_for_cmds
if arg
.IsConstant()]
6872 def GetInitArgs(self
):
6873 """Gets the init args for this function."""
6874 return self
.init_args
6876 def GetOriginalArgs(self
):
6877 """Gets the original arguments to this function."""
6878 return self
.original_args
6880 def GetLastOriginalArg(self
):
6881 """Gets the last original argument to this function."""
6882 return self
.original_args
[len(self
.original_args
) - 1]
6884 def __MaybePrependComma(self
, arg_string
, add_comma
):
6885 """Adds a comma if arg_string is not empty and add_comma is true."""
6887 if add_comma
and len(arg_string
):
6889 return "%s%s" % (comma
, arg_string
)
6891 def MakeTypedOriginalArgString(self
, prefix
, add_comma
= False):
6892 """Gets a list of arguments as they are in GL."""
6893 args
= self
.GetOriginalArgs()
6894 arg_string
= ", ".join(
6895 ["%s %s%s" % (arg
.type, prefix
, arg
.name
) for arg
in args
])
6896 return self
.__MaybePrependComma
(arg_string
, add_comma
)
6898 def MakeOriginalArgString(self
, prefix
, add_comma
= False, separator
= ", "):
6899 """Gets the list of arguments as they are in GL."""
6900 args
= self
.GetOriginalArgs()
6901 arg_string
= separator
.join(
6902 ["%s%s" % (prefix
, arg
.name
) for arg
in args
])
6903 return self
.__MaybePrependComma
(arg_string
, add_comma
)
6905 def MakeTypedHelperArgString(self
, prefix
, add_comma
= False):
6906 """Gets a list of typed GL arguments after removing unneeded arguments."""
6907 args
= self
.GetOriginalArgs()
6908 arg_string
= ", ".join(
6913 ) for arg
in args
if not arg
.IsConstant()])
6914 return self
.__MaybePrependComma
(arg_string
, add_comma
)
6916 def MakeHelperArgString(self
, prefix
, add_comma
= False, separator
= ", "):
6917 """Gets a list of GL arguments after removing unneeded arguments."""
6918 args
= self
.GetOriginalArgs()
6919 arg_string
= separator
.join(
6920 ["%s%s" % (prefix
, arg
.name
)
6921 for arg
in args
if not arg
.IsConstant()])
6922 return self
.__MaybePrependComma
(arg_string
, add_comma
)
6924 def MakeTypedPepperArgString(self
, prefix
):
6925 """Gets a list of arguments as they need to be for Pepper."""
6926 if self
.GetInfo("pepper_args"):
6927 return self
.GetInfo("pepper_args")
6929 return self
.MakeTypedOriginalArgString(prefix
, False)
6931 def MapCTypeToPepperIdlType(self
, ctype
, is_for_return_type
=False):
6932 """Converts a C type name to the corresponding Pepper IDL type."""
6934 'char*': '[out] str_t',
6935 'const GLchar* const*': '[out] cstr_t',
6936 'const char*': 'cstr_t',
6937 'const void*': 'mem_t',
6938 'void*': '[out] mem_t',
6939 'void**': '[out] mem_ptr_t',
6941 # We use "GLxxx_ptr_t" for "GLxxx*".
6942 matched
= re
.match(r
'(const )?(GL\w+)\*$', ctype
)
6944 idltype
= matched
.group(2) + '_ptr_t'
6945 if not matched
.group(1):
6946 idltype
= '[out] ' + idltype
6947 # If an in/out specifier is not specified yet, prepend [in].
6948 if idltype
[0] != '[':
6949 idltype
= '[in] ' + idltype
6950 # Strip the in/out specifier for a return type.
6951 if is_for_return_type
:
6952 idltype
= re
.sub(r
'\[\w+\] ', '', idltype
)
6955 def MakeTypedPepperIdlArgStrings(self
):
6956 """Gets a list of arguments as they need to be for Pepper IDL."""
6957 args
= self
.GetOriginalArgs()
6958 return ["%s %s" % (self
.MapCTypeToPepperIdlType(arg
.type), arg
.name
)
6961 def GetPepperName(self
):
6962 if self
.GetInfo("pepper_name"):
6963 return self
.GetInfo("pepper_name")
6966 def MakeTypedCmdArgString(self
, prefix
, add_comma
= False):
6967 """Gets a typed list of arguments as they need to be for command buffers."""
6968 args
= self
.GetCmdArgs()
6969 arg_string
= ", ".join(
6970 ["%s %s%s" % (arg
.type, prefix
, arg
.name
) for arg
in args
])
6971 return self
.__MaybePrependComma
(arg_string
, add_comma
)
6973 def MakeCmdArgString(self
, prefix
, add_comma
= False):
6974 """Gets the list of arguments as they need to be for command buffers."""
6975 args
= self
.GetCmdArgs()
6976 arg_string
= ", ".join(
6977 ["%s%s" % (prefix
, arg
.name
) for arg
in args
])
6978 return self
.__MaybePrependComma
(arg_string
, add_comma
)
6980 def MakeTypedInitString(self
, prefix
, add_comma
= False):
6981 """Gets a typed list of arguments as they need to be for cmd Init/Set."""
6982 args
= self
.GetInitArgs()
6983 arg_string
= ", ".join(
6984 ["%s %s%s" % (arg
.type, prefix
, arg
.name
) for arg
in args
])
6985 return self
.__MaybePrependComma
(arg_string
, add_comma
)
6987 def MakeInitString(self
, prefix
, add_comma
= False):
6988 """Gets the list of arguments as they need to be for cmd Init/Set."""
6989 args
= self
.GetInitArgs()
6990 arg_string
= ", ".join(
6991 ["%s%s" % (prefix
, arg
.name
) for arg
in args
])
6992 return self
.__MaybePrependComma
(arg_string
, add_comma
)
6994 def MakeLogArgString(self
):
6995 """Makes a string of the arguments for the LOG macros"""
6996 args
= self
.GetOriginalArgs()
6997 return ' << ", " << '.join([arg
.GetLogArg() for arg
in args
])
6999 def WriteCommandDescription(self
, file):
7000 """Writes a description of the command."""
7001 file.Write("//! Command that corresponds to gl%s.\n" % self
.original_name
)
7003 def WriteHandlerValidation(self
, file):
7004 """Writes validation code for the function."""
7005 for arg
in self
.GetOriginalArgs():
7006 arg
.WriteValidationCode(file, self
)
7007 self
.WriteValidationCode(file)
7009 def WriteHandlerImplementation(self
, file):
7010 """Writes the handler implementation for this command."""
7011 self
.type_handler
.WriteHandlerImplementation(self
, file)
7013 def WriteValidationCode(self
, file):
7014 """Writes the validation code for a command."""
7017 def WriteCmdFlag(self
, file):
7018 """Writes the cmd cmd_flags constant."""
7020 # By default trace only at the highest level 3.
7021 trace_level
= int(self
.GetInfo('trace_level', default
= 3))
7022 if trace_level
not in xrange(0, 4):
7023 raise KeyError("Unhandled trace_level: %d" % trace_level
)
7025 flags
.append('CMD_FLAG_SET_TRACE_LEVEL(%d)' % trace_level
)
7028 cmd_flags
= ' | '.join(flags
)
7032 file.Write(" static const uint8 cmd_flags = %s;\n" % cmd_flags
)
7035 def WriteCmdArgFlag(self
, file):
7036 """Writes the cmd kArgFlags constant."""
7037 file.Write(" static const cmd::ArgFlags kArgFlags = cmd::kFixed;\n")
7039 def WriteCmdComputeSize(self
, file):
7040 """Writes the ComputeSize function for the command."""
7041 file.Write(" static uint32_t ComputeSize() {\n")
7043 " return static_cast<uint32_t>(sizeof(ValueType)); // NOLINT\n")
7047 def WriteCmdSetHeader(self
, file):
7048 """Writes the cmd's SetHeader function."""
7049 file.Write(" void SetHeader() {\n")
7050 file.Write(" header.SetCmd<ValueType>();\n")
7054 def WriteCmdInit(self
, file):
7055 """Writes the cmd's Init function."""
7056 file.Write(" void Init(%s) {\n" % self
.MakeTypedCmdArgString("_"))
7057 file.Write(" SetHeader();\n")
7058 args
= self
.GetCmdArgs()
7060 file.Write(" %s = _%s;\n" % (arg
.name
, arg
.name
))
7064 def WriteCmdSet(self
, file):
7065 """Writes the cmd's Set function."""
7066 copy_args
= self
.MakeCmdArgString("_", False)
7067 file.Write(" void* Set(void* cmd%s) {\n" %
7068 self
.MakeTypedCmdArgString("_", True))
7069 file.Write(" static_cast<ValueType*>(cmd)->Init(%s);\n" % copy_args
)
7070 file.Write(" return NextCmdAddress<ValueType>(cmd);\n")
7074 def WriteStruct(self
, file):
7075 self
.type_handler
.WriteStruct(self
, file)
7077 def WriteDocs(self
, file):
7078 self
.type_handler
.WriteDocs(self
, file)
7080 def WriteCmdHelper(self
, file):
7081 """Writes the cmd's helper."""
7082 self
.type_handler
.WriteCmdHelper(self
, file)
7084 def WriteServiceImplementation(self
, file):
7085 """Writes the service implementation for a command."""
7086 self
.type_handler
.WriteServiceImplementation(self
, file)
7088 def WriteServiceUnitTest(self
, file, *extras
):
7089 """Writes the service implementation for a command."""
7090 self
.type_handler
.WriteServiceUnitTest(self
, file, *extras
)
7092 def WriteGLES2CLibImplementation(self
, file):
7093 """Writes the GLES2 C Lib Implemention."""
7094 self
.type_handler
.WriteGLES2CLibImplementation(self
, file)
7096 def WriteGLES2InterfaceHeader(self
, file):
7097 """Writes the GLES2 Interface declaration."""
7098 self
.type_handler
.WriteGLES2InterfaceHeader(self
, file)
7100 def WriteGLES2InterfaceStub(self
, file):
7101 """Writes the GLES2 Interface Stub declaration."""
7102 self
.type_handler
.WriteGLES2InterfaceStub(self
, file)
7104 def WriteGLES2InterfaceStubImpl(self
, file):
7105 """Writes the GLES2 Interface Stub declaration."""
7106 self
.type_handler
.WriteGLES2InterfaceStubImpl(self
, file)
7108 def WriteGLES2ImplementationHeader(self
, file):
7109 """Writes the GLES2 Implemention declaration."""
7110 self
.type_handler
.WriteGLES2ImplementationHeader(self
, file)
7112 def WriteGLES2Implementation(self
, file):
7113 """Writes the GLES2 Implemention definition."""
7114 self
.type_handler
.WriteGLES2Implementation(self
, file)
7116 def WriteGLES2TraceImplementationHeader(self
, file):
7117 """Writes the GLES2 Trace Implemention declaration."""
7118 self
.type_handler
.WriteGLES2TraceImplementationHeader(self
, file)
7120 def WriteGLES2TraceImplementation(self
, file):
7121 """Writes the GLES2 Trace Implemention definition."""
7122 self
.type_handler
.WriteGLES2TraceImplementation(self
, file)
7124 def WriteGLES2Header(self
, file):
7125 """Writes the GLES2 Implemention unit test."""
7126 self
.type_handler
.WriteGLES2Header(self
, file)
7128 def WriteGLES2ImplementationUnitTest(self
, file):
7129 """Writes the GLES2 Implemention unit test."""
7130 self
.type_handler
.WriteGLES2ImplementationUnitTest(self
, file)
7132 def WriteDestinationInitalizationValidation(self
, file):
7133 """Writes the client side destintion initialization validation."""
7134 self
.type_handler
.WriteDestinationInitalizationValidation(self
, file)
7136 def WriteFormatTest(self
, file):
7137 """Writes the cmd's format test."""
7138 self
.type_handler
.WriteFormatTest(self
, file)
7141 class PepperInterface(object):
7142 """A class that represents a function."""
7144 def __init__(self
, info
):
7145 self
.name
= info
["name"]
7146 self
.dev
= info
["dev"]
7151 def GetInterfaceName(self
):
7155 upperint
= "_" + self
.name
.upper()
7158 return "PPB_OPENGLES2%s%s_INTERFACE" % (upperint
, dev
)
7160 def GetInterfaceString(self
):
7164 return "PPB_OpenGLES2%s%s" % (self
.name
, dev
)
7166 def GetStructName(self
):
7170 return "PPB_OpenGLES2%s%s" % (self
.name
, dev
)
7173 class ImmediateFunction(Function
):
7174 """A class that represnets an immediate function command."""
7176 def __init__(self
, func
):
7179 "%sImmediate" % func
.name
,
7182 def InitFunction(self
):
7183 # Override args in original_args and args_for_cmds with immediate versions
7186 new_original_args
= []
7187 for arg
in self
.original_args
:
7188 new_arg
= arg
.GetImmediateVersion()
7190 new_original_args
.append(new_arg
)
7191 self
.original_args
= new_original_args
7193 new_args_for_cmds
= []
7194 for arg
in self
.args_for_cmds
:
7195 new_arg
= arg
.GetImmediateVersion()
7197 new_args_for_cmds
.append(new_arg
)
7199 self
.args_for_cmds
= new_args_for_cmds
7201 Function
.InitFunction(self
)
7203 def IsImmediate(self
):
7206 def WriteCommandDescription(self
, file):
7207 """Overridden from Function"""
7208 file.Write("//! Immediate version of command that corresponds to gl%s.\n" %
7211 def WriteServiceImplementation(self
, file):
7212 """Overridden from Function"""
7213 self
.type_handler
.WriteImmediateServiceImplementation(self
, file)
7215 def WriteHandlerImplementation(self
, file):
7216 """Overridden from Function"""
7217 self
.type_handler
.WriteImmediateHandlerImplementation(self
, file)
7219 def WriteServiceUnitTest(self
, file, *extras
):
7220 """Writes the service implementation for a command."""
7221 self
.type_handler
.WriteImmediateServiceUnitTest(self
, file, *extras
)
7223 def WriteValidationCode(self
, file):
7224 """Overridden from Function"""
7225 self
.type_handler
.WriteImmediateValidationCode(self
, file)
7227 def WriteCmdArgFlag(self
, file):
7228 """Overridden from Function"""
7229 file.Write(" static const cmd::ArgFlags kArgFlags = cmd::kAtLeastN;\n")
7231 def WriteCmdComputeSize(self
, file):
7232 """Overridden from Function"""
7233 self
.type_handler
.WriteImmediateCmdComputeSize(self
, file)
7235 def WriteCmdSetHeader(self
, file):
7236 """Overridden from Function"""
7237 self
.type_handler
.WriteImmediateCmdSetHeader(self
, file)
7239 def WriteCmdInit(self
, file):
7240 """Overridden from Function"""
7241 self
.type_handler
.WriteImmediateCmdInit(self
, file)
7243 def WriteCmdSet(self
, file):
7244 """Overridden from Function"""
7245 self
.type_handler
.WriteImmediateCmdSet(self
, file)
7247 def WriteCmdHelper(self
, file):
7248 """Overridden from Function"""
7249 self
.type_handler
.WriteImmediateCmdHelper(self
, file)
7251 def WriteFormatTest(self
, file):
7252 """Overridden from Function"""
7253 self
.type_handler
.WriteImmediateFormatTest(self
, file)
7256 class BucketFunction(Function
):
7257 """A class that represnets a bucket version of a function command."""
7259 def __init__(self
, func
):
7262 "%sBucket" % func
.name
,
7265 def InitFunction(self
):
7266 # Override args in original_args and args_for_cmds with bucket versions
7269 new_original_args
= []
7270 for arg
in self
.original_args
:
7271 new_arg
= arg
.GetBucketVersion()
7273 new_original_args
.append(new_arg
)
7274 self
.original_args
= new_original_args
7276 new_args_for_cmds
= []
7277 for arg
in self
.args_for_cmds
:
7278 new_arg
= arg
.GetBucketVersion()
7280 new_args_for_cmds
.append(new_arg
)
7282 self
.args_for_cmds
= new_args_for_cmds
7284 Function
.InitFunction(self
)
7286 def WriteCommandDescription(self
, file):
7287 """Overridden from Function"""
7288 file.Write("//! Bucket version of command that corresponds to gl%s.\n" %
7291 def WriteServiceImplementation(self
, file):
7292 """Overridden from Function"""
7293 self
.type_handler
.WriteBucketServiceImplementation(self
, file)
7295 def WriteHandlerImplementation(self
, file):
7296 """Overridden from Function"""
7297 self
.type_handler
.WriteBucketHandlerImplementation(self
, file)
7299 def WriteServiceUnitTest(self
, file, *extras
):
7300 """Writes the service implementation for a command."""
7301 self
.type_handler
.WriteBucketServiceUnitTest(self
, file, *extras
)
7304 def CreateArg(arg_string
):
7305 """Creates an Argument."""
7306 arg_parts
= arg_string
.split()
7307 if len(arg_parts
) == 1 and arg_parts
[0] == 'void':
7309 # Is this a pointer argument?
7310 elif arg_string
.find('*') >= 0:
7311 return PointerArgument(
7313 " ".join(arg_parts
[0:-1]))
7314 # Is this a resource argument? Must come after pointer check.
7315 elif arg_parts
[0].startswith('GLidBind'):
7316 return ResourceIdBindArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
7317 elif arg_parts
[0].startswith('GLidZero'):
7318 return ResourceIdZeroArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
7319 elif arg_parts
[0].startswith('GLid'):
7320 return ResourceIdArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
7321 elif arg_parts
[0].startswith('GLenum') and len(arg_parts
[0]) > 6:
7322 return EnumArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
7323 elif arg_parts
[0].startswith('GLboolean') and len(arg_parts
[0]) > 9:
7324 return ValidatedBoolArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
7325 elif arg_parts
[0].startswith('GLboolean'):
7326 return BoolArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
7327 elif arg_parts
[0].startswith('GLintUniformLocation'):
7328 return UniformLocationArgument(arg_parts
[-1])
7329 elif (arg_parts
[0].startswith('GLint') and len(arg_parts
[0]) > 5 and
7330 not arg_parts
[0].startswith('GLintptr')):
7331 return IntArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
7332 elif (arg_parts
[0].startswith('GLsizeiNotNegative') or
7333 arg_parts
[0].startswith('GLintptrNotNegative')):
7334 return SizeNotNegativeArgument(arg_parts
[-1],
7335 " ".join(arg_parts
[0:-1]),
7336 arg_parts
[0][0:-11])
7337 elif arg_parts
[0].startswith('GLsize'):
7338 return SizeArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
7340 return Argument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
7343 class GLGenerator(object):
7344 """A class to generate GL command buffers."""
7346 _function_re
= re
.compile(r
'GL_APICALL(.*?)GL_APIENTRY (.*?) \((.*?)\);')
7348 def __init__(self
, verbose
):
7349 self
.original_functions
= []
7351 self
.verbose
= verbose
7353 self
.pepper_interfaces
= []
7354 self
.interface_info
= {}
7355 self
.generated_cpp_filenames
= []
7357 for interface
in _PEPPER_INTERFACES
:
7358 interface
= PepperInterface(interface
)
7359 self
.pepper_interfaces
.append(interface
)
7360 self
.interface_info
[interface
.GetName()] = interface
7362 def AddFunction(self
, func
):
7363 """Adds a function."""
7364 self
.functions
.append(func
)
7366 def GetFunctionInfo(self
, name
):
7367 """Gets a type info for the given function name."""
7368 if name
in _FUNCTION_INFO
:
7369 func_info
= _FUNCTION_INFO
[name
].copy()
7373 if not 'type' in func_info
:
7374 func_info
['type'] = ''
7379 """Prints something if verbose is true."""
7383 def Error(self
, msg
):
7384 """Prints an error."""
7385 print "Error: %s" % msg
7388 def WriteLicense(self
, file):
7389 """Writes the license."""
7390 file.Write(_LICENSE
)
7392 def WriteNamespaceOpen(self
, file):
7393 """Writes the code for the namespace."""
7394 file.Write("namespace gpu {\n")
7395 file.Write("namespace gles2 {\n")
7398 def WriteNamespaceClose(self
, file):
7399 """Writes the code to close the namespace."""
7400 file.Write("} // namespace gles2\n")
7401 file.Write("} // namespace gpu\n")
7404 def ParseGLH(self
, filename
):
7405 """Parses the cmd_buffer_functions.txt file and extracts the functions"""
7406 f
= open(filename
, "r")
7407 functions
= f
.read()
7409 for line
in functions
.splitlines():
7410 match
= self
._function
_re
.match(line
)
7412 func_name
= match
.group(2)[2:]
7413 func_info
= self
.GetFunctionInfo(func_name
)
7414 if func_info
['type'] == 'Noop':
7417 parsed_func_info
= {
7418 'original_name': func_name
,
7419 'original_args': match
.group(3),
7420 'return_type': match
.group(1).strip(),
7423 for k
in parsed_func_info
.keys():
7424 if not k
in func_info
:
7425 func_info
[k
] = parsed_func_info
[k
]
7427 f
= Function(func_name
, func_info
)
7428 self
.original_functions
.append(f
)
7430 #for arg in f.GetOriginalArgs():
7431 # if not isinstance(arg, EnumArgument) and arg.type == 'GLenum':
7432 # self.Log("%s uses bare GLenum %s." % (func_name, arg.name))
7434 gen_cmd
= f
.GetInfo('gen_cmd')
7435 if gen_cmd
== True or gen_cmd
== None:
7436 if f
.type_handler
.NeedsDataTransferFunction(f
):
7437 methods
= f
.GetDataTransferMethods()
7438 if 'immediate' in methods
:
7439 self
.AddFunction(ImmediateFunction(f
))
7440 if 'bucket' in methods
:
7441 self
.AddFunction(BucketFunction(f
))
7442 if 'shm' in methods
:
7447 self
.Log("Auto Generated Functions : %d" %
7448 len([f
for f
in self
.functions
if f
.can_auto_generate
or
7449 (not f
.IsType('') and not f
.IsType('Custom') and
7450 not f
.IsType('Todo'))]))
7452 funcs
= [f
for f
in self
.functions
if not f
.can_auto_generate
and
7453 (f
.IsType('') or f
.IsType('Custom') or f
.IsType('Todo'))]
7454 self
.Log("Non Auto Generated Functions: %d" % len(funcs
))
7457 self
.Log(" %-10s %-20s gl%s" % (f
.info
['type'], f
.return_type
, f
.name
))
7459 def WriteCommandIds(self
, filename
):
7460 """Writes the command buffer format"""
7461 file = CHeaderWriter(filename
)
7462 file.Write("#define GLES2_COMMAND_LIST(OP) \\\n")
7464 for func
in self
.functions
:
7465 file.Write(" %-60s /* %d */ \\\n" %
7466 ("OP(%s)" % func
.name
, id))
7470 file.Write("enum CommandId {\n")
7471 file.Write(" kStartPoint = cmd::kLastCommonId, "
7472 "// All GLES2 commands start after this.\n")
7473 file.Write("#define GLES2_CMD_OP(name) k ## name,\n")
7474 file.Write(" GLES2_COMMAND_LIST(GLES2_CMD_OP)\n")
7475 file.Write("#undef GLES2_CMD_OP\n")
7476 file.Write(" kNumCommands\n")
7480 self
.generated_cpp_filenames
.append(file.filename
)
7482 def WriteFormat(self
, filename
):
7483 """Writes the command buffer format"""
7484 file = CHeaderWriter(filename
)
7485 for func
in self
.functions
:
7487 #gen_cmd = func.GetInfo('gen_cmd')
7488 #if gen_cmd == True or gen_cmd == None:
7489 func
.WriteStruct(file)
7492 self
.generated_cpp_filenames
.append(file.filename
)
7494 def WriteDocs(self
, filename
):
7495 """Writes the command buffer doc version of the commands"""
7496 file = CWriter(filename
)
7497 for func
in self
.functions
:
7499 #gen_cmd = func.GetInfo('gen_cmd')
7500 #if gen_cmd == True or gen_cmd == None:
7501 func
.WriteDocs(file)
7504 self
.generated_cpp_filenames
.append(file.filename
)
7506 def WriteFormatTest(self
, filename
):
7507 """Writes the command buffer format test."""
7508 file = CHeaderWriter(
7510 "// This file contains unit tests for gles2 commmands\n"
7511 "// It is included by gles2_cmd_format_test.cc\n"
7514 for func
in self
.functions
:
7516 #gen_cmd = func.GetInfo('gen_cmd')
7517 #if gen_cmd == True or gen_cmd == None:
7518 func
.WriteFormatTest(file)
7521 self
.generated_cpp_filenames
.append(file.filename
)
7523 def WriteCmdHelperHeader(self
, filename
):
7524 """Writes the gles2 command helper."""
7525 file = CHeaderWriter(filename
)
7527 for func
in self
.functions
:
7529 #gen_cmd = func.GetInfo('gen_cmd')
7530 #if gen_cmd == True or gen_cmd == None:
7531 func
.WriteCmdHelper(file)
7534 self
.generated_cpp_filenames
.append(file.filename
)
7536 def WriteServiceContextStateHeader(self
, filename
):
7537 """Writes the service context state header."""
7538 file = CHeaderWriter(
7540 "// It is included by context_state.h\n")
7541 file.Write("struct EnableFlags {\n")
7542 file.Write(" EnableFlags();\n")
7543 for capability
in _CAPABILITY_FLAGS
:
7544 file.Write(" bool %s;\n" % capability
['name'])
7545 file.Write(" bool cached_%s;\n" % capability
['name'])
7546 file.Write("};\n\n")
7548 for state_name
in sorted(_STATES
.keys()):
7549 state
= _STATES
[state_name
]
7550 for item
in state
['states']:
7551 if isinstance(item
['default'], list):
7552 file.Write("%s %s[%d];\n" % (item
['type'], item
['name'],
7553 len(item
['default'])))
7555 file.Write("%s %s;\n" % (item
['type'], item
['name']))
7557 if item
.get('cached', False):
7558 if isinstance(item
['default'], list):
7559 file.Write("%s cached_%s[%d];\n" % (item
['type'], item
['name'],
7560 len(item
['default'])))
7562 file.Write("%s cached_%s;\n" % (item
['type'], item
['name']))
7567 inline void SetDeviceCapabilityState(GLenum cap, bool enable) {
7570 for capability
in _CAPABILITY_FLAGS
:
7573 """ % capability
['name'].upper())
7575 if (enable_flags.cached_%(name)s == enable &&
7576 !ignore_cached_state)
7578 enable_flags.cached_%(name)s = enable;
7595 self
.generated_cpp_filenames
.append(file.filename
)
7597 def WriteClientContextStateHeader(self
, filename
):
7598 """Writes the client context state header."""
7599 file = CHeaderWriter(
7601 "// It is included by client_context_state.h\n")
7602 file.Write("struct EnableFlags {\n")
7603 file.Write(" EnableFlags();\n")
7604 for capability
in _CAPABILITY_FLAGS
:
7605 file.Write(" bool %s;\n" % capability
['name'])
7606 file.Write("};\n\n")
7609 self
.generated_cpp_filenames
.append(file.filename
)
7611 def WriteContextStateGetters(self
, file, class_name
):
7612 """Writes the state getters."""
7613 for gl_type
in ["GLint", "GLfloat"]:
7615 bool %s::GetStateAs%s(
7616 GLenum pname, %s* params, GLsizei* num_written) const {
7618 """ % (class_name
, gl_type
, gl_type
))
7619 for state_name
in sorted(_STATES
.keys()):
7620 state
= _STATES
[state_name
]
7622 file.Write(" case %s:\n" % state
['enum'])
7623 file.Write(" *num_written = %d;\n" % len(state
['states']))
7624 file.Write(" if (params) {\n")
7625 for ndx
,item
in enumerate(state
['states']):
7626 file.Write(" params[%d] = static_cast<%s>(%s);\n" %
7627 (ndx
, gl_type
, item
['name']))
7629 file.Write(" return true;\n")
7631 for item
in state
['states']:
7632 file.Write(" case %s:\n" % item
['enum'])
7633 if isinstance(item
['default'], list):
7634 item_len
= len(item
['default'])
7635 file.Write(" *num_written = %d;\n" % item_len
)
7636 file.Write(" if (params) {\n")
7637 if item
['type'] == gl_type
:
7638 file.Write(" memcpy(params, %s, sizeof(%s) * %d);\n" %
7639 (item
['name'], item
['type'], item_len
))
7641 file.Write(" for (size_t i = 0; i < %s; ++i) {\n" %
7643 file.Write(" params[i] = %s;\n" %
7644 (GetGLGetTypeConversion(gl_type
, item
['type'],
7645 "%s[i]" % item
['name'])))
7648 file.Write(" *num_written = 1;\n")
7649 file.Write(" if (params) {\n")
7650 file.Write(" params[0] = %s;\n" %
7651 (GetGLGetTypeConversion(gl_type
, item
['type'],
7654 file.Write(" return true;\n")
7655 for capability
in _CAPABILITY_FLAGS
:
7656 file.Write(" case GL_%s:\n" % capability
['name'].upper())
7657 file.Write(" *num_written = 1;\n")
7658 file.Write(" if (params) {\n")
7660 " params[0] = static_cast<%s>(enable_flags.%s);\n" %
7661 (gl_type
, capability
['name']))
7663 file.Write(" return true;\n")
7664 file.Write(""" default:
7670 def WriteServiceContextStateImpl(self
, filename
):
7671 """Writes the context state service implementation."""
7672 file = CHeaderWriter(
7674 "// It is included by context_state.cc\n")
7676 for capability
in _CAPABILITY_FLAGS
:
7677 code
.append("%s(%s)" %
7678 (capability
['name'],
7679 ('false', 'true')['default' in capability
]))
7680 code
.append("cached_%s(%s)" %
7681 (capability
['name'],
7682 ('false', 'true')['default' in capability
]))
7683 file.Write("ContextState::EnableFlags::EnableFlags()\n : %s {\n}\n" %
7687 file.Write("void ContextState::Initialize() {\n")
7688 for state_name
in sorted(_STATES
.keys()):
7689 state
= _STATES
[state_name
]
7690 for item
in state
['states']:
7691 if isinstance(item
['default'], list):
7692 for ndx
, value
in enumerate(item
['default']):
7693 file.Write(" %s[%d] = %s;\n" % (item
['name'], ndx
, value
))
7695 file.Write(" %s = %s;\n" % (item
['name'], item
['default']))
7696 if item
.get('cached', False):
7697 if isinstance(item
['default'], list):
7698 for ndx
, value
in enumerate(item
['default']):
7699 file.Write(" cached_%s[%d] = %s;\n" % (item
['name'], ndx
, value
))
7701 file.Write(" cached_%s = %s;\n" % (item
['name'], item
['default']))
7705 void ContextState::InitCapabilities(const ContextState* prev_state) const {
7707 def WriteCapabilities(test_prev
):
7708 for capability
in _CAPABILITY_FLAGS
:
7709 capability_name
= capability
['name']
7711 file.Write(""" if (prev_state->enable_flags.cached_%s !=
7712 enable_flags.cached_%s)\n""" %
7713 (capability_name
, capability_name
))
7714 file.Write(" EnableDisable(GL_%s, enable_flags.cached_%s);\n" %
7715 (capability_name
.upper(), capability_name
))
7717 file.Write(" if (prev_state) {")
7718 WriteCapabilities(True)
7719 file.Write(" } else {")
7720 WriteCapabilities(False)
7725 void ContextState::InitState(const ContextState *prev_state) const {
7728 def WriteStates(test_prev
):
7729 # We need to sort the keys so the expectations match
7730 for state_name
in sorted(_STATES
.keys()):
7731 state
= _STATES
[state_name
]
7732 if state
['type'] == 'FrontBack':
7733 num_states
= len(state
['states'])
7734 for ndx
, group
in enumerate(Grouper(num_states
/ 2, state
['states'])):
7738 for place
, item
in enumerate(group
):
7739 item_name
= CachedStateName(item
)
7740 args
.append('%s' % item_name
)
7744 file.Write("(%s != prev_state->%s)" % (item_name
, item_name
))
7748 " gl%s(%s, %s);\n" %
7749 (state
['func'], ('GL_FRONT', 'GL_BACK')[ndx
], ", ".join(args
)))
7750 elif state
['type'] == 'NamedParameter':
7751 for item
in state
['states']:
7752 item_name
= CachedStateName(item
)
7754 if 'extension_flag' in item
:
7755 file.Write(" if (feature_info_->feature_flags().%s) {\n " %
7756 item
['extension_flag'])
7758 if isinstance(item
['default'], list):
7759 file.Write(" if (memcmp(prev_state->%s, %s, "
7760 "sizeof(%s) * %d)) {\n" %
7761 (item_name
, item_name
, item
['type'],
7762 len(item
['default'])))
7764 file.Write(" if (prev_state->%s != %s) {\n " %
7765 (item_name
, item_name
))
7766 file.Write(" gl%s(%s, %s);\n" %
7769 if 'enum_set' in item
else item
['enum']),
7772 if 'extension_flag' in item
:
7775 if 'extension_flag' in item
:
7778 if 'extension_flag' in state
:
7779 file.Write(" if (feature_info_->feature_flags().%s)\n " %
7780 state
['extension_flag'])
7784 for place
, item
in enumerate(state
['states']):
7785 item_name
= CachedStateName(item
)
7786 args
.append('%s' % item_name
)
7790 file.Write("(%s != prev_state->%s)" %
7791 (item_name
, item_name
))
7794 file.Write(" gl%s(%s);\n" % (state
['func'], ", ".join(args
)))
7796 file.Write(" if (prev_state) {")
7798 file.Write(" } else {")
7803 file.Write("""bool ContextState::GetEnabled(GLenum cap) const {
7806 for capability
in _CAPABILITY_FLAGS
:
7807 file.Write(" case GL_%s:\n" % capability
['name'].upper())
7808 file.Write(" return enable_flags.%s;\n" % capability
['name'])
7809 file.Write(""" default:
7816 self
.WriteContextStateGetters(file, "ContextState")
7818 self
.generated_cpp_filenames
.append(file.filename
)
7820 def WriteClientContextStateImpl(self
, filename
):
7821 """Writes the context state client side implementation."""
7822 file = CHeaderWriter(
7824 "// It is included by client_context_state.cc\n")
7826 for capability
in _CAPABILITY_FLAGS
:
7827 code
.append("%s(%s)" %
7828 (capability
['name'],
7829 ('false', 'true')['default' in capability
]))
7831 "ClientContextState::EnableFlags::EnableFlags()\n : %s {\n}\n" %
7836 bool ClientContextState::SetCapabilityState(
7837 GLenum cap, bool enabled, bool* changed) {
7841 for capability
in _CAPABILITY_FLAGS
:
7842 file.Write(" case GL_%s:\n" % capability
['name'].upper())
7843 file.Write(""" if (enable_flags.%(name)s != enabled) {
7845 enable_flags.%(name)s = enabled;
7849 file.Write(""" default:
7854 file.Write("""bool ClientContextState::GetEnabled(
7855 GLenum cap, bool* enabled) const {
7858 for capability
in _CAPABILITY_FLAGS
:
7859 file.Write(" case GL_%s:\n" % capability
['name'].upper())
7860 file.Write(" *enabled = enable_flags.%s;\n" % capability
['name'])
7861 file.Write(" return true;\n")
7862 file.Write(""" default:
7868 self
.generated_cpp_filenames
.append(file.filename
)
7870 def WriteServiceImplementation(self
, filename
):
7871 """Writes the service decorder implementation."""
7872 file = CHeaderWriter(
7874 "// It is included by gles2_cmd_decoder.cc\n")
7876 for func
in self
.functions
:
7878 #gen_cmd = func.GetInfo('gen_cmd')
7879 #if gen_cmd == True or gen_cmd == None:
7880 func
.WriteServiceImplementation(file)
7883 bool GLES2DecoderImpl::SetCapabilityState(GLenum cap, bool enabled) {
7886 for capability
in _CAPABILITY_FLAGS
:
7887 file.Write(" case GL_%s:\n" % capability
['name'].upper())
7888 if 'state_flag' in capability
:
7891 state_.enable_flags.%(name)s = enabled;
7892 if (state_.enable_flags.cached_%(name)s != enabled
7893 || state_.ignore_cached_state) {
7894 %(state_flag)s = true;
7900 state_.enable_flags.%(name)s = enabled;
7901 if (state_.enable_flags.cached_%(name)s != enabled
7902 || state_.ignore_cached_state) {
7903 state_.enable_flags.cached_%(name)s = enabled;
7908 file.Write(""" default:
7915 self
.generated_cpp_filenames
.append(file.filename
)
7917 def WriteServiceUnitTests(self
, filename
):
7918 """Writes the service decorder unit tests."""
7919 num_tests
= len(self
.functions
)
7920 FUNCTIONS_PER_FILE
= 98 # hard code this so it doesn't change.
7922 for test_num
in range(0, num_tests
, FUNCTIONS_PER_FILE
):
7924 name
= filename
% count
7925 file = CHeaderWriter(
7927 "// It is included by gles2_cmd_decoder_unittest_%d.cc\n" % count
)
7928 test_name
= 'GLES2DecoderTest%d' % count
7929 end
= test_num
+ FUNCTIONS_PER_FILE
7932 for idx
in range(test_num
, end
):
7933 func
= self
.functions
[idx
]
7935 # Do any filtering of the functions here, so that the functions
7936 # will not move between the numbered files if filtering properties
7938 if func
.GetInfo('extension_flag'):
7942 #gen_cmd = func.GetInfo('gen_cmd')
7943 #if gen_cmd == True or gen_cmd == None:
7944 if func
.GetInfo('unit_test') == False:
7945 file.Write("// TODO(gman): %s\n" % func
.name
)
7947 func
.WriteServiceUnitTest(file, {
7948 'test_name': test_name
7951 self
.generated_cpp_filenames
.append(file.filename
)
7952 file = CHeaderWriter(
7954 "// It is included by gles2_cmd_decoder_unittest_base.cc\n")
7956 """void GLES2DecoderTestBase::SetupInitCapabilitiesExpectations() {
7958 for capability
in _CAPABILITY_FLAGS
:
7959 file.Write(" ExpectEnableDisable(GL_%s, %s);\n" %
7960 (capability
['name'].upper(),
7961 ('false', 'true')['default' in capability
]))
7964 void GLES2DecoderTestBase::SetupInitStateExpectations() {
7967 # We need to sort the keys so the expectations match
7968 for state_name
in sorted(_STATES
.keys()):
7969 state
= _STATES
[state_name
]
7970 if state
['type'] == 'FrontBack':
7971 num_states
= len(state
['states'])
7972 for ndx
, group
in enumerate(Grouper(num_states
/ 2, state
['states'])):
7975 if 'expected' in item
:
7976 args
.append(item
['expected'])
7978 args
.append(item
['default'])
7980 " EXPECT_CALL(*gl_, %s(%s, %s))\n" %
7981 (state
['func'], ('GL_FRONT', 'GL_BACK')[ndx
], ", ".join(args
)))
7982 file.Write(" .Times(1)\n")
7983 file.Write(" .RetiresOnSaturation();\n")
7984 elif state
['type'] == 'NamedParameter':
7985 for item
in state
['states']:
7986 if 'extension_flag' in item
:
7987 file.Write(" if (group_->feature_info()->feature_flags().%s) {\n" %
7988 item
['extension_flag'])
7990 expect_value
= item
['default']
7991 if isinstance(expect_value
, list):
7992 # TODO: Currently we do not check array values.
7996 " EXPECT_CALL(*gl_, %s(%s, %s))\n" %
7999 if 'enum_set' in item
else item
['enum']),
8001 file.Write(" .Times(1)\n")
8002 file.Write(" .RetiresOnSaturation();\n")
8003 if 'extension_flag' in item
:
8006 if 'extension_flag' in state
:
8007 file.Write(" if (group_->feature_info()->feature_flags().%s) {\n" %
8008 state
['extension_flag'])
8011 for item
in state
['states']:
8012 if 'expected' in item
:
8013 args
.append(item
['expected'])
8015 args
.append(item
['default'])
8016 # TODO: Currently we do not check array values.
8017 args
= ["_" if isinstance(arg
, list) else arg
for arg
in args
]
8018 file.Write(" EXPECT_CALL(*gl_, %s(%s))\n" %
8019 (state
['func'], ", ".join(args
)))
8020 file.Write(" .Times(1)\n")
8021 file.Write(" .RetiresOnSaturation();\n")
8022 if 'extension_flag' in state
:
8027 self
.generated_cpp_filenames
.append(file.filename
)
8029 def WriteServiceUnitTestsForExtensions(self
, filename
):
8030 """Writes the service decorder unit tests for functions with extension_flag.
8032 The functions are special in that they need a specific unit test
8033 baseclass to turn on the extension.
8035 functions
= [f
for f
in self
.functions
if f
.GetInfo('extension_flag')]
8036 file = CHeaderWriter(
8038 "// It is included by gles2_cmd_decoder_unittest_extensions.cc\n")
8039 for func
in functions
:
8041 if func
.GetInfo('unit_test') == False:
8042 file.Write("// TODO(gman): %s\n" % func
.name
)
8044 extension
= ToCamelCase(
8045 ToGLExtensionString(func
.GetInfo('extension_flag')))
8046 func
.WriteServiceUnitTest(file, {
8047 'test_name': 'GLES2DecoderTestWith%s' % extension
8051 self
.generated_cpp_filenames
.append(file.filename
)
8053 def WriteGLES2Header(self
, filename
):
8054 """Writes the GLES2 header."""
8055 file = CHeaderWriter(
8057 "// This file contains Chromium-specific GLES2 declarations.\n\n")
8059 for func
in self
.original_functions
:
8060 func
.WriteGLES2Header(file)
8064 self
.generated_cpp_filenames
.append(file.filename
)
8066 def WriteGLES2CLibImplementation(self
, filename
):
8067 """Writes the GLES2 c lib implementation."""
8068 file = CHeaderWriter(
8070 "// These functions emulate GLES2 over command buffers.\n")
8072 for func
in self
.original_functions
:
8073 func
.WriteGLES2CLibImplementation(file)
8078 extern const NameToFunc g_gles2_function_table[] = {
8080 for func
in self
.original_functions
:
8082 ' { "gl%s", reinterpret_cast<GLES2FunctionPointer>(gl%s), },\n' %
8083 (func
.name
, func
.name
))
8084 file.Write(""" { NULL, NULL, },
8087 } // namespace gles2
8090 self
.generated_cpp_filenames
.append(file.filename
)
8092 def WriteGLES2InterfaceHeader(self
, filename
):
8093 """Writes the GLES2 interface header."""
8094 file = CHeaderWriter(
8096 "// This file is included by gles2_interface.h to declare the\n"
8097 "// GL api functions.\n")
8098 for func
in self
.original_functions
:
8099 func
.WriteGLES2InterfaceHeader(file)
8101 self
.generated_cpp_filenames
.append(file.filename
)
8103 def WriteGLES2InterfaceStub(self
, filename
):
8104 """Writes the GLES2 interface stub header."""
8105 file = CHeaderWriter(
8107 "// This file is included by gles2_interface_stub.h.\n")
8108 for func
in self
.original_functions
:
8109 func
.WriteGLES2InterfaceStub(file)
8111 self
.generated_cpp_filenames
.append(file.filename
)
8113 def WriteGLES2InterfaceStubImpl(self
, filename
):
8114 """Writes the GLES2 interface header."""
8115 file = CHeaderWriter(
8117 "// This file is included by gles2_interface_stub.cc.\n")
8118 for func
in self
.original_functions
:
8119 func
.WriteGLES2InterfaceStubImpl(file)
8121 self
.generated_cpp_filenames
.append(file.filename
)
8123 def WriteGLES2ImplementationHeader(self
, filename
):
8124 """Writes the GLES2 Implementation header."""
8125 file = CHeaderWriter(
8127 "// This file is included by gles2_implementation.h to declare the\n"
8128 "// GL api functions.\n")
8129 for func
in self
.original_functions
:
8130 func
.WriteGLES2ImplementationHeader(file)
8132 self
.generated_cpp_filenames
.append(file.filename
)
8134 def WriteGLES2Implementation(self
, filename
):
8135 """Writes the GLES2 Implementation."""
8136 file = CHeaderWriter(
8138 "// This file is included by gles2_implementation.cc to define the\n"
8139 "// GL api functions.\n")
8140 for func
in self
.original_functions
:
8141 func
.WriteGLES2Implementation(file)
8143 self
.generated_cpp_filenames
.append(file.filename
)
8145 def WriteGLES2TraceImplementationHeader(self
, filename
):
8146 """Writes the GLES2 Trace Implementation header."""
8147 file = CHeaderWriter(
8149 "// This file is included by gles2_trace_implementation.h\n")
8150 for func
in self
.original_functions
:
8151 func
.WriteGLES2TraceImplementationHeader(file)
8153 self
.generated_cpp_filenames
.append(file.filename
)
8155 def WriteGLES2TraceImplementation(self
, filename
):
8156 """Writes the GLES2 Trace Implementation."""
8157 file = CHeaderWriter(
8159 "// This file is included by gles2_trace_implementation.cc\n")
8160 for func
in self
.original_functions
:
8161 func
.WriteGLES2TraceImplementation(file)
8163 self
.generated_cpp_filenames
.append(file.filename
)
8165 def WriteGLES2ImplementationUnitTests(self
, filename
):
8166 """Writes the GLES2 helper header."""
8167 file = CHeaderWriter(
8169 "// This file is included by gles2_implementation.h to declare the\n"
8170 "// GL api functions.\n")
8171 for func
in self
.original_functions
:
8172 func
.WriteGLES2ImplementationUnitTest(file)
8174 self
.generated_cpp_filenames
.append(file.filename
)
8176 def WriteServiceUtilsHeader(self
, filename
):
8177 """Writes the gles2 auto generated utility header."""
8178 file = CHeaderWriter(filename
)
8179 for name
in sorted(_NAMED_TYPE_INFO
.keys()):
8180 named_type
= NamedType(_NAMED_TYPE_INFO
[name
])
8181 if named_type
.IsConstant():
8183 file.Write("ValueValidator<%s> %s;\n" %
8184 (named_type
.GetType(), ToUnderscore(name
)))
8187 self
.generated_cpp_filenames
.append(file.filename
)
8189 def WriteServiceUtilsImplementation(self
, filename
):
8190 """Writes the gles2 auto generated utility implementation."""
8191 file = CHeaderWriter(filename
)
8192 names
= sorted(_NAMED_TYPE_INFO
.keys())
8194 named_type
= NamedType(_NAMED_TYPE_INFO
[name
])
8195 if named_type
.IsConstant():
8197 if named_type
.GetValidValues():
8198 file.Write("static const %s valid_%s_table[] = {\n" %
8199 (named_type
.GetType(), ToUnderscore(name
)))
8200 for value
in named_type
.GetValidValues():
8201 file.Write(" %s,\n" % value
)
8204 file.Write("Validators::Validators()")
8206 for count
, name
in enumerate(names
):
8207 named_type
= NamedType(_NAMED_TYPE_INFO
[name
])
8208 if named_type
.IsConstant():
8210 if named_type
.GetValidValues():
8211 code
= """%(pre)s%(name)s(
8212 valid_%(name)s_table, arraysize(valid_%(name)s_table))"""
8214 code
= "%(pre)s%(name)s()"
8216 'name': ToUnderscore(name
),
8221 file.Write("}\n\n");
8223 self
.generated_cpp_filenames
.append(file.filename
)
8225 def WriteCommonUtilsHeader(self
, filename
):
8226 """Writes the gles2 common utility header."""
8227 file = CHeaderWriter(filename
)
8228 type_infos
= sorted(_NAMED_TYPE_INFO
.keys())
8229 for type_info
in type_infos
:
8230 if _NAMED_TYPE_INFO
[type_info
]['type'] == 'GLenum':
8231 file.Write("static std::string GetString%s(uint32_t value);\n" %
8235 self
.generated_cpp_filenames
.append(file.filename
)
8237 def WriteCommonUtilsImpl(self
, filename
):
8238 """Writes the gles2 common utility header."""
8239 enum_re
= re
.compile(r
'\#define\s+(GL_[a-zA-Z0-9_]+)\s+([0-9A-Fa-fx]+)')
8241 for fname
in ['third_party/khronos/GLES2/gl2.h',
8242 'third_party/khronos/GLES2/gl2ext.h',
8243 'gpu/GLES2/gl2chromium.h',
8244 'gpu/GLES2/gl2extchromium.h']:
8245 lines
= open(fname
).readlines()
8247 m
= enum_re
.match(line
)
8251 if len(value
) <= 10 and not value
in dict:
8254 file = CHeaderWriter(filename
)
8255 file.Write("static const GLES2Util::EnumToString "
8256 "enum_to_string_table[] = {\n")
8258 file.Write(' { %s, "%s", },\n' % (value
, dict[value
]))
8261 const GLES2Util::EnumToString* const GLES2Util::enum_to_string_table_ =
8262 enum_to_string_table;
8263 const size_t GLES2Util::enum_to_string_table_len_ =
8264 sizeof(enum_to_string_table) / sizeof(enum_to_string_table[0]);
8268 enums
= sorted(_NAMED_TYPE_INFO
.keys())
8270 if _NAMED_TYPE_INFO
[enum
]['type'] == 'GLenum':
8271 file.Write("std::string GLES2Util::GetString%s(uint32_t value) {\n" %
8273 if len(_NAMED_TYPE_INFO
[enum
]['valid']) > 0:
8274 file.Write(" static const EnumToString string_table[] = {\n")
8275 for value
in _NAMED_TYPE_INFO
[enum
]['valid']:
8276 file.Write(' { %s, "%s" },\n' % (value
, value
))
8278 return GLES2Util::GetQualifiedEnumString(
8279 string_table, arraysize(string_table), value);
8284 file.Write(""" return GLES2Util::GetQualifiedEnumString(
8290 self
.generated_cpp_filenames
.append(file.filename
)
8292 def WritePepperGLES2Interface(self
, filename
, dev
):
8293 """Writes the Pepper OpenGLES interface definition."""
8294 file = CWriter(filename
)
8295 file.Write(_LICENSE
)
8296 file.Write(_DO_NOT_EDIT_WARNING
)
8298 file.Write("label Chrome {\n")
8299 file.Write(" M39 = 1.0\n")
8300 file.Write("};\n\n")
8304 file.Write("[version=1.0]\n")
8305 file.Write("describe {\n")
8306 for gltype
in ['GLbitfield', 'GLboolean', 'GLbyte', 'GLclampf',
8307 'GLclampx', 'GLenum', 'GLfixed', 'GLfloat', 'GLint',
8308 'GLintptr', 'GLshort', 'GLsizei', 'GLsizeiptr',
8309 'GLubyte', 'GLuint', 'GLushort']:
8310 file.Write(" %s;\n" % gltype
)
8311 file.Write(" %s_ptr_t;\n" % gltype
)
8312 file.Write("};\n\n")
8315 file.Write("#inline c\n")
8316 file.Write("#include \"ppapi/c/pp_resource.h\"\n")
8318 file.Write("#include \"ppapi/c/ppb_opengles2.h\"\n\n")
8320 file.Write("\n#ifndef __gl2_h_\n")
8321 for (k
, v
) in _GL_TYPES
.iteritems():
8322 file.Write("typedef %s %s;\n" % (v
, k
))
8323 file.Write("#ifdef _WIN64\n")
8324 for (k
, v
) in _GL_TYPES_64
.iteritems():
8325 file.Write("typedef %s %s;\n" % (v
, k
))
8326 file.Write("#else\n")
8327 for (k
, v
) in _GL_TYPES_32
.iteritems():
8328 file.Write("typedef %s %s;\n" % (v
, k
))
8329 file.Write("#endif // _WIN64\n")
8330 file.Write("#endif // __gl2_h_\n\n")
8331 file.Write("#endinl\n")
8333 for interface
in self
.pepper_interfaces
:
8334 if interface
.dev
!= dev
:
8336 # Historically, we provide OpenGLES2 interfaces with struct
8337 # namespace. Not to break code which uses the interface as
8338 # "struct OpenGLES2", we put it in struct namespace.
8339 file.Write('\n[macro="%s", force_struct_namespace]\n' %
8340 interface
.GetInterfaceName())
8341 file.Write("interface %s {\n" % interface
.GetStructName())
8342 for func
in self
.original_functions
:
8343 if not func
.InPepperInterface(interface
):
8346 ret_type
= func
.MapCTypeToPepperIdlType(func
.return_type
,
8347 is_for_return_type
=True)
8348 func_prefix
= " %s %s(" % (ret_type
, func
.GetPepperName())
8349 file.Write(func_prefix
)
8350 file.Write("[in] PP_Resource context")
8351 for arg
in func
.MakeTypedPepperIdlArgStrings():
8352 file.Write(",\n" + " " * len(func_prefix
) + arg
)
8354 file.Write("};\n\n")
8359 def WritePepperGLES2Implementation(self
, filename
):
8360 """Writes the Pepper OpenGLES interface implementation."""
8362 file = CWriter(filename
)
8363 file.Write(_LICENSE
)
8364 file.Write(_DO_NOT_EDIT_WARNING
)
8366 file.Write("#include \"ppapi/shared_impl/ppb_opengles2_shared.h\"\n\n")
8367 file.Write("#include \"base/logging.h\"\n")
8368 file.Write("#include \"gpu/command_buffer/client/gles2_implementation.h\"\n")
8369 file.Write("#include \"ppapi/shared_impl/ppb_graphics_3d_shared.h\"\n")
8370 file.Write("#include \"ppapi/thunk/enter.h\"\n\n")
8372 file.Write("namespace ppapi {\n\n")
8373 file.Write("namespace {\n\n")
8375 file.Write("typedef thunk::EnterResource<thunk::PPB_Graphics3D_API>"
8378 file.Write("gpu::gles2::GLES2Implementation* ToGles2Impl(Enter3D*"
8380 file.Write(" DCHECK(enter);\n")
8381 file.Write(" DCHECK(enter->succeeded());\n")
8382 file.Write(" return static_cast<PPB_Graphics3D_Shared*>(enter->object())->"
8384 file.Write("}\n\n");
8386 for func
in self
.original_functions
:
8387 if not func
.InAnyPepperExtension():
8390 original_arg
= func
.MakeTypedPepperArgString("")
8391 context_arg
= "PP_Resource context_id"
8392 if len(original_arg
):
8393 arg
= context_arg
+ ", " + original_arg
8396 file.Write("%s %s(%s) {\n" %
8397 (func
.return_type
, func
.GetPepperName(), arg
))
8398 file.Write(" Enter3D enter(context_id, true);\n")
8399 file.Write(" if (enter.succeeded()) {\n")
8401 return_str
= "" if func
.return_type
== "void" else "return "
8402 file.Write(" %sToGles2Impl(&enter)->%s(%s);\n" %
8403 (return_str
, func
.original_name
,
8404 func
.MakeOriginalArgString("")))
8406 if func
.return_type
== "void":
8409 file.Write(" else {\n")
8410 file.Write(" return %s;\n" % func
.GetErrorReturnString())
8414 file.Write("} // namespace\n")
8416 for interface
in self
.pepper_interfaces
:
8417 file.Write("const %s* PPB_OpenGLES2_Shared::Get%sInterface() {\n" %
8418 (interface
.GetStructName(), interface
.GetName()))
8419 file.Write(" static const struct %s "
8420 "ppb_opengles2 = {\n" % interface
.GetStructName())
8422 file.Write(",\n &".join(
8423 f
.GetPepperName() for f
in self
.original_functions
8424 if f
.InPepperInterface(interface
)))
8428 file.Write(" return &ppb_opengles2;\n")
8431 file.Write("} // namespace ppapi\n")
8433 self
.generated_cpp_filenames
.append(file.filename
)
8435 def WriteGLES2ToPPAPIBridge(self
, filename
):
8436 """Connects GLES2 helper library to PPB_OpenGLES2 interface"""
8438 file = CWriter(filename
)
8439 file.Write(_LICENSE
)
8440 file.Write(_DO_NOT_EDIT_WARNING
)
8442 file.Write("#ifndef GL_GLEXT_PROTOTYPES\n")
8443 file.Write("#define GL_GLEXT_PROTOTYPES\n")
8444 file.Write("#endif\n")
8445 file.Write("#include <GLES2/gl2.h>\n")
8446 file.Write("#include <GLES2/gl2ext.h>\n")
8447 file.Write("#include \"ppapi/lib/gl/gles2/gl2ext_ppapi.h\"\n\n")
8449 for func
in self
.original_functions
:
8450 if not func
.InAnyPepperExtension():
8453 interface
= self
.interface_info
[func
.GetInfo('pepper_interface') or '']
8455 file.Write("%s GL_APIENTRY gl%s(%s) {\n" %
8456 (func
.return_type
, func
.GetPepperName(),
8457 func
.MakeTypedPepperArgString("")))
8458 return_str
= "" if func
.return_type
== "void" else "return "
8459 interface_str
= "glGet%sInterfacePPAPI()" % interface
.GetName()
8460 original_arg
= func
.MakeOriginalArgString("")
8461 context_arg
= "glGetCurrentContextPPAPI()"
8462 if len(original_arg
):
8463 arg
= context_arg
+ ", " + original_arg
8466 if interface
.GetName():
8467 file.Write(" const struct %s* ext = %s;\n" %
8468 (interface
.GetStructName(), interface_str
))
8469 file.Write(" if (ext)\n")
8470 file.Write(" %sext->%s(%s);\n" %
8471 (return_str
, func
.GetPepperName(), arg
))
8473 file.Write(" %s0;\n" % return_str
)
8475 file.Write(" %s%s->%s(%s);\n" %
8476 (return_str
, interface_str
, func
.GetPepperName(), arg
))
8479 self
.generated_cpp_filenames
.append(file.filename
)
8481 def WriteMojoGLCallVisitor(self
, filename
):
8482 """Provides the GL implementation for mojo"""
8483 file = CWriter(filename
)
8484 file.Write(_LICENSE
)
8485 file.Write(_DO_NOT_EDIT_WARNING
)
8487 for func
in self
.original_functions
:
8488 if not func
.IsCoreGLFunction():
8490 file.Write("VISIT_GL_CALL(%s, %s, (%s), (%s))\n" %
8491 (func
.name
, func
.return_type
,
8492 func
.MakeTypedOriginalArgString(""),
8493 func
.MakeOriginalArgString("")))
8496 self
.generated_cpp_filenames
.append(file.filename
)
8498 def WriteMojoGLCallVisitorForExtension(self
, filename
, extension
):
8499 """Provides the GL implementation for mojo for a particular extension"""
8500 file = CWriter(filename
)
8501 file.Write(_LICENSE
)
8502 file.Write(_DO_NOT_EDIT_WARNING
)
8504 for func
in self
.original_functions
:
8505 if func
.GetInfo("extension") != extension
:
8507 file.Write("VISIT_GL_CALL(%s, %s, (%s), (%s))\n" %
8508 (func
.name
, func
.return_type
,
8509 func
.MakeTypedOriginalArgString(""),
8510 func
.MakeOriginalArgString("")))
8513 self
.generated_cpp_filenames
.append(file.filename
)
8515 def Format(generated_files
):
8516 for filename
in generated_files
:
8517 call(["clang-format", "-i", "-style=chromium", filename
])
8520 """This is the main function."""
8521 parser
= OptionParser()
8524 help="base directory for resulting files, under chrome/src. default is "
8525 "empty. Use this if you want the result stored under gen.")
8527 "-v", "--verbose", action
="store_true",
8528 help="prints more output.")
8530 (options
, args
) = parser
.parse_args(args
=argv
)
8532 # Add in states and capabilites to GLState
8533 gl_state_valid
= _NAMED_TYPE_INFO
['GLState']['valid']
8534 for state_name
in sorted(_STATES
.keys()):
8535 state
= _STATES
[state_name
]
8536 if 'extension_flag' in state
:
8539 if not state
['enum'] in gl_state_valid
:
8540 gl_state_valid
.append(state
['enum'])
8542 for item
in state
['states']:
8543 if 'extension_flag' in item
:
8545 if not item
['enum'] in gl_state_valid
:
8546 gl_state_valid
.append(item
['enum'])
8547 for capability
in _CAPABILITY_FLAGS
:
8548 valid_value
= "GL_%s" % capability
['name'].upper()
8549 if not valid_value
in gl_state_valid
:
8550 gl_state_valid
.append(valid_value
)
8552 # This script lives under gpu/command_buffer, cd to base directory.
8553 os
.chdir(os
.path
.dirname(__file__
) + "/../..")
8554 base_dir
= os
.getcwd()
8555 gen
= GLGenerator(options
.verbose
)
8556 gen
.ParseGLH("gpu/command_buffer/cmd_buffer_functions.txt")
8558 # Support generating files under gen/
8559 if options
.output_dir
!= None:
8560 os
.chdir(options
.output_dir
)
8562 gen
.WritePepperGLES2Interface("ppapi/api/ppb_opengles2.idl", False)
8563 gen
.WritePepperGLES2Interface("ppapi/api/dev/ppb_opengles2ext_dev.idl", True)
8564 gen
.WriteGLES2ToPPAPIBridge("ppapi/lib/gl/gles2/gles2.c")
8565 gen
.WritePepperGLES2Implementation(
8566 "ppapi/shared_impl/ppb_opengles2_shared.cc")
8568 gen
.WriteCommandIds("gpu/command_buffer/common/gles2_cmd_ids_autogen.h")
8569 gen
.WriteFormat("gpu/command_buffer/common/gles2_cmd_format_autogen.h")
8570 gen
.WriteFormatTest(
8571 "gpu/command_buffer/common/gles2_cmd_format_test_autogen.h")
8572 gen
.WriteGLES2InterfaceHeader(
8573 "gpu/command_buffer/client/gles2_interface_autogen.h")
8574 gen
.WriteGLES2InterfaceStub(
8575 "gpu/command_buffer/client/gles2_interface_stub_autogen.h")
8576 gen
.WriteGLES2InterfaceStubImpl(
8577 "gpu/command_buffer/client/gles2_interface_stub_impl_autogen.h")
8578 gen
.WriteGLES2ImplementationHeader(
8579 "gpu/command_buffer/client/gles2_implementation_autogen.h")
8580 gen
.WriteGLES2Implementation(
8581 "gpu/command_buffer/client/gles2_implementation_impl_autogen.h")
8582 gen
.WriteGLES2ImplementationUnitTests(
8583 "gpu/command_buffer/client/gles2_implementation_unittest_autogen.h")
8584 gen
.WriteGLES2TraceImplementationHeader(
8585 "gpu/command_buffer/client/gles2_trace_implementation_autogen.h")
8586 gen
.WriteGLES2TraceImplementation(
8587 "gpu/command_buffer/client/gles2_trace_implementation_impl_autogen.h")
8588 gen
.WriteGLES2CLibImplementation(
8589 "gpu/command_buffer/client/gles2_c_lib_autogen.h")
8590 gen
.WriteCmdHelperHeader(
8591 "gpu/command_buffer/client/gles2_cmd_helper_autogen.h")
8592 gen
.WriteServiceImplementation(
8593 "gpu/command_buffer/service/gles2_cmd_decoder_autogen.h")
8594 gen
.WriteServiceContextStateHeader(
8595 "gpu/command_buffer/service/context_state_autogen.h")
8596 gen
.WriteServiceContextStateImpl(
8597 "gpu/command_buffer/service/context_state_impl_autogen.h")
8598 gen
.WriteClientContextStateHeader(
8599 "gpu/command_buffer/client/client_context_state_autogen.h")
8600 gen
.WriteClientContextStateImpl(
8601 "gpu/command_buffer/client/client_context_state_impl_autogen.h")
8602 gen
.WriteServiceUnitTests(
8603 "gpu/command_buffer/service/gles2_cmd_decoder_unittest_%d_autogen.h")
8604 gen
.WriteServiceUnitTestsForExtensions(
8605 "gpu/command_buffer/service/"
8606 "gles2_cmd_decoder_unittest_extensions_autogen.h")
8607 gen
.WriteServiceUtilsHeader(
8608 "gpu/command_buffer/service/gles2_cmd_validation_autogen.h")
8609 gen
.WriteServiceUtilsImplementation(
8610 "gpu/command_buffer/service/"
8611 "gles2_cmd_validation_implementation_autogen.h")
8612 gen
.WriteCommonUtilsHeader(
8613 "gpu/command_buffer/common/gles2_cmd_utils_autogen.h")
8614 gen
.WriteCommonUtilsImpl(
8615 "gpu/command_buffer/common/gles2_cmd_utils_implementation_autogen.h")
8616 gen
.WriteGLES2Header("gpu/GLES2/gl2chromium_autogen.h")
8617 mojo_gles2_prefix
= "mojo/public/c/gles2/gles2_call_visitor"
8618 gen
.WriteMojoGLCallVisitor(mojo_gles2_prefix
+ "_autogen.h")
8619 gen
.WriteMojoGLCallVisitorForExtension(
8620 mojo_gles2_prefix
+ "_chromium_texture_mailbox_autogen.h",
8621 "CHROMIUM_texture_mailbox")
8622 gen
.WriteMojoGLCallVisitorForExtension(
8623 mojo_gles2_prefix
+ "_chromium_sync_point_autogen.h",
8624 "CHROMIUM_sync_point")
8626 Format(gen
.generated_cpp_filenames
)
8629 print "%d errors" % gen
.errors
8634 if __name__
== '__main__':
8635 sys
.exit(main(sys
.argv
[1:]))