[MD settings] moving attached() code
[chromium-blink-merge.git] / gpu / command_buffer / build_gles2_cmd_buffer.py
blob00c64147934d13b49b7f540685b1b9cdc3f8609a
1 #!/usr/bin/env python
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."""
8 import itertools
9 import os
10 import os.path
11 import sys
12 import re
13 import platform
14 from optparse import OptionParser
15 from subprocess import call
17 _SIZE_OF_UINT32 = 4
18 _SIZE_OF_COMMAND_HEADER = 4
19 _FIRST_SPECIFIC_COMMAND_ID = 256
21 _LICENSE = """// Copyright 2014 The Chromium Authors. All rights reserved.
22 // Use of this source code is governed by a BSD-style license that can be
23 // found in the LICENSE file.
25 """
27 _DO_NOT_EDIT_WARNING = """// This file is auto-generated from
28 // gpu/command_buffer/build_gles2_cmd_buffer.py
29 // It's formatted by clang-format using chromium coding style:
30 // clang-format -i -style=chromium filename
31 // DO NOT EDIT!
33 """
35 # This string is copied directly out of the gl2.h file from GLES2.0
37 # Edits:
39 # *) Any argument that is a resourceID has been changed to GLid<Type>.
40 # (not pointer arguments) and if it's allowed to be zero it's GLidZero<Type>
41 # If it's allowed to not exist it's GLidBind<Type>
43 # *) All GLenums have been changed to GLenumTypeOfEnum
45 _GL_TYPES = {
46 'GLenum': 'unsigned int',
47 'GLboolean': 'unsigned char',
48 'GLbitfield': 'unsigned int',
49 'GLbyte': 'signed char',
50 'GLshort': 'short',
51 'GLint': 'int',
52 'GLsizei': 'int',
53 'GLubyte': 'unsigned char',
54 'GLushort': 'unsigned short',
55 'GLuint': 'unsigned int',
56 'GLfloat': 'float',
57 'GLclampf': 'float',
58 'GLvoid': 'void',
59 'GLfixed': 'int',
60 'GLclampx': 'int'
63 _GL_TYPES_32 = {
64 'GLintptr': 'long int',
65 'GLsizeiptr': 'long int'
68 _GL_TYPES_64 = {
69 'GLintptr': 'long long int',
70 'GLsizeiptr': 'long long int'
73 # Capabilites selected with glEnable
74 _CAPABILITY_FLAGS = [
75 {'name': 'blend'},
76 {'name': 'cull_face'},
77 {'name': 'depth_test', 'state_flag': 'framebuffer_state_.clear_state_dirty'},
78 {'name': 'dither', 'default': True},
79 {'name': 'polygon_offset_fill'},
80 {'name': 'sample_alpha_to_coverage'},
81 {'name': 'sample_coverage'},
82 {'name': 'scissor_test'},
83 {'name': 'stencil_test',
84 'state_flag': 'framebuffer_state_.clear_state_dirty'},
85 {'name': 'rasterizer_discard', 'es3': True},
86 {'name': 'primitive_restart_fixed_index', 'es3': True},
89 _STATES = {
90 'ClearColor': {
91 'type': 'Normal',
92 'func': 'ClearColor',
93 'enum': 'GL_COLOR_CLEAR_VALUE',
94 'states': [
95 {'name': 'color_clear_red', 'type': 'GLfloat', 'default': '0.0f'},
96 {'name': 'color_clear_green', 'type': 'GLfloat', 'default': '0.0f'},
97 {'name': 'color_clear_blue', 'type': 'GLfloat', 'default': '0.0f'},
98 {'name': 'color_clear_alpha', 'type': 'GLfloat', 'default': '0.0f'},
101 'ClearDepthf': {
102 'type': 'Normal',
103 'func': 'ClearDepth',
104 'enum': 'GL_DEPTH_CLEAR_VALUE',
105 'states': [
106 {'name': 'depth_clear', 'type': 'GLclampf', 'default': '1.0f'},
109 'ColorMask': {
110 'type': 'Normal',
111 'func': 'ColorMask',
112 'enum': 'GL_COLOR_WRITEMASK',
113 'states': [
115 'name': 'color_mask_red',
116 'type': 'GLboolean',
117 'default': 'true',
118 'cached': True
121 'name': 'color_mask_green',
122 'type': 'GLboolean',
123 'default': 'true',
124 'cached': True
127 'name': 'color_mask_blue',
128 'type': 'GLboolean',
129 'default': 'true',
130 'cached': True
133 'name': 'color_mask_alpha',
134 'type': 'GLboolean',
135 'default': 'true',
136 'cached': True
139 'state_flag': 'framebuffer_state_.clear_state_dirty',
141 'ClearStencil': {
142 'type': 'Normal',
143 'func': 'ClearStencil',
144 'enum': 'GL_STENCIL_CLEAR_VALUE',
145 'states': [
146 {'name': 'stencil_clear', 'type': 'GLint', 'default': '0'},
149 'BlendColor': {
150 'type': 'Normal',
151 'func': 'BlendColor',
152 'enum': 'GL_BLEND_COLOR',
153 'states': [
154 {'name': 'blend_color_red', 'type': 'GLfloat', 'default': '0.0f'},
155 {'name': 'blend_color_green', 'type': 'GLfloat', 'default': '0.0f'},
156 {'name': 'blend_color_blue', 'type': 'GLfloat', 'default': '0.0f'},
157 {'name': 'blend_color_alpha', 'type': 'GLfloat', 'default': '0.0f'},
160 'BlendEquation': {
161 'type': 'SrcDst',
162 'func': 'BlendEquationSeparate',
163 'states': [
165 'name': 'blend_equation_rgb',
166 'type': 'GLenum',
167 'enum': 'GL_BLEND_EQUATION_RGB',
168 'default': 'GL_FUNC_ADD',
171 'name': 'blend_equation_alpha',
172 'type': 'GLenum',
173 'enum': 'GL_BLEND_EQUATION_ALPHA',
174 'default': 'GL_FUNC_ADD',
178 'BlendFunc': {
179 'type': 'SrcDst',
180 'func': 'BlendFuncSeparate',
181 'states': [
183 'name': 'blend_source_rgb',
184 'type': 'GLenum',
185 'enum': 'GL_BLEND_SRC_RGB',
186 'default': 'GL_ONE',
189 'name': 'blend_dest_rgb',
190 'type': 'GLenum',
191 'enum': 'GL_BLEND_DST_RGB',
192 'default': 'GL_ZERO',
195 'name': 'blend_source_alpha',
196 'type': 'GLenum',
197 'enum': 'GL_BLEND_SRC_ALPHA',
198 'default': 'GL_ONE',
201 'name': 'blend_dest_alpha',
202 'type': 'GLenum',
203 'enum': 'GL_BLEND_DST_ALPHA',
204 'default': 'GL_ZERO',
208 'PolygonOffset': {
209 'type': 'Normal',
210 'func': 'PolygonOffset',
211 'states': [
213 'name': 'polygon_offset_factor',
214 'type': 'GLfloat',
215 'enum': 'GL_POLYGON_OFFSET_FACTOR',
216 'default': '0.0f',
219 'name': 'polygon_offset_units',
220 'type': 'GLfloat',
221 'enum': 'GL_POLYGON_OFFSET_UNITS',
222 'default': '0.0f',
226 'CullFace': {
227 'type': 'Normal',
228 'func': 'CullFace',
229 'enum': 'GL_CULL_FACE_MODE',
230 'states': [
232 'name': 'cull_mode',
233 'type': 'GLenum',
234 'default': 'GL_BACK',
238 'FrontFace': {
239 'type': 'Normal',
240 'func': 'FrontFace',
241 'enum': 'GL_FRONT_FACE',
242 'states': [{'name': 'front_face', 'type': 'GLenum', 'default': 'GL_CCW'}],
244 'DepthFunc': {
245 'type': 'Normal',
246 'func': 'DepthFunc',
247 'enum': 'GL_DEPTH_FUNC',
248 'states': [{'name': 'depth_func', 'type': 'GLenum', 'default': 'GL_LESS'}],
250 'DepthRange': {
251 'type': 'Normal',
252 'func': 'DepthRange',
253 'enum': 'GL_DEPTH_RANGE',
254 'states': [
255 {'name': 'z_near', 'type': 'GLclampf', 'default': '0.0f'},
256 {'name': 'z_far', 'type': 'GLclampf', 'default': '1.0f'},
259 'SampleCoverage': {
260 'type': 'Normal',
261 'func': 'SampleCoverage',
262 'states': [
264 'name': 'sample_coverage_value',
265 'type': 'GLclampf',
266 'enum': 'GL_SAMPLE_COVERAGE_VALUE',
267 'default': '1.0f',
270 'name': 'sample_coverage_invert',
271 'type': 'GLboolean',
272 'enum': 'GL_SAMPLE_COVERAGE_INVERT',
273 'default': 'false',
277 'StencilMask': {
278 'type': 'FrontBack',
279 'func': 'StencilMaskSeparate',
280 'state_flag': 'framebuffer_state_.clear_state_dirty',
281 'states': [
283 'name': 'stencil_front_writemask',
284 'type': 'GLuint',
285 'enum': 'GL_STENCIL_WRITEMASK',
286 'default': '0xFFFFFFFFU',
287 'cached': True,
290 'name': 'stencil_back_writemask',
291 'type': 'GLuint',
292 'enum': 'GL_STENCIL_BACK_WRITEMASK',
293 'default': '0xFFFFFFFFU',
294 'cached': True,
298 'StencilOp': {
299 'type': 'FrontBack',
300 'func': 'StencilOpSeparate',
301 'states': [
303 'name': 'stencil_front_fail_op',
304 'type': 'GLenum',
305 'enum': 'GL_STENCIL_FAIL',
306 'default': 'GL_KEEP',
309 'name': 'stencil_front_z_fail_op',
310 'type': 'GLenum',
311 'enum': 'GL_STENCIL_PASS_DEPTH_FAIL',
312 'default': 'GL_KEEP',
315 'name': 'stencil_front_z_pass_op',
316 'type': 'GLenum',
317 'enum': 'GL_STENCIL_PASS_DEPTH_PASS',
318 'default': 'GL_KEEP',
321 'name': 'stencil_back_fail_op',
322 'type': 'GLenum',
323 'enum': 'GL_STENCIL_BACK_FAIL',
324 'default': 'GL_KEEP',
327 'name': 'stencil_back_z_fail_op',
328 'type': 'GLenum',
329 'enum': 'GL_STENCIL_BACK_PASS_DEPTH_FAIL',
330 'default': 'GL_KEEP',
333 'name': 'stencil_back_z_pass_op',
334 'type': 'GLenum',
335 'enum': 'GL_STENCIL_BACK_PASS_DEPTH_PASS',
336 'default': 'GL_KEEP',
340 'StencilFunc': {
341 'type': 'FrontBack',
342 'func': 'StencilFuncSeparate',
343 'states': [
345 'name': 'stencil_front_func',
346 'type': 'GLenum',
347 'enum': 'GL_STENCIL_FUNC',
348 'default': 'GL_ALWAYS',
351 'name': 'stencil_front_ref',
352 'type': 'GLint',
353 'enum': 'GL_STENCIL_REF',
354 'default': '0',
357 'name': 'stencil_front_mask',
358 'type': 'GLuint',
359 'enum': 'GL_STENCIL_VALUE_MASK',
360 'default': '0xFFFFFFFFU',
363 'name': 'stencil_back_func',
364 'type': 'GLenum',
365 'enum': 'GL_STENCIL_BACK_FUNC',
366 'default': 'GL_ALWAYS',
369 'name': 'stencil_back_ref',
370 'type': 'GLint',
371 'enum': 'GL_STENCIL_BACK_REF',
372 'default': '0',
375 'name': 'stencil_back_mask',
376 'type': 'GLuint',
377 'enum': 'GL_STENCIL_BACK_VALUE_MASK',
378 'default': '0xFFFFFFFFU',
382 'Hint': {
383 'type': 'NamedParameter',
384 'func': 'Hint',
385 'states': [
387 'name': 'hint_generate_mipmap',
388 'type': 'GLenum',
389 'enum': 'GL_GENERATE_MIPMAP_HINT',
390 'default': 'GL_DONT_CARE',
391 'gl_version_flag': '!is_desktop_core_profile'
394 'name': 'hint_fragment_shader_derivative',
395 'type': 'GLenum',
396 'enum': 'GL_FRAGMENT_SHADER_DERIVATIVE_HINT_OES',
397 'default': 'GL_DONT_CARE',
398 'extension_flag': 'oes_standard_derivatives'
402 'PixelStore': {
403 'type': 'NamedParameter',
404 'func': 'PixelStorei',
405 'states': [
407 'name': 'pack_alignment',
408 'type': 'GLint',
409 'enum': 'GL_PACK_ALIGNMENT',
410 'default': '4'
413 'name': 'unpack_alignment',
414 'type': 'GLint',
415 'enum': 'GL_UNPACK_ALIGNMENT',
416 'default': '4'
420 # TODO: Consider implemenenting these states
421 # GL_ACTIVE_TEXTURE
422 'LineWidth': {
423 'type': 'Normal',
424 'func': 'LineWidth',
425 'enum': 'GL_LINE_WIDTH',
426 'states': [
428 'name': 'line_width',
429 'type': 'GLfloat',
430 'default': '1.0f',
431 'range_checks': [{'check': "<= 0.0f", 'test_value': "0.0f"}],
432 'nan_check': True,
435 'DepthMask': {
436 'type': 'Normal',
437 'func': 'DepthMask',
438 'enum': 'GL_DEPTH_WRITEMASK',
439 'states': [
441 'name': 'depth_mask',
442 'type': 'GLboolean',
443 'default': 'true',
444 'cached': True
447 'state_flag': 'framebuffer_state_.clear_state_dirty',
449 'Scissor': {
450 'type': 'Normal',
451 'func': 'Scissor',
452 'enum': 'GL_SCISSOR_BOX',
453 'states': [
454 # NOTE: These defaults reset at GLES2DecoderImpl::Initialization.
456 'name': 'scissor_x',
457 'type': 'GLint',
458 'default': '0',
459 'expected': 'kViewportX',
462 'name': 'scissor_y',
463 'type': 'GLint',
464 'default': '0',
465 'expected': 'kViewportY',
468 'name': 'scissor_width',
469 'type': 'GLsizei',
470 'default': '1',
471 'expected': 'kViewportWidth',
474 'name': 'scissor_height',
475 'type': 'GLsizei',
476 'default': '1',
477 'expected': 'kViewportHeight',
481 'Viewport': {
482 'type': 'Normal',
483 'func': 'Viewport',
484 'enum': 'GL_VIEWPORT',
485 'states': [
486 # NOTE: These defaults reset at GLES2DecoderImpl::Initialization.
488 'name': 'viewport_x',
489 'type': 'GLint',
490 'default': '0',
491 'expected': 'kViewportX',
494 'name': 'viewport_y',
495 'type': 'GLint',
496 'default': '0',
497 'expected': 'kViewportY',
500 'name': 'viewport_width',
501 'type': 'GLsizei',
502 'default': '1',
503 'expected': 'kViewportWidth',
506 'name': 'viewport_height',
507 'type': 'GLsizei',
508 'default': '1',
509 'expected': 'kViewportHeight',
513 'MatrixValuesCHROMIUM': {
514 'type': 'NamedParameter',
515 'func': 'MatrixLoadfEXT',
516 'states': [
517 { 'enum': 'GL_PATH_MODELVIEW_MATRIX_CHROMIUM',
518 'enum_set': 'GL_PATH_MODELVIEW_CHROMIUM',
519 'name': 'modelview_matrix',
520 'type': 'GLfloat',
521 'default': [
522 '1.0f', '0.0f','0.0f','0.0f',
523 '0.0f', '1.0f','0.0f','0.0f',
524 '0.0f', '0.0f','1.0f','0.0f',
525 '0.0f', '0.0f','0.0f','1.0f',
527 'extension_flag': 'chromium_path_rendering',
529 { 'enum': 'GL_PATH_PROJECTION_MATRIX_CHROMIUM',
530 'enum_set': 'GL_PATH_PROJECTION_CHROMIUM',
531 'name': 'projection_matrix',
532 'type': 'GLfloat',
533 'default': [
534 '1.0f', '0.0f','0.0f','0.0f',
535 '0.0f', '1.0f','0.0f','0.0f',
536 '0.0f', '0.0f','1.0f','0.0f',
537 '0.0f', '0.0f','0.0f','1.0f',
539 'extension_flag': 'chromium_path_rendering',
543 'PathStencilFuncCHROMIUM': {
544 'type': 'Normal',
545 'func': 'PathStencilFuncNV',
546 'extension_flag': 'chromium_path_rendering',
547 'states': [
549 'name': 'stencil_path_func',
550 'type': 'GLenum',
551 'enum': 'GL_PATH_STENCIL_FUNC_CHROMIUM',
552 'default': 'GL_ALWAYS',
555 'name': 'stencil_path_ref',
556 'type': 'GLint',
557 'enum': 'GL_PATH_STENCIL_REF_CHROMIUM',
558 'default': '0',
561 'name': 'stencil_path_mask',
562 'type': 'GLuint',
563 'enum': 'GL_PATH_STENCIL_VALUE_MASK_CHROMIUM',
564 'default': '0xFFFFFFFFU',
570 # Named type info object represents a named type that is used in OpenGL call
571 # arguments. Each named type defines a set of valid OpenGL call arguments. The
572 # named types are used in 'cmd_buffer_functions.txt'.
573 # type: The actual GL type of the named type.
574 # valid: The list of values that are valid for both the client and the service.
575 # valid_es3: The list of values that are valid in OpenGL ES 3, but not ES 2.
576 # invalid: Examples of invalid values for the type. At least these values
577 # should be tested to be invalid.
578 # deprecated_es3: The list of values that are valid in OpenGL ES 2, but
579 # deprecated in ES 3.
580 # is_complete: The list of valid values of type are final and will not be
581 # modified during runtime.
582 _NAMED_TYPE_INFO = {
583 'BlitFilter': {
584 'type': 'GLenum',
585 'valid': [
586 'GL_NEAREST',
587 'GL_LINEAR',
589 'invalid': [
590 'GL_LINEAR_MIPMAP_LINEAR',
593 'FrameBufferTarget': {
594 'type': 'GLenum',
595 'valid': [
596 'GL_FRAMEBUFFER',
598 'valid_es3': [
599 'GL_DRAW_FRAMEBUFFER' ,
600 'GL_READ_FRAMEBUFFER' ,
602 'invalid': [
603 'GL_RENDERBUFFER',
606 'InvalidateFrameBufferTarget': {
607 'type': 'GLenum',
608 'valid': [
609 'GL_FRAMEBUFFER',
611 'invalid': [
612 'GL_DRAW_FRAMEBUFFER' ,
613 'GL_READ_FRAMEBUFFER' ,
616 'RenderBufferTarget': {
617 'type': 'GLenum',
618 'valid': [
619 'GL_RENDERBUFFER',
621 'invalid': [
622 'GL_FRAMEBUFFER',
625 'BufferTarget': {
626 'type': 'GLenum',
627 'valid': [
628 'GL_ARRAY_BUFFER',
629 'GL_ELEMENT_ARRAY_BUFFER',
631 'valid_es3': [
632 'GL_COPY_READ_BUFFER',
633 'GL_COPY_WRITE_BUFFER',
634 'GL_PIXEL_PACK_BUFFER',
635 'GL_PIXEL_UNPACK_BUFFER',
636 'GL_TRANSFORM_FEEDBACK_BUFFER',
637 'GL_UNIFORM_BUFFER',
639 'invalid': [
640 'GL_RENDERBUFFER',
643 'IndexedBufferTarget': {
644 'type': 'GLenum',
645 'valid': [
646 'GL_TRANSFORM_FEEDBACK_BUFFER',
647 'GL_UNIFORM_BUFFER',
649 'invalid': [
650 'GL_RENDERBUFFER',
653 'MapBufferAccess': {
654 'type': 'GLenum',
655 'valid': [
656 'GL_MAP_READ_BIT',
657 'GL_MAP_WRITE_BIT',
658 'GL_MAP_INVALIDATE_RANGE_BIT',
659 'GL_MAP_INVALIDATE_BUFFER_BIT',
660 'GL_MAP_FLUSH_EXPLICIT_BIT',
661 'GL_MAP_UNSYNCHRONIZED_BIT',
663 'invalid': [
664 'GL_SYNC_FLUSH_COMMANDS_BIT',
667 'Bufferiv': {
668 'type': 'GLenum',
669 'valid': [
670 'GL_COLOR',
671 'GL_STENCIL',
673 'invalid': [
674 'GL_RENDERBUFFER',
677 'Bufferuiv': {
678 'type': 'GLenum',
679 'valid': [
680 'GL_COLOR',
682 'invalid': [
683 'GL_RENDERBUFFER',
686 'Bufferfv': {
687 'type': 'GLenum',
688 'valid': [
689 'GL_COLOR',
690 'GL_DEPTH',
692 'invalid': [
693 'GL_RENDERBUFFER',
696 'Bufferfi': {
697 'type': 'GLenum',
698 'valid': [
699 'GL_DEPTH_STENCIL',
701 'invalid': [
702 'GL_RENDERBUFFER',
705 'BufferUsage': {
706 'type': 'GLenum',
707 'valid': [
708 'GL_STREAM_DRAW',
709 'GL_STATIC_DRAW',
710 'GL_DYNAMIC_DRAW',
712 'valid_es3': [
713 'GL_STREAM_READ',
714 'GL_STREAM_COPY',
715 'GL_STATIC_READ',
716 'GL_STATIC_COPY',
717 'GL_DYNAMIC_READ',
718 'GL_DYNAMIC_COPY',
720 'invalid': [
721 'GL_NONE',
724 'CompressedTextureFormat': {
725 'type': 'GLenum',
726 'valid': [
728 'valid_es3': [
729 'GL_COMPRESSED_R11_EAC',
730 'GL_COMPRESSED_SIGNED_R11_EAC',
731 'GL_COMPRESSED_RG11_EAC',
732 'GL_COMPRESSED_SIGNED_RG11_EAC',
733 'GL_COMPRESSED_RGB8_ETC2',
734 'GL_COMPRESSED_SRGB8_ETC2',
735 'GL_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2',
736 'GL_COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2',
737 'GL_COMPRESSED_RGBA8_ETC2_EAC',
738 'GL_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC',
741 'GLState': {
742 'type': 'GLenum',
743 'valid': [
744 # NOTE: State an Capability entries added later.
745 'GL_ACTIVE_TEXTURE',
746 'GL_ALIASED_LINE_WIDTH_RANGE',
747 'GL_ALIASED_POINT_SIZE_RANGE',
748 'GL_ALPHA_BITS',
749 'GL_ARRAY_BUFFER_BINDING',
750 'GL_BLUE_BITS',
751 'GL_COMPRESSED_TEXTURE_FORMATS',
752 'GL_CURRENT_PROGRAM',
753 'GL_DEPTH_BITS',
754 'GL_DEPTH_RANGE',
755 'GL_ELEMENT_ARRAY_BUFFER_BINDING',
756 'GL_FRAMEBUFFER_BINDING',
757 'GL_GENERATE_MIPMAP_HINT',
758 'GL_GREEN_BITS',
759 'GL_IMPLEMENTATION_COLOR_READ_FORMAT',
760 'GL_IMPLEMENTATION_COLOR_READ_TYPE',
761 'GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS',
762 'GL_MAX_CUBE_MAP_TEXTURE_SIZE',
763 'GL_MAX_FRAGMENT_UNIFORM_VECTORS',
764 'GL_MAX_RENDERBUFFER_SIZE',
765 'GL_MAX_TEXTURE_IMAGE_UNITS',
766 'GL_MAX_TEXTURE_SIZE',
767 'GL_MAX_VARYING_VECTORS',
768 'GL_MAX_VERTEX_ATTRIBS',
769 'GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS',
770 'GL_MAX_VERTEX_UNIFORM_VECTORS',
771 'GL_MAX_VIEWPORT_DIMS',
772 'GL_NUM_COMPRESSED_TEXTURE_FORMATS',
773 'GL_NUM_SHADER_BINARY_FORMATS',
774 'GL_PACK_ALIGNMENT',
775 'GL_RED_BITS',
776 'GL_RENDERBUFFER_BINDING',
777 'GL_SAMPLE_BUFFERS',
778 'GL_SAMPLE_COVERAGE_INVERT',
779 'GL_SAMPLE_COVERAGE_VALUE',
780 'GL_SAMPLES',
781 'GL_SCISSOR_BOX',
782 'GL_SHADER_BINARY_FORMATS',
783 'GL_SHADER_COMPILER',
784 'GL_SUBPIXEL_BITS',
785 'GL_STENCIL_BITS',
786 'GL_TEXTURE_BINDING_2D',
787 'GL_TEXTURE_BINDING_CUBE_MAP',
788 'GL_UNPACK_ALIGNMENT',
789 'GL_BIND_GENERATES_RESOURCE_CHROMIUM',
790 # we can add this because we emulate it if the driver does not support it.
791 'GL_VERTEX_ARRAY_BINDING_OES',
792 'GL_VIEWPORT',
794 'valid_es3': [
795 'GL_COPY_READ_BUFFER_BINDING',
796 'GL_COPY_WRITE_BUFFER_BINDING',
797 'GL_DRAW_BUFFER0',
798 'GL_DRAW_BUFFER1',
799 'GL_DRAW_BUFFER2',
800 'GL_DRAW_BUFFER3',
801 'GL_DRAW_BUFFER4',
802 'GL_DRAW_BUFFER5',
803 'GL_DRAW_BUFFER6',
804 'GL_DRAW_BUFFER7',
805 'GL_DRAW_BUFFER8',
806 'GL_DRAW_BUFFER9',
807 'GL_DRAW_BUFFER10',
808 'GL_DRAW_BUFFER11',
809 'GL_DRAW_BUFFER12',
810 'GL_DRAW_BUFFER13',
811 'GL_DRAW_BUFFER14',
812 'GL_DRAW_BUFFER15',
813 'GL_DRAW_FRAMEBUFFER_BINDING',
814 'GL_FRAGMENT_SHADER_DERIVATIVE_HINT',
815 'GL_GPU_DISJOINT_EXT',
816 'GL_MAJOR_VERSION',
817 'GL_MAX_3D_TEXTURE_SIZE',
818 'GL_MAX_ARRAY_TEXTURE_LAYERS',
819 'GL_MAX_COLOR_ATTACHMENTS',
820 'GL_MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS',
821 'GL_MAX_COMBINED_UNIFORM_BLOCKS',
822 'GL_MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS',
823 'GL_MAX_DRAW_BUFFERS',
824 'GL_MAX_ELEMENT_INDEX',
825 'GL_MAX_ELEMENTS_INDICES',
826 'GL_MAX_ELEMENTS_VERTICES',
827 'GL_MAX_FRAGMENT_INPUT_COMPONENTS',
828 'GL_MAX_FRAGMENT_UNIFORM_BLOCKS',
829 'GL_MAX_FRAGMENT_UNIFORM_COMPONENTS',
830 'GL_MAX_PROGRAM_TEXEL_OFFSET',
831 'GL_MAX_SAMPLES',
832 'GL_MAX_SERVER_WAIT_TIMEOUT',
833 'GL_MAX_TEXTURE_LOD_BIAS',
834 'GL_MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS',
835 'GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS',
836 'GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS',
837 'GL_MAX_UNIFORM_BLOCK_SIZE',
838 'GL_MAX_UNIFORM_BUFFER_BINDINGS',
839 'GL_MAX_VARYING_COMPONENTS',
840 'GL_MAX_VERTEX_OUTPUT_COMPONENTS',
841 'GL_MAX_VERTEX_UNIFORM_BLOCKS',
842 'GL_MAX_VERTEX_UNIFORM_COMPONENTS',
843 'GL_MIN_PROGRAM_TEXEL_OFFSET',
844 'GL_MINOR_VERSION',
845 'GL_NUM_EXTENSIONS',
846 'GL_NUM_PROGRAM_BINARY_FORMATS',
847 'GL_PACK_ROW_LENGTH',
848 'GL_PACK_SKIP_PIXELS',
849 'GL_PACK_SKIP_ROWS',
850 'GL_PIXEL_PACK_BUFFER_BINDING',
851 'GL_PIXEL_UNPACK_BUFFER_BINDING',
852 'GL_PROGRAM_BINARY_FORMATS',
853 'GL_READ_BUFFER',
854 'GL_READ_FRAMEBUFFER_BINDING',
855 'GL_SAMPLER_BINDING',
856 'GL_TIMESTAMP_EXT',
857 'GL_TEXTURE_BINDING_2D_ARRAY',
858 'GL_TEXTURE_BINDING_3D',
859 'GL_TRANSFORM_FEEDBACK_BINDING',
860 'GL_TRANSFORM_FEEDBACK_ACTIVE',
861 'GL_TRANSFORM_FEEDBACK_BUFFER_BINDING',
862 'GL_TRANSFORM_FEEDBACK_PAUSED',
863 'GL_TRANSFORM_FEEDBACK_BUFFER_SIZE',
864 'GL_TRANSFORM_FEEDBACK_BUFFER_START',
865 'GL_UNIFORM_BUFFER_BINDING',
866 'GL_UNIFORM_BUFFER_OFFSET_ALIGNMENT',
867 'GL_UNIFORM_BUFFER_SIZE',
868 'GL_UNIFORM_BUFFER_START',
869 'GL_UNPACK_IMAGE_HEIGHT',
870 'GL_UNPACK_ROW_LENGTH',
871 'GL_UNPACK_SKIP_IMAGES',
872 'GL_UNPACK_SKIP_PIXELS',
873 'GL_UNPACK_SKIP_ROWS',
874 # GL_VERTEX_ARRAY_BINDING is the same as GL_VERTEX_ARRAY_BINDING_OES
875 # 'GL_VERTEX_ARRAY_BINDING',
877 'invalid': [
878 'GL_FOG_HINT',
881 'IndexedGLState': {
882 'type': 'GLenum',
883 'valid': [
884 'GL_TRANSFORM_FEEDBACK_BUFFER_BINDING',
885 'GL_TRANSFORM_FEEDBACK_BUFFER_SIZE',
886 'GL_TRANSFORM_FEEDBACK_BUFFER_START',
887 'GL_UNIFORM_BUFFER_BINDING',
888 'GL_UNIFORM_BUFFER_SIZE',
889 'GL_UNIFORM_BUFFER_START',
891 'invalid': [
892 'GL_FOG_HINT',
895 'GetTexParamTarget': {
896 'type': 'GLenum',
897 'valid': [
898 'GL_TEXTURE_2D',
899 'GL_TEXTURE_CUBE_MAP',
901 'valid_es3': [
902 'GL_TEXTURE_2D_ARRAY',
903 'GL_TEXTURE_3D',
905 'invalid': [
906 'GL_PROXY_TEXTURE_CUBE_MAP',
909 'ReadBuffer': {
910 'type': 'GLenum',
911 'valid': [
912 'GL_NONE',
913 'GL_BACK',
914 'GL_COLOR_ATTACHMENT0',
915 'GL_COLOR_ATTACHMENT1',
916 'GL_COLOR_ATTACHMENT2',
917 'GL_COLOR_ATTACHMENT3',
918 'GL_COLOR_ATTACHMENT4',
919 'GL_COLOR_ATTACHMENT5',
920 'GL_COLOR_ATTACHMENT6',
921 'GL_COLOR_ATTACHMENT7',
922 'GL_COLOR_ATTACHMENT8',
923 'GL_COLOR_ATTACHMENT9',
924 'GL_COLOR_ATTACHMENT10',
925 'GL_COLOR_ATTACHMENT11',
926 'GL_COLOR_ATTACHMENT12',
927 'GL_COLOR_ATTACHMENT13',
928 'GL_COLOR_ATTACHMENT14',
929 'GL_COLOR_ATTACHMENT15',
931 'invalid': [
932 'GL_RENDERBUFFER',
935 'TextureTarget': {
936 'type': 'GLenum',
937 'valid': [
938 'GL_TEXTURE_2D',
939 'GL_TEXTURE_CUBE_MAP_POSITIVE_X',
940 'GL_TEXTURE_CUBE_MAP_NEGATIVE_X',
941 'GL_TEXTURE_CUBE_MAP_POSITIVE_Y',
942 'GL_TEXTURE_CUBE_MAP_NEGATIVE_Y',
943 'GL_TEXTURE_CUBE_MAP_POSITIVE_Z',
944 'GL_TEXTURE_CUBE_MAP_NEGATIVE_Z',
946 'invalid': [
947 'GL_PROXY_TEXTURE_CUBE_MAP',
950 'Texture3DTarget': {
951 'type': 'GLenum',
952 'valid': [
953 'GL_TEXTURE_3D',
954 'GL_TEXTURE_2D_ARRAY',
956 'invalid': [
957 'GL_TEXTURE_2D',
960 'TextureBindTarget': {
961 'type': 'GLenum',
962 'valid': [
963 'GL_TEXTURE_2D',
964 'GL_TEXTURE_CUBE_MAP',
966 'valid_es3': [
967 'GL_TEXTURE_3D',
968 'GL_TEXTURE_2D_ARRAY',
970 'invalid': [
971 'GL_TEXTURE_1D',
972 'GL_TEXTURE_3D',
975 'TransformFeedbackBindTarget': {
976 'type': 'GLenum',
977 'valid': [
978 'GL_TRANSFORM_FEEDBACK',
980 'invalid': [
981 'GL_TEXTURE_2D',
984 'TransformFeedbackPrimitiveMode': {
985 'type': 'GLenum',
986 'valid': [
987 'GL_POINTS',
988 'GL_LINES',
989 'GL_TRIANGLES',
991 'invalid': [
992 'GL_LINE_LOOP',
995 'ShaderType': {
996 'type': 'GLenum',
997 'valid': [
998 'GL_VERTEX_SHADER',
999 'GL_FRAGMENT_SHADER',
1001 'invalid': [
1002 'GL_GEOMETRY_SHADER',
1005 'FaceType': {
1006 'type': 'GLenum',
1007 'valid': [
1008 'GL_FRONT',
1009 'GL_BACK',
1010 'GL_FRONT_AND_BACK',
1013 'FaceMode': {
1014 'type': 'GLenum',
1015 'valid': [
1016 'GL_CW',
1017 'GL_CCW',
1020 'CmpFunction': {
1021 'type': 'GLenum',
1022 'valid': [
1023 'GL_NEVER',
1024 'GL_LESS',
1025 'GL_EQUAL',
1026 'GL_LEQUAL',
1027 'GL_GREATER',
1028 'GL_NOTEQUAL',
1029 'GL_GEQUAL',
1030 'GL_ALWAYS',
1033 'Equation': {
1034 'type': 'GLenum',
1035 'valid': [
1036 'GL_FUNC_ADD',
1037 'GL_FUNC_SUBTRACT',
1038 'GL_FUNC_REVERSE_SUBTRACT',
1040 'valid_es3': [
1041 'GL_MIN',
1042 'GL_MAX',
1044 'invalid': [
1045 'GL_NONE',
1048 'SrcBlendFactor': {
1049 'type': 'GLenum',
1050 'valid': [
1051 'GL_ZERO',
1052 'GL_ONE',
1053 'GL_SRC_COLOR',
1054 'GL_ONE_MINUS_SRC_COLOR',
1055 'GL_DST_COLOR',
1056 'GL_ONE_MINUS_DST_COLOR',
1057 'GL_SRC_ALPHA',
1058 'GL_ONE_MINUS_SRC_ALPHA',
1059 'GL_DST_ALPHA',
1060 'GL_ONE_MINUS_DST_ALPHA',
1061 'GL_CONSTANT_COLOR',
1062 'GL_ONE_MINUS_CONSTANT_COLOR',
1063 'GL_CONSTANT_ALPHA',
1064 'GL_ONE_MINUS_CONSTANT_ALPHA',
1065 'GL_SRC_ALPHA_SATURATE',
1068 'DstBlendFactor': {
1069 'type': 'GLenum',
1070 'valid': [
1071 'GL_ZERO',
1072 'GL_ONE',
1073 'GL_SRC_COLOR',
1074 'GL_ONE_MINUS_SRC_COLOR',
1075 'GL_DST_COLOR',
1076 'GL_ONE_MINUS_DST_COLOR',
1077 'GL_SRC_ALPHA',
1078 'GL_ONE_MINUS_SRC_ALPHA',
1079 'GL_DST_ALPHA',
1080 'GL_ONE_MINUS_DST_ALPHA',
1081 'GL_CONSTANT_COLOR',
1082 'GL_ONE_MINUS_CONSTANT_COLOR',
1083 'GL_CONSTANT_ALPHA',
1084 'GL_ONE_MINUS_CONSTANT_ALPHA',
1087 'Capability': {
1088 'type': 'GLenum',
1089 'valid': ["GL_%s" % cap['name'].upper() for cap in _CAPABILITY_FLAGS
1090 if 'es3' not in cap or cap['es3'] != True],
1091 'valid_es3': ["GL_%s" % cap['name'].upper() for cap in _CAPABILITY_FLAGS
1092 if 'es3' in cap and cap['es3'] == True],
1093 'invalid': [
1094 'GL_CLIP_PLANE0',
1095 'GL_POINT_SPRITE',
1098 'DrawMode': {
1099 'type': 'GLenum',
1100 'valid': [
1101 'GL_POINTS',
1102 'GL_LINE_STRIP',
1103 'GL_LINE_LOOP',
1104 'GL_LINES',
1105 'GL_TRIANGLE_STRIP',
1106 'GL_TRIANGLE_FAN',
1107 'GL_TRIANGLES',
1109 'invalid': [
1110 'GL_QUADS',
1111 'GL_POLYGON',
1114 'IndexType': {
1115 'type': 'GLenum',
1116 'valid': [
1117 'GL_UNSIGNED_BYTE',
1118 'GL_UNSIGNED_SHORT',
1120 'valid_es3': [
1121 'GL_UNSIGNED_INT',
1123 'invalid': [
1124 'GL_INT',
1127 'GetMaxIndexType': {
1128 'type': 'GLenum',
1129 'valid': [
1130 'GL_UNSIGNED_BYTE',
1131 'GL_UNSIGNED_SHORT',
1132 'GL_UNSIGNED_INT',
1134 'invalid': [
1135 'GL_INT',
1138 'Attachment': {
1139 'type': 'GLenum',
1140 'valid': [
1141 'GL_COLOR_ATTACHMENT0',
1142 'GL_DEPTH_ATTACHMENT',
1143 'GL_STENCIL_ATTACHMENT',
1145 'valid_es3': [
1146 'GL_DEPTH_STENCIL_ATTACHMENT',
1147 # For backbuffer.
1148 'GL_COLOR_EXT',
1149 'GL_DEPTH_EXT',
1150 'GL_STENCIL_EXT',
1153 'BackbufferAttachment': {
1154 'type': 'GLenum',
1155 'valid': [
1156 'GL_COLOR_EXT',
1157 'GL_DEPTH_EXT',
1158 'GL_STENCIL_EXT',
1161 'BufferParameter': {
1162 'type': 'GLenum',
1163 'valid': [
1164 'GL_BUFFER_SIZE',
1165 'GL_BUFFER_USAGE',
1167 'valid_es3': [
1168 'GL_BUFFER_ACCESS_FLAGS',
1169 'GL_BUFFER_MAPPED',
1171 'invalid': [
1172 'GL_PIXEL_PACK_BUFFER',
1175 'BufferParameter64': {
1176 'type': 'GLenum',
1177 'valid': [
1178 'GL_BUFFER_SIZE',
1179 'GL_BUFFER_MAP_LENGTH',
1180 'GL_BUFFER_MAP_OFFSET',
1182 'invalid': [
1183 'GL_PIXEL_PACK_BUFFER',
1186 'BufferMode': {
1187 'type': 'GLenum',
1188 'valid': [
1189 'GL_INTERLEAVED_ATTRIBS',
1190 'GL_SEPARATE_ATTRIBS',
1192 'invalid': [
1193 'GL_PIXEL_PACK_BUFFER',
1196 'FrameBufferParameter': {
1197 'type': 'GLenum',
1198 'valid': [
1199 'GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE',
1200 'GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME',
1201 'GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL',
1202 'GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE',
1204 'valid_es3': [
1205 'GL_FRAMEBUFFER_ATTACHMENT_RED_SIZE',
1206 'GL_FRAMEBUFFER_ATTACHMENT_GREEN_SIZE',
1207 'GL_FRAMEBUFFER_ATTACHMENT_BLUE_SIZE',
1208 'GL_FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE',
1209 'GL_FRAMEBUFFER_ATTACHMENT_DEPTH_SIZE',
1210 'GL_FRAMEBUFFER_ATTACHMENT_STENCIL_SIZE',
1211 'GL_FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE',
1212 'GL_FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING',
1213 'GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER',
1216 'MatrixMode': {
1217 'type': 'GLenum',
1218 'valid': [
1219 'GL_PATH_PROJECTION_CHROMIUM',
1220 'GL_PATH_MODELVIEW_CHROMIUM',
1223 'ProgramParameter': {
1224 'type': 'GLenum',
1225 'valid': [
1226 'GL_DELETE_STATUS',
1227 'GL_LINK_STATUS',
1228 'GL_VALIDATE_STATUS',
1229 'GL_INFO_LOG_LENGTH',
1230 'GL_ATTACHED_SHADERS',
1231 'GL_ACTIVE_ATTRIBUTES',
1232 'GL_ACTIVE_ATTRIBUTE_MAX_LENGTH',
1233 'GL_ACTIVE_UNIFORMS',
1234 'GL_ACTIVE_UNIFORM_MAX_LENGTH',
1236 'valid_es3': [
1237 'GL_ACTIVE_UNIFORM_BLOCKS',
1238 'GL_ACTIVE_UNIFORM_BLOCK_MAX_NAME_LENGTH',
1239 'GL_TRANSFORM_FEEDBACK_BUFFER_MODE',
1240 'GL_TRANSFORM_FEEDBACK_VARYINGS',
1241 'GL_TRANSFORM_FEEDBACK_VARYING_MAX_LENGTH',
1243 'invalid': [
1244 'GL_PROGRAM_BINARY_RETRIEVABLE_HINT', # not supported in Chromium.
1247 'QueryObjectParameter': {
1248 'type': 'GLenum',
1249 'valid': [
1250 'GL_QUERY_RESULT_EXT',
1251 'GL_QUERY_RESULT_AVAILABLE_EXT',
1254 'QueryParameter': {
1255 'type': 'GLenum',
1256 'valid': [
1257 'GL_CURRENT_QUERY_EXT',
1260 'QueryTarget': {
1261 'type': 'GLenum',
1262 'valid': [
1263 'GL_ANY_SAMPLES_PASSED_EXT',
1264 'GL_ANY_SAMPLES_PASSED_CONSERVATIVE_EXT',
1265 'GL_COMMANDS_ISSUED_CHROMIUM',
1266 'GL_LATENCY_QUERY_CHROMIUM',
1267 'GL_ASYNC_PIXEL_PACK_COMPLETED_CHROMIUM',
1268 'GL_COMMANDS_COMPLETED_CHROMIUM',
1271 'RenderBufferParameter': {
1272 'type': 'GLenum',
1273 'valid': [
1274 'GL_RENDERBUFFER_RED_SIZE',
1275 'GL_RENDERBUFFER_GREEN_SIZE',
1276 'GL_RENDERBUFFER_BLUE_SIZE',
1277 'GL_RENDERBUFFER_ALPHA_SIZE',
1278 'GL_RENDERBUFFER_DEPTH_SIZE',
1279 'GL_RENDERBUFFER_STENCIL_SIZE',
1280 'GL_RENDERBUFFER_WIDTH',
1281 'GL_RENDERBUFFER_HEIGHT',
1282 'GL_RENDERBUFFER_INTERNAL_FORMAT',
1284 'valid_es3': [
1285 'GL_RENDERBUFFER_SAMPLES',
1288 'InternalFormatParameter': {
1289 'type': 'GLenum',
1290 'valid': [
1291 'GL_NUM_SAMPLE_COUNTS',
1292 'GL_SAMPLES',
1295 'SamplerParameter': {
1296 'type': 'GLenum',
1297 'valid': [
1298 'GL_TEXTURE_MAG_FILTER',
1299 'GL_TEXTURE_MIN_FILTER',
1300 'GL_TEXTURE_MIN_LOD',
1301 'GL_TEXTURE_MAX_LOD',
1302 'GL_TEXTURE_WRAP_S',
1303 'GL_TEXTURE_WRAP_T',
1304 'GL_TEXTURE_WRAP_R',
1305 'GL_TEXTURE_COMPARE_MODE',
1306 'GL_TEXTURE_COMPARE_FUNC',
1308 'invalid': [
1309 'GL_GENERATE_MIPMAP',
1312 'ShaderParameter': {
1313 'type': 'GLenum',
1314 'valid': [
1315 'GL_SHADER_TYPE',
1316 'GL_DELETE_STATUS',
1317 'GL_COMPILE_STATUS',
1318 'GL_INFO_LOG_LENGTH',
1319 'GL_SHADER_SOURCE_LENGTH',
1320 'GL_TRANSLATED_SHADER_SOURCE_LENGTH_ANGLE',
1323 'ShaderPrecision': {
1324 'type': 'GLenum',
1325 'valid': [
1326 'GL_LOW_FLOAT',
1327 'GL_MEDIUM_FLOAT',
1328 'GL_HIGH_FLOAT',
1329 'GL_LOW_INT',
1330 'GL_MEDIUM_INT',
1331 'GL_HIGH_INT',
1334 'StringType': {
1335 'type': 'GLenum',
1336 'valid': [
1337 'GL_VENDOR',
1338 'GL_RENDERER',
1339 'GL_VERSION',
1340 'GL_SHADING_LANGUAGE_VERSION',
1341 'GL_EXTENSIONS',
1344 'TextureParameter': {
1345 'type': 'GLenum',
1346 'valid': [
1347 'GL_TEXTURE_MAG_FILTER',
1348 'GL_TEXTURE_MIN_FILTER',
1349 'GL_TEXTURE_POOL_CHROMIUM',
1350 'GL_TEXTURE_WRAP_S',
1351 'GL_TEXTURE_WRAP_T',
1353 'valid_es3': [
1354 'GL_TEXTURE_BASE_LEVEL',
1355 'GL_TEXTURE_COMPARE_FUNC',
1356 'GL_TEXTURE_COMPARE_MODE',
1357 'GL_TEXTURE_IMMUTABLE_FORMAT',
1358 'GL_TEXTURE_IMMUTABLE_LEVELS',
1359 'GL_TEXTURE_MAX_LEVEL',
1360 'GL_TEXTURE_MAX_LOD',
1361 'GL_TEXTURE_MIN_LOD',
1362 'GL_TEXTURE_WRAP_R',
1364 'invalid': [
1365 'GL_GENERATE_MIPMAP',
1368 'TexturePool': {
1369 'type': 'GLenum',
1370 'valid': [
1371 'GL_TEXTURE_POOL_MANAGED_CHROMIUM',
1372 'GL_TEXTURE_POOL_UNMANAGED_CHROMIUM',
1375 'TextureWrapMode': {
1376 'type': 'GLenum',
1377 'valid': [
1378 'GL_CLAMP_TO_EDGE',
1379 'GL_MIRRORED_REPEAT',
1380 'GL_REPEAT',
1383 'TextureMinFilterMode': {
1384 'type': 'GLenum',
1385 'valid': [
1386 'GL_NEAREST',
1387 'GL_LINEAR',
1388 'GL_NEAREST_MIPMAP_NEAREST',
1389 'GL_LINEAR_MIPMAP_NEAREST',
1390 'GL_NEAREST_MIPMAP_LINEAR',
1391 'GL_LINEAR_MIPMAP_LINEAR',
1394 'TextureMagFilterMode': {
1395 'type': 'GLenum',
1396 'valid': [
1397 'GL_NEAREST',
1398 'GL_LINEAR',
1401 'TextureCompareFunc': {
1402 'type': 'GLenum',
1403 'valid': [
1404 'GL_LEQUAL',
1405 'GL_GEQUAL',
1406 'GL_LESS',
1407 'GL_GREATER',
1408 'GL_EQUAL',
1409 'GL_NOTEQUAL',
1410 'GL_ALWAYS',
1411 'GL_NEVER',
1414 'TextureCompareMode': {
1415 'type': 'GLenum',
1416 'valid': [
1417 'GL_NONE',
1418 'GL_COMPARE_REF_TO_TEXTURE',
1421 'TextureUsage': {
1422 'type': 'GLenum',
1423 'valid': [
1424 'GL_NONE',
1425 'GL_FRAMEBUFFER_ATTACHMENT_ANGLE',
1428 'VertexAttribute': {
1429 'type': 'GLenum',
1430 'valid': [
1431 # some enum that the decoder actually passes through to GL needs
1432 # to be the first listed here since it's used in unit tests.
1433 'GL_VERTEX_ATTRIB_ARRAY_NORMALIZED',
1434 'GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING',
1435 'GL_VERTEX_ATTRIB_ARRAY_ENABLED',
1436 'GL_VERTEX_ATTRIB_ARRAY_SIZE',
1437 'GL_VERTEX_ATTRIB_ARRAY_STRIDE',
1438 'GL_VERTEX_ATTRIB_ARRAY_TYPE',
1439 'GL_CURRENT_VERTEX_ATTRIB',
1441 'valid_es3': [
1442 'GL_VERTEX_ATTRIB_ARRAY_INTEGER',
1443 'GL_VERTEX_ATTRIB_ARRAY_DIVISOR',
1446 'VertexPointer': {
1447 'type': 'GLenum',
1448 'valid': [
1449 'GL_VERTEX_ATTRIB_ARRAY_POINTER',
1452 'HintTarget': {
1453 'type': 'GLenum',
1454 'valid': [
1455 'GL_GENERATE_MIPMAP_HINT',
1457 'valid_es3': [
1458 'GL_FRAGMENT_SHADER_DERIVATIVE_HINT',
1460 'invalid': [
1461 'GL_PERSPECTIVE_CORRECTION_HINT',
1464 'HintMode': {
1465 'type': 'GLenum',
1466 'valid': [
1467 'GL_FASTEST',
1468 'GL_NICEST',
1469 'GL_DONT_CARE',
1472 'PixelStore': {
1473 'type': 'GLenum',
1474 'valid': [
1475 'GL_PACK_ALIGNMENT',
1476 'GL_UNPACK_ALIGNMENT',
1478 'valid_es3': [
1479 'GL_PACK_ROW_LENGTH',
1480 'GL_PACK_SKIP_PIXELS',
1481 'GL_PACK_SKIP_ROWS',
1482 'GL_UNPACK_ROW_LENGTH',
1483 'GL_UNPACK_IMAGE_HEIGHT',
1484 'GL_UNPACK_SKIP_PIXELS',
1485 'GL_UNPACK_SKIP_ROWS',
1486 'GL_UNPACK_SKIP_IMAGES',
1488 'invalid': [
1489 'GL_PACK_SWAP_BYTES',
1490 'GL_UNPACK_SWAP_BYTES',
1493 'PixelStoreAlignment': {
1494 'type': 'GLint',
1495 'valid': [
1496 '1',
1497 '2',
1498 '4',
1499 '8',
1501 'invalid': [
1502 '3',
1503 '9',
1506 'ReadPixelFormat': {
1507 'type': 'GLenum',
1508 'valid': [
1509 'GL_ALPHA',
1510 'GL_RGB',
1511 'GL_RGBA',
1513 'valid_es3': [
1514 'GL_RED',
1515 'GL_RED_INTEGER',
1516 'GL_RG',
1517 'GL_RG_INTEGER',
1518 'GL_RGB_INTEGER',
1519 'GL_RGBA_INTEGER',
1522 'PixelType': {
1523 'type': 'GLenum',
1524 'valid': [
1525 'GL_UNSIGNED_BYTE',
1526 'GL_UNSIGNED_SHORT_5_6_5',
1527 'GL_UNSIGNED_SHORT_4_4_4_4',
1528 'GL_UNSIGNED_SHORT_5_5_5_1',
1530 'valid_es3': [
1531 'GL_BYTE',
1532 'GL_UNSIGNED_SHORT',
1533 'GL_SHORT',
1534 'GL_UNSIGNED_INT',
1535 'GL_INT',
1536 'GL_HALF_FLOAT',
1537 'GL_FLOAT',
1538 'GL_UNSIGNED_INT_2_10_10_10_REV',
1539 'GL_UNSIGNED_INT_10F_11F_11F_REV',
1540 'GL_UNSIGNED_INT_5_9_9_9_REV',
1541 'GL_UNSIGNED_INT_24_8',
1542 'GL_FLOAT_32_UNSIGNED_INT_24_8_REV',
1544 'invalid': [
1545 'GL_UNSIGNED_BYTE_3_3_2',
1548 'PathCoordType': {
1549 'type': 'GLenum',
1550 'valid': [
1551 'GL_BYTE',
1552 'GL_UNSIGNED_BYTE',
1553 'GL_SHORT',
1554 'GL_UNSIGNED_SHORT',
1555 'GL_FLOAT',
1558 'PathCoverMode': {
1559 'type': 'GLenum',
1560 'valid': [
1561 'GL_CONVEX_HULL_CHROMIUM',
1562 'GL_BOUNDING_BOX_CHROMIUM',
1565 'PathFillMode': {
1566 'type': 'GLenum',
1567 'valid': [
1568 'GL_INVERT',
1569 'GL_COUNT_UP_CHROMIUM',
1570 'GL_COUNT_DOWN_CHROMIUM',
1573 'PathParameter': {
1574 'type': 'GLenum',
1575 'valid': [
1576 'GL_PATH_STROKE_WIDTH_CHROMIUM',
1577 'GL_PATH_END_CAPS_CHROMIUM',
1578 'GL_PATH_JOIN_STYLE_CHROMIUM',
1579 'GL_PATH_MITER_LIMIT_CHROMIUM',
1580 'GL_PATH_STROKE_BOUND_CHROMIUM',
1583 'PathParameterCapValues': {
1584 'type': 'GLint',
1585 'valid': [
1586 'GL_FLAT',
1587 'GL_SQUARE_CHROMIUM',
1588 'GL_ROUND_CHROMIUM',
1591 'PathParameterJoinValues': {
1592 'type': 'GLint',
1593 'valid': [
1594 'GL_MITER_REVERT_CHROMIUM',
1595 'GL_BEVEL_CHROMIUM',
1596 'GL_ROUND_CHROMIUM',
1599 'ReadPixelType': {
1600 'type': 'GLenum',
1601 'valid': [
1602 'GL_UNSIGNED_BYTE',
1603 'GL_UNSIGNED_SHORT_5_6_5',
1604 'GL_UNSIGNED_SHORT_4_4_4_4',
1605 'GL_UNSIGNED_SHORT_5_5_5_1',
1607 'valid_es3': [
1608 'GL_BYTE',
1609 'GL_UNSIGNED_SHORT',
1610 'GL_SHORT',
1611 'GL_UNSIGNED_INT',
1612 'GL_INT',
1613 'GL_HALF_FLOAT',
1614 'GL_FLOAT',
1615 'GL_UNSIGNED_INT_2_10_10_10_REV',
1618 'RenderBufferFormat': {
1619 'type': 'GLenum',
1620 'valid': [
1621 'GL_RGBA4',
1622 'GL_RGB565',
1623 'GL_RGB5_A1',
1624 'GL_DEPTH_COMPONENT16',
1625 'GL_STENCIL_INDEX8',
1627 'valid_es3': [
1628 'GL_R8',
1629 'GL_R8UI',
1630 'GL_R8I',
1631 'GL_R16UI',
1632 'GL_R16I',
1633 'GL_R32UI',
1634 'GL_R32I',
1635 'GL_RG8',
1636 'GL_RG8UI',
1637 'GL_RG8I',
1638 'GL_RG16UI',
1639 'GL_RG16I',
1640 'GL_RG32UI',
1641 'GL_RG32I',
1642 'GL_RGB8',
1643 'GL_RGBA8',
1644 'GL_SRGB8_ALPHA8',
1645 'GL_RGB10_A2',
1646 'GL_RGBA8UI',
1647 'GL_RGBA8I',
1648 'GL_RGB10_A2UI',
1649 'GL_RGBA16UI',
1650 'GL_RGBA16I',
1651 'GL_RGBA32UI',
1652 'GL_RGBA32I',
1653 'GL_DEPTH_COMPONENT24',
1654 'GL_DEPTH_COMPONENT32F',
1655 'GL_DEPTH24_STENCIL8',
1656 'GL_DEPTH32F_STENCIL8',
1659 'ShaderBinaryFormat': {
1660 'type': 'GLenum',
1661 'valid': [
1664 'StencilOp': {
1665 'type': 'GLenum',
1666 'valid': [
1667 'GL_KEEP',
1668 'GL_ZERO',
1669 'GL_REPLACE',
1670 'GL_INCR',
1671 'GL_INCR_WRAP',
1672 'GL_DECR',
1673 'GL_DECR_WRAP',
1674 'GL_INVERT',
1677 'TextureFormat': {
1678 'type': 'GLenum',
1679 'valid': [
1680 'GL_ALPHA',
1681 'GL_LUMINANCE',
1682 'GL_LUMINANCE_ALPHA',
1683 'GL_RGB',
1684 'GL_RGBA',
1686 'valid_es3': [
1687 'GL_RED',
1688 'GL_RED_INTEGER',
1689 'GL_RG',
1690 'GL_RG_INTEGER',
1691 'GL_RGB_INTEGER',
1692 'GL_RGBA_INTEGER',
1693 'GL_DEPTH_COMPONENT',
1694 'GL_DEPTH_STENCIL',
1696 'invalid': [
1697 'GL_BGRA',
1698 'GL_BGR',
1701 'TextureInternalFormat': {
1702 'type': 'GLenum',
1703 'valid': [
1704 'GL_ALPHA',
1705 'GL_LUMINANCE',
1706 'GL_LUMINANCE_ALPHA',
1707 'GL_RGB',
1708 'GL_RGBA',
1710 'valid_es3': [
1711 'GL_R8',
1712 'GL_R8_SNORM',
1713 'GL_R16F',
1714 'GL_R32F',
1715 'GL_R8UI',
1716 'GL_R8I',
1717 'GL_R16UI',
1718 'GL_R16I',
1719 'GL_R32UI',
1720 'GL_R32I',
1721 'GL_RG8',
1722 'GL_RG8_SNORM',
1723 'GL_RG16F',
1724 'GL_RG32F',
1725 'GL_RG8UI',
1726 'GL_RG8I',
1727 'GL_RG16UI',
1728 'GL_RG16I',
1729 'GL_RG32UI',
1730 'GL_RG32I',
1731 'GL_RGB8',
1732 'GL_SRGB8',
1733 'GL_RGB565',
1734 'GL_RGB8_SNORM',
1735 'GL_R11F_G11F_B10F',
1736 'GL_RGB9_E5',
1737 'GL_RGB16F',
1738 'GL_RGB32F',
1739 'GL_RGB8UI',
1740 'GL_RGB8I',
1741 'GL_RGB16UI',
1742 'GL_RGB16I',
1743 'GL_RGB32UI',
1744 'GL_RGB32I',
1745 'GL_RGBA8',
1746 'GL_SRGB8_ALPHA8',
1747 'GL_RGBA8_SNORM',
1748 'GL_RGB5_A1',
1749 'GL_RGBA4',
1750 'GL_RGB10_A2',
1751 'GL_RGBA16F',
1752 'GL_RGBA32F',
1753 'GL_RGBA8UI',
1754 'GL_RGBA8I',
1755 'GL_RGB10_A2UI',
1756 'GL_RGBA16UI',
1757 'GL_RGBA16I',
1758 'GL_RGBA32UI',
1759 'GL_RGBA32I',
1760 # The DEPTH/STENCIL formats are not supported in CopyTexImage2D.
1761 # We will reject them dynamically in GPU command buffer.
1762 'GL_DEPTH_COMPONENT16',
1763 'GL_DEPTH_COMPONENT24',
1764 'GL_DEPTH_COMPONENT32F',
1765 'GL_DEPTH24_STENCIL8',
1766 'GL_DEPTH32F_STENCIL8',
1768 'invalid': [
1769 'GL_BGRA',
1770 'GL_BGR',
1773 'TextureInternalFormatStorage': {
1774 'type': 'GLenum',
1775 'valid': [
1776 'GL_RGB565',
1777 'GL_RGBA4',
1778 'GL_RGB5_A1',
1779 'GL_ALPHA8_EXT',
1780 'GL_LUMINANCE8_EXT',
1781 'GL_LUMINANCE8_ALPHA8_EXT',
1782 'GL_RGB8_OES',
1783 'GL_RGBA8_OES',
1785 'valid_es3': [
1786 'GL_R8',
1787 'GL_R8_SNORM',
1788 'GL_R16F',
1789 'GL_R32F',
1790 'GL_R8UI',
1791 'GL_R8I',
1792 'GL_R16UI',
1793 'GL_R16I',
1794 'GL_R32UI',
1795 'GL_R32I',
1796 'GL_RG8',
1797 'GL_RG8_SNORM',
1798 'GL_RG16F',
1799 'GL_RG32F',
1800 'GL_RG8UI',
1801 'GL_RG8I',
1802 'GL_RG16UI',
1803 'GL_RG16I',
1804 'GL_RG32UI',
1805 'GL_RG32I',
1806 'GL_RGB8',
1807 'GL_SRGB8',
1808 'GL_RGB8_SNORM',
1809 'GL_R11F_G11F_B10F',
1810 'GL_RGB9_E5',
1811 'GL_RGB16F',
1812 'GL_RGB32F',
1813 'GL_RGB8UI',
1814 'GL_RGB8I',
1815 'GL_RGB16UI',
1816 'GL_RGB16I',
1817 'GL_RGB32UI',
1818 'GL_RGB32I',
1819 'GL_RGBA8',
1820 'GL_SRGB8_ALPHA8',
1821 'GL_RGBA8_SNORM',
1822 'GL_RGB10_A2',
1823 'GL_RGBA16F',
1824 'GL_RGBA32F',
1825 'GL_RGBA8UI',
1826 'GL_RGBA8I',
1827 'GL_RGB10_A2UI',
1828 'GL_RGBA16UI',
1829 'GL_RGBA16I',
1830 'GL_RGBA32UI',
1831 'GL_RGBA32I',
1832 'GL_DEPTH_COMPONENT16',
1833 'GL_DEPTH_COMPONENT24',
1834 'GL_DEPTH_COMPONENT32F',
1835 'GL_DEPTH24_STENCIL8',
1836 'GL_DEPTH32F_STENCIL8',
1837 'GL_COMPRESSED_R11_EAC',
1838 'GL_COMPRESSED_SIGNED_R11_EAC',
1839 'GL_COMPRESSED_RG11_EAC',
1840 'GL_COMPRESSED_SIGNED_RG11_EAC',
1841 'GL_COMPRESSED_RGB8_ETC2',
1842 'GL_COMPRESSED_SRGB8_ETC2',
1843 'GL_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2',
1844 'GL_COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2',
1845 'GL_COMPRESSED_RGBA8_ETC2_EAC',
1846 'GL_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC',
1848 'deprecated_es3': [
1849 'GL_ALPHA8_EXT',
1850 'GL_LUMINANCE8_EXT',
1851 'GL_LUMINANCE8_ALPHA8_EXT',
1852 'GL_ALPHA16F_EXT',
1853 'GL_LUMINANCE16F_EXT',
1854 'GL_LUMINANCE_ALPHA16F_EXT',
1855 'GL_ALPHA32F_EXT',
1856 'GL_LUMINANCE32F_EXT',
1857 'GL_LUMINANCE_ALPHA32F_EXT',
1860 'ImageInternalFormat': {
1861 'type': 'GLenum',
1862 'valid': [
1863 'GL_RGB',
1864 'GL_RGB_YUV_420_CHROMIUM',
1865 'GL_RGB_YCBCR_422_CHROMIUM',
1866 'GL_RGBA',
1869 'ImageUsage': {
1870 'type': 'GLenum',
1871 'valid': [
1872 'GL_MAP_CHROMIUM',
1873 'GL_SCANOUT_CHROMIUM'
1876 'ValueBufferTarget': {
1877 'type': 'GLenum',
1878 'valid': [
1879 'GL_SUBSCRIBED_VALUES_BUFFER_CHROMIUM',
1882 'SubscriptionTarget': {
1883 'type': 'GLenum',
1884 'valid': [
1885 'GL_MOUSE_POSITION_CHROMIUM',
1888 'UniformParameter': {
1889 'type': 'GLenum',
1890 'valid': [
1891 'GL_UNIFORM_SIZE',
1892 'GL_UNIFORM_TYPE',
1893 'GL_UNIFORM_NAME_LENGTH',
1894 'GL_UNIFORM_BLOCK_INDEX',
1895 'GL_UNIFORM_OFFSET',
1896 'GL_UNIFORM_ARRAY_STRIDE',
1897 'GL_UNIFORM_MATRIX_STRIDE',
1898 'GL_UNIFORM_IS_ROW_MAJOR',
1900 'invalid': [
1901 'GL_UNIFORM_BLOCK_NAME_LENGTH',
1904 'UniformBlockParameter': {
1905 'type': 'GLenum',
1906 'valid': [
1907 'GL_UNIFORM_BLOCK_BINDING',
1908 'GL_UNIFORM_BLOCK_DATA_SIZE',
1909 'GL_UNIFORM_BLOCK_NAME_LENGTH',
1910 'GL_UNIFORM_BLOCK_ACTIVE_UNIFORMS',
1911 'GL_UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES',
1912 'GL_UNIFORM_BLOCK_REFERENCED_BY_VERTEX_SHADER',
1913 'GL_UNIFORM_BLOCK_REFERENCED_BY_FRAGMENT_SHADER',
1915 'invalid': [
1916 'GL_NEAREST',
1919 'VertexAttribType': {
1920 'type': 'GLenum',
1921 'valid': [
1922 'GL_BYTE',
1923 'GL_UNSIGNED_BYTE',
1924 'GL_SHORT',
1925 'GL_UNSIGNED_SHORT',
1926 # 'GL_FIXED', // This is not available on Desktop GL.
1927 'GL_FLOAT',
1929 'valid_es3': [
1930 'GL_INT',
1931 'GL_UNSIGNED_INT',
1932 'GL_HALF_FLOAT',
1933 'GL_INT_2_10_10_10_REV',
1934 'GL_UNSIGNED_INT_2_10_10_10_REV',
1936 'invalid': [
1937 'GL_DOUBLE',
1940 'VertexAttribIType': {
1941 'type': 'GLenum',
1942 'valid': [
1943 'GL_BYTE',
1944 'GL_UNSIGNED_BYTE',
1945 'GL_SHORT',
1946 'GL_UNSIGNED_SHORT',
1947 'GL_INT',
1948 'GL_UNSIGNED_INT',
1950 'invalid': [
1951 'GL_FLOAT',
1952 'GL_DOUBLE',
1955 'TextureBorder': {
1956 'type': 'GLint',
1957 'is_complete': True,
1958 'valid': [
1959 '0',
1961 'invalid': [
1962 '1',
1965 'VertexAttribSize': {
1966 'type': 'GLint',
1967 'valid': [
1968 '1',
1969 '2',
1970 '3',
1971 '4',
1973 'invalid': [
1974 '0',
1975 '5',
1978 'ZeroOnly': {
1979 'type': 'GLint',
1980 'is_complete': True,
1981 'valid': [
1982 '0',
1984 'invalid': [
1985 '1',
1988 'FalseOnly': {
1989 'type': 'GLboolean',
1990 'is_complete': True,
1991 'valid': [
1992 'false',
1994 'invalid': [
1995 'true',
1998 'ResetStatus': {
1999 'type': 'GLenum',
2000 'valid': [
2001 'GL_GUILTY_CONTEXT_RESET_ARB',
2002 'GL_INNOCENT_CONTEXT_RESET_ARB',
2003 'GL_UNKNOWN_CONTEXT_RESET_ARB',
2006 'SyncCondition': {
2007 'type': 'GLenum',
2008 'is_complete': True,
2009 'valid': [
2010 'GL_SYNC_GPU_COMMANDS_COMPLETE',
2012 'invalid': [
2013 '0',
2016 'SyncFlags': {
2017 'type': 'GLbitfield',
2018 'is_complete': True,
2019 'valid': [
2020 '0',
2022 'invalid': [
2023 '1',
2026 'SyncFlushFlags': {
2027 'type': 'GLbitfield',
2028 'valid': [
2029 'GL_SYNC_FLUSH_COMMANDS_BIT',
2030 '0',
2032 'invalid': [
2033 '0xFFFFFFFF',
2036 'SyncParameter': {
2037 'type': 'GLenum',
2038 'valid': [
2039 'GL_SYNC_STATUS', # This needs to be the 1st; all others are cached.
2040 'GL_OBJECT_TYPE',
2041 'GL_SYNC_CONDITION',
2042 'GL_SYNC_FLAGS',
2044 'invalid': [
2045 'GL_SYNC_FENCE',
2050 # This table specifies the different pepper interfaces that are supported for
2051 # GL commands. 'dev' is true if it's a dev interface.
2052 _PEPPER_INTERFACES = [
2053 {'name': '', 'dev': False},
2054 {'name': 'InstancedArrays', 'dev': False},
2055 {'name': 'FramebufferBlit', 'dev': False},
2056 {'name': 'FramebufferMultisample', 'dev': False},
2057 {'name': 'ChromiumEnableFeature', 'dev': False},
2058 {'name': 'ChromiumMapSub', 'dev': False},
2059 {'name': 'Query', 'dev': False},
2060 {'name': 'VertexArrayObject', 'dev': False},
2061 {'name': 'DrawBuffers', 'dev': True},
2064 # A function info object specifies the type and other special data for the
2065 # command that will be generated. A base function info object is generated by
2066 # parsing the "cmd_buffer_functions.txt", one for each function in the
2067 # file. These function info objects can be augmented and their values can be
2068 # overridden by adding an object to the table below.
2070 # Must match function names specified in "cmd_buffer_functions.txt".
2072 # cmd_comment: A comment added to the cmd format.
2073 # type: defines which handler will be used to generate code.
2074 # decoder_func: defines which function to call in the decoder to execute the
2075 # corresponding GL command. If not specified the GL command will
2076 # be called directly.
2077 # gl_test_func: GL function that is expected to be called when testing.
2078 # cmd_args: The arguments to use for the command. This overrides generating
2079 # them based on the GL function arguments.
2080 # gen_cmd: Whether or not this function geneates a command. Default = True.
2081 # data_transfer_methods: Array of methods that are used for transfering the
2082 # pointer data. Possible values: 'immediate', 'shm', 'bucket'.
2083 # The default is 'immediate' if the command has one pointer
2084 # argument, otherwise 'shm'. One command is generated for each
2085 # transfer method. Affects only commands which are not of type
2086 # 'HandWritten', 'GETn' or 'GLcharN'.
2087 # Note: the command arguments that affect this are the final args,
2088 # taking cmd_args override into consideration.
2089 # impl_func: Whether or not to generate the GLES2Implementation part of this
2090 # command.
2091 # impl_decl: Whether or not to generate the GLES2Implementation declaration
2092 # for this command.
2093 # needs_size: If True a data_size field is added to the command.
2094 # count: The number of units per element. For PUTn or PUT types.
2095 # use_count_func: If True the actual data count needs to be computed; the count
2096 # argument specifies the maximum count.
2097 # unit_test: If False no service side unit test will be generated.
2098 # client_test: If False no client side unit test will be generated.
2099 # expectation: If False the unit test will have no expected calls.
2100 # gen_func: Name of function that generates GL resource for corresponding
2101 # bind function.
2102 # states: array of states that get set by this function corresponding to
2103 # the given arguments
2104 # state_flag: name of flag that is set to true when function is called.
2105 # no_gl: no GL function is called.
2106 # valid_args: A dictionary of argument indices to args to use in unit tests
2107 # when they can not be automatically determined.
2108 # pepper_interface: The pepper interface that is used for this extension
2109 # pepper_name: The name of the function as exposed to pepper.
2110 # pepper_args: A string representing the argument list (what would appear in
2111 # C/C++ between the parentheses for the function declaration)
2112 # that the Pepper API expects for this function. Use this only if
2113 # the stable Pepper API differs from the GLES2 argument list.
2114 # invalid_test: False if no invalid test needed.
2115 # shadowed: True = the value is shadowed so no glGetXXX call will be made.
2116 # first_element_only: For PUT types, True if only the first element of an
2117 # array is used and we end up calling the single value
2118 # corresponding function. eg. TexParameteriv -> TexParameteri
2119 # extension: Function is an extension to GL and should not be exposed to
2120 # pepper unless pepper_interface is defined.
2121 # extension_flag: Function is an extension and should be enabled only when
2122 # the corresponding feature info flag is enabled. Implies
2123 # 'extension': True.
2124 # not_shared: For GENn types, True if objects can't be shared between contexts
2125 # unsafe: True = no validation is implemented on the service side and the
2126 # command is only available with --enable-unsafe-es3-apis.
2127 # id_mapping: A list of resource type names whose client side IDs need to be
2128 # mapped to service side IDs. This is only used for unsafe APIs.
2130 _FUNCTION_INFO = {
2131 'ActiveTexture': {
2132 'decoder_func': 'DoActiveTexture',
2133 'unit_test': False,
2134 'impl_func': False,
2135 'client_test': False,
2137 'ApplyScreenSpaceAntialiasingCHROMIUM': {
2138 'decoder_func': 'DoApplyScreenSpaceAntialiasingCHROMIUM',
2139 'extension_flag': 'chromium_screen_space_antialiasing',
2140 'unit_test': False,
2141 'client_test': False,
2143 'AttachShader': {'decoder_func': 'DoAttachShader'},
2144 'BindAttribLocation': {
2145 'type': 'GLchar',
2146 'data_transfer_methods': ['bucket'],
2147 'needs_size': True,
2149 'BindBuffer': {
2150 'type': 'Bind',
2151 'decoder_func': 'DoBindBuffer',
2152 'gen_func': 'GenBuffersARB',
2154 'BindBufferBase': {
2155 'type': 'Bind',
2156 'decoder_func': 'DoBindBufferBase',
2157 'gen_func': 'GenBuffersARB',
2158 'unsafe': True,
2160 'BindBufferRange': {
2161 'type': 'Bind',
2162 'decoder_func': 'DoBindBufferRange',
2163 'gen_func': 'GenBuffersARB',
2164 'valid_args': {
2165 '3': '4',
2166 '4': '4'
2168 'unsafe': True,
2170 'BindFramebuffer': {
2171 'type': 'Bind',
2172 'decoder_func': 'DoBindFramebuffer',
2173 'gl_test_func': 'glBindFramebufferEXT',
2174 'gen_func': 'GenFramebuffersEXT',
2175 'trace_level': 1,
2177 'BindRenderbuffer': {
2178 'type': 'Bind',
2179 'decoder_func': 'DoBindRenderbuffer',
2180 'gl_test_func': 'glBindRenderbufferEXT',
2181 'gen_func': 'GenRenderbuffersEXT',
2183 'BindSampler': {
2184 'type': 'Bind',
2185 'id_mapping': [ 'Sampler' ],
2186 'unsafe': True,
2188 'BindTexture': {
2189 'type': 'Bind',
2190 'decoder_func': 'DoBindTexture',
2191 'gen_func': 'GenTextures',
2192 # TODO(gman): remove this once client side caching works.
2193 'client_test': False,
2194 'trace_level': 2,
2196 'BindTransformFeedback': {
2197 'type': 'Bind',
2198 'id_mapping': [ 'TransformFeedback' ],
2199 'unsafe': True,
2201 'BlitFramebufferCHROMIUM': {
2202 'decoder_func': 'DoBlitFramebufferCHROMIUM',
2203 'unit_test': False,
2204 'extension': 'chromium_framebuffer_multisample',
2205 'extension_flag': 'chromium_framebuffer_multisample',
2206 'pepper_interface': 'FramebufferBlit',
2207 'pepper_name': 'BlitFramebufferEXT',
2208 'defer_reads': True,
2209 'defer_draws': True,
2210 'trace_level': 1,
2212 'BufferData': {
2213 'type': 'Manual',
2214 'data_transfer_methods': ['shm'],
2215 'client_test': False,
2216 'trace_level': 2,
2218 'BufferSubData': {
2219 'type': 'Data',
2220 'client_test': False,
2221 'decoder_func': 'DoBufferSubData',
2222 'data_transfer_methods': ['shm'],
2223 'trace_level': 2,
2225 'CheckFramebufferStatus': {
2226 'type': 'Is',
2227 'decoder_func': 'DoCheckFramebufferStatus',
2228 'gl_test_func': 'glCheckFramebufferStatusEXT',
2229 'error_value': 'GL_FRAMEBUFFER_UNSUPPORTED',
2230 'result': ['GLenum'],
2232 'Clear': {
2233 'decoder_func': 'DoClear',
2234 'defer_draws': True,
2235 'trace_level': 2,
2237 'ClearBufferiv': {
2238 'type': 'PUT',
2239 'use_count_func': True,
2240 'count': 4,
2241 'decoder_func': 'DoClearBufferiv',
2242 'unit_test': False,
2243 'unsafe': True,
2244 'trace_level': 2,
2246 'ClearBufferuiv': {
2247 'type': 'PUT',
2248 'count': 4,
2249 'decoder_func': 'DoClearBufferuiv',
2250 'unit_test': False,
2251 'unsafe': True,
2252 'trace_level': 2,
2254 'ClearBufferfv': {
2255 'type': 'PUT',
2256 'use_count_func': True,
2257 'count': 4,
2258 'decoder_func': 'DoClearBufferfv',
2259 'unit_test': False,
2260 'unsafe': True,
2261 'trace_level': 2,
2263 'ClearBufferfi': {
2264 'unsafe': True,
2265 'decoder_func': 'DoClearBufferfi',
2266 'unit_test': False,
2267 'trace_level': 2,
2269 'ClearColor': {
2270 'type': 'StateSet',
2271 'state': 'ClearColor',
2273 'ClearDepthf': {
2274 'type': 'StateSet',
2275 'state': 'ClearDepthf',
2276 'decoder_func': 'glClearDepth',
2277 'gl_test_func': 'glClearDepth',
2278 'valid_args': {
2279 '0': '0.5f'
2282 'ClientWaitSync': {
2283 'type': 'Custom',
2284 'data_transfer_methods': ['shm'],
2285 'cmd_args': 'GLuint sync, GLbitfieldSyncFlushFlags flags, '
2286 'GLuint timeout_0, GLuint timeout_1, GLenum* result',
2287 'unsafe': True,
2288 'result': ['GLenum'],
2289 'trace_level': 2,
2291 'ColorMask': {
2292 'type': 'StateSet',
2293 'state': 'ColorMask',
2294 'no_gl': True,
2295 'expectation': False,
2297 'ConsumeTextureCHROMIUM': {
2298 'decoder_func': 'DoConsumeTextureCHROMIUM',
2299 'impl_func': False,
2300 'type': 'PUT',
2301 'count': 64, # GL_MAILBOX_SIZE_CHROMIUM
2302 'unit_test': False,
2303 'client_test': False,
2304 'extension': "CHROMIUM_texture_mailbox",
2305 'chromium': True,
2306 'trace_level': 2,
2308 'CopyBufferSubData': {
2309 'unsafe': True,
2311 'CreateAndConsumeTextureCHROMIUM': {
2312 'decoder_func': 'DoCreateAndConsumeTextureCHROMIUM',
2313 'impl_func': False,
2314 'type': 'HandWritten',
2315 'data_transfer_methods': ['immediate'],
2316 'unit_test': False,
2317 'client_test': False,
2318 'extension': "CHROMIUM_texture_mailbox",
2319 'chromium': True,
2320 'trace_level': 2,
2322 'GenValuebuffersCHROMIUM': {
2323 'type': 'GENn',
2324 'gl_test_func': 'glGenValuebuffersCHROMIUM',
2325 'resource_type': 'Valuebuffer',
2326 'resource_types': 'Valuebuffers',
2327 'unit_test': False,
2328 'extension': True,
2329 'chromium': True,
2331 'DeleteValuebuffersCHROMIUM': {
2332 'type': 'DELn',
2333 'gl_test_func': 'glDeleteValuebuffersCHROMIUM',
2334 'resource_type': 'Valuebuffer',
2335 'resource_types': 'Valuebuffers',
2336 'unit_test': False,
2337 'extension': True,
2338 'chromium': True,
2340 'IsValuebufferCHROMIUM': {
2341 'type': 'Is',
2342 'decoder_func': 'DoIsValuebufferCHROMIUM',
2343 'expectation': False,
2344 'extension': True,
2345 'chromium': True,
2347 'BindValuebufferCHROMIUM': {
2348 'type': 'Bind',
2349 'decoder_func': 'DoBindValueBufferCHROMIUM',
2350 'gen_func': 'GenValueBuffersCHROMIUM',
2351 'unit_test': False,
2352 'extension': True,
2353 'chromium': True,
2355 'SubscribeValueCHROMIUM': {
2356 'decoder_func': 'DoSubscribeValueCHROMIUM',
2357 'unit_test': False,
2358 'extension': True,
2359 'chromium': True,
2361 'PopulateSubscribedValuesCHROMIUM': {
2362 'decoder_func': 'DoPopulateSubscribedValuesCHROMIUM',
2363 'unit_test': False,
2364 'extension': True,
2365 'chromium': True,
2367 'UniformValuebufferCHROMIUM': {
2368 'decoder_func': 'DoUniformValueBufferCHROMIUM',
2369 'unit_test': False,
2370 'extension': True,
2371 'chromium': True,
2373 'ClearStencil': {
2374 'type': 'StateSet',
2375 'state': 'ClearStencil',
2377 'EnableFeatureCHROMIUM': {
2378 'type': 'Custom',
2379 'data_transfer_methods': ['shm'],
2380 'decoder_func': 'DoEnableFeatureCHROMIUM',
2381 'expectation': False,
2382 'cmd_args': 'GLuint bucket_id, GLint* result',
2383 'result': ['GLint'],
2384 'extension': True,
2385 'chromium': True,
2386 'pepper_interface': 'ChromiumEnableFeature',
2388 'CompileShader': {'decoder_func': 'DoCompileShader', 'unit_test': False},
2389 'CompressedTexImage2D': {
2390 'type': 'Manual',
2391 'data_transfer_methods': ['bucket', 'shm'],
2392 'trace_level': 1,
2394 'CompressedTexSubImage2D': {
2395 'type': 'Data',
2396 'data_transfer_methods': ['bucket', 'shm'],
2397 'decoder_func': 'DoCompressedTexSubImage2D',
2398 'trace_level': 1,
2400 'CopyTexImage2D': {
2401 'decoder_func': 'DoCopyTexImage2D',
2402 'unit_test': False,
2403 'defer_reads': True,
2404 'trace_level': 1,
2406 'CopyTexSubImage2D': {
2407 'decoder_func': 'DoCopyTexSubImage2D',
2408 'defer_reads': True,
2409 'trace_level': 1,
2411 'CompressedTexImage3D': {
2412 'type': 'Manual',
2413 'data_transfer_methods': ['bucket', 'shm'],
2414 'unsafe': True,
2415 'trace_level': 1,
2417 'CompressedTexSubImage3D': {
2418 'type': 'Data',
2419 'data_transfer_methods': ['bucket', 'shm'],
2420 'decoder_func': 'DoCompressedTexSubImage3D',
2421 'unsafe': True,
2422 'trace_level': 1,
2424 'CopyTexSubImage3D': {
2425 'defer_reads': True,
2426 'unsafe': True,
2427 'trace_level': 1,
2429 'CreateImageCHROMIUM': {
2430 'type': 'Manual',
2431 'cmd_args':
2432 'ClientBuffer buffer, GLsizei width, GLsizei height, '
2433 'GLenum internalformat',
2434 'result': ['GLuint'],
2435 'client_test': False,
2436 'gen_cmd': False,
2437 'expectation': False,
2438 'extension': "CHROMIUM_image",
2439 'chromium': True,
2440 'trace_level': 1,
2442 'DestroyImageCHROMIUM': {
2443 'type': 'Manual',
2444 'client_test': False,
2445 'gen_cmd': False,
2446 'extension': "CHROMIUM_image",
2447 'chromium': True,
2448 'trace_level': 1,
2450 'CreateGpuMemoryBufferImageCHROMIUM': {
2451 'type': 'Manual',
2452 'cmd_args':
2453 'GLsizei width, GLsizei height, GLenum internalformat, GLenum usage',
2454 'result': ['GLuint'],
2455 'client_test': False,
2456 'gen_cmd': False,
2457 'expectation': False,
2458 'extension': "CHROMIUM_image",
2459 'chromium': True,
2460 'trace_level': 1,
2462 'CreateProgram': {
2463 'type': 'Create',
2464 'client_test': False,
2466 'CreateShader': {
2467 'type': 'Create',
2468 'client_test': False,
2470 'BlendColor': {
2471 'type': 'StateSet',
2472 'state': 'BlendColor',
2474 'BlendEquation': {
2475 'type': 'StateSetRGBAlpha',
2476 'state': 'BlendEquation',
2477 'valid_args': {
2478 '0': 'GL_FUNC_SUBTRACT'
2481 'BlendEquationSeparate': {
2482 'type': 'StateSet',
2483 'state': 'BlendEquation',
2484 'valid_args': {
2485 '0': 'GL_FUNC_SUBTRACT'
2488 'BlendFunc': {
2489 'type': 'StateSetRGBAlpha',
2490 'state': 'BlendFunc',
2492 'BlendFuncSeparate': {
2493 'type': 'StateSet',
2494 'state': 'BlendFunc',
2496 'BlendBarrierKHR': {
2497 'gl_test_func': 'glBlendBarrierKHR',
2498 'extension': True,
2499 'extension_flag': 'blend_equation_advanced',
2500 'client_test': False,
2502 'SampleCoverage': {'decoder_func': 'DoSampleCoverage'},
2503 'StencilFunc': {
2504 'type': 'StateSetFrontBack',
2505 'state': 'StencilFunc',
2507 'StencilFuncSeparate': {
2508 'type': 'StateSetFrontBackSeparate',
2509 'state': 'StencilFunc',
2511 'StencilOp': {
2512 'type': 'StateSetFrontBack',
2513 'state': 'StencilOp',
2514 'valid_args': {
2515 '1': 'GL_INCR'
2518 'StencilOpSeparate': {
2519 'type': 'StateSetFrontBackSeparate',
2520 'state': 'StencilOp',
2521 'valid_args': {
2522 '1': 'GL_INCR'
2525 'Hint': {
2526 'type': 'StateSetNamedParameter',
2527 'state': 'Hint',
2529 'CullFace': {'type': 'StateSet', 'state': 'CullFace'},
2530 'FrontFace': {'type': 'StateSet', 'state': 'FrontFace'},
2531 'DepthFunc': {'type': 'StateSet', 'state': 'DepthFunc'},
2532 'LineWidth': {
2533 'type': 'StateSet',
2534 'state': 'LineWidth',
2535 'valid_args': {
2536 '0': '0.5f'
2539 'PolygonOffset': {
2540 'type': 'StateSet',
2541 'state': 'PolygonOffset',
2543 'DeleteBuffers': {
2544 'type': 'DELn',
2545 'gl_test_func': 'glDeleteBuffersARB',
2546 'resource_type': 'Buffer',
2547 'resource_types': 'Buffers',
2549 'DeleteFramebuffers': {
2550 'type': 'DELn',
2551 'gl_test_func': 'glDeleteFramebuffersEXT',
2552 'resource_type': 'Framebuffer',
2553 'resource_types': 'Framebuffers',
2554 'trace_level': 2,
2556 'DeleteProgram': { 'type': 'Delete' },
2557 'DeleteRenderbuffers': {
2558 'type': 'DELn',
2559 'gl_test_func': 'glDeleteRenderbuffersEXT',
2560 'resource_type': 'Renderbuffer',
2561 'resource_types': 'Renderbuffers',
2562 'trace_level': 2,
2564 'DeleteSamplers': {
2565 'type': 'DELn',
2566 'resource_type': 'Sampler',
2567 'resource_types': 'Samplers',
2568 'unsafe': True,
2570 'DeleteShader': { 'type': 'Delete' },
2571 'DeleteSync': {
2572 'type': 'Delete',
2573 'cmd_args': 'GLuint sync',
2574 'resource_type': 'Sync',
2575 'unsafe': True,
2577 'DeleteTextures': {
2578 'type': 'DELn',
2579 'resource_type': 'Texture',
2580 'resource_types': 'Textures',
2582 'DeleteTransformFeedbacks': {
2583 'type': 'DELn',
2584 'resource_type': 'TransformFeedback',
2585 'resource_types': 'TransformFeedbacks',
2586 'unsafe': True,
2588 'DepthRangef': {
2589 'decoder_func': 'DoDepthRangef',
2590 'gl_test_func': 'glDepthRange',
2592 'DepthMask': {
2593 'type': 'StateSet',
2594 'state': 'DepthMask',
2595 'no_gl': True,
2596 'expectation': False,
2598 'DetachShader': {'decoder_func': 'DoDetachShader'},
2599 'Disable': {
2600 'decoder_func': 'DoDisable',
2601 'impl_func': False,
2602 'client_test': False,
2604 'DisableVertexAttribArray': {
2605 'decoder_func': 'DoDisableVertexAttribArray',
2606 'impl_decl': False,
2608 'DrawArrays': {
2609 'type': 'Manual',
2610 'cmd_args': 'GLenumDrawMode mode, GLint first, GLsizei count',
2611 'defer_draws': True,
2612 'trace_level': 2,
2614 'DrawElements': {
2615 'type': 'Manual',
2616 'cmd_args': 'GLenumDrawMode mode, GLsizei count, '
2617 'GLenumIndexType type, GLuint index_offset',
2618 'client_test': False,
2619 'defer_draws': True,
2620 'trace_level': 2,
2622 'DrawRangeElements': {
2623 'type': 'Manual',
2624 'gen_cmd': 'False',
2625 'unsafe': True,
2627 'Enable': {
2628 'decoder_func': 'DoEnable',
2629 'impl_func': False,
2630 'client_test': False,
2632 'EnableVertexAttribArray': {
2633 'decoder_func': 'DoEnableVertexAttribArray',
2634 'impl_decl': False,
2636 'FenceSync': {
2637 'type': 'Create',
2638 'client_test': False,
2639 'unsafe': True,
2640 'trace_level': 1,
2642 'Finish': {
2643 'impl_func': False,
2644 'client_test': False,
2645 'decoder_func': 'DoFinish',
2646 'defer_reads': True,
2647 'trace_level': 1,
2649 'Flush': {
2650 'impl_func': False,
2651 'decoder_func': 'DoFlush',
2652 'trace_level': 1,
2654 'FramebufferRenderbuffer': {
2655 'decoder_func': 'DoFramebufferRenderbuffer',
2656 'gl_test_func': 'glFramebufferRenderbufferEXT',
2657 'trace_level': 1,
2659 'FramebufferTexture2D': {
2660 'decoder_func': 'DoFramebufferTexture2D',
2661 'gl_test_func': 'glFramebufferTexture2DEXT',
2662 'trace_level': 1,
2664 'FramebufferTexture2DMultisampleEXT': {
2665 'decoder_func': 'DoFramebufferTexture2DMultisample',
2666 'gl_test_func': 'glFramebufferTexture2DMultisampleEXT',
2667 'expectation': False,
2668 'unit_test': False,
2669 'extension_flag': 'multisampled_render_to_texture',
2670 'trace_level': 1,
2672 'FramebufferTextureLayer': {
2673 'decoder_func': 'DoFramebufferTextureLayer',
2674 'unsafe': True,
2675 'trace_level': 1,
2677 'GenerateMipmap': {
2678 'decoder_func': 'DoGenerateMipmap',
2679 'gl_test_func': 'glGenerateMipmapEXT',
2680 'trace_level': 1,
2682 'GenBuffers': {
2683 'type': 'GENn',
2684 'gl_test_func': 'glGenBuffersARB',
2685 'resource_type': 'Buffer',
2686 'resource_types': 'Buffers',
2688 'GenMailboxCHROMIUM': {
2689 'type': 'HandWritten',
2690 'impl_func': False,
2691 'extension': "CHROMIUM_texture_mailbox",
2692 'chromium': True,
2694 'GenFramebuffers': {
2695 'type': 'GENn',
2696 'gl_test_func': 'glGenFramebuffersEXT',
2697 'resource_type': 'Framebuffer',
2698 'resource_types': 'Framebuffers',
2700 'GenRenderbuffers': {
2701 'type': 'GENn', 'gl_test_func': 'glGenRenderbuffersEXT',
2702 'resource_type': 'Renderbuffer',
2703 'resource_types': 'Renderbuffers',
2705 'GenSamplers': {
2706 'type': 'GENn',
2707 'gl_test_func': 'glGenSamplers',
2708 'resource_type': 'Sampler',
2709 'resource_types': 'Samplers',
2710 'unsafe': True,
2712 'GenTextures': {
2713 'type': 'GENn',
2714 'gl_test_func': 'glGenTextures',
2715 'resource_type': 'Texture',
2716 'resource_types': 'Textures',
2718 'GenTransformFeedbacks': {
2719 'type': 'GENn',
2720 'gl_test_func': 'glGenTransformFeedbacks',
2721 'resource_type': 'TransformFeedback',
2722 'resource_types': 'TransformFeedbacks',
2723 'unsafe': True,
2725 'GetActiveAttrib': {
2726 'type': 'Custom',
2727 'data_transfer_methods': ['shm'],
2728 'cmd_args':
2729 'GLidProgram program, GLuint index, uint32_t name_bucket_id, '
2730 'void* result',
2731 'result': [
2732 'int32_t success',
2733 'int32_t size',
2734 'uint32_t type',
2737 'GetActiveUniform': {
2738 'type': 'Custom',
2739 'data_transfer_methods': ['shm'],
2740 'cmd_args':
2741 'GLidProgram program, GLuint index, uint32_t name_bucket_id, '
2742 'void* result',
2743 'result': [
2744 'int32_t success',
2745 'int32_t size',
2746 'uint32_t type',
2749 'GetActiveUniformBlockiv': {
2750 'type': 'Custom',
2751 'data_transfer_methods': ['shm'],
2752 'result': ['SizedResult<GLint>'],
2753 'unsafe': True,
2755 'GetActiveUniformBlockName': {
2756 'type': 'Custom',
2757 'data_transfer_methods': ['shm'],
2758 'cmd_args':
2759 'GLidProgram program, GLuint index, uint32_t name_bucket_id, '
2760 'void* result',
2761 'result': ['int32_t'],
2762 'unsafe': True,
2764 'GetActiveUniformsiv': {
2765 'type': 'Custom',
2766 'data_transfer_methods': ['shm'],
2767 'cmd_args':
2768 'GLidProgram program, uint32_t indices_bucket_id, GLenum pname, '
2769 'GLint* params',
2770 'result': ['SizedResult<GLint>'],
2771 'unsafe': True,
2773 'GetAttachedShaders': {
2774 'type': 'Custom',
2775 'data_transfer_methods': ['shm'],
2776 'cmd_args': 'GLidProgram program, void* result, uint32_t result_size',
2777 'result': ['SizedResult<GLuint>'],
2779 'GetAttribLocation': {
2780 'type': 'Custom',
2781 'data_transfer_methods': ['shm'],
2782 'cmd_args':
2783 'GLidProgram program, uint32_t name_bucket_id, GLint* location',
2784 'result': ['GLint'],
2785 'error_return': -1,
2787 'GetFragDataLocation': {
2788 'type': 'Custom',
2789 'data_transfer_methods': ['shm'],
2790 'cmd_args':
2791 'GLidProgram program, uint32_t name_bucket_id, GLint* location',
2792 'result': ['GLint'],
2793 'error_return': -1,
2794 'unsafe': True,
2796 'GetBooleanv': {
2797 'type': 'GETn',
2798 'result': ['SizedResult<GLboolean>'],
2799 'decoder_func': 'DoGetBooleanv',
2800 'gl_test_func': 'glGetBooleanv',
2802 'GetBufferParameteri64v': {
2803 'type': 'GETn',
2804 'result': ['SizedResult<GLint64>'],
2805 'decoder_func': 'DoGetBufferParameteri64v',
2806 'expectation': False,
2807 'shadowed': True,
2808 'unsafe': True,
2810 'GetBufferParameteriv': {
2811 'type': 'GETn',
2812 'result': ['SizedResult<GLint>'],
2813 'decoder_func': 'DoGetBufferParameteriv',
2814 'expectation': False,
2815 'shadowed': True,
2817 'GetError': {
2818 'type': 'Is',
2819 'decoder_func': 'GetErrorState()->GetGLError',
2820 'impl_func': False,
2821 'result': ['GLenum'],
2822 'client_test': False,
2824 'GetFloatv': {
2825 'type': 'GETn',
2826 'result': ['SizedResult<GLfloat>'],
2827 'decoder_func': 'DoGetFloatv',
2828 'gl_test_func': 'glGetFloatv',
2830 'GetFramebufferAttachmentParameteriv': {
2831 'type': 'GETn',
2832 'decoder_func': 'DoGetFramebufferAttachmentParameteriv',
2833 'gl_test_func': 'glGetFramebufferAttachmentParameterivEXT',
2834 'result': ['SizedResult<GLint>'],
2836 'GetGraphicsResetStatusKHR': {
2837 'extension': True,
2838 'client_test': False,
2839 'gen_cmd': False,
2840 'trace_level': 1,
2842 'GetInteger64v': {
2843 'type': 'GETn',
2844 'result': ['SizedResult<GLint64>'],
2845 'client_test': False,
2846 'decoder_func': 'DoGetInteger64v',
2847 'unsafe': True
2849 'GetIntegerv': {
2850 'type': 'GETn',
2851 'result': ['SizedResult<GLint>'],
2852 'decoder_func': 'DoGetIntegerv',
2853 'client_test': False,
2855 'GetInteger64i_v': {
2856 'type': 'GETn',
2857 'result': ['SizedResult<GLint64>'],
2858 'client_test': False,
2859 'unsafe': True
2861 'GetIntegeri_v': {
2862 'type': 'GETn',
2863 'result': ['SizedResult<GLint>'],
2864 'client_test': False,
2865 'unsafe': True
2867 'GetInternalformativ': {
2868 'type': 'Custom',
2869 'data_transfer_methods': ['shm'],
2870 'result': ['SizedResult<GLint>'],
2871 'cmd_args':
2872 'GLenumRenderBufferTarget target, GLenumRenderBufferFormat format, '
2873 'GLenumInternalFormatParameter pname, GLint* params',
2874 'unsafe': True,
2876 'GetMaxValueInBufferCHROMIUM': {
2877 'type': 'Is',
2878 'decoder_func': 'DoGetMaxValueInBufferCHROMIUM',
2879 'result': ['GLuint'],
2880 'unit_test': False,
2881 'client_test': False,
2882 'extension': True,
2883 'chromium': True,
2884 'impl_func': False,
2886 'GetProgramiv': {
2887 'type': 'GETn',
2888 'decoder_func': 'DoGetProgramiv',
2889 'result': ['SizedResult<GLint>'],
2890 'expectation': False,
2892 'GetProgramInfoCHROMIUM': {
2893 'type': 'Custom',
2894 'expectation': False,
2895 'impl_func': False,
2896 'extension': True,
2897 'chromium': True,
2898 'client_test': False,
2899 'cmd_args': 'GLidProgram program, uint32_t bucket_id',
2900 'result': [
2901 'uint32_t link_status',
2902 'uint32_t num_attribs',
2903 'uint32_t num_uniforms',
2906 'GetProgramInfoLog': {
2907 'type': 'STRn',
2908 'expectation': False,
2910 'GetRenderbufferParameteriv': {
2911 'type': 'GETn',
2912 'decoder_func': 'DoGetRenderbufferParameteriv',
2913 'gl_test_func': 'glGetRenderbufferParameterivEXT',
2914 'result': ['SizedResult<GLint>'],
2916 'GetSamplerParameterfv': {
2917 'type': 'GETn',
2918 'result': ['SizedResult<GLfloat>'],
2919 'id_mapping': [ 'Sampler' ],
2920 'unsafe': True,
2922 'GetSamplerParameteriv': {
2923 'type': 'GETn',
2924 'result': ['SizedResult<GLint>'],
2925 'id_mapping': [ 'Sampler' ],
2926 'unsafe': True,
2928 'GetShaderiv': {
2929 'type': 'GETn',
2930 'decoder_func': 'DoGetShaderiv',
2931 'result': ['SizedResult<GLint>'],
2933 'GetShaderInfoLog': {
2934 'type': 'STRn',
2935 'get_len_func': 'glGetShaderiv',
2936 'get_len_enum': 'GL_INFO_LOG_LENGTH',
2937 'unit_test': False,
2939 'GetShaderPrecisionFormat': {
2940 'type': 'Custom',
2941 'data_transfer_methods': ['shm'],
2942 'cmd_args':
2943 'GLenumShaderType shadertype, GLenumShaderPrecision precisiontype, '
2944 'void* result',
2945 'result': [
2946 'int32_t success',
2947 'int32_t min_range',
2948 'int32_t max_range',
2949 'int32_t precision',
2952 'GetShaderSource': {
2953 'type': 'STRn',
2954 'get_len_func': 'DoGetShaderiv',
2955 'get_len_enum': 'GL_SHADER_SOURCE_LENGTH',
2956 'unit_test': False,
2957 'client_test': False,
2959 'GetString': {
2960 'type': 'Custom',
2961 'client_test': False,
2962 'cmd_args': 'GLenumStringType name, uint32_t bucket_id',
2964 'GetSynciv': {
2965 'type': 'GETn',
2966 'cmd_args': 'GLuint sync, GLenumSyncParameter pname, void* values',
2967 'result': ['SizedResult<GLint>'],
2968 'id_mapping': ['Sync'],
2969 'unsafe': True,
2971 'GetTexParameterfv': {
2972 'type': 'GETn',
2973 'decoder_func': 'DoGetTexParameterfv',
2974 'result': ['SizedResult<GLfloat>']
2976 'GetTexParameteriv': {
2977 'type': 'GETn',
2978 'decoder_func': 'DoGetTexParameteriv',
2979 'result': ['SizedResult<GLint>']
2981 'GetTranslatedShaderSourceANGLE': {
2982 'type': 'STRn',
2983 'get_len_func': 'DoGetShaderiv',
2984 'get_len_enum': 'GL_TRANSLATED_SHADER_SOURCE_LENGTH_ANGLE',
2985 'unit_test': False,
2986 'extension': True,
2988 'GetUniformBlockIndex': {
2989 'type': 'Custom',
2990 'data_transfer_methods': ['shm'],
2991 'cmd_args':
2992 'GLidProgram program, uint32_t name_bucket_id, GLuint* index',
2993 'result': ['GLuint'],
2994 'error_return': 'GL_INVALID_INDEX',
2995 'unsafe': True,
2997 'GetUniformBlocksCHROMIUM': {
2998 'type': 'Custom',
2999 'expectation': False,
3000 'impl_func': False,
3001 'extension': True,
3002 'chromium': True,
3003 'client_test': False,
3004 'cmd_args': 'GLidProgram program, uint32_t bucket_id',
3005 'result': ['uint32_t'],
3006 'unsafe': True,
3008 'GetUniformsES3CHROMIUM': {
3009 'type': 'Custom',
3010 'expectation': False,
3011 'impl_func': False,
3012 'extension': True,
3013 'chromium': True,
3014 'client_test': False,
3015 'cmd_args': 'GLidProgram program, uint32_t bucket_id',
3016 'result': ['uint32_t'],
3017 'unsafe': True,
3019 'GetTransformFeedbackVarying': {
3020 'type': 'Custom',
3021 'data_transfer_methods': ['shm'],
3022 'cmd_args':
3023 'GLidProgram program, GLuint index, uint32_t name_bucket_id, '
3024 'void* result',
3025 'result': [
3026 'int32_t success',
3027 'int32_t size',
3028 'uint32_t type',
3030 'unsafe': True,
3032 'GetTransformFeedbackVaryingsCHROMIUM': {
3033 'type': 'Custom',
3034 'expectation': False,
3035 'impl_func': False,
3036 'extension': True,
3037 'chromium': True,
3038 'client_test': False,
3039 'cmd_args': 'GLidProgram program, uint32_t bucket_id',
3040 'result': ['uint32_t'],
3041 'unsafe': True,
3043 'GetUniformfv': {
3044 'type': 'Custom',
3045 'data_transfer_methods': ['shm'],
3046 'result': ['SizedResult<GLfloat>'],
3048 'GetUniformiv': {
3049 'type': 'Custom',
3050 'data_transfer_methods': ['shm'],
3051 'result': ['SizedResult<GLint>'],
3053 'GetUniformuiv': {
3054 'type': 'Custom',
3055 'data_transfer_methods': ['shm'],
3056 'result': ['SizedResult<GLuint>'],
3057 'unsafe': True,
3059 'GetUniformIndices': {
3060 'type': 'Custom',
3061 'data_transfer_methods': ['shm'],
3062 'result': ['SizedResult<GLuint>'],
3063 'cmd_args': 'GLidProgram program, uint32_t names_bucket_id, '
3064 'GLuint* indices',
3065 'unsafe': True,
3067 'GetUniformLocation': {
3068 'type': 'Custom',
3069 'data_transfer_methods': ['shm'],
3070 'cmd_args':
3071 'GLidProgram program, uint32_t name_bucket_id, GLint* location',
3072 'result': ['GLint'],
3073 'error_return': -1, # http://www.opengl.org/sdk/docs/man/xhtml/glGetUniformLocation.xml
3075 'GetVertexAttribfv': {
3076 'type': 'GETn',
3077 'result': ['SizedResult<GLfloat>'],
3078 'impl_decl': False,
3079 'decoder_func': 'DoGetVertexAttribfv',
3080 'expectation': False,
3081 'client_test': False,
3083 'GetVertexAttribiv': {
3084 'type': 'GETn',
3085 'result': ['SizedResult<GLint>'],
3086 'impl_decl': False,
3087 'decoder_func': 'DoGetVertexAttribiv',
3088 'expectation': False,
3089 'client_test': False,
3091 'GetVertexAttribIiv': {
3092 'type': 'GETn',
3093 'result': ['SizedResult<GLint>'],
3094 'impl_decl': False,
3095 'decoder_func': 'DoGetVertexAttribIiv',
3096 'expectation': False,
3097 'client_test': False,
3098 'unsafe': True,
3100 'GetVertexAttribIuiv': {
3101 'type': 'GETn',
3102 'result': ['SizedResult<GLuint>'],
3103 'impl_decl': False,
3104 'decoder_func': 'DoGetVertexAttribIuiv',
3105 'expectation': False,
3106 'client_test': False,
3107 'unsafe': True,
3109 'GetVertexAttribPointerv': {
3110 'type': 'Custom',
3111 'data_transfer_methods': ['shm'],
3112 'result': ['SizedResult<GLuint>'],
3113 'client_test': False,
3115 'InvalidateFramebuffer': {
3116 'type': 'PUTn',
3117 'count': 1,
3118 'client_test': False,
3119 'unit_test': False,
3120 'unsafe': True,
3122 'InvalidateSubFramebuffer': {
3123 'type': 'PUTn',
3124 'count': 1,
3125 'client_test': False,
3126 'unit_test': False,
3127 'unsafe': True,
3129 'IsBuffer': {
3130 'type': 'Is',
3131 'decoder_func': 'DoIsBuffer',
3132 'expectation': False,
3134 'IsEnabled': {
3135 'type': 'Is',
3136 'decoder_func': 'DoIsEnabled',
3137 'client_test': False,
3138 'impl_func': False,
3139 'expectation': False,
3141 'IsFramebuffer': {
3142 'type': 'Is',
3143 'decoder_func': 'DoIsFramebuffer',
3144 'expectation': False,
3146 'IsProgram': {
3147 'type': 'Is',
3148 'decoder_func': 'DoIsProgram',
3149 'expectation': False,
3151 'IsRenderbuffer': {
3152 'type': 'Is',
3153 'decoder_func': 'DoIsRenderbuffer',
3154 'expectation': False,
3156 'IsShader': {
3157 'type': 'Is',
3158 'decoder_func': 'DoIsShader',
3159 'expectation': False,
3161 'IsSampler': {
3162 'type': 'Is',
3163 'id_mapping': [ 'Sampler' ],
3164 'expectation': False,
3165 'unsafe': True,
3167 'IsSync': {
3168 'type': 'Is',
3169 'id_mapping': [ 'Sync' ],
3170 'cmd_args': 'GLuint sync',
3171 'expectation': False,
3172 'unsafe': True,
3174 'IsTexture': {
3175 'type': 'Is',
3176 'decoder_func': 'DoIsTexture',
3177 'expectation': False,
3179 'IsTransformFeedback': {
3180 'type': 'Is',
3181 'id_mapping': [ 'TransformFeedback' ],
3182 'expectation': False,
3183 'unsafe': True,
3185 'LinkProgram': {
3186 'decoder_func': 'DoLinkProgram',
3187 'impl_func': False,
3188 'trace_level': 1,
3190 'MapBufferCHROMIUM': {
3191 'gen_cmd': False,
3192 'extension': "CHROMIUM_pixel_transfer_buffer_object",
3193 'chromium': True,
3194 'client_test': False,
3195 'trace_level': 1,
3197 'MapBufferSubDataCHROMIUM': {
3198 'gen_cmd': False,
3199 'extension': True,
3200 'chromium': True,
3201 'client_test': False,
3202 'pepper_interface': 'ChromiumMapSub',
3203 'trace_level': 1,
3205 'MapTexSubImage2DCHROMIUM': {
3206 'gen_cmd': False,
3207 'extension': "CHROMIUM_sub_image",
3208 'chromium': True,
3209 'client_test': False,
3210 'pepper_interface': 'ChromiumMapSub',
3211 'trace_level': 1,
3213 'MapBufferRange': {
3214 'type': 'Custom',
3215 'data_transfer_methods': ['shm'],
3216 'cmd_args': 'GLenumBufferTarget target, GLintptrNotNegative offset, '
3217 'GLsizeiptr size, GLbitfieldMapBufferAccess access, '
3218 'uint32_t data_shm_id, uint32_t data_shm_offset, '
3219 'uint32_t result_shm_id, uint32_t result_shm_offset',
3220 'unsafe': True,
3221 'result': ['uint32_t'],
3222 'trace_level': 1,
3224 'PauseTransformFeedback': {
3225 'unsafe': True,
3227 'PixelStorei': {'type': 'Manual'},
3228 'PostSubBufferCHROMIUM': {
3229 'type': 'Custom',
3230 'impl_func': False,
3231 'unit_test': False,
3232 'client_test': False,
3233 'extension': True,
3234 'chromium': True,
3236 'ProduceTextureCHROMIUM': {
3237 'decoder_func': 'DoProduceTextureCHROMIUM',
3238 'impl_func': False,
3239 'type': 'PUT',
3240 'count': 64, # GL_MAILBOX_SIZE_CHROMIUM
3241 'unit_test': False,
3242 'client_test': False,
3243 'extension': "CHROMIUM_texture_mailbox",
3244 'chromium': True,
3245 'trace_level': 1,
3247 'ProduceTextureDirectCHROMIUM': {
3248 'decoder_func': 'DoProduceTextureDirectCHROMIUM',
3249 'impl_func': False,
3250 'type': 'PUT',
3251 'count': 64, # GL_MAILBOX_SIZE_CHROMIUM
3252 'unit_test': False,
3253 'client_test': False,
3254 'extension': "CHROMIUM_texture_mailbox",
3255 'chromium': True,
3256 'trace_level': 1,
3258 'RenderbufferStorage': {
3259 'decoder_func': 'DoRenderbufferStorage',
3260 'gl_test_func': 'glRenderbufferStorageEXT',
3261 'expectation': False,
3262 'trace_level': 1,
3264 'RenderbufferStorageMultisampleCHROMIUM': {
3265 'cmd_comment':
3266 '// GL_CHROMIUM_framebuffer_multisample\n',
3267 'decoder_func': 'DoRenderbufferStorageMultisampleCHROMIUM',
3268 'gl_test_func': 'glRenderbufferStorageMultisampleCHROMIUM',
3269 'expectation': False,
3270 'unit_test': False,
3271 'extension': 'chromium_framebuffer_multisample',
3272 'extension_flag': 'chromium_framebuffer_multisample',
3273 'pepper_interface': 'FramebufferMultisample',
3274 'pepper_name': 'RenderbufferStorageMultisampleEXT',
3275 'trace_level': 1,
3277 'RenderbufferStorageMultisampleEXT': {
3278 'cmd_comment':
3279 '// GL_EXT_multisampled_render_to_texture\n',
3280 'decoder_func': 'DoRenderbufferStorageMultisampleEXT',
3281 'gl_test_func': 'glRenderbufferStorageMultisampleEXT',
3282 'expectation': False,
3283 'unit_test': False,
3284 'extension_flag': 'multisampled_render_to_texture',
3285 'trace_level': 1,
3287 'ReadBuffer': {
3288 'unsafe': True,
3289 'decoder_func': 'DoReadBuffer',
3290 'trace_level': 1,
3292 'ReadPixels': {
3293 'cmd_comment':
3294 '// ReadPixels has the result separated from the pixel buffer so that\n'
3295 '// it is easier to specify the result going to some specific place\n'
3296 '// that exactly fits the rectangle of pixels.\n',
3297 'type': 'Custom',
3298 'data_transfer_methods': ['shm'],
3299 'impl_func': False,
3300 'client_test': False,
3301 'cmd_args':
3302 'GLint x, GLint y, GLsizei width, GLsizei height, '
3303 'GLenumReadPixelFormat format, GLenumReadPixelType type, '
3304 'uint32_t pixels_shm_id, uint32_t pixels_shm_offset, '
3305 'uint32_t result_shm_id, uint32_t result_shm_offset, '
3306 'GLboolean async',
3307 'result': ['uint32_t'],
3308 'defer_reads': True,
3309 'trace_level': 1,
3311 'ReleaseShaderCompiler': {
3312 'decoder_func': 'DoReleaseShaderCompiler',
3313 'unit_test': False,
3315 'ResumeTransformFeedback': {
3316 'unsafe': True,
3318 'SamplerParameterf': {
3319 'valid_args': {
3320 '2': 'GL_NEAREST'
3322 'id_mapping': [ 'Sampler' ],
3323 'unsafe': True,
3325 'SamplerParameterfv': {
3326 'type': 'PUT',
3327 'data_value': 'GL_NEAREST',
3328 'count': 1,
3329 'gl_test_func': 'glSamplerParameterf',
3330 'decoder_func': 'DoSamplerParameterfv',
3331 'first_element_only': True,
3332 'id_mapping': [ 'Sampler' ],
3333 'unsafe': True,
3335 'SamplerParameteri': {
3336 'valid_args': {
3337 '2': 'GL_NEAREST'
3339 'id_mapping': [ 'Sampler' ],
3340 'unsafe': True,
3342 'SamplerParameteriv': {
3343 'type': 'PUT',
3344 'data_value': 'GL_NEAREST',
3345 'count': 1,
3346 'gl_test_func': 'glSamplerParameteri',
3347 'decoder_func': 'DoSamplerParameteriv',
3348 'first_element_only': True,
3349 'unsafe': True,
3351 'ShaderBinary': {
3352 'type': 'Custom',
3353 'client_test': False,
3355 'ShaderSource': {
3356 'type': 'PUTSTR',
3357 'decoder_func': 'DoShaderSource',
3358 'expectation': False,
3359 'data_transfer_methods': ['bucket'],
3360 'cmd_args':
3361 'GLuint shader, const char** str',
3362 'pepper_args':
3363 'GLuint shader, GLsizei count, const char** str, const GLint* length',
3365 'StencilMask': {
3366 'type': 'StateSetFrontBack',
3367 'state': 'StencilMask',
3368 'no_gl': True,
3369 'expectation': False,
3371 'StencilMaskSeparate': {
3372 'type': 'StateSetFrontBackSeparate',
3373 'state': 'StencilMask',
3374 'no_gl': True,
3375 'expectation': False,
3377 'SwapBuffers': {
3378 'impl_func': False,
3379 'decoder_func': 'DoSwapBuffers',
3380 'unit_test': False,
3381 'client_test': False,
3382 'extension': True,
3383 'trace_level': 1,
3385 'SwapInterval': {
3386 'impl_func': False,
3387 'decoder_func': 'DoSwapInterval',
3388 'unit_test': False,
3389 'client_test': False,
3390 'extension': True,
3391 'trace_level': 1,
3393 'TexImage2D': {
3394 'type': 'Manual',
3395 'data_transfer_methods': ['shm'],
3396 'client_test': False,
3397 'trace_level': 2,
3399 'TexImage3D': {
3400 'type': 'Manual',
3401 'data_transfer_methods': ['shm'],
3402 'client_test': False,
3403 'unsafe': True,
3404 'trace_level': 2,
3406 'TexParameterf': {
3407 'decoder_func': 'DoTexParameterf',
3408 'valid_args': {
3409 '2': 'GL_NEAREST'
3412 'TexParameteri': {
3413 'decoder_func': 'DoTexParameteri',
3414 'valid_args': {
3415 '2': 'GL_NEAREST'
3418 'TexParameterfv': {
3419 'type': 'PUT',
3420 'data_value': 'GL_NEAREST',
3421 'count': 1,
3422 'decoder_func': 'DoTexParameterfv',
3423 'gl_test_func': 'glTexParameterf',
3424 'first_element_only': True,
3426 'TexParameteriv': {
3427 'type': 'PUT',
3428 'data_value': 'GL_NEAREST',
3429 'count': 1,
3430 'decoder_func': 'DoTexParameteriv',
3431 'gl_test_func': 'glTexParameteri',
3432 'first_element_only': True,
3434 'TexStorage3D': {
3435 'unsafe': True,
3436 'trace_level': 2,
3438 'TexSubImage2D': {
3439 'type': 'Manual',
3440 'data_transfer_methods': ['shm'],
3441 'client_test': False,
3442 'trace_level': 2,
3443 'cmd_args': 'GLenumTextureTarget target, GLint level, '
3444 'GLint xoffset, GLint yoffset, '
3445 'GLsizei width, GLsizei height, '
3446 'GLenumTextureFormat format, GLenumPixelType type, '
3447 'const void* pixels, GLboolean internal'
3449 'TexSubImage3D': {
3450 'type': 'Manual',
3451 'data_transfer_methods': ['shm'],
3452 'client_test': False,
3453 'trace_level': 2,
3454 'cmd_args': 'GLenumTextureTarget target, GLint level, '
3455 'GLint xoffset, GLint yoffset, GLint zoffset, '
3456 'GLsizei width, GLsizei height, GLsizei depth, '
3457 'GLenumTextureFormat format, GLenumPixelType type, '
3458 'const void* pixels, GLboolean internal',
3459 'unsafe': True,
3461 'TransformFeedbackVaryings': {
3462 'type': 'PUTSTR',
3463 'data_transfer_methods': ['bucket'],
3464 'decoder_func': 'DoTransformFeedbackVaryings',
3465 'cmd_args':
3466 'GLuint program, const char** varyings, GLenum buffermode',
3467 'expectation': False,
3468 'unsafe': True,
3470 'Uniform1f': {'type': 'PUTXn', 'count': 1},
3471 'Uniform1fv': {
3472 'type': 'PUTn',
3473 'count': 1,
3474 'decoder_func': 'DoUniform1fv',
3476 'Uniform1i': {'decoder_func': 'DoUniform1i', 'unit_test': False},
3477 'Uniform1iv': {
3478 'type': 'PUTn',
3479 'count': 1,
3480 'decoder_func': 'DoUniform1iv',
3481 'unit_test': False,
3483 'Uniform1ui': {
3484 'type': 'PUTXn',
3485 'count': 1,
3486 'unit_test': False,
3487 'unsafe': True,
3489 'Uniform1uiv': {
3490 'type': 'PUTn',
3491 'count': 1,
3492 'decoder_func': 'DoUniform1uiv',
3493 'unit_test': False,
3494 'unsafe': True,
3496 'Uniform2i': {'type': 'PUTXn', 'count': 2},
3497 'Uniform2f': {'type': 'PUTXn', 'count': 2},
3498 'Uniform2fv': {
3499 'type': 'PUTn',
3500 'count': 2,
3501 'decoder_func': 'DoUniform2fv',
3503 'Uniform2iv': {
3504 'type': 'PUTn',
3505 'count': 2,
3506 'decoder_func': 'DoUniform2iv',
3508 'Uniform2ui': {
3509 'type': 'PUTXn',
3510 'count': 2,
3511 'unit_test': False,
3512 'unsafe': True,
3514 'Uniform2uiv': {
3515 'type': 'PUTn',
3516 'count': 2,
3517 'decoder_func': 'DoUniform2uiv',
3518 'unit_test': False,
3519 'unsafe': True,
3521 'Uniform3i': {'type': 'PUTXn', 'count': 3},
3522 'Uniform3f': {'type': 'PUTXn', 'count': 3},
3523 'Uniform3fv': {
3524 'type': 'PUTn',
3525 'count': 3,
3526 'decoder_func': 'DoUniform3fv',
3528 'Uniform3iv': {
3529 'type': 'PUTn',
3530 'count': 3,
3531 'decoder_func': 'DoUniform3iv',
3533 'Uniform3ui': {
3534 'type': 'PUTXn',
3535 'count': 3,
3536 'unit_test': False,
3537 'unsafe': True,
3539 'Uniform3uiv': {
3540 'type': 'PUTn',
3541 'count': 3,
3542 'decoder_func': 'DoUniform3uiv',
3543 'unit_test': False,
3544 'unsafe': True,
3546 'Uniform4i': {'type': 'PUTXn', 'count': 4},
3547 'Uniform4f': {'type': 'PUTXn', 'count': 4},
3548 'Uniform4fv': {
3549 'type': 'PUTn',
3550 'count': 4,
3551 'decoder_func': 'DoUniform4fv',
3553 'Uniform4iv': {
3554 'type': 'PUTn',
3555 'count': 4,
3556 'decoder_func': 'DoUniform4iv',
3558 'Uniform4ui': {
3559 'type': 'PUTXn',
3560 'count': 4,
3561 'unit_test': False,
3562 'unsafe': True,
3564 'Uniform4uiv': {
3565 'type': 'PUTn',
3566 'count': 4,
3567 'decoder_func': 'DoUniform4uiv',
3568 'unit_test': False,
3569 'unsafe': True,
3571 'UniformMatrix2fv': {
3572 'type': 'PUTn',
3573 'count': 4,
3574 'decoder_func': 'DoUniformMatrix2fv',
3576 'UniformMatrix2x3fv': {
3577 'type': 'PUTn',
3578 'count': 6,
3579 'decoder_func': 'DoUniformMatrix2x3fv',
3580 'unsafe': True,
3582 'UniformMatrix2x4fv': {
3583 'type': 'PUTn',
3584 'count': 8,
3585 'decoder_func': 'DoUniformMatrix2x4fv',
3586 'unsafe': True,
3588 'UniformMatrix3fv': {
3589 'type': 'PUTn',
3590 'count': 9,
3591 'decoder_func': 'DoUniformMatrix3fv',
3593 'UniformMatrix3x2fv': {
3594 'type': 'PUTn',
3595 'count': 6,
3596 'decoder_func': 'DoUniformMatrix3x2fv',
3597 'unsafe': True,
3599 'UniformMatrix3x4fv': {
3600 'type': 'PUTn',
3601 'count': 12,
3602 'decoder_func': 'DoUniformMatrix3x4fv',
3603 'unsafe': True,
3605 'UniformMatrix4fv': {
3606 'type': 'PUTn',
3607 'count': 16,
3608 'decoder_func': 'DoUniformMatrix4fv',
3610 'UniformMatrix4x2fv': {
3611 'type': 'PUTn',
3612 'count': 8,
3613 'decoder_func': 'DoUniformMatrix4x2fv',
3614 'unsafe': True,
3616 'UniformMatrix4x3fv': {
3617 'type': 'PUTn',
3618 'count': 12,
3619 'decoder_func': 'DoUniformMatrix4x3fv',
3620 'unsafe': True,
3622 'UniformBlockBinding': {
3623 'type': 'Custom',
3624 'impl_func': False,
3625 'unsafe': True,
3627 'UnmapBufferCHROMIUM': {
3628 'gen_cmd': False,
3629 'extension': "CHROMIUM_pixel_transfer_buffer_object",
3630 'chromium': True,
3631 'client_test': False,
3632 'trace_level': 1,
3634 'UnmapBufferSubDataCHROMIUM': {
3635 'gen_cmd': False,
3636 'extension': True,
3637 'chromium': True,
3638 'client_test': False,
3639 'pepper_interface': 'ChromiumMapSub',
3640 'trace_level': 1,
3642 'UnmapBuffer': {
3643 'type': 'Custom',
3644 'unsafe': True,
3645 'trace_level': 1,
3647 'UnmapTexSubImage2DCHROMIUM': {
3648 'gen_cmd': False,
3649 'extension': "CHROMIUM_sub_image",
3650 'chromium': True,
3651 'client_test': False,
3652 'pepper_interface': 'ChromiumMapSub',
3653 'trace_level': 1,
3655 'UseProgram': {
3656 'type': 'Bind',
3657 'decoder_func': 'DoUseProgram',
3659 'ValidateProgram': {'decoder_func': 'DoValidateProgram'},
3660 'VertexAttrib1f': {'decoder_func': 'DoVertexAttrib1f'},
3661 'VertexAttrib1fv': {
3662 'type': 'PUT',
3663 'count': 1,
3664 'decoder_func': 'DoVertexAttrib1fv',
3666 'VertexAttrib2f': {'decoder_func': 'DoVertexAttrib2f'},
3667 'VertexAttrib2fv': {
3668 'type': 'PUT',
3669 'count': 2,
3670 'decoder_func': 'DoVertexAttrib2fv',
3672 'VertexAttrib3f': {'decoder_func': 'DoVertexAttrib3f'},
3673 'VertexAttrib3fv': {
3674 'type': 'PUT',
3675 'count': 3,
3676 'decoder_func': 'DoVertexAttrib3fv',
3678 'VertexAttrib4f': {'decoder_func': 'DoVertexAttrib4f'},
3679 'VertexAttrib4fv': {
3680 'type': 'PUT',
3681 'count': 4,
3682 'decoder_func': 'DoVertexAttrib4fv',
3684 'VertexAttribI4i': {
3685 'unsafe': True,
3686 'decoder_func': 'DoVertexAttribI4i',
3688 'VertexAttribI4iv': {
3689 'type': 'PUT',
3690 'count': 4,
3691 'unsafe': True,
3692 'decoder_func': 'DoVertexAttribI4iv',
3694 'VertexAttribI4ui': {
3695 'unsafe': True,
3696 'decoder_func': 'DoVertexAttribI4ui',
3698 'VertexAttribI4uiv': {
3699 'type': 'PUT',
3700 'count': 4,
3701 'unsafe': True,
3702 'decoder_func': 'DoVertexAttribI4uiv',
3704 'VertexAttribIPointer': {
3705 'type': 'Manual',
3706 'cmd_args': 'GLuint indx, GLintVertexAttribSize size, '
3707 'GLenumVertexAttribIType type, GLsizei stride, '
3708 'GLuint offset',
3709 'client_test': False,
3710 'unsafe': True,
3712 'VertexAttribPointer': {
3713 'type': 'Manual',
3714 'cmd_args': 'GLuint indx, GLintVertexAttribSize size, '
3715 'GLenumVertexAttribType type, GLboolean normalized, '
3716 'GLsizei stride, GLuint offset',
3717 'client_test': False,
3719 'WaitSync': {
3720 'type': 'Custom',
3721 'cmd_args': 'GLuint sync, GLbitfieldSyncFlushFlags flags, '
3722 'GLuint timeout_0, GLuint timeout_1',
3723 'impl_func': False,
3724 'client_test': False,
3725 'unsafe': True,
3726 'trace_level': 1,
3728 'Scissor': {
3729 'type': 'StateSet',
3730 'state': 'Scissor',
3732 'Viewport': {
3733 'decoder_func': 'DoViewport',
3735 'ResizeCHROMIUM': {
3736 'type': 'Custom',
3737 'impl_func': False,
3738 'unit_test': False,
3739 'extension': True,
3740 'chromium': True,
3741 'trace_level': 1,
3743 'GetRequestableExtensionsCHROMIUM': {
3744 'type': 'Custom',
3745 'impl_func': False,
3746 'cmd_args': 'uint32_t bucket_id',
3747 'extension': True,
3748 'chromium': True,
3750 'RequestExtensionCHROMIUM': {
3751 'type': 'Custom',
3752 'impl_func': False,
3753 'client_test': False,
3754 'cmd_args': 'uint32_t bucket_id',
3755 'extension': True,
3756 'chromium': True,
3758 'RateLimitOffscreenContextCHROMIUM': {
3759 'gen_cmd': False,
3760 'extension': True,
3761 'chromium': True,
3762 'client_test': False,
3764 'CreateStreamTextureCHROMIUM': {
3765 'type': 'HandWritten',
3766 'impl_func': False,
3767 'gen_cmd': False,
3768 'extension': True,
3769 'chromium': True,
3770 'trace_level': 1,
3772 'TexImageIOSurface2DCHROMIUM': {
3773 'decoder_func': 'DoTexImageIOSurface2DCHROMIUM',
3774 'unit_test': False,
3775 'extension': True,
3776 'chromium': True,
3777 'trace_level': 1,
3779 'CopyTextureCHROMIUM': {
3780 'decoder_func': 'DoCopyTextureCHROMIUM',
3781 'unit_test': False,
3782 'extension': "CHROMIUM_copy_texture",
3783 'chromium': True,
3784 'trace_level': 2,
3786 'CopySubTextureCHROMIUM': {
3787 'decoder_func': 'DoCopySubTextureCHROMIUM',
3788 'unit_test': False,
3789 'extension': "CHROMIUM_copy_texture",
3790 'chromium': True,
3791 'trace_level': 2,
3793 'CompressedCopyTextureCHROMIUM': {
3794 'decoder_func': 'DoCompressedCopyTextureCHROMIUM',
3795 'unit_test': False,
3796 'extension': True,
3797 'chromium': True,
3799 'CompressedCopySubTextureCHROMIUM': {
3800 'decoder_func': 'DoCompressedCopySubTextureCHROMIUM',
3801 'unit_test': False,
3802 'extension': True,
3803 'chromium': True,
3805 'TexStorage2DEXT': {
3806 'unit_test': False,
3807 'extension': True,
3808 'decoder_func': 'DoTexStorage2DEXT',
3809 'trace_level': 2,
3811 'DrawArraysInstancedANGLE': {
3812 'type': 'Manual',
3813 'cmd_args': 'GLenumDrawMode mode, GLint first, GLsizei count, '
3814 'GLsizei primcount',
3815 'extension': True,
3816 'unit_test': False,
3817 'pepper_interface': 'InstancedArrays',
3818 'defer_draws': True,
3819 'trace_level': 2,
3821 'DrawBuffersEXT': {
3822 'type': 'PUTn',
3823 'decoder_func': 'DoDrawBuffersEXT',
3824 'count': 1,
3825 'client_test': False,
3826 'unit_test': False,
3827 # could use 'extension_flag': 'ext_draw_buffers' but currently expected to
3828 # work without.
3829 'extension': True,
3830 'pepper_interface': 'DrawBuffers',
3831 'trace_level': 2,
3833 'DrawElementsInstancedANGLE': {
3834 'type': 'Manual',
3835 'cmd_args': 'GLenumDrawMode mode, GLsizei count, '
3836 'GLenumIndexType type, GLuint index_offset, GLsizei primcount',
3837 'extension': True,
3838 'unit_test': False,
3839 'client_test': False,
3840 'pepper_interface': 'InstancedArrays',
3841 'defer_draws': True,
3842 'trace_level': 2,
3844 'VertexAttribDivisorANGLE': {
3845 'type': 'Manual',
3846 'cmd_args': 'GLuint index, GLuint divisor',
3847 'extension': True,
3848 'unit_test': False,
3849 'pepper_interface': 'InstancedArrays',
3851 'GenQueriesEXT': {
3852 'type': 'GENn',
3853 'gl_test_func': 'glGenQueriesARB',
3854 'resource_type': 'Query',
3855 'resource_types': 'Queries',
3856 'unit_test': False,
3857 'pepper_interface': 'Query',
3858 'not_shared': 'True',
3859 'extension': "occlusion_query_EXT",
3861 'DeleteQueriesEXT': {
3862 'type': 'DELn',
3863 'gl_test_func': 'glDeleteQueriesARB',
3864 'resource_type': 'Query',
3865 'resource_types': 'Queries',
3866 'unit_test': False,
3867 'pepper_interface': 'Query',
3868 'extension': "occlusion_query_EXT",
3870 'IsQueryEXT': {
3871 'gen_cmd': False,
3872 'client_test': False,
3873 'pepper_interface': 'Query',
3874 'extension': "occlusion_query_EXT",
3876 'BeginQueryEXT': {
3877 'type': 'Manual',
3878 'cmd_args': 'GLenumQueryTarget target, GLidQuery id, void* sync_data',
3879 'data_transfer_methods': ['shm'],
3880 'gl_test_func': 'glBeginQuery',
3881 'pepper_interface': 'Query',
3882 'extension': "occlusion_query_EXT",
3884 'BeginTransformFeedback': {
3885 'unsafe': True,
3887 'EndQueryEXT': {
3888 'type': 'Manual',
3889 'cmd_args': 'GLenumQueryTarget target, GLuint submit_count',
3890 'gl_test_func': 'glEndnQuery',
3891 'client_test': False,
3892 'pepper_interface': 'Query',
3893 'extension': "occlusion_query_EXT",
3895 'EndTransformFeedback': {
3896 'unsafe': True,
3898 'FlushDriverCachesCHROMIUM': {
3899 'decoder_func': 'DoFlushDriverCachesCHROMIUM',
3900 'unit_test': False,
3901 'extension': True,
3902 'chromium': True,
3903 'trace_level': 1,
3905 'GetQueryivEXT': {
3906 'gen_cmd': False,
3907 'client_test': False,
3908 'gl_test_func': 'glGetQueryiv',
3909 'pepper_interface': 'Query',
3910 'extension': "occlusion_query_EXT",
3912 'QueryCounterEXT' : {
3913 'type': 'Manual',
3914 'cmd_args': 'GLidQuery id, GLenumQueryTarget target, '
3915 'void* sync_data, GLuint submit_count',
3916 'data_transfer_methods': ['shm'],
3917 'gl_test_func': 'glQueryCounter',
3918 'extension': "disjoint_timer_query_EXT",
3920 'GetQueryObjectivEXT': {
3921 'gen_cmd': False,
3922 'client_test': False,
3923 'gl_test_func': 'glGetQueryObjectiv',
3924 'extension': "disjoint_timer_query_EXT",
3926 'GetQueryObjectuivEXT': {
3927 'gen_cmd': False,
3928 'client_test': False,
3929 'gl_test_func': 'glGetQueryObjectuiv',
3930 'pepper_interface': 'Query',
3931 'extension': "occlusion_query_EXT",
3933 'GetQueryObjecti64vEXT': {
3934 'gen_cmd': False,
3935 'client_test': False,
3936 'gl_test_func': 'glGetQueryObjecti64v',
3937 'extension': "disjoint_timer_query_EXT",
3939 'GetQueryObjectui64vEXT': {
3940 'gen_cmd': False,
3941 'client_test': False,
3942 'gl_test_func': 'glGetQueryObjectui64v',
3943 'extension': "disjoint_timer_query_EXT",
3945 'SetDisjointValueSyncCHROMIUM': {
3946 'type': 'Manual',
3947 'data_transfer_methods': ['shm'],
3948 'client_test': False,
3949 'cmd_args': 'void* sync_data',
3950 'extension': True,
3951 'chromium': True,
3953 'BindUniformLocationCHROMIUM': {
3954 'type': 'GLchar',
3955 'extension': True,
3956 'data_transfer_methods': ['bucket'],
3957 'needs_size': True,
3958 'gl_test_func': 'DoBindUniformLocationCHROMIUM',
3960 'InsertEventMarkerEXT': {
3961 'type': 'GLcharN',
3962 'decoder_func': 'DoInsertEventMarkerEXT',
3963 'expectation': False,
3964 'extension': True,
3966 'PushGroupMarkerEXT': {
3967 'type': 'GLcharN',
3968 'decoder_func': 'DoPushGroupMarkerEXT',
3969 'expectation': False,
3970 'extension': True,
3972 'PopGroupMarkerEXT': {
3973 'decoder_func': 'DoPopGroupMarkerEXT',
3974 'expectation': False,
3975 'extension': True,
3976 'impl_func': False,
3979 'GenVertexArraysOES': {
3980 'type': 'GENn',
3981 'extension': True,
3982 'gl_test_func': 'glGenVertexArraysOES',
3983 'resource_type': 'VertexArray',
3984 'resource_types': 'VertexArrays',
3985 'unit_test': False,
3986 'pepper_interface': 'VertexArrayObject',
3988 'BindVertexArrayOES': {
3989 'type': 'Bind',
3990 'extension': True,
3991 'gl_test_func': 'glBindVertexArrayOES',
3992 'decoder_func': 'DoBindVertexArrayOES',
3993 'gen_func': 'GenVertexArraysOES',
3994 'unit_test': False,
3995 'client_test': False,
3996 'pepper_interface': 'VertexArrayObject',
3998 'DeleteVertexArraysOES': {
3999 'type': 'DELn',
4000 'extension': True,
4001 'gl_test_func': 'glDeleteVertexArraysOES',
4002 'resource_type': 'VertexArray',
4003 'resource_types': 'VertexArrays',
4004 'unit_test': False,
4005 'pepper_interface': 'VertexArrayObject',
4007 'IsVertexArrayOES': {
4008 'type': 'Is',
4009 'extension': True,
4010 'gl_test_func': 'glIsVertexArrayOES',
4011 'decoder_func': 'DoIsVertexArrayOES',
4012 'expectation': False,
4013 'unit_test': False,
4014 'pepper_interface': 'VertexArrayObject',
4016 'BindTexImage2DCHROMIUM': {
4017 'decoder_func': 'DoBindTexImage2DCHROMIUM',
4018 'unit_test': False,
4019 'extension': "CHROMIUM_image",
4020 'chromium': True,
4022 'ReleaseTexImage2DCHROMIUM': {
4023 'decoder_func': 'DoReleaseTexImage2DCHROMIUM',
4024 'unit_test': False,
4025 'extension': "CHROMIUM_image",
4026 'chromium': True,
4028 'ShallowFinishCHROMIUM': {
4029 'impl_func': False,
4030 'gen_cmd': False,
4031 'extension': True,
4032 'chromium': True,
4033 'client_test': False,
4035 'ShallowFlushCHROMIUM': {
4036 'impl_func': False,
4037 'gen_cmd': False,
4038 'extension': "CHROMIUM_miscellaneous",
4039 'chromium': True,
4040 'client_test': False,
4042 'OrderingBarrierCHROMIUM': {
4043 'impl_func': False,
4044 'gen_cmd': False,
4045 'extension': "CHROMIUM_miscellaneous",
4046 'chromium': True,
4047 'client_test': False,
4049 'TraceBeginCHROMIUM': {
4050 'type': 'Custom',
4051 'impl_func': False,
4052 'client_test': False,
4053 'cmd_args': 'GLuint category_bucket_id, GLuint name_bucket_id',
4054 'extension': True,
4055 'chromium': True,
4057 'TraceEndCHROMIUM': {
4058 'impl_func': False,
4059 'client_test': False,
4060 'decoder_func': 'DoTraceEndCHROMIUM',
4061 'unit_test': False,
4062 'extension': True,
4063 'chromium': True,
4065 'DiscardFramebufferEXT': {
4066 'type': 'PUTn',
4067 'count': 1,
4068 'decoder_func': 'DoDiscardFramebufferEXT',
4069 'unit_test': False,
4070 'client_test': False,
4071 'extension_flag': 'ext_discard_framebuffer',
4072 'trace_level': 2,
4074 'LoseContextCHROMIUM': {
4075 'decoder_func': 'DoLoseContextCHROMIUM',
4076 'unit_test': False,
4077 'extension': True,
4078 'chromium': True,
4079 'trace_level': 1,
4081 'InsertSyncPointCHROMIUM': {
4082 'type': 'HandWritten',
4083 'impl_func': False,
4084 'extension': "CHROMIUM_sync_point",
4085 'chromium': True,
4086 'trace_level': 1,
4088 'WaitSyncPointCHROMIUM': {
4089 'type': 'Custom',
4090 'impl_func': True,
4091 'extension': "CHROMIUM_sync_point",
4092 'chromium': True,
4093 'trace_level': 1,
4095 'DiscardBackbufferCHROMIUM': {
4096 'type': 'Custom',
4097 'impl_func': True,
4098 'extension': True,
4099 'chromium': True,
4100 'trace_level': 2,
4102 'ScheduleOverlayPlaneCHROMIUM': {
4103 'type': 'Custom',
4104 'impl_func': True,
4105 'unit_test': False,
4106 'client_test': False,
4107 'extension': True,
4108 'chromium': True,
4110 'MatrixLoadfCHROMIUM': {
4111 'type': 'PUT',
4112 'count': 16,
4113 'data_type': 'GLfloat',
4114 'decoder_func': 'DoMatrixLoadfCHROMIUM',
4115 'gl_test_func': 'glMatrixLoadfEXT',
4116 'chromium': True,
4117 'extension': True,
4118 'extension_flag': 'chromium_path_rendering',
4120 'MatrixLoadIdentityCHROMIUM': {
4121 'decoder_func': 'DoMatrixLoadIdentityCHROMIUM',
4122 'gl_test_func': 'glMatrixLoadIdentityEXT',
4123 'chromium': True,
4124 'extension': True,
4125 'extension_flag': 'chromium_path_rendering',
4127 'GenPathsCHROMIUM': {
4128 'type': 'Custom',
4129 'cmd_args': 'GLuint first_client_id, GLsizei range',
4130 'chromium': True,
4131 'extension': True,
4132 'extension_flag': 'chromium_path_rendering',
4134 'DeletePathsCHROMIUM': {
4135 'type': 'Custom',
4136 'cmd_args': 'GLuint first_client_id, GLsizei range',
4137 'impl_func': False,
4138 'unit_test': False,
4139 'chromium': True,
4140 'extension': True,
4141 'extension_flag': 'chromium_path_rendering',
4143 'IsPathCHROMIUM': {
4144 'type': 'Is',
4145 'decoder_func': 'DoIsPathCHROMIUM',
4146 'gl_test_func': 'glIsPathNV',
4147 'chromium': True,
4148 'extension': True,
4149 'extension_flag': 'chromium_path_rendering',
4151 'PathCommandsCHROMIUM': {
4152 'type': 'Manual',
4153 'immediate': False,
4154 'chromium': True,
4155 'extension': True,
4156 'extension_flag': 'chromium_path_rendering',
4158 'PathParameterfCHROMIUM': {
4159 'type': 'Custom',
4160 'chromium': True,
4161 'extension': True,
4162 'extension_flag': 'chromium_path_rendering',
4164 'PathParameteriCHROMIUM': {
4165 'type': 'Custom',
4166 'chromium': True,
4167 'extension': True,
4168 'extension_flag': 'chromium_path_rendering',
4170 'PathStencilFuncCHROMIUM': {
4171 'type': 'StateSet',
4172 'state': 'PathStencilFuncCHROMIUM',
4173 'decoder_func': 'glPathStencilFuncNV',
4174 'chromium': True,
4175 'extension': True,
4176 'extension_flag': 'chromium_path_rendering',
4178 'StencilFillPathCHROMIUM': {
4179 'type': 'Custom',
4180 'chromium': True,
4181 'extension': True,
4182 'extension_flag': 'chromium_path_rendering',
4184 'StencilStrokePathCHROMIUM': {
4185 'type': 'Custom',
4186 'chromium': True,
4187 'extension': True,
4188 'extension_flag': 'chromium_path_rendering',
4190 'CoverFillPathCHROMIUM': {
4191 'type': 'Custom',
4192 'chromium': True,
4193 'extension': True,
4194 'extension_flag': 'chromium_path_rendering',
4196 'CoverStrokePathCHROMIUM': {
4197 'type': 'Custom',
4198 'chromium': True,
4199 'extension': True,
4200 'extension_flag': 'chromium_path_rendering',
4202 'StencilThenCoverFillPathCHROMIUM': {
4203 'type': 'Custom',
4204 'chromium': True,
4205 'extension': True,
4206 'extension_flag': 'chromium_path_rendering',
4208 'StencilThenCoverStrokePathCHROMIUM': {
4209 'type': 'Custom',
4210 'chromium': True,
4211 'extension': True,
4212 'extension_flag': 'chromium_path_rendering',
4218 def Grouper(n, iterable, fillvalue=None):
4219 """Collect data into fixed-length chunks or blocks"""
4220 args = [iter(iterable)] * n
4221 return itertools.izip_longest(fillvalue=fillvalue, *args)
4224 def SplitWords(input_string):
4225 """Split by '_' if found, otherwise split at uppercase/numeric chars.
4227 Will split "some_TEXT" into ["some", "TEXT"], "CamelCase" into ["Camel",
4228 "Case"], and "Vector3" into ["Vector", "3"].
4230 if input_string.find('_') > -1:
4231 # 'some_TEXT_' -> 'some TEXT'
4232 return input_string.replace('_', ' ').strip().split()
4233 else:
4234 if re.search('[A-Z]', input_string) and re.search('[a-z]', input_string):
4235 # mixed case.
4236 # look for capitalization to cut input_strings
4237 # 'SomeText' -> 'Some Text'
4238 input_string = re.sub('([A-Z])', r' \1', input_string).strip()
4239 # 'Vector3' -> 'Vector 3'
4240 input_string = re.sub('([^0-9])([0-9])', r'\1 \2', input_string)
4241 return input_string.split()
4243 def ToUnderscore(input_string):
4244 """converts CamelCase to camel_case."""
4245 words = SplitWords(input_string)
4246 return '_'.join([word.lower() for word in words])
4248 def CachedStateName(item):
4249 if item.get('cached', False):
4250 return 'cached_' + item['name']
4251 return item['name']
4253 def ToGLExtensionString(extension_flag):
4254 """Returns GL-type extension string of a extension flag."""
4255 if extension_flag == "oes_compressed_etc1_rgb8_texture":
4256 return "OES_compressed_ETC1_RGB8_texture" # Fixup inconsitency with rgb8,
4257 # unfortunate.
4258 uppercase_words = [ 'img', 'ext', 'arb', 'chromium', 'oes', 'amd', 'bgra8888',
4259 'egl', 'atc', 'etc1', 'angle']
4260 parts = extension_flag.split('_')
4261 return "_".join(
4262 [part.upper() if part in uppercase_words else part for part in parts])
4264 def ToCamelCase(input_string):
4265 """converts ABC_underscore_case to ABCUnderscoreCase."""
4266 return ''.join(w[0].upper() + w[1:] for w in input_string.split('_'))
4268 def GetGLGetTypeConversion(result_type, value_type, value):
4269 """Makes a gl compatible type conversion string for accessing state variables.
4271 Useful when accessing state variables through glGetXXX calls.
4272 glGet documetation (for example, the manual pages):
4273 [...] If glGetIntegerv is called, [...] most floating-point values are
4274 rounded to the nearest integer value. [...]
4276 Args:
4277 result_type: the gl type to be obtained
4278 value_type: the GL type of the state variable
4279 value: the name of the state variable
4281 Returns:
4282 String that converts the state variable to desired GL type according to GL
4283 rules.
4286 if result_type == 'GLint':
4287 if value_type == 'GLfloat':
4288 return 'static_cast<GLint>(round(%s))' % value
4289 return 'static_cast<%s>(%s)' % (result_type, value)
4292 class CWriter(object):
4293 """Context manager that creates a C source file.
4295 To be used with the `with` statement. Returns a normal `file` type, open only
4296 for writing - any existing files with that name will be overwritten. It will
4297 automatically write the contents of `_LICENSE` and `_DO_NOT_EDIT_WARNING`
4298 at the beginning.
4300 Example:
4301 with CWriter("file.cpp") as myfile:
4302 myfile.write("hello")
4303 # type(myfile) == file
4305 def __init__(self, filename):
4306 self.filename = filename
4307 self._file = open(filename, 'w')
4308 self._ENTER_MSG = _LICENSE + _DO_NOT_EDIT_WARNING
4309 self._EXIT_MSG = ""
4311 def __enter__(self):
4312 self._file.write(self._ENTER_MSG)
4313 return self._file
4315 def __exit__(self, exc_type, exc_value, traceback):
4316 self._file.write(self._EXIT_MSG)
4317 self._file.close()
4320 class CHeaderWriter(CWriter):
4321 """Context manager that creates a C header file.
4323 Works the same way as CWriter, except it will also add the #ifdef guard
4324 around it. If `file_comment` is set, it will write that before the #ifdef
4325 guard.
4327 def __init__(self, filename, file_comment=None):
4328 super(CHeaderWriter, self).__init__(filename)
4329 guard = self._get_guard()
4330 if file_comment is None:
4331 file_comment = ""
4332 self._ENTER_MSG = self._ENTER_MSG + file_comment \
4333 + "#ifndef %s\n#define %s\n\n" % (guard, guard)
4334 self._EXIT_MSG = self._EXIT_MSG + "#endif // %s\n" % guard
4336 def _get_guard(self):
4337 non_alnum_re = re.compile(r'[^a-zA-Z0-9]')
4338 base = os.path.abspath(self.filename)
4339 while os.path.basename(base) != 'src':
4340 new_base = os.path.dirname(base)
4341 assert new_base != base # Prevent infinite loop.
4342 base = new_base
4343 hpath = os.path.relpath(self.filename, base)
4344 return non_alnum_re.sub('_', hpath).upper() + '_'
4347 class TypeHandler(object):
4348 """This class emits code for a particular type of function."""
4350 _remove_expected_call_re = re.compile(r' EXPECT_CALL.*?;\n', re.S)
4352 def InitFunction(self, func):
4353 """Add or adjust anything type specific for this function."""
4354 if func.GetInfo('needs_size') and not func.name.endswith('Bucket'):
4355 func.AddCmdArg(DataSizeArgument('data_size'))
4357 def NeedsDataTransferFunction(self, func):
4358 """Overriden from TypeHandler."""
4359 return func.num_pointer_args >= 1
4361 def WriteStruct(self, func, f):
4362 """Writes a structure that matches the arguments to a function."""
4363 comment = func.GetInfo('cmd_comment')
4364 if not comment == None:
4365 f.write(comment)
4366 f.write("struct %s {\n" % func.name)
4367 f.write(" typedef %s ValueType;\n" % func.name)
4368 f.write(" static const CommandId kCmdId = k%s;\n" % func.name)
4369 func.WriteCmdArgFlag(f)
4370 func.WriteCmdFlag(f)
4371 f.write("\n")
4372 result = func.GetInfo('result')
4373 if not result == None:
4374 if len(result) == 1:
4375 f.write(" typedef %s Result;\n\n" % result[0])
4376 else:
4377 f.write(" struct Result {\n")
4378 for line in result:
4379 f.write(" %s;\n" % line)
4380 f.write(" };\n\n")
4382 func.WriteCmdComputeSize(f)
4383 func.WriteCmdSetHeader(f)
4384 func.WriteCmdInit(f)
4385 func.WriteCmdSet(f)
4387 f.write(" gpu::CommandHeader header;\n")
4388 args = func.GetCmdArgs()
4389 for arg in args:
4390 f.write(" %s %s;\n" % (arg.cmd_type, arg.name))
4392 consts = func.GetCmdConstants()
4393 for const in consts:
4394 f.write(" static const %s %s = %s;\n" %
4395 (const.cmd_type, const.name, const.GetConstantValue()))
4397 f.write("};\n")
4398 f.write("\n")
4400 size = len(args) * _SIZE_OF_UINT32 + _SIZE_OF_COMMAND_HEADER
4401 f.write("static_assert(sizeof(%s) == %d,\n" % (func.name, size))
4402 f.write(" \"size of %s should be %d\");\n" %
4403 (func.name, size))
4404 f.write("static_assert(offsetof(%s, header) == 0,\n" % func.name)
4405 f.write(" \"offset of %s header should be 0\");\n" %
4406 func.name)
4407 offset = _SIZE_OF_COMMAND_HEADER
4408 for arg in args:
4409 f.write("static_assert(offsetof(%s, %s) == %d,\n" %
4410 (func.name, arg.name, offset))
4411 f.write(" \"offset of %s %s should be %d\");\n" %
4412 (func.name, arg.name, offset))
4413 offset += _SIZE_OF_UINT32
4414 if not result == None and len(result) > 1:
4415 offset = 0;
4416 for line in result:
4417 parts = line.split()
4418 name = parts[-1]
4419 check = """
4420 static_assert(offsetof(%(cmd_name)s::Result, %(field_name)s) == %(offset)d,
4421 "offset of %(cmd_name)s Result %(field_name)s should be "
4422 "%(offset)d");
4424 f.write((check.strip() + "\n") % {
4425 'cmd_name': func.name,
4426 'field_name': name,
4427 'offset': offset,
4429 offset += _SIZE_OF_UINT32
4430 f.write("\n")
4432 def WriteHandlerImplementation(self, func, f):
4433 """Writes the handler implementation for this command."""
4434 if func.IsUnsafe() and func.GetInfo('id_mapping'):
4435 code_no_gen = """ if (!group_->Get%(type)sServiceId(
4436 %(var)s, &%(service_var)s)) {
4437 LOCAL_SET_GL_ERROR(GL_INVALID_OPERATION, "%(func)s", "invalid %(var)s id");
4438 return error::kNoError;
4441 code_gen = """ if (!group_->Get%(type)sServiceId(
4442 %(var)s, &%(service_var)s)) {
4443 if (!group_->bind_generates_resource()) {
4444 LOCAL_SET_GL_ERROR(
4445 GL_INVALID_OPERATION, "%(func)s", "invalid %(var)s id");
4446 return error::kNoError;
4448 GLuint client_id = %(var)s;
4449 gl%(gen_func)s(1, &%(service_var)s);
4450 Create%(type)s(client_id, %(service_var)s);
4453 gen_func = func.GetInfo('gen_func')
4454 for id_type in func.GetInfo('id_mapping'):
4455 service_var = id_type.lower()
4456 if id_type == 'Sync':
4457 service_var = "service_%s" % service_var
4458 f.write(" GLsync %s = 0;\n" % service_var)
4459 if id_type == 'Sampler' and func.IsType('Bind'):
4460 # No error generated when binding a reserved zero sampler.
4461 args = [arg.name for arg in func.GetOriginalArgs()]
4462 f.write(""" if(%(var)s == 0) {
4463 %(func)s(%(args)s);
4464 return error::kNoError;
4465 }""" % { 'var': id_type.lower(),
4466 'func': func.GetGLFunctionName(),
4467 'args': ", ".join(args) })
4468 if gen_func and id_type in gen_func:
4469 f.write(code_gen % { 'type': id_type,
4470 'var': id_type.lower(),
4471 'service_var': service_var,
4472 'func': func.GetGLFunctionName(),
4473 'gen_func': gen_func })
4474 else:
4475 f.write(code_no_gen % { 'type': id_type,
4476 'var': id_type.lower(),
4477 'service_var': service_var,
4478 'func': func.GetGLFunctionName() })
4479 args = []
4480 for arg in func.GetOriginalArgs():
4481 if arg.type == "GLsync":
4482 args.append("service_%s" % arg.name)
4483 elif arg.name.endswith("size") and arg.type == "GLsizei":
4484 args.append("num_%s" % func.GetLastOriginalArg().name)
4485 elif arg.name == "length":
4486 args.append("nullptr")
4487 else:
4488 args.append(arg.name)
4489 f.write(" %s(%s);\n" %
4490 (func.GetGLFunctionName(), ", ".join(args)))
4492 def WriteCmdSizeTest(self, func, f):
4493 """Writes the size test for a command."""
4494 f.write(" EXPECT_EQ(sizeof(cmd), cmd.header.size * 4u);\n")
4496 def WriteFormatTest(self, func, f):
4497 """Writes a format test for a command."""
4498 f.write("TEST_F(GLES2FormatTest, %s) {\n" % func.name)
4499 f.write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
4500 (func.name, func.name))
4501 f.write(" void* next_cmd = cmd.Set(\n")
4502 f.write(" &cmd")
4503 args = func.GetCmdArgs()
4504 for value, arg in enumerate(args):
4505 f.write(",\n static_cast<%s>(%d)" % (arg.type, value + 11))
4506 f.write(");\n")
4507 f.write(" EXPECT_EQ(static_cast<uint32_t>(cmds::%s::kCmdId),\n" %
4508 func.name)
4509 f.write(" cmd.header.command);\n")
4510 func.type_handler.WriteCmdSizeTest(func, f)
4511 for value, arg in enumerate(args):
4512 f.write(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);\n" %
4513 (arg.type, value + 11, arg.name))
4514 f.write(" CheckBytesWrittenMatchesExpectedSize(\n")
4515 f.write(" next_cmd, sizeof(cmd));\n")
4516 f.write("}\n")
4517 f.write("\n")
4519 def WriteImmediateFormatTest(self, func, f):
4520 """Writes a format test for an immediate version of a command."""
4521 pass
4523 def WriteGetDataSizeCode(self, func, f):
4524 """Writes the code to set data_size used in validation"""
4525 pass
4527 def __WriteIdMapping(self, func, f):
4528 """Writes client side / service side ID mapping."""
4529 if not func.IsUnsafe() or not func.GetInfo('id_mapping'):
4530 return
4531 for id_type in func.GetInfo('id_mapping'):
4532 f.write(" group_->Get%sServiceId(%s, &%s);\n" %
4533 (id_type, id_type.lower(), id_type.lower()))
4535 def WriteImmediateHandlerImplementation (self, func, f):
4536 """Writes the handler impl for the immediate version of a command."""
4537 self.__WriteIdMapping(func, f)
4538 f.write(" %s(%s);\n" %
4539 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
4541 def WriteBucketHandlerImplementation (self, func, f):
4542 """Writes the handler impl for the bucket version of a command."""
4543 self.__WriteIdMapping(func, f)
4544 f.write(" %s(%s);\n" %
4545 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
4547 def WriteServiceHandlerFunctionHeader(self, func, f):
4548 """Writes function header for service implementation handlers."""
4549 f.write("""error::Error GLES2DecoderImpl::Handle%(name)s(
4550 uint32_t immediate_data_size, const void* cmd_data) {
4551 """ % {'name': func.name})
4552 if func.IsUnsafe():
4553 f.write("""if (!unsafe_es3_apis_enabled())
4554 return error::kUnknownCommand;
4555 """)
4556 f.write("""const gles2::cmds::%(name)s& c =
4557 *static_cast<const gles2::cmds::%(name)s*>(cmd_data);
4558 (void)c;
4559 """ % {'name': func.name})
4561 def WriteServiceImplementation(self, func, f):
4562 """Writes the service implementation for a command."""
4563 self.WriteServiceHandlerFunctionHeader(func, f)
4564 self.WriteHandlerExtensionCheck(func, f)
4565 self.WriteHandlerDeferReadWrite(func, f);
4566 if len(func.GetOriginalArgs()) > 0:
4567 last_arg = func.GetLastOriginalArg()
4568 all_but_last_arg = func.GetOriginalArgs()[:-1]
4569 for arg in all_but_last_arg:
4570 arg.WriteGetCode(f)
4571 self.WriteGetDataSizeCode(func, f)
4572 last_arg.WriteGetCode(f)
4573 func.WriteHandlerValidation(f)
4574 func.WriteHandlerImplementation(f)
4575 f.write(" return error::kNoError;\n")
4576 f.write("}\n")
4577 f.write("\n")
4579 def WriteImmediateServiceImplementation(self, func, f):
4580 """Writes the service implementation for an immediate version of command."""
4581 self.WriteServiceHandlerFunctionHeader(func, f)
4582 self.WriteHandlerExtensionCheck(func, f)
4583 self.WriteHandlerDeferReadWrite(func, f);
4584 for arg in func.GetOriginalArgs():
4585 if arg.IsPointer():
4586 self.WriteGetDataSizeCode(func, f)
4587 arg.WriteGetCode(f)
4588 func.WriteHandlerValidation(f)
4589 func.WriteHandlerImplementation(f)
4590 f.write(" return error::kNoError;\n")
4591 f.write("}\n")
4592 f.write("\n")
4594 def WriteBucketServiceImplementation(self, func, f):
4595 """Writes the service implementation for a bucket version of command."""
4596 self.WriteServiceHandlerFunctionHeader(func, f)
4597 self.WriteHandlerExtensionCheck(func, f)
4598 self.WriteHandlerDeferReadWrite(func, f);
4599 for arg in func.GetCmdArgs():
4600 arg.WriteGetCode(f)
4601 func.WriteHandlerValidation(f)
4602 func.WriteHandlerImplementation(f)
4603 f.write(" return error::kNoError;\n")
4604 f.write("}\n")
4605 f.write("\n")
4607 def WriteHandlerExtensionCheck(self, func, f):
4608 if func.GetInfo('extension_flag'):
4609 f.write(" if (!features().%s) {\n" % func.GetInfo('extension_flag'))
4610 f.write(" LOCAL_SET_GL_ERROR(GL_INVALID_OPERATION, \"gl%s\","
4611 " \"function not available\");\n" % func.original_name)
4612 f.write(" return error::kNoError;")
4613 f.write(" }\n\n")
4615 def WriteHandlerDeferReadWrite(self, func, f):
4616 """Writes the code to handle deferring reads or writes."""
4617 defer_draws = func.GetInfo('defer_draws')
4618 defer_reads = func.GetInfo('defer_reads')
4619 if defer_draws or defer_reads:
4620 f.write(" error::Error error;\n")
4621 if defer_draws:
4622 f.write(" error = WillAccessBoundFramebufferForDraw();\n")
4623 f.write(" if (error != error::kNoError)\n")
4624 f.write(" return error;\n")
4625 if defer_reads:
4626 f.write(" error = WillAccessBoundFramebufferForRead();\n")
4627 f.write(" if (error != error::kNoError)\n")
4628 f.write(" return error;\n")
4630 def WriteValidUnitTest(self, func, f, test, *extras):
4631 """Writes a valid unit test for the service implementation."""
4632 if func.GetInfo('expectation') == False:
4633 test = self._remove_expected_call_re.sub('', test)
4634 name = func.name
4635 arg_strings = [
4636 arg.GetValidArg(func) \
4637 for arg in func.GetOriginalArgs() if not arg.IsConstant()
4639 gl_arg_strings = [
4640 arg.GetValidGLArg(func) \
4641 for arg in func.GetOriginalArgs()
4643 gl_func_name = func.GetGLTestFunctionName()
4644 vars = {
4645 'name':name,
4646 'gl_func_name': gl_func_name,
4647 'args': ", ".join(arg_strings),
4648 'gl_args': ", ".join(gl_arg_strings),
4650 for extra in extras:
4651 vars.update(extra)
4652 old_test = ""
4653 while (old_test != test):
4654 old_test = test
4655 test = test % vars
4656 f.write(test % vars)
4658 def WriteInvalidUnitTest(self, func, f, test, *extras):
4659 """Writes an invalid unit test for the service implementation."""
4660 if func.IsUnsafe():
4661 return
4662 for invalid_arg_index, invalid_arg in enumerate(func.GetOriginalArgs()):
4663 # Service implementation does not test constants, as they are not part of
4664 # the call in the service side.
4665 if invalid_arg.IsConstant():
4666 continue
4668 num_invalid_values = invalid_arg.GetNumInvalidValues(func)
4669 for value_index in range(0, num_invalid_values):
4670 arg_strings = []
4671 parse_result = "kNoError"
4672 gl_error = None
4673 for arg in func.GetOriginalArgs():
4674 if arg.IsConstant():
4675 continue
4676 if invalid_arg is arg:
4677 (arg_string, parse_result, gl_error) = arg.GetInvalidArg(
4678 value_index)
4679 else:
4680 arg_string = arg.GetValidArg(func)
4681 arg_strings.append(arg_string)
4682 gl_arg_strings = []
4683 for arg in func.GetOriginalArgs():
4684 gl_arg_strings.append("_")
4685 gl_func_name = func.GetGLTestFunctionName()
4686 gl_error_test = ''
4687 if not gl_error == None:
4688 gl_error_test = '\n EXPECT_EQ(%s, GetGLError());' % gl_error
4690 vars = {
4691 'name': func.name,
4692 'arg_index': invalid_arg_index,
4693 'value_index': value_index,
4694 'gl_func_name': gl_func_name,
4695 'args': ", ".join(arg_strings),
4696 'all_but_last_args': ", ".join(arg_strings[:-1]),
4697 'gl_args': ", ".join(gl_arg_strings),
4698 'parse_result': parse_result,
4699 'gl_error_test': gl_error_test,
4701 for extra in extras:
4702 vars.update(extra)
4703 f.write(test % vars)
4705 def WriteServiceUnitTest(self, func, f, *extras):
4706 """Writes the service unit test for a command."""
4708 if func.name == 'Enable':
4709 valid_test = """
4710 TEST_P(%(test_name)s, %(name)sValidArgs) {
4711 SetupExpectationsForEnableDisable(%(gl_args)s, true);
4712 SpecializedSetup<cmds::%(name)s, 0>(true);
4713 cmds::%(name)s cmd;
4714 cmd.Init(%(args)s);"""
4715 elif func.name == 'Disable':
4716 valid_test = """
4717 TEST_P(%(test_name)s, %(name)sValidArgs) {
4718 SetupExpectationsForEnableDisable(%(gl_args)s, false);
4719 SpecializedSetup<cmds::%(name)s, 0>(true);
4720 cmds::%(name)s cmd;
4721 cmd.Init(%(args)s);"""
4722 else:
4723 valid_test = """
4724 TEST_P(%(test_name)s, %(name)sValidArgs) {
4725 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
4726 SpecializedSetup<cmds::%(name)s, 0>(true);
4727 cmds::%(name)s cmd;
4728 cmd.Init(%(args)s);"""
4729 if func.IsUnsafe():
4730 valid_test += """
4731 decoder_->set_unsafe_es3_apis_enabled(true);
4732 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4733 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4734 decoder_->set_unsafe_es3_apis_enabled(false);
4735 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));
4738 else:
4739 valid_test += """
4740 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4741 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4744 self.WriteValidUnitTest(func, f, valid_test, *extras)
4746 if not func.IsUnsafe():
4747 invalid_test = """
4748 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
4749 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
4750 SpecializedSetup<cmds::%(name)s, 0>(false);
4751 cmds::%(name)s cmd;
4752 cmd.Init(%(args)s);
4753 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
4756 self.WriteInvalidUnitTest(func, f, invalid_test, *extras)
4758 def WriteImmediateServiceUnitTest(self, func, f, *extras):
4759 """Writes the service unit test for an immediate command."""
4760 f.write("// TODO(gman): %s\n" % func.name)
4762 def WriteImmediateValidationCode(self, func, f):
4763 """Writes the validation code for an immediate version of a command."""
4764 pass
4766 def WriteBucketServiceUnitTest(self, func, f, *extras):
4767 """Writes the service unit test for a bucket command."""
4768 f.write("// TODO(gman): %s\n" % func.name)
4770 def WriteGLES2ImplementationDeclaration(self, func, f):
4771 """Writes the GLES2 Implemention declaration."""
4772 impl_decl = func.GetInfo('impl_decl')
4773 if impl_decl == None or impl_decl == True:
4774 f.write("%s %s(%s) override;\n" %
4775 (func.return_type, func.original_name,
4776 func.MakeTypedOriginalArgString("")))
4777 f.write("\n")
4779 def WriteGLES2CLibImplementation(self, func, f):
4780 f.write("%s GL_APIENTRY GLES2%s(%s) {\n" %
4781 (func.return_type, func.name,
4782 func.MakeTypedOriginalArgString("")))
4783 result_string = "return "
4784 if func.return_type == "void":
4785 result_string = ""
4786 f.write(" %sgles2::GetGLContext()->%s(%s);\n" %
4787 (result_string, func.original_name,
4788 func.MakeOriginalArgString("")))
4789 f.write("}\n")
4791 def WriteGLES2Header(self, func, f):
4792 """Writes a re-write macro for GLES"""
4793 f.write("#define gl%s GLES2_GET_FUN(%s)\n" %(func.name, func.name))
4795 def WriteClientGLCallLog(self, func, f):
4796 """Writes a logging macro for the client side code."""
4797 comma = ""
4798 if len(func.GetOriginalArgs()):
4799 comma = " << "
4800 f.write(
4801 ' GPU_CLIENT_LOG("[" << GetLogPrefix() << "] gl%s("%s%s << ")");\n' %
4802 (func.original_name, comma, func.MakeLogArgString()))
4804 def WriteClientGLReturnLog(self, func, f):
4805 """Writes the return value logging code."""
4806 if func.return_type != "void":
4807 f.write(' GPU_CLIENT_LOG("return:" << result)\n')
4809 def WriteGLES2ImplementationHeader(self, func, f):
4810 """Writes the GLES2 Implemention."""
4811 self.WriteGLES2ImplementationDeclaration(func, f)
4813 def WriteGLES2TraceImplementationHeader(self, func, f):
4814 """Writes the GLES2 Trace Implemention header."""
4815 f.write("%s %s(%s) override;\n" %
4816 (func.return_type, func.original_name,
4817 func.MakeTypedOriginalArgString("")))
4819 def WriteGLES2TraceImplementation(self, func, f):
4820 """Writes the GLES2 Trace Implemention."""
4821 f.write("%s GLES2TraceImplementation::%s(%s) {\n" %
4822 (func.return_type, func.original_name,
4823 func.MakeTypedOriginalArgString("")))
4824 result_string = "return "
4825 if func.return_type == "void":
4826 result_string = ""
4827 f.write(' TRACE_EVENT_BINARY_EFFICIENT0("gpu", "GLES2Trace::%s");\n' %
4828 func.name)
4829 f.write(" %sgl_->%s(%s);\n" %
4830 (result_string, func.name, func.MakeOriginalArgString("")))
4831 f.write("}\n")
4832 f.write("\n")
4834 def WriteGLES2Implementation(self, func, f):
4835 """Writes the GLES2 Implemention."""
4836 impl_func = func.GetInfo('impl_func')
4837 impl_decl = func.GetInfo('impl_decl')
4838 gen_cmd = func.GetInfo('gen_cmd')
4839 if (func.can_auto_generate and
4840 (impl_func == None or impl_func == True) and
4841 (impl_decl == None or impl_decl == True) and
4842 (gen_cmd == None or gen_cmd == True)):
4843 f.write("%s GLES2Implementation::%s(%s) {\n" %
4844 (func.return_type, func.original_name,
4845 func.MakeTypedOriginalArgString("")))
4846 f.write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
4847 self.WriteClientGLCallLog(func, f)
4848 func.WriteDestinationInitalizationValidation(f)
4849 for arg in func.GetOriginalArgs():
4850 arg.WriteClientSideValidationCode(f, func)
4851 f.write(" helper_->%s(%s);\n" %
4852 (func.name, func.MakeHelperArgString("")))
4853 f.write(" CheckGLError();\n")
4854 self.WriteClientGLReturnLog(func, f)
4855 f.write("}\n")
4856 f.write("\n")
4858 def WriteGLES2InterfaceHeader(self, func, f):
4859 """Writes the GLES2 Interface."""
4860 f.write("virtual %s %s(%s) = 0;\n" %
4861 (func.return_type, func.original_name,
4862 func.MakeTypedOriginalArgString("")))
4864 def WriteMojoGLES2ImplHeader(self, func, f):
4865 """Writes the Mojo GLES2 implementation header."""
4866 f.write("%s %s(%s) override;\n" %
4867 (func.return_type, func.original_name,
4868 func.MakeTypedOriginalArgString("")))
4870 def WriteMojoGLES2Impl(self, func, f):
4871 """Writes the Mojo GLES2 implementation."""
4872 f.write("%s MojoGLES2Impl::%s(%s) {\n" %
4873 (func.return_type, func.original_name,
4874 func.MakeTypedOriginalArgString("")))
4875 extensions = ["CHROMIUM_sync_point", "CHROMIUM_texture_mailbox",
4876 "CHROMIUM_sub_image", "CHROMIUM_miscellaneous",
4877 "occlusion_query_EXT", "CHROMIUM_image",
4878 "CHROMIUM_copy_texture",
4879 "CHROMIUM_pixel_transfer_buffer_object",
4880 "chromium_framebuffer_multisample"]
4881 if func.IsCoreGLFunction() or func.GetInfo("extension") in extensions:
4882 f.write("MojoGLES2MakeCurrent(context_);");
4883 func_return = "gl" + func.original_name + "(" + \
4884 func.MakeOriginalArgString("") + ");"
4885 if func.return_type == "void":
4886 f.write(func_return);
4887 else:
4888 f.write("return " + func_return);
4889 else:
4890 f.write("NOTREACHED() << \"Unimplemented %s.\";\n" %
4891 func.original_name);
4892 if func.return_type != "void":
4893 f.write("return 0;")
4894 f.write("}")
4896 def WriteGLES2InterfaceStub(self, func, f):
4897 """Writes the GLES2 Interface stub declaration."""
4898 f.write("%s %s(%s) override;\n" %
4899 (func.return_type, func.original_name,
4900 func.MakeTypedOriginalArgString("")))
4902 def WriteGLES2InterfaceStubImpl(self, func, f):
4903 """Writes the GLES2 Interface stub declaration."""
4904 args = func.GetOriginalArgs()
4905 arg_string = ", ".join(
4906 ["%s /* %s */" % (arg.type, arg.name) for arg in args])
4907 f.write("%s GLES2InterfaceStub::%s(%s) {\n" %
4908 (func.return_type, func.original_name, arg_string))
4909 if func.return_type != "void":
4910 f.write(" return 0;\n")
4911 f.write("}\n")
4913 def WriteGLES2ImplementationUnitTest(self, func, f):
4914 """Writes the GLES2 Implemention unit test."""
4915 client_test = func.GetInfo('client_test')
4916 if (func.can_auto_generate and
4917 (client_test == None or client_test == True)):
4918 code = """
4919 TEST_F(GLES2ImplementationTest, %(name)s) {
4920 struct Cmds {
4921 cmds::%(name)s cmd;
4923 Cmds expected;
4924 expected.cmd.Init(%(cmd_args)s);
4926 gl_->%(name)s(%(args)s);
4927 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
4930 cmd_arg_strings = [
4931 arg.GetValidClientSideCmdArg(func) for arg in func.GetCmdArgs()
4934 gl_arg_strings = [
4935 arg.GetValidClientSideArg(func) for arg in func.GetOriginalArgs()
4938 f.write(code % {
4939 'name': func.name,
4940 'args': ", ".join(gl_arg_strings),
4941 'cmd_args': ", ".join(cmd_arg_strings),
4944 # Test constants for invalid values, as they are not tested by the
4945 # service.
4946 constants = [arg for arg in func.GetOriginalArgs() if arg.IsConstant()]
4947 if constants:
4948 code = """
4949 TEST_F(GLES2ImplementationTest, %(name)sInvalidConstantArg%(invalid_index)d) {
4950 gl_->%(name)s(%(args)s);
4951 EXPECT_TRUE(NoCommandsWritten());
4952 EXPECT_EQ(%(gl_error)s, CheckError());
4955 for invalid_arg in constants:
4956 gl_arg_strings = []
4957 invalid = invalid_arg.GetInvalidArg(func)
4958 for arg in func.GetOriginalArgs():
4959 if arg is invalid_arg:
4960 gl_arg_strings.append(invalid[0])
4961 else:
4962 gl_arg_strings.append(arg.GetValidClientSideArg(func))
4964 f.write(code % {
4965 'name': func.name,
4966 'invalid_index': func.GetOriginalArgs().index(invalid_arg),
4967 'args': ", ".join(gl_arg_strings),
4968 'gl_error': invalid[2],
4970 else:
4971 if client_test != False:
4972 f.write("// TODO(zmo): Implement unit test for %s\n" % func.name)
4974 def WriteDestinationInitalizationValidation(self, func, f):
4975 """Writes the client side destintion initialization validation."""
4976 for arg in func.GetOriginalArgs():
4977 arg.WriteDestinationInitalizationValidation(f, func)
4979 def WriteTraceEvent(self, func, f):
4980 f.write(' TRACE_EVENT0("gpu", "GLES2Implementation::%s");\n' %
4981 func.original_name)
4983 def WriteImmediateCmdComputeSize(self, func, f):
4984 """Writes the size computation code for the immediate version of a cmd."""
4985 f.write(" static uint32_t ComputeSize(uint32_t size_in_bytes) {\n")
4986 f.write(" return static_cast<uint32_t>(\n")
4987 f.write(" sizeof(ValueType) + // NOLINT\n")
4988 f.write(" RoundSizeToMultipleOfEntries(size_in_bytes));\n")
4989 f.write(" }\n")
4990 f.write("\n")
4992 def WriteImmediateCmdSetHeader(self, func, f):
4993 """Writes the SetHeader function for the immediate version of a cmd."""
4994 f.write(" void SetHeader(uint32_t size_in_bytes) {\n")
4995 f.write(" header.SetCmdByTotalSize<ValueType>(size_in_bytes);\n")
4996 f.write(" }\n")
4997 f.write("\n")
4999 def WriteImmediateCmdInit(self, func, f):
5000 """Writes the Init function for the immediate version of a command."""
5001 raise NotImplementedError(func.name)
5003 def WriteImmediateCmdSet(self, func, f):
5004 """Writes the Set function for the immediate version of a command."""
5005 raise NotImplementedError(func.name)
5007 def WriteCmdHelper(self, func, f):
5008 """Writes the cmd helper definition for a cmd."""
5009 code = """ void %(name)s(%(typed_args)s) {
5010 gles2::cmds::%(name)s* c = GetCmdSpace<gles2::cmds::%(name)s>();
5011 if (c) {
5012 c->Init(%(args)s);
5017 f.write(code % {
5018 "name": func.name,
5019 "typed_args": func.MakeTypedCmdArgString(""),
5020 "args": func.MakeCmdArgString(""),
5023 def WriteImmediateCmdHelper(self, func, f):
5024 """Writes the cmd helper definition for the immediate version of a cmd."""
5025 code = """ void %(name)s(%(typed_args)s) {
5026 const uint32_t s = 0; // TODO(gman): compute correct size
5027 gles2::cmds::%(name)s* c =
5028 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(s);
5029 if (c) {
5030 c->Init(%(args)s);
5035 f.write(code % {
5036 "name": func.name,
5037 "typed_args": func.MakeTypedCmdArgString(""),
5038 "args": func.MakeCmdArgString(""),
5042 class StateSetHandler(TypeHandler):
5043 """Handler for commands that simply set state."""
5045 def WriteHandlerImplementation(self, func, f):
5046 """Overrriden from TypeHandler."""
5047 state_name = func.GetInfo('state')
5048 state = _STATES[state_name]
5049 states = state['states']
5050 args = func.GetOriginalArgs()
5051 for ndx,item in enumerate(states):
5052 code = []
5053 if 'range_checks' in item:
5054 for range_check in item['range_checks']:
5055 code.append("%s %s" % (args[ndx].name, range_check['check']))
5056 if 'nan_check' in item:
5057 # Drivers might generate an INVALID_VALUE error when a value is set
5058 # to NaN. This is allowed behavior under GLES 3.0 section 2.1.1 or
5059 # OpenGL 4.5 section 2.3.4.1 - providing NaN allows undefined results.
5060 # Make this behavior consistent within Chromium, and avoid leaking GL
5061 # errors by generating the error in the command buffer instead of
5062 # letting the GL driver generate it.
5063 code.append("std::isnan(%s)" % args[ndx].name)
5064 if len(code):
5065 f.write(" if (%s) {\n" % " ||\n ".join(code))
5066 f.write(
5067 ' LOCAL_SET_GL_ERROR(GL_INVALID_VALUE,'
5068 ' "%s", "%s out of range");\n' %
5069 (func.name, args[ndx].name))
5070 f.write(" return error::kNoError;\n")
5071 f.write(" }\n")
5072 code = []
5073 for ndx,item in enumerate(states):
5074 code.append("state_.%s != %s" % (item['name'], args[ndx].name))
5075 f.write(" if (%s) {\n" % " ||\n ".join(code))
5076 for ndx,item in enumerate(states):
5077 f.write(" state_.%s = %s;\n" % (item['name'], args[ndx].name))
5078 if 'state_flag' in state:
5079 f.write(" %s = true;\n" % state['state_flag'])
5080 if not func.GetInfo("no_gl"):
5081 for ndx,item in enumerate(states):
5082 if item.get('cached', False):
5083 f.write(" state_.%s = %s;\n" %
5084 (CachedStateName(item), args[ndx].name))
5085 f.write(" %s(%s);\n" %
5086 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
5087 f.write(" }\n")
5089 def WriteServiceUnitTest(self, func, f, *extras):
5090 """Overrriden from TypeHandler."""
5091 TypeHandler.WriteServiceUnitTest(self, func, f, *extras)
5092 state_name = func.GetInfo('state')
5093 state = _STATES[state_name]
5094 states = state['states']
5095 for ndx,item in enumerate(states):
5096 if 'range_checks' in item:
5097 for check_ndx, range_check in enumerate(item['range_checks']):
5098 valid_test = """
5099 TEST_P(%(test_name)s, %(name)sInvalidValue%(ndx)d_%(check_ndx)d) {
5100 SpecializedSetup<cmds::%(name)s, 0>(false);
5101 cmds::%(name)s cmd;
5102 cmd.Init(%(args)s);
5103 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5104 EXPECT_EQ(GL_INVALID_VALUE, GetGLError());
5107 name = func.name
5108 arg_strings = [
5109 arg.GetValidArg(func) \
5110 for arg in func.GetOriginalArgs() if not arg.IsConstant()
5113 arg_strings[ndx] = range_check['test_value']
5114 vars = {
5115 'name': name,
5116 'ndx': ndx,
5117 'check_ndx': check_ndx,
5118 'args': ", ".join(arg_strings),
5120 for extra in extras:
5121 vars.update(extra)
5122 f.write(valid_test % vars)
5123 if 'nan_check' in item:
5124 valid_test = """
5125 TEST_P(%(test_name)s, %(name)sNaNValue%(ndx)d) {
5126 SpecializedSetup<cmds::%(name)s, 0>(false);
5127 cmds::%(name)s cmd;
5128 cmd.Init(%(args)s);
5129 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5130 EXPECT_EQ(GL_INVALID_VALUE, GetGLError());
5133 name = func.name
5134 arg_strings = [
5135 arg.GetValidArg(func) \
5136 for arg in func.GetOriginalArgs() if not arg.IsConstant()
5139 arg_strings[ndx] = 'nanf("")'
5140 vars = {
5141 'name': name,
5142 'ndx': ndx,
5143 'args': ", ".join(arg_strings),
5145 for extra in extras:
5146 vars.update(extra)
5147 f.write(valid_test % vars)
5150 class StateSetRGBAlphaHandler(TypeHandler):
5151 """Handler for commands that simply set state that have rgb/alpha."""
5153 def WriteHandlerImplementation(self, func, f):
5154 """Overrriden from TypeHandler."""
5155 state_name = func.GetInfo('state')
5156 state = _STATES[state_name]
5157 states = state['states']
5158 args = func.GetOriginalArgs()
5159 num_args = len(args)
5160 code = []
5161 for ndx,item in enumerate(states):
5162 code.append("state_.%s != %s" % (item['name'], args[ndx % num_args].name))
5163 f.write(" if (%s) {\n" % " ||\n ".join(code))
5164 for ndx, item in enumerate(states):
5165 f.write(" state_.%s = %s;\n" %
5166 (item['name'], args[ndx % num_args].name))
5167 if 'state_flag' in state:
5168 f.write(" %s = true;\n" % state['state_flag'])
5169 if not func.GetInfo("no_gl"):
5170 f.write(" %s(%s);\n" %
5171 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
5172 f.write(" }\n")
5175 class StateSetFrontBackSeparateHandler(TypeHandler):
5176 """Handler for commands that simply set state that have front/back."""
5178 def WriteHandlerImplementation(self, func, f):
5179 """Overrriden from TypeHandler."""
5180 state_name = func.GetInfo('state')
5181 state = _STATES[state_name]
5182 states = state['states']
5183 args = func.GetOriginalArgs()
5184 face = args[0].name
5185 num_args = len(args)
5186 f.write(" bool changed = false;\n")
5187 for group_ndx, group in enumerate(Grouper(num_args - 1, states)):
5188 f.write(" if (%s == %s || %s == GL_FRONT_AND_BACK) {\n" %
5189 (face, ('GL_FRONT', 'GL_BACK')[group_ndx], face))
5190 code = []
5191 for ndx, item in enumerate(group):
5192 code.append("state_.%s != %s" % (item['name'], args[ndx + 1].name))
5193 f.write(" changed |= %s;\n" % " ||\n ".join(code))
5194 f.write(" }\n")
5195 f.write(" if (changed) {\n")
5196 for group_ndx, group in enumerate(Grouper(num_args - 1, states)):
5197 f.write(" if (%s == %s || %s == GL_FRONT_AND_BACK) {\n" %
5198 (face, ('GL_FRONT', 'GL_BACK')[group_ndx], face))
5199 for ndx, item in enumerate(group):
5200 f.write(" state_.%s = %s;\n" %
5201 (item['name'], args[ndx + 1].name))
5202 f.write(" }\n")
5203 if 'state_flag' in state:
5204 f.write(" %s = true;\n" % state['state_flag'])
5205 if not func.GetInfo("no_gl"):
5206 f.write(" %s(%s);\n" %
5207 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
5208 f.write(" }\n")
5211 class StateSetFrontBackHandler(TypeHandler):
5212 """Handler for commands that simply set state that set both front/back."""
5214 def WriteHandlerImplementation(self, func, f):
5215 """Overrriden from TypeHandler."""
5216 state_name = func.GetInfo('state')
5217 state = _STATES[state_name]
5218 states = state['states']
5219 args = func.GetOriginalArgs()
5220 num_args = len(args)
5221 code = []
5222 for group_ndx, group in enumerate(Grouper(num_args, states)):
5223 for ndx, item in enumerate(group):
5224 code.append("state_.%s != %s" % (item['name'], args[ndx].name))
5225 f.write(" if (%s) {\n" % " ||\n ".join(code))
5226 for group_ndx, group in enumerate(Grouper(num_args, states)):
5227 for ndx, item in enumerate(group):
5228 f.write(" state_.%s = %s;\n" % (item['name'], args[ndx].name))
5229 if 'state_flag' in state:
5230 f.write(" %s = true;\n" % state['state_flag'])
5231 if not func.GetInfo("no_gl"):
5232 f.write(" %s(%s);\n" %
5233 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
5234 f.write(" }\n")
5237 class StateSetNamedParameter(TypeHandler):
5238 """Handler for commands that set a state chosen with an enum parameter."""
5240 def WriteHandlerImplementation(self, func, f):
5241 """Overridden from TypeHandler."""
5242 state_name = func.GetInfo('state')
5243 state = _STATES[state_name]
5244 states = state['states']
5245 args = func.GetOriginalArgs()
5246 num_args = len(args)
5247 assert num_args == 2
5248 f.write(" switch (%s) {\n" % args[0].name)
5249 for state in states:
5250 f.write(" case %s:\n" % state['enum'])
5251 f.write(" if (state_.%s != %s) {\n" %
5252 (state['name'], args[1].name))
5253 f.write(" state_.%s = %s;\n" % (state['name'], args[1].name))
5254 if not func.GetInfo("no_gl"):
5255 f.write(" %s(%s);\n" %
5256 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
5257 f.write(" }\n")
5258 f.write(" break;\n")
5259 f.write(" default:\n")
5260 f.write(" NOTREACHED();\n")
5261 f.write(" }\n")
5264 class CustomHandler(TypeHandler):
5265 """Handler for commands that are auto-generated but require minor tweaks."""
5267 def WriteServiceImplementation(self, func, f):
5268 """Overrriden from TypeHandler."""
5269 pass
5271 def WriteImmediateServiceImplementation(self, func, f):
5272 """Overrriden from TypeHandler."""
5273 pass
5275 def WriteBucketServiceImplementation(self, func, f):
5276 """Overrriden from TypeHandler."""
5277 pass
5279 def WriteServiceUnitTest(self, func, f, *extras):
5280 """Overrriden from TypeHandler."""
5281 f.write("// TODO(gman): %s\n\n" % func.name)
5283 def WriteImmediateServiceUnitTest(self, func, f, *extras):
5284 """Overrriden from TypeHandler."""
5285 f.write("// TODO(gman): %s\n\n" % func.name)
5287 def WriteImmediateCmdGetTotalSize(self, func, f):
5288 """Overrriden from TypeHandler."""
5289 f.write(
5290 " uint32_t total_size = 0; // TODO(gman): get correct size.\n")
5292 def WriteImmediateCmdInit(self, func, f):
5293 """Overrriden from TypeHandler."""
5294 f.write(" void Init(%s) {\n" % func.MakeTypedCmdArgString("_"))
5295 self.WriteImmediateCmdGetTotalSize(func, f)
5296 f.write(" SetHeader(total_size);\n")
5297 args = func.GetCmdArgs()
5298 for arg in args:
5299 f.write(" %s = _%s;\n" % (arg.name, arg.name))
5300 f.write(" }\n")
5301 f.write("\n")
5303 def WriteImmediateCmdSet(self, func, f):
5304 """Overrriden from TypeHandler."""
5305 copy_args = func.MakeCmdArgString("_", False)
5306 f.write(" void* Set(void* cmd%s) {\n" %
5307 func.MakeTypedCmdArgString("_", True))
5308 self.WriteImmediateCmdGetTotalSize(func, f)
5309 f.write(" static_cast<ValueType*>(cmd)->Init(%s);\n" % copy_args)
5310 f.write(" return NextImmediateCmdAddressTotalSize<ValueType>("
5311 "cmd, total_size);\n")
5312 f.write(" }\n")
5313 f.write("\n")
5316 class HandWrittenHandler(CustomHandler):
5317 """Handler for comands where everything must be written by hand."""
5319 def InitFunction(self, func):
5320 """Add or adjust anything type specific for this function."""
5321 CustomHandler.InitFunction(self, func)
5322 func.can_auto_generate = False
5324 def NeedsDataTransferFunction(self, func):
5325 """Overriden from TypeHandler."""
5326 # If specified explicitly, force the data transfer method.
5327 if func.GetInfo('data_transfer_methods'):
5328 return True
5329 return False
5331 def WriteStruct(self, func, f):
5332 """Overrriden from TypeHandler."""
5333 pass
5335 def WriteDocs(self, func, f):
5336 """Overrriden from TypeHandler."""
5337 pass
5339 def WriteServiceUnitTest(self, func, f, *extras):
5340 """Overrriden from TypeHandler."""
5341 f.write("// TODO(gman): %s\n\n" % func.name)
5343 def WriteImmediateServiceUnitTest(self, func, f, *extras):
5344 """Overrriden from TypeHandler."""
5345 f.write("// TODO(gman): %s\n\n" % func.name)
5347 def WriteBucketServiceUnitTest(self, func, f, *extras):
5348 """Overrriden from TypeHandler."""
5349 f.write("// TODO(gman): %s\n\n" % func.name)
5351 def WriteServiceImplementation(self, func, f):
5352 """Overrriden from TypeHandler."""
5353 pass
5355 def WriteImmediateServiceImplementation(self, func, f):
5356 """Overrriden from TypeHandler."""
5357 pass
5359 def WriteBucketServiceImplementation(self, func, f):
5360 """Overrriden from TypeHandler."""
5361 pass
5363 def WriteImmediateCmdHelper(self, func, f):
5364 """Overrriden from TypeHandler."""
5365 pass
5367 def WriteCmdHelper(self, func, f):
5368 """Overrriden from TypeHandler."""
5369 pass
5371 def WriteFormatTest(self, func, f):
5372 """Overrriden from TypeHandler."""
5373 f.write("// TODO(gman): Write test for %s\n" % func.name)
5375 def WriteImmediateFormatTest(self, func, f):
5376 """Overrriden from TypeHandler."""
5377 f.write("// TODO(gman): Write test for %s\n" % func.name)
5380 class ManualHandler(CustomHandler):
5381 """Handler for commands who's handlers must be written by hand."""
5383 def InitFunction(self, func):
5384 """Overrriden from TypeHandler."""
5385 if (func.name == 'CompressedTexImage2DBucket' or
5386 func.name == 'CompressedTexImage3DBucket'):
5387 func.cmd_args = func.cmd_args[:-1]
5388 func.AddCmdArg(Argument('bucket_id', 'GLuint'))
5389 else:
5390 CustomHandler.InitFunction(self, func)
5392 def WriteServiceImplementation(self, func, f):
5393 """Overrriden from TypeHandler."""
5394 pass
5396 def WriteBucketServiceImplementation(self, func, f):
5397 """Overrriden from TypeHandler."""
5398 pass
5400 def WriteServiceUnitTest(self, func, f, *extras):
5401 """Overrriden from TypeHandler."""
5402 f.write("// TODO(gman): %s\n\n" % func.name)
5404 def WriteImmediateServiceUnitTest(self, func, f, *extras):
5405 """Overrriden from TypeHandler."""
5406 f.write("// TODO(gman): %s\n\n" % func.name)
5408 def WriteImmediateServiceImplementation(self, func, f):
5409 """Overrriden from TypeHandler."""
5410 pass
5412 def WriteImmediateFormatTest(self, func, f):
5413 """Overrriden from TypeHandler."""
5414 f.write("// TODO(gman): Implement test for %s\n" % func.name)
5416 def WriteGLES2Implementation(self, func, f):
5417 """Overrriden from TypeHandler."""
5418 if func.GetInfo('impl_func'):
5419 super(ManualHandler, self).WriteGLES2Implementation(func, f)
5421 def WriteGLES2ImplementationHeader(self, func, f):
5422 """Overrriden from TypeHandler."""
5423 f.write("%s %s(%s) override;\n" %
5424 (func.return_type, func.original_name,
5425 func.MakeTypedOriginalArgString("")))
5426 f.write("\n")
5428 def WriteImmediateCmdGetTotalSize(self, func, f):
5429 """Overrriden from TypeHandler."""
5430 # TODO(gman): Move this data to _FUNCTION_INFO?
5431 CustomHandler.WriteImmediateCmdGetTotalSize(self, func, f)
5434 class DataHandler(TypeHandler):
5435 """Handler for glBufferData, glBufferSubData, glTexImage*D, glTexSubImage*D,
5436 glCompressedTexImage*D, glCompressedTexImageSub*D."""
5438 def InitFunction(self, func):
5439 """Overrriden from TypeHandler."""
5440 if (func.name == 'CompressedTexSubImage2DBucket' or
5441 func.name == 'CompressedTexSubImage3DBucket'):
5442 func.cmd_args = func.cmd_args[:-1]
5443 func.AddCmdArg(Argument('bucket_id', 'GLuint'))
5445 def WriteGetDataSizeCode(self, func, f):
5446 """Overrriden from TypeHandler."""
5447 # TODO(gman): Move this data to _FUNCTION_INFO?
5448 name = func.name
5449 if name.endswith("Immediate"):
5450 name = name[0:-9]
5451 if name == 'BufferData' or name == 'BufferSubData':
5452 f.write(" uint32_t data_size = size;\n")
5453 elif (name == 'CompressedTexImage2D' or
5454 name == 'CompressedTexSubImage2D' or
5455 name == 'CompressedTexImage3D' or
5456 name == 'CompressedTexSubImage3D'):
5457 f.write(" uint32_t data_size = imageSize;\n")
5458 elif (name == 'CompressedTexSubImage2DBucket' or
5459 name == 'CompressedTexSubImage3DBucket'):
5460 f.write(" Bucket* bucket = GetBucket(c.bucket_id);\n")
5461 f.write(" uint32_t data_size = bucket->size();\n")
5462 f.write(" GLsizei imageSize = data_size;\n")
5463 elif name == 'TexImage2D' or name == 'TexSubImage2D':
5464 code = """ uint32_t data_size;
5465 if (!GLES2Util::ComputeImageDataSize(
5466 width, height, format, type, unpack_alignment_, &data_size)) {
5467 return error::kOutOfBounds;
5470 f.write(code)
5471 else:
5472 f.write(
5473 "// uint32_t data_size = 0; // TODO(gman): get correct size!\n")
5475 def WriteImmediateCmdGetTotalSize(self, func, f):
5476 """Overrriden from TypeHandler."""
5477 pass
5479 def WriteImmediateCmdInit(self, func, f):
5480 """Overrriden from TypeHandler."""
5481 f.write(" void Init(%s) {\n" % func.MakeTypedCmdArgString("_"))
5482 self.WriteImmediateCmdGetTotalSize(func, f)
5483 f.write(" SetHeader(total_size);\n")
5484 args = func.GetCmdArgs()
5485 for arg in args:
5486 f.write(" %s = _%s;\n" % (arg.name, arg.name))
5487 f.write(" }\n")
5488 f.write("\n")
5490 def WriteImmediateCmdSet(self, func, f):
5491 """Overrriden from TypeHandler."""
5492 copy_args = func.MakeCmdArgString("_", False)
5493 f.write(" void* Set(void* cmd%s) {\n" %
5494 func.MakeTypedCmdArgString("_", True))
5495 self.WriteImmediateCmdGetTotalSize(func, f)
5496 f.write(" static_cast<ValueType*>(cmd)->Init(%s);\n" % copy_args)
5497 f.write(" return NextImmediateCmdAddressTotalSize<ValueType>("
5498 "cmd, total_size);\n")
5499 f.write(" }\n")
5500 f.write("\n")
5502 def WriteImmediateFormatTest(self, func, f):
5503 """Overrriden from TypeHandler."""
5504 # TODO(gman): Remove this exception.
5505 f.write("// TODO(gman): Implement test for %s\n" % func.name)
5506 return
5508 def WriteServiceUnitTest(self, func, f, *extras):
5509 """Overrriden from TypeHandler."""
5510 f.write("// TODO(gman): %s\n\n" % func.name)
5512 def WriteImmediateServiceUnitTest(self, func, f, *extras):
5513 """Overrriden from TypeHandler."""
5514 f.write("// TODO(gman): %s\n\n" % func.name)
5516 def WriteBucketServiceImplementation(self, func, f):
5517 """Overrriden from TypeHandler."""
5518 if ((not func.name == 'CompressedTexSubImage2DBucket') and
5519 (not func.name == 'CompressedTexSubImage3DBucket')):
5520 TypeHandler.WriteBucketServiceImplemenation(self, func, f)
5523 class BindHandler(TypeHandler):
5524 """Handler for glBind___ type functions."""
5526 def WriteServiceUnitTest(self, func, f, *extras):
5527 """Overrriden from TypeHandler."""
5529 if len(func.GetOriginalArgs()) == 1:
5530 valid_test = """
5531 TEST_P(%(test_name)s, %(name)sValidArgs) {
5532 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
5533 SpecializedSetup<cmds::%(name)s, 0>(true);
5534 cmds::%(name)s cmd;
5535 cmd.Init(%(args)s);"""
5536 if func.IsUnsafe():
5537 valid_test += """
5538 decoder_->set_unsafe_es3_apis_enabled(true);
5539 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5540 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5541 decoder_->set_unsafe_es3_apis_enabled(false);
5542 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));
5545 else:
5546 valid_test += """
5547 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5548 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5551 if func.GetInfo("gen_func"):
5552 valid_test += """
5553 TEST_P(%(test_name)s, %(name)sValidArgsNewId) {
5554 EXPECT_CALL(*gl_, %(gl_func_name)s(kNewServiceId));
5555 EXPECT_CALL(*gl_, %(gl_gen_func_name)s(1, _))
5556 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
5557 SpecializedSetup<cmds::%(name)s, 0>(true);
5558 cmds::%(name)s cmd;
5559 cmd.Init(kNewClientId);
5560 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5561 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5562 EXPECT_TRUE(Get%(resource_type)s(kNewClientId) != NULL);
5565 self.WriteValidUnitTest(func, f, valid_test, {
5566 'resource_type': func.GetOriginalArgs()[0].resource_type,
5567 'gl_gen_func_name': func.GetInfo("gen_func"),
5568 }, *extras)
5569 else:
5570 valid_test = """
5571 TEST_P(%(test_name)s, %(name)sValidArgs) {
5572 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
5573 SpecializedSetup<cmds::%(name)s, 0>(true);
5574 cmds::%(name)s cmd;
5575 cmd.Init(%(args)s);"""
5576 if func.IsUnsafe():
5577 valid_test += """
5578 decoder_->set_unsafe_es3_apis_enabled(true);
5579 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5580 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5581 decoder_->set_unsafe_es3_apis_enabled(false);
5582 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));
5585 else:
5586 valid_test += """
5587 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5588 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5591 if func.GetInfo("gen_func"):
5592 valid_test += """
5593 TEST_P(%(test_name)s, %(name)sValidArgsNewId) {
5594 EXPECT_CALL(*gl_,
5595 %(gl_func_name)s(%(gl_args_with_new_id)s));
5596 EXPECT_CALL(*gl_, %(gl_gen_func_name)s(1, _))
5597 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
5598 SpecializedSetup<cmds::%(name)s, 0>(true);
5599 cmds::%(name)s cmd;
5600 cmd.Init(%(args_with_new_id)s);"""
5601 if func.IsUnsafe():
5602 valid_test += """
5603 decoder_->set_unsafe_es3_apis_enabled(true);
5604 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5605 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5606 EXPECT_TRUE(Get%(resource_type)s(kNewClientId) != NULL);
5607 decoder_->set_unsafe_es3_apis_enabled(false);
5608 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));
5611 else:
5612 valid_test += """
5613 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5614 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5615 EXPECT_TRUE(Get%(resource_type)s(kNewClientId) != NULL);
5619 gl_args_with_new_id = []
5620 args_with_new_id = []
5621 for arg in func.GetOriginalArgs():
5622 if hasattr(arg, 'resource_type'):
5623 gl_args_with_new_id.append('kNewServiceId')
5624 args_with_new_id.append('kNewClientId')
5625 else:
5626 gl_args_with_new_id.append(arg.GetValidGLArg(func))
5627 args_with_new_id.append(arg.GetValidArg(func))
5628 self.WriteValidUnitTest(func, f, valid_test, {
5629 'args_with_new_id': ", ".join(args_with_new_id),
5630 'gl_args_with_new_id': ", ".join(gl_args_with_new_id),
5631 'resource_type': func.GetResourceIdArg().resource_type,
5632 'gl_gen_func_name': func.GetInfo("gen_func"),
5633 }, *extras)
5635 invalid_test = """
5636 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
5637 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
5638 SpecializedSetup<cmds::%(name)s, 0>(false);
5639 cmds::%(name)s cmd;
5640 cmd.Init(%(args)s);
5641 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
5644 self.WriteInvalidUnitTest(func, f, invalid_test, *extras)
5646 def WriteGLES2Implementation(self, func, f):
5647 """Writes the GLES2 Implemention."""
5649 impl_func = func.GetInfo('impl_func')
5650 impl_decl = func.GetInfo('impl_decl')
5652 if (func.can_auto_generate and
5653 (impl_func == None or impl_func == True) and
5654 (impl_decl == None or impl_decl == True)):
5656 f.write("%s GLES2Implementation::%s(%s) {\n" %
5657 (func.return_type, func.original_name,
5658 func.MakeTypedOriginalArgString("")))
5659 f.write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
5660 func.WriteDestinationInitalizationValidation(f)
5661 self.WriteClientGLCallLog(func, f)
5662 for arg in func.GetOriginalArgs():
5663 arg.WriteClientSideValidationCode(f, func)
5665 code = """ if (Is%(type)sReservedId(%(id)s)) {
5666 SetGLError(GL_INVALID_OPERATION, "%(name)s\", \"%(id)s reserved id");
5667 return;
5669 %(name)sHelper(%(arg_string)s);
5670 CheckGLError();
5674 name_arg = func.GetResourceIdArg()
5675 f.write(code % {
5676 'name': func.name,
5677 'arg_string': func.MakeOriginalArgString(""),
5678 'id': name_arg.name,
5679 'type': name_arg.resource_type,
5680 'lc_type': name_arg.resource_type.lower(),
5683 def WriteGLES2ImplementationUnitTest(self, func, f):
5684 """Overrriden from TypeHandler."""
5685 client_test = func.GetInfo('client_test')
5686 if client_test == False:
5687 return
5688 code = """
5689 TEST_F(GLES2ImplementationTest, %(name)s) {
5690 struct Cmds {
5691 cmds::%(name)s cmd;
5693 Cmds expected;
5694 expected.cmd.Init(%(cmd_args)s);
5696 gl_->%(name)s(%(args)s);
5697 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));"""
5698 if not func.IsUnsafe():
5699 code += """
5700 ClearCommands();
5701 gl_->%(name)s(%(args)s);
5702 EXPECT_TRUE(NoCommandsWritten());"""
5703 code += """
5706 cmd_arg_strings = [
5707 arg.GetValidClientSideCmdArg(func) for arg in func.GetCmdArgs()
5709 gl_arg_strings = [
5710 arg.GetValidClientSideArg(func) for arg in func.GetOriginalArgs()
5713 f.write(code % {
5714 'name': func.name,
5715 'args': ", ".join(gl_arg_strings),
5716 'cmd_args': ", ".join(cmd_arg_strings),
5720 class GENnHandler(TypeHandler):
5721 """Handler for glGen___ type functions."""
5723 def InitFunction(self, func):
5724 """Overrriden from TypeHandler."""
5725 pass
5727 def WriteGetDataSizeCode(self, func, f):
5728 """Overrriden from TypeHandler."""
5729 code = """ uint32_t data_size;
5730 if (!SafeMultiplyUint32(n, sizeof(GLuint), &data_size)) {
5731 return error::kOutOfBounds;
5734 f.write(code)
5736 def WriteHandlerImplementation (self, func, f):
5737 """Overrriden from TypeHandler."""
5738 f.write(" if (!%sHelper(n, %s)) {\n"
5739 " return error::kInvalidArguments;\n"
5740 " }\n" %
5741 (func.name, func.GetLastOriginalArg().name))
5743 def WriteImmediateHandlerImplementation(self, func, f):
5744 """Overrriden from TypeHandler."""
5745 if func.IsUnsafe():
5746 f.write(""" for (GLsizei ii = 0; ii < n; ++ii) {
5747 if (group_->Get%(resource_name)sServiceId(%(last_arg_name)s[ii], NULL)) {
5748 return error::kInvalidArguments;
5751 scoped_ptr<GLuint[]> service_ids(new GLuint[n]);
5752 gl%(func_name)s(n, service_ids.get());
5753 for (GLsizei ii = 0; ii < n; ++ii) {
5754 group_->Add%(resource_name)sId(%(last_arg_name)s[ii], service_ids[ii]);
5756 """ % { 'func_name': func.original_name,
5757 'last_arg_name': func.GetLastOriginalArg().name,
5758 'resource_name': func.GetInfo('resource_type') })
5759 else:
5760 f.write(" if (!%sHelper(n, %s)) {\n"
5761 " return error::kInvalidArguments;\n"
5762 " }\n" %
5763 (func.original_name, func.GetLastOriginalArg().name))
5765 def WriteGLES2Implementation(self, func, f):
5766 """Overrriden from TypeHandler."""
5767 log_code = (""" GPU_CLIENT_LOG_CODE_BLOCK({
5768 for (GLsizei i = 0; i < n; ++i) {
5769 GPU_CLIENT_LOG(" " << i << ": " << %s[i]);
5771 });""" % func.GetOriginalArgs()[1].name)
5772 args = {
5773 'log_code': log_code,
5774 'return_type': func.return_type,
5775 'name': func.original_name,
5776 'typed_args': func.MakeTypedOriginalArgString(""),
5777 'args': func.MakeOriginalArgString(""),
5778 'resource_types': func.GetInfo('resource_types'),
5779 'count_name': func.GetOriginalArgs()[0].name,
5781 f.write(
5782 "%(return_type)s GLES2Implementation::%(name)s(%(typed_args)s) {\n" %
5783 args)
5784 func.WriteDestinationInitalizationValidation(f)
5785 self.WriteClientGLCallLog(func, f)
5786 for arg in func.GetOriginalArgs():
5787 arg.WriteClientSideValidationCode(f, func)
5788 not_shared = func.GetInfo('not_shared')
5789 if not_shared:
5790 alloc_code = (
5792 """ IdAllocator* id_allocator = GetIdAllocator(id_namespaces::k%s);
5793 for (GLsizei ii = 0; ii < n; ++ii)
5794 %s[ii] = id_allocator->AllocateID();""" %
5795 (func.GetInfo('resource_types'), func.GetOriginalArgs()[1].name))
5796 else:
5797 alloc_code = (""" GetIdHandler(id_namespaces::k%(resource_types)s)->
5798 MakeIds(this, 0, %(args)s);""" % args)
5799 args['alloc_code'] = alloc_code
5801 code = """ GPU_CLIENT_SINGLE_THREAD_CHECK();
5802 %(alloc_code)s
5803 %(name)sHelper(%(args)s);
5804 helper_->%(name)sImmediate(%(args)s);
5805 if (share_group_->bind_generates_resource())
5806 helper_->CommandBufferHelper::Flush();
5807 %(log_code)s
5808 CheckGLError();
5812 f.write(code % args)
5814 def WriteGLES2ImplementationUnitTest(self, func, f):
5815 """Overrriden from TypeHandler."""
5816 code = """
5817 TEST_F(GLES2ImplementationTest, %(name)s) {
5818 GLuint ids[2] = { 0, };
5819 struct Cmds {
5820 cmds::%(name)sImmediate gen;
5821 GLuint data[2];
5823 Cmds expected;
5824 expected.gen.Init(arraysize(ids), &ids[0]);
5825 expected.data[0] = k%(types)sStartId;
5826 expected.data[1] = k%(types)sStartId + 1;
5827 gl_->%(name)s(arraysize(ids), &ids[0]);
5828 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
5829 EXPECT_EQ(k%(types)sStartId, ids[0]);
5830 EXPECT_EQ(k%(types)sStartId + 1, ids[1]);
5833 f.write(code % {
5834 'name': func.name,
5835 'types': func.GetInfo('resource_types'),
5838 def WriteServiceUnitTest(self, func, f, *extras):
5839 """Overrriden from TypeHandler."""
5840 valid_test = """
5841 TEST_P(%(test_name)s, %(name)sValidArgs) {
5842 EXPECT_CALL(*gl_, %(gl_func_name)s(1, _))
5843 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
5844 GetSharedMemoryAs<GLuint*>()[0] = kNewClientId;
5845 SpecializedSetup<cmds::%(name)s, 0>(true);
5846 cmds::%(name)s cmd;
5847 cmd.Init(%(args)s);
5848 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5849 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
5850 if func.IsUnsafe():
5851 valid_test += """
5852 GLuint service_id;
5853 EXPECT_TRUE(Get%(resource_name)sServiceId(kNewClientId, &service_id));
5854 EXPECT_EQ(kNewServiceId, service_id)
5857 else:
5858 valid_test += """
5859 EXPECT_TRUE(Get%(resource_name)s(kNewClientId, &service_id) != NULL);
5862 self.WriteValidUnitTest(func, f, valid_test, {
5863 'resource_name': func.GetInfo('resource_type'),
5864 }, *extras)
5865 invalid_test = """
5866 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
5867 EXPECT_CALL(*gl_, %(gl_func_name)s(_, _)).Times(0);
5868 GetSharedMemoryAs<GLuint*>()[0] = client_%(resource_name)s_id_;
5869 SpecializedSetup<cmds::%(name)s, 0>(false);
5870 cmds::%(name)s cmd;
5871 cmd.Init(%(args)s);
5872 EXPECT_EQ(error::kInvalidArguments, ExecuteCmd(cmd));
5875 self.WriteValidUnitTest(func, f, invalid_test, {
5876 'resource_name': func.GetInfo('resource_type').lower(),
5877 }, *extras)
5879 def WriteImmediateServiceUnitTest(self, func, f, *extras):
5880 """Overrriden from TypeHandler."""
5881 valid_test = """
5882 TEST_P(%(test_name)s, %(name)sValidArgs) {
5883 EXPECT_CALL(*gl_, %(gl_func_name)s(1, _))
5884 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
5885 cmds::%(name)s* cmd = GetImmediateAs<cmds::%(name)s>();
5886 GLuint temp = kNewClientId;
5887 SpecializedSetup<cmds::%(name)s, 0>(true);"""
5888 if func.IsUnsafe():
5889 valid_test += """
5890 decoder_->set_unsafe_es3_apis_enabled(true);"""
5891 valid_test += """
5892 cmd->Init(1, &temp);
5893 EXPECT_EQ(error::kNoError,
5894 ExecuteImmediateCmd(*cmd, sizeof(temp)));
5895 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
5896 if func.IsUnsafe():
5897 valid_test += """
5898 GLuint service_id;
5899 EXPECT_TRUE(Get%(resource_name)sServiceId(kNewClientId, &service_id));
5900 EXPECT_EQ(kNewServiceId, service_id);
5901 decoder_->set_unsafe_es3_apis_enabled(false);
5902 EXPECT_EQ(error::kUnknownCommand,
5903 ExecuteImmediateCmd(*cmd, sizeof(temp)));
5906 else:
5907 valid_test += """
5908 EXPECT_TRUE(Get%(resource_name)s(kNewClientId) != NULL);
5911 self.WriteValidUnitTest(func, f, valid_test, {
5912 'resource_name': func.GetInfo('resource_type'),
5913 }, *extras)
5914 invalid_test = """
5915 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
5916 EXPECT_CALL(*gl_, %(gl_func_name)s(_, _)).Times(0);
5917 cmds::%(name)s* cmd = GetImmediateAs<cmds::%(name)s>();
5918 SpecializedSetup<cmds::%(name)s, 0>(false);
5919 cmd->Init(1, &client_%(resource_name)s_id_);"""
5920 if func.IsUnsafe():
5921 invalid_test += """
5922 decoder_->set_unsafe_es3_apis_enabled(true);
5923 EXPECT_EQ(error::kInvalidArguments,
5924 ExecuteImmediateCmd(*cmd, sizeof(&client_%(resource_name)s_id_)));
5925 decoder_->set_unsafe_es3_apis_enabled(false);
5928 else:
5929 invalid_test += """
5930 EXPECT_EQ(error::kInvalidArguments,
5931 ExecuteImmediateCmd(*cmd, sizeof(&client_%(resource_name)s_id_)));
5934 self.WriteValidUnitTest(func, f, invalid_test, {
5935 'resource_name': func.GetInfo('resource_type').lower(),
5936 }, *extras)
5938 def WriteImmediateCmdComputeSize(self, func, f):
5939 """Overrriden from TypeHandler."""
5940 f.write(" static uint32_t ComputeDataSize(GLsizei n) {\n")
5941 f.write(
5942 " return static_cast<uint32_t>(sizeof(GLuint) * n); // NOLINT\n")
5943 f.write(" }\n")
5944 f.write("\n")
5945 f.write(" static uint32_t ComputeSize(GLsizei n) {\n")
5946 f.write(" return static_cast<uint32_t>(\n")
5947 f.write(" sizeof(ValueType) + ComputeDataSize(n)); // NOLINT\n")
5948 f.write(" }\n")
5949 f.write("\n")
5951 def WriteImmediateCmdSetHeader(self, func, f):
5952 """Overrriden from TypeHandler."""
5953 f.write(" void SetHeader(GLsizei n) {\n")
5954 f.write(" header.SetCmdByTotalSize<ValueType>(ComputeSize(n));\n")
5955 f.write(" }\n")
5956 f.write("\n")
5958 def WriteImmediateCmdInit(self, func, f):
5959 """Overrriden from TypeHandler."""
5960 last_arg = func.GetLastOriginalArg()
5961 f.write(" void Init(%s, %s _%s) {\n" %
5962 (func.MakeTypedCmdArgString("_"),
5963 last_arg.type, last_arg.name))
5964 f.write(" SetHeader(_n);\n")
5965 args = func.GetCmdArgs()
5966 for arg in args:
5967 f.write(" %s = _%s;\n" % (arg.name, arg.name))
5968 f.write(" memcpy(ImmediateDataAddress(this),\n")
5969 f.write(" _%s, ComputeDataSize(_n));\n" % last_arg.name)
5970 f.write(" }\n")
5971 f.write("\n")
5973 def WriteImmediateCmdSet(self, func, f):
5974 """Overrriden from TypeHandler."""
5975 last_arg = func.GetLastOriginalArg()
5976 copy_args = func.MakeCmdArgString("_", False)
5977 f.write(" void* Set(void* cmd%s, %s _%s) {\n" %
5978 (func.MakeTypedCmdArgString("_", True),
5979 last_arg.type, last_arg.name))
5980 f.write(" static_cast<ValueType*>(cmd)->Init(%s, _%s);\n" %
5981 (copy_args, last_arg.name))
5982 f.write(" const uint32_t size = ComputeSize(_n);\n")
5983 f.write(" return NextImmediateCmdAddressTotalSize<ValueType>("
5984 "cmd, size);\n")
5985 f.write(" }\n")
5986 f.write("\n")
5988 def WriteImmediateCmdHelper(self, func, f):
5989 """Overrriden from TypeHandler."""
5990 code = """ void %(name)s(%(typed_args)s) {
5991 const uint32_t size = gles2::cmds::%(name)s::ComputeSize(n);
5992 gles2::cmds::%(name)s* c =
5993 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
5994 if (c) {
5995 c->Init(%(args)s);
6000 f.write(code % {
6001 "name": func.name,
6002 "typed_args": func.MakeTypedOriginalArgString(""),
6003 "args": func.MakeOriginalArgString(""),
6006 def WriteImmediateFormatTest(self, func, f):
6007 """Overrriden from TypeHandler."""
6008 f.write("TEST_F(GLES2FormatTest, %s) {\n" % func.name)
6009 f.write(" static GLuint ids[] = { 12, 23, 34, };\n")
6010 f.write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
6011 (func.name, func.name))
6012 f.write(" void* next_cmd = cmd.Set(\n")
6013 f.write(" &cmd, static_cast<GLsizei>(arraysize(ids)), ids);\n")
6014 f.write(" EXPECT_EQ(static_cast<uint32_t>(cmds::%s::kCmdId),\n" %
6015 func.name)
6016 f.write(" cmd.header.command);\n")
6017 f.write(" EXPECT_EQ(sizeof(cmd) +\n")
6018 f.write(" RoundSizeToMultipleOfEntries(cmd.n * 4u),\n")
6019 f.write(" cmd.header.size * 4u);\n")
6020 f.write(" EXPECT_EQ(static_cast<GLsizei>(arraysize(ids)), cmd.n);\n");
6021 f.write(" CheckBytesWrittenMatchesExpectedSize(\n")
6022 f.write(" next_cmd, sizeof(cmd) +\n")
6023 f.write(" RoundSizeToMultipleOfEntries(arraysize(ids) * 4u));\n")
6024 f.write(" // TODO(gman): Check that ids were inserted;\n")
6025 f.write("}\n")
6026 f.write("\n")
6029 class CreateHandler(TypeHandler):
6030 """Handler for glCreate___ type functions."""
6032 def InitFunction(self, func):
6033 """Overrriden from TypeHandler."""
6034 func.AddCmdArg(Argument("client_id", 'uint32_t'))
6036 def __GetResourceType(self, func):
6037 if func.return_type == "GLsync":
6038 return "Sync"
6039 else:
6040 return func.name[6:] # Create*
6042 def WriteServiceUnitTest(self, func, f, *extras):
6043 """Overrriden from TypeHandler."""
6044 valid_test = """
6045 TEST_P(%(test_name)s, %(name)sValidArgs) {
6046 %(id_type_cast)sEXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s))
6047 .WillOnce(Return(%(const_service_id)s));
6048 SpecializedSetup<cmds::%(name)s, 0>(true);
6049 cmds::%(name)s cmd;
6050 cmd.Init(%(args)s%(comma)skNewClientId);"""
6051 if func.IsUnsafe():
6052 valid_test += """
6053 decoder_->set_unsafe_es3_apis_enabled(true);"""
6054 valid_test += """
6055 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
6056 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
6057 if func.IsUnsafe():
6058 valid_test += """
6059 %(return_type)s service_id = 0;
6060 EXPECT_TRUE(Get%(resource_type)sServiceId(kNewClientId, &service_id));
6061 EXPECT_EQ(%(const_service_id)s, service_id);
6062 decoder_->set_unsafe_es3_apis_enabled(false);
6063 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));
6066 else:
6067 valid_test += """
6068 EXPECT_TRUE(Get%(resource_type)s(kNewClientId));
6071 comma = ""
6072 cmd_arg_count = 0
6073 for arg in func.GetOriginalArgs():
6074 if not arg.IsConstant():
6075 cmd_arg_count += 1
6076 if cmd_arg_count:
6077 comma = ", "
6078 if func.return_type == 'GLsync':
6079 id_type_cast = ("const GLsync kNewServiceIdGLuint = reinterpret_cast"
6080 "<GLsync>(kNewServiceId);\n ")
6081 const_service_id = "kNewServiceIdGLuint"
6082 else:
6083 id_type_cast = ""
6084 const_service_id = "kNewServiceId"
6085 self.WriteValidUnitTest(func, f, valid_test, {
6086 'comma': comma,
6087 'resource_type': self.__GetResourceType(func),
6088 'return_type': func.return_type,
6089 'id_type_cast': id_type_cast,
6090 'const_service_id': const_service_id,
6091 }, *extras)
6092 invalid_test = """
6093 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
6094 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
6095 SpecializedSetup<cmds::%(name)s, 0>(false);
6096 cmds::%(name)s cmd;
6097 cmd.Init(%(args)s%(comma)skNewClientId);
6098 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));%(gl_error_test)s
6101 self.WriteInvalidUnitTest(func, f, invalid_test, {
6102 'comma': comma,
6103 }, *extras)
6105 def WriteHandlerImplementation (self, func, f):
6106 """Overrriden from TypeHandler."""
6107 if func.IsUnsafe():
6108 code = """ uint32_t client_id = c.client_id;
6109 %(return_type)s service_id = 0;
6110 if (group_->Get%(resource_name)sServiceId(client_id, &service_id)) {
6111 return error::kInvalidArguments;
6113 service_id = %(gl_func_name)s(%(gl_args)s);
6114 if (service_id) {
6115 group_->Add%(resource_name)sId(client_id, service_id);
6118 else:
6119 code = """ uint32_t client_id = c.client_id;
6120 if (Get%(resource_name)s(client_id)) {
6121 return error::kInvalidArguments;
6123 %(return_type)s service_id = %(gl_func_name)s(%(gl_args)s);
6124 if (service_id) {
6125 Create%(resource_name)s(client_id, service_id%(gl_args_with_comma)s);
6128 f.write(code % {
6129 'resource_name': self.__GetResourceType(func),
6130 'return_type': func.return_type,
6131 'gl_func_name': func.GetGLFunctionName(),
6132 'gl_args': func.MakeOriginalArgString(""),
6133 'gl_args_with_comma': func.MakeOriginalArgString("", True) })
6135 def WriteGLES2Implementation(self, func, f):
6136 """Overrriden from TypeHandler."""
6137 f.write("%s GLES2Implementation::%s(%s) {\n" %
6138 (func.return_type, func.original_name,
6139 func.MakeTypedOriginalArgString("")))
6140 f.write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
6141 func.WriteDestinationInitalizationValidation(f)
6142 self.WriteClientGLCallLog(func, f)
6143 for arg in func.GetOriginalArgs():
6144 arg.WriteClientSideValidationCode(f, func)
6145 f.write(" GLuint client_id;\n")
6146 if func.return_type == "GLsync":
6147 f.write(
6148 " GetIdHandler(id_namespaces::kSyncs)->\n")
6149 else:
6150 f.write(
6151 " GetIdHandler(id_namespaces::kProgramsAndShaders)->\n")
6152 f.write(" MakeIds(this, 0, 1, &client_id);\n")
6153 f.write(" helper_->%s(%s);\n" %
6154 (func.name, func.MakeCmdArgString("")))
6155 f.write(' GPU_CLIENT_LOG("returned " << client_id);\n')
6156 f.write(" CheckGLError();\n")
6157 if func.return_type == "GLsync":
6158 f.write(" return reinterpret_cast<GLsync>(client_id);\n")
6159 else:
6160 f.write(" return client_id;\n")
6161 f.write("}\n")
6162 f.write("\n")
6165 class DeleteHandler(TypeHandler):
6166 """Handler for glDelete___ single resource type functions."""
6168 def WriteServiceImplementation(self, func, f):
6169 """Overrriden from TypeHandler."""
6170 if func.IsUnsafe():
6171 TypeHandler.WriteServiceImplementation(self, func, f)
6172 # HandleDeleteShader and HandleDeleteProgram are manually written.
6173 pass
6175 def WriteGLES2Implementation(self, func, f):
6176 """Overrriden from TypeHandler."""
6177 f.write("%s GLES2Implementation::%s(%s) {\n" %
6178 (func.return_type, func.original_name,
6179 func.MakeTypedOriginalArgString("")))
6180 f.write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
6181 func.WriteDestinationInitalizationValidation(f)
6182 self.WriteClientGLCallLog(func, f)
6183 for arg in func.GetOriginalArgs():
6184 arg.WriteClientSideValidationCode(f, func)
6185 f.write(
6186 " GPU_CLIENT_DCHECK(%s != 0);\n" % func.GetOriginalArgs()[-1].name)
6187 f.write(" %sHelper(%s);\n" %
6188 (func.original_name, func.GetOriginalArgs()[-1].name))
6189 f.write(" CheckGLError();\n")
6190 f.write("}\n")
6191 f.write("\n")
6193 def WriteHandlerImplementation (self, func, f):
6194 """Overrriden from TypeHandler."""
6195 assert len(func.GetOriginalArgs()) == 1
6196 arg = func.GetOriginalArgs()[0]
6197 if func.IsUnsafe():
6198 f.write(""" %(arg_type)s service_id = 0;
6199 if (group_->Get%(resource_type)sServiceId(%(arg_name)s, &service_id)) {
6200 glDelete%(resource_type)s(service_id);
6201 group_->Remove%(resource_type)sId(%(arg_name)s);
6202 } else {
6203 LOCAL_SET_GL_ERROR(
6204 GL_INVALID_VALUE, "gl%(func_name)s", "unknown %(arg_name)s");
6206 """ % { 'resource_type': func.GetInfo('resource_type'),
6207 'arg_name': arg.name,
6208 'arg_type': arg.type,
6209 'func_name': func.original_name })
6210 else:
6211 f.write(" %sHelper(%s);\n" % (func.original_name, arg.name))
6213 class DELnHandler(TypeHandler):
6214 """Handler for glDelete___ type functions."""
6216 def WriteGetDataSizeCode(self, func, f):
6217 """Overrriden from TypeHandler."""
6218 code = """ uint32_t data_size;
6219 if (!SafeMultiplyUint32(n, sizeof(GLuint), &data_size)) {
6220 return error::kOutOfBounds;
6223 f.write(code)
6225 def WriteGLES2ImplementationUnitTest(self, func, f):
6226 """Overrriden from TypeHandler."""
6227 code = """
6228 TEST_F(GLES2ImplementationTest, %(name)s) {
6229 GLuint ids[2] = { k%(types)sStartId, k%(types)sStartId + 1 };
6230 struct Cmds {
6231 cmds::%(name)sImmediate del;
6232 GLuint data[2];
6234 Cmds expected;
6235 expected.del.Init(arraysize(ids), &ids[0]);
6236 expected.data[0] = k%(types)sStartId;
6237 expected.data[1] = k%(types)sStartId + 1;
6238 gl_->%(name)s(arraysize(ids), &ids[0]);
6239 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
6242 f.write(code % {
6243 'name': func.name,
6244 'types': func.GetInfo('resource_types'),
6247 def WriteServiceUnitTest(self, func, f, *extras):
6248 """Overrriden from TypeHandler."""
6249 valid_test = """
6250 TEST_P(%(test_name)s, %(name)sValidArgs) {
6251 EXPECT_CALL(
6252 *gl_,
6253 %(gl_func_name)s(1, Pointee(kService%(upper_resource_name)sId)))
6254 .Times(1);
6255 GetSharedMemoryAs<GLuint*>()[0] = client_%(resource_name)s_id_;
6256 SpecializedSetup<cmds::%(name)s, 0>(true);
6257 cmds::%(name)s cmd;
6258 cmd.Init(%(args)s);
6259 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
6260 EXPECT_EQ(GL_NO_ERROR, GetGLError());
6261 EXPECT_TRUE(
6262 Get%(upper_resource_name)s(client_%(resource_name)s_id_) == NULL);
6265 self.WriteValidUnitTest(func, f, valid_test, {
6266 'resource_name': func.GetInfo('resource_type').lower(),
6267 'upper_resource_name': func.GetInfo('resource_type'),
6268 }, *extras)
6269 invalid_test = """
6270 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
6271 GetSharedMemoryAs<GLuint*>()[0] = kInvalidClientId;
6272 SpecializedSetup<cmds::%(name)s, 0>(false);
6273 cmds::%(name)s cmd;
6274 cmd.Init(%(args)s);
6275 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
6278 self.WriteValidUnitTest(func, f, invalid_test, *extras)
6280 def WriteImmediateServiceUnitTest(self, func, f, *extras):
6281 """Overrriden from TypeHandler."""
6282 valid_test = """
6283 TEST_P(%(test_name)s, %(name)sValidArgs) {
6284 EXPECT_CALL(
6285 *gl_,
6286 %(gl_func_name)s(1, Pointee(kService%(upper_resource_name)sId)))
6287 .Times(1);
6288 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
6289 SpecializedSetup<cmds::%(name)s, 0>(true);
6290 cmd.Init(1, &client_%(resource_name)s_id_);"""
6291 if func.IsUnsafe():
6292 valid_test += """
6293 decoder_->set_unsafe_es3_apis_enabled(true);"""
6294 valid_test += """
6295 EXPECT_EQ(error::kNoError,
6296 ExecuteImmediateCmd(cmd, sizeof(client_%(resource_name)s_id_)));
6297 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
6298 if func.IsUnsafe():
6299 valid_test += """
6300 EXPECT_FALSE(Get%(upper_resource_name)sServiceId(
6301 client_%(resource_name)s_id_, NULL));
6302 decoder_->set_unsafe_es3_apis_enabled(false);
6303 EXPECT_EQ(error::kUnknownCommand,
6304 ExecuteImmediateCmd(cmd, sizeof(client_%(resource_name)s_id_)));
6307 else:
6308 valid_test += """
6309 EXPECT_TRUE(
6310 Get%(upper_resource_name)s(client_%(resource_name)s_id_) == NULL);
6313 self.WriteValidUnitTest(func, f, valid_test, {
6314 'resource_name': func.GetInfo('resource_type').lower(),
6315 'upper_resource_name': func.GetInfo('resource_type'),
6316 }, *extras)
6317 invalid_test = """
6318 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
6319 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
6320 SpecializedSetup<cmds::%(name)s, 0>(false);
6321 GLuint temp = kInvalidClientId;
6322 cmd.Init(1, &temp);"""
6323 if func.IsUnsafe():
6324 invalid_test += """
6325 decoder_->set_unsafe_es3_apis_enabled(true);
6326 EXPECT_EQ(error::kNoError,
6327 ExecuteImmediateCmd(cmd, sizeof(temp)));
6328 decoder_->set_unsafe_es3_apis_enabled(false);
6329 EXPECT_EQ(error::kUnknownCommand,
6330 ExecuteImmediateCmd(cmd, sizeof(temp)));
6333 else:
6334 invalid_test += """
6335 EXPECT_EQ(error::kNoError,
6336 ExecuteImmediateCmd(cmd, sizeof(temp)));
6339 self.WriteValidUnitTest(func, f, invalid_test, *extras)
6341 def WriteHandlerImplementation (self, func, f):
6342 """Overrriden from TypeHandler."""
6343 f.write(" %sHelper(n, %s);\n" %
6344 (func.name, func.GetLastOriginalArg().name))
6346 def WriteImmediateHandlerImplementation (self, func, f):
6347 """Overrriden from TypeHandler."""
6348 if func.IsUnsafe():
6349 f.write(""" for (GLsizei ii = 0; ii < n; ++ii) {
6350 GLuint service_id = 0;
6351 if (group_->Get%(resource_type)sServiceId(
6352 %(last_arg_name)s[ii], &service_id)) {
6353 glDelete%(resource_type)ss(1, &service_id);
6354 group_->Remove%(resource_type)sId(%(last_arg_name)s[ii]);
6357 """ % { 'resource_type': func.GetInfo('resource_type'),
6358 'last_arg_name': func.GetLastOriginalArg().name })
6359 else:
6360 f.write(" %sHelper(n, %s);\n" %
6361 (func.original_name, func.GetLastOriginalArg().name))
6363 def WriteGLES2Implementation(self, func, f):
6364 """Overrriden from TypeHandler."""
6365 impl_decl = func.GetInfo('impl_decl')
6366 if impl_decl == None or impl_decl == True:
6367 args = {
6368 'return_type': func.return_type,
6369 'name': func.original_name,
6370 'typed_args': func.MakeTypedOriginalArgString(""),
6371 'args': func.MakeOriginalArgString(""),
6372 'resource_type': func.GetInfo('resource_type').lower(),
6373 'count_name': func.GetOriginalArgs()[0].name,
6375 f.write(
6376 "%(return_type)s GLES2Implementation::%(name)s(%(typed_args)s) {\n" %
6377 args)
6378 f.write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
6379 func.WriteDestinationInitalizationValidation(f)
6380 self.WriteClientGLCallLog(func, f)
6381 f.write(""" GPU_CLIENT_LOG_CODE_BLOCK({
6382 for (GLsizei i = 0; i < n; ++i) {
6383 GPU_CLIENT_LOG(" " << i << ": " << %s[i]);
6386 """ % func.GetOriginalArgs()[1].name)
6387 f.write(""" GPU_CLIENT_DCHECK_CODE_BLOCK({
6388 for (GLsizei i = 0; i < n; ++i) {
6389 DCHECK(%s[i] != 0);
6392 """ % func.GetOriginalArgs()[1].name)
6393 for arg in func.GetOriginalArgs():
6394 arg.WriteClientSideValidationCode(f, func)
6395 code = """ %(name)sHelper(%(args)s);
6396 CheckGLError();
6400 f.write(code % args)
6402 def WriteImmediateCmdComputeSize(self, func, f):
6403 """Overrriden from TypeHandler."""
6404 f.write(" static uint32_t ComputeDataSize(GLsizei n) {\n")
6405 f.write(
6406 " return static_cast<uint32_t>(sizeof(GLuint) * n); // NOLINT\n")
6407 f.write(" }\n")
6408 f.write("\n")
6409 f.write(" static uint32_t ComputeSize(GLsizei n) {\n")
6410 f.write(" return static_cast<uint32_t>(\n")
6411 f.write(" sizeof(ValueType) + ComputeDataSize(n)); // NOLINT\n")
6412 f.write(" }\n")
6413 f.write("\n")
6415 def WriteImmediateCmdSetHeader(self, func, f):
6416 """Overrriden from TypeHandler."""
6417 f.write(" void SetHeader(GLsizei n) {\n")
6418 f.write(" header.SetCmdByTotalSize<ValueType>(ComputeSize(n));\n")
6419 f.write(" }\n")
6420 f.write("\n")
6422 def WriteImmediateCmdInit(self, func, f):
6423 """Overrriden from TypeHandler."""
6424 last_arg = func.GetLastOriginalArg()
6425 f.write(" void Init(%s, %s _%s) {\n" %
6426 (func.MakeTypedCmdArgString("_"),
6427 last_arg.type, last_arg.name))
6428 f.write(" SetHeader(_n);\n")
6429 args = func.GetCmdArgs()
6430 for arg in args:
6431 f.write(" %s = _%s;\n" % (arg.name, arg.name))
6432 f.write(" memcpy(ImmediateDataAddress(this),\n")
6433 f.write(" _%s, ComputeDataSize(_n));\n" % last_arg.name)
6434 f.write(" }\n")
6435 f.write("\n")
6437 def WriteImmediateCmdSet(self, func, f):
6438 """Overrriden from TypeHandler."""
6439 last_arg = func.GetLastOriginalArg()
6440 copy_args = func.MakeCmdArgString("_", False)
6441 f.write(" void* Set(void* cmd%s, %s _%s) {\n" %
6442 (func.MakeTypedCmdArgString("_", True),
6443 last_arg.type, last_arg.name))
6444 f.write(" static_cast<ValueType*>(cmd)->Init(%s, _%s);\n" %
6445 (copy_args, last_arg.name))
6446 f.write(" const uint32_t size = ComputeSize(_n);\n")
6447 f.write(" return NextImmediateCmdAddressTotalSize<ValueType>("
6448 "cmd, size);\n")
6449 f.write(" }\n")
6450 f.write("\n")
6452 def WriteImmediateCmdHelper(self, func, f):
6453 """Overrriden from TypeHandler."""
6454 code = """ void %(name)s(%(typed_args)s) {
6455 const uint32_t size = gles2::cmds::%(name)s::ComputeSize(n);
6456 gles2::cmds::%(name)s* c =
6457 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
6458 if (c) {
6459 c->Init(%(args)s);
6464 f.write(code % {
6465 "name": func.name,
6466 "typed_args": func.MakeTypedOriginalArgString(""),
6467 "args": func.MakeOriginalArgString(""),
6470 def WriteImmediateFormatTest(self, func, f):
6471 """Overrriden from TypeHandler."""
6472 f.write("TEST_F(GLES2FormatTest, %s) {\n" % func.name)
6473 f.write(" static GLuint ids[] = { 12, 23, 34, };\n")
6474 f.write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
6475 (func.name, func.name))
6476 f.write(" void* next_cmd = cmd.Set(\n")
6477 f.write(" &cmd, static_cast<GLsizei>(arraysize(ids)), ids);\n")
6478 f.write(" EXPECT_EQ(static_cast<uint32_t>(cmds::%s::kCmdId),\n" %
6479 func.name)
6480 f.write(" cmd.header.command);\n")
6481 f.write(" EXPECT_EQ(sizeof(cmd) +\n")
6482 f.write(" RoundSizeToMultipleOfEntries(cmd.n * 4u),\n")
6483 f.write(" cmd.header.size * 4u);\n")
6484 f.write(" EXPECT_EQ(static_cast<GLsizei>(arraysize(ids)), cmd.n);\n");
6485 f.write(" CheckBytesWrittenMatchesExpectedSize(\n")
6486 f.write(" next_cmd, sizeof(cmd) +\n")
6487 f.write(" RoundSizeToMultipleOfEntries(arraysize(ids) * 4u));\n")
6488 f.write(" // TODO(gman): Check that ids were inserted;\n")
6489 f.write("}\n")
6490 f.write("\n")
6493 class GETnHandler(TypeHandler):
6494 """Handler for GETn for glGetBooleanv, glGetFloatv, ... type functions."""
6496 def NeedsDataTransferFunction(self, func):
6497 """Overriden from TypeHandler."""
6498 return False
6500 def WriteServiceImplementation(self, func, f):
6501 """Overrriden from TypeHandler."""
6502 self.WriteServiceHandlerFunctionHeader(func, f)
6503 last_arg = func.GetLastOriginalArg()
6504 # All except shm_id and shm_offset.
6505 all_but_last_args = func.GetCmdArgs()[:-2]
6506 for arg in all_but_last_args:
6507 arg.WriteGetCode(f)
6509 code = """ typedef cmds::%(func_name)s::Result Result;
6510 GLsizei num_values = 0;
6511 GetNumValuesReturnedForGLGet(pname, &num_values);
6512 Result* result = GetSharedMemoryAs<Result*>(
6513 c.%(last_arg_name)s_shm_id, c.%(last_arg_name)s_shm_offset,
6514 Result::ComputeSize(num_values));
6515 %(last_arg_type)s %(last_arg_name)s = result ? result->GetData() : NULL;
6517 f.write(code % {
6518 'last_arg_type': last_arg.type,
6519 'last_arg_name': last_arg.name,
6520 'func_name': func.name,
6522 func.WriteHandlerValidation(f)
6523 code = """ // Check that the client initialized the result.
6524 if (result->size != 0) {
6525 return error::kInvalidArguments;
6528 shadowed = func.GetInfo('shadowed')
6529 if not shadowed:
6530 f.write(' LOCAL_COPY_REAL_GL_ERRORS_TO_WRAPPER("%s");\n' % func.name)
6531 f.write(code)
6532 func.WriteHandlerImplementation(f)
6533 if shadowed:
6534 code = """ result->SetNumResults(num_values);
6535 return error::kNoError;
6538 else:
6539 code = """ GLenum error = LOCAL_PEEK_GL_ERROR("%(func_name)s");
6540 if (error == GL_NO_ERROR) {
6541 result->SetNumResults(num_values);
6543 return error::kNoError;
6547 f.write(code % {'func_name': func.name})
6549 def WriteGLES2Implementation(self, func, f):
6550 """Overrriden from TypeHandler."""
6551 impl_decl = func.GetInfo('impl_decl')
6552 if impl_decl == None or impl_decl == True:
6553 f.write("%s GLES2Implementation::%s(%s) {\n" %
6554 (func.return_type, func.original_name,
6555 func.MakeTypedOriginalArgString("")))
6556 f.write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
6557 func.WriteDestinationInitalizationValidation(f)
6558 self.WriteClientGLCallLog(func, f)
6559 for arg in func.GetOriginalArgs():
6560 arg.WriteClientSideValidationCode(f, func)
6561 all_but_last_args = func.GetOriginalArgs()[:-1]
6562 args = []
6563 has_length_arg = False
6564 for arg in all_but_last_args:
6565 if arg.type == 'GLsync':
6566 args.append('ToGLuint(%s)' % arg.name)
6567 elif arg.name.endswith('size') and arg.type == 'GLsizei':
6568 continue
6569 elif arg.name == 'length':
6570 has_length_arg = True
6571 continue
6572 else:
6573 args.append(arg.name)
6574 arg_string = ", ".join(args)
6575 all_arg_string = (
6576 ", ".join([
6577 "%s" % arg.name
6578 for arg in func.GetOriginalArgs() if not arg.IsConstant()]))
6579 self.WriteTraceEvent(func, f)
6580 code = """ if (%(func_name)sHelper(%(all_arg_string)s)) {
6581 return;
6583 typedef cmds::%(func_name)s::Result Result;
6584 Result* result = GetResultAs<Result*>();
6585 if (!result) {
6586 return;
6588 result->SetNumResults(0);
6589 helper_->%(func_name)s(%(arg_string)s,
6590 GetResultShmId(), GetResultShmOffset());
6591 WaitForCmd();
6592 result->CopyResult(%(last_arg_name)s);
6593 GPU_CLIENT_LOG_CODE_BLOCK({
6594 for (int32_t i = 0; i < result->GetNumResults(); ++i) {
6595 GPU_CLIENT_LOG(" " << i << ": " << result->GetData()[i]);
6597 });"""
6598 if has_length_arg:
6599 code += """
6600 if (length) {
6601 *length = result->GetNumResults();
6602 }"""
6603 code += """
6604 CheckGLError();
6607 f.write(code % {
6608 'func_name': func.name,
6609 'arg_string': arg_string,
6610 'all_arg_string': all_arg_string,
6611 'last_arg_name': func.GetLastOriginalArg().name,
6614 def WriteGLES2ImplementationUnitTest(self, func, f):
6615 """Writes the GLES2 Implemention unit test."""
6616 code = """
6617 TEST_F(GLES2ImplementationTest, %(name)s) {
6618 struct Cmds {
6619 cmds::%(name)s cmd;
6621 typedef cmds::%(name)s::Result::Type ResultType;
6622 ResultType result = 0;
6623 Cmds expected;
6624 ExpectedMemoryInfo result1 = GetExpectedResultMemory(
6625 sizeof(uint32_t) + sizeof(ResultType));
6626 expected.cmd.Init(%(cmd_args)s, result1.id, result1.offset);
6627 EXPECT_CALL(*command_buffer(), OnFlush())
6628 .WillOnce(SetMemory(result1.ptr, SizedResultHelper<ResultType>(1)))
6629 .RetiresOnSaturation();
6630 gl_->%(name)s(%(args)s, &result);
6631 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
6632 EXPECT_EQ(static_cast<ResultType>(1), result);
6635 first_cmd_arg = func.GetCmdArgs()[0].GetValidNonCachedClientSideCmdArg(func)
6636 if not first_cmd_arg:
6637 return
6639 first_gl_arg = func.GetOriginalArgs()[0].GetValidNonCachedClientSideArg(
6640 func)
6642 cmd_arg_strings = [first_cmd_arg]
6643 for arg in func.GetCmdArgs()[1:-2]:
6644 cmd_arg_strings.append(arg.GetValidClientSideCmdArg(func))
6645 gl_arg_strings = [first_gl_arg]
6646 for arg in func.GetOriginalArgs()[1:-1]:
6647 gl_arg_strings.append(arg.GetValidClientSideArg(func))
6649 f.write(code % {
6650 'name': func.name,
6651 'args': ", ".join(gl_arg_strings),
6652 'cmd_args': ", ".join(cmd_arg_strings),
6655 def WriteServiceUnitTest(self, func, f, *extras):
6656 """Overrriden from TypeHandler."""
6657 valid_test = """
6658 TEST_P(%(test_name)s, %(name)sValidArgs) {
6659 EXPECT_CALL(*gl_, GetError())
6660 .WillRepeatedly(Return(GL_NO_ERROR));
6661 SpecializedSetup<cmds::%(name)s, 0>(true);
6662 typedef cmds::%(name)s::Result Result;
6663 Result* result = static_cast<Result*>(shared_memory_address_);
6664 EXPECT_CALL(*gl_, %(gl_func_name)s(%(local_gl_args)s));
6665 result->size = 0;
6666 cmds::%(name)s cmd;
6667 cmd.Init(%(cmd_args)s);"""
6668 if func.IsUnsafe():
6669 valid_test += """
6670 decoder_->set_unsafe_es3_apis_enabled(true);"""
6671 valid_test += """
6672 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
6673 EXPECT_EQ(decoder_->GetGLES2Util()->GLGetNumValuesReturned(
6674 %(valid_pname)s),
6675 result->GetNumResults());
6676 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
6677 if func.IsUnsafe():
6678 valid_test += """
6679 decoder_->set_unsafe_es3_apis_enabled(false);
6680 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));"""
6681 valid_test += """
6684 gl_arg_strings = []
6685 cmd_arg_strings = []
6686 valid_pname = ''
6687 for arg in func.GetOriginalArgs()[:-1]:
6688 if arg.name == 'length':
6689 gl_arg_value = 'nullptr'
6690 elif arg.name.endswith('size'):
6691 gl_arg_value = ("decoder_->GetGLES2Util()->GLGetNumValuesReturned(%s)" %
6692 valid_pname)
6693 elif arg.type == 'GLsync':
6694 gl_arg_value = 'reinterpret_cast<GLsync>(kServiceSyncId)'
6695 else:
6696 gl_arg_value = arg.GetValidGLArg(func)
6697 gl_arg_strings.append(gl_arg_value)
6698 if arg.name == 'pname':
6699 valid_pname = gl_arg_value
6700 if arg.name.endswith('size') or arg.name == 'length':
6701 continue
6702 if arg.type == 'GLsync':
6703 arg_value = 'client_sync_id_'
6704 else:
6705 arg_value = arg.GetValidArg(func)
6706 cmd_arg_strings.append(arg_value)
6707 if func.GetInfo('gl_test_func') == 'glGetIntegerv':
6708 gl_arg_strings.append("_")
6709 else:
6710 gl_arg_strings.append("result->GetData()")
6711 cmd_arg_strings.append("shared_memory_id_")
6712 cmd_arg_strings.append("shared_memory_offset_")
6714 self.WriteValidUnitTest(func, f, valid_test, {
6715 'local_gl_args': ", ".join(gl_arg_strings),
6716 'cmd_args': ", ".join(cmd_arg_strings),
6717 'valid_pname': valid_pname,
6718 }, *extras)
6720 if not func.IsUnsafe():
6721 invalid_test = """
6722 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
6723 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
6724 SpecializedSetup<cmds::%(name)s, 0>(false);
6725 cmds::%(name)s::Result* result =
6726 static_cast<cmds::%(name)s::Result*>(shared_memory_address_);
6727 result->size = 0;
6728 cmds::%(name)s cmd;
6729 cmd.Init(%(args)s);
6730 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));
6731 EXPECT_EQ(0u, result->size);%(gl_error_test)s
6734 self.WriteInvalidUnitTest(func, f, invalid_test, *extras)
6736 class ArrayArgTypeHandler(TypeHandler):
6737 """Base class for type handlers that handle args that are arrays"""
6739 def GetArrayType(self, func):
6740 """Returns the type of the element in the element array being PUT to."""
6741 for arg in func.GetOriginalArgs():
6742 if arg.IsPointer():
6743 element_type = arg.GetPointedType()
6744 return element_type
6746 # Special case: array type handler is used for a function that is forwarded
6747 # to the actual array type implementation
6748 element_type = func.GetOriginalArgs()[-1].type
6749 assert all(arg.type == element_type \
6750 for arg in func.GetOriginalArgs()[-self.GetArrayCount(func):])
6751 return element_type
6753 def GetArrayCount(self, func):
6754 """Returns the count of the elements in the array being PUT to."""
6755 return func.GetInfo('count')
6757 class PUTHandler(ArrayArgTypeHandler):
6758 """Handler for glTexParameter_v, glVertexAttrib_v functions."""
6760 def WriteServiceUnitTest(self, func, f, *extras):
6761 """Writes the service unit test for a command."""
6762 expected_call = "EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));"
6763 if func.GetInfo("first_element_only"):
6764 gl_arg_strings = [
6765 arg.GetValidGLArg(func) for arg in func.GetOriginalArgs()
6767 gl_arg_strings[-1] = "*" + gl_arg_strings[-1]
6768 expected_call = ("EXPECT_CALL(*gl_, %%(gl_func_name)s(%s));" %
6769 ", ".join(gl_arg_strings))
6770 valid_test = """
6771 TEST_P(%(test_name)s, %(name)sValidArgs) {
6772 SpecializedSetup<cmds::%(name)s, 0>(true);
6773 cmds::%(name)s cmd;
6774 cmd.Init(%(args)s);
6775 GetSharedMemoryAs<%(data_type)s*>()[0] = %(data_value)s;
6776 %(expected_call)s
6777 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
6778 EXPECT_EQ(GL_NO_ERROR, GetGLError());
6781 extra = {
6782 'data_type': self.GetArrayType(func),
6783 'data_value': func.GetInfo('data_value') or '0',
6784 'expected_call': expected_call,
6786 self.WriteValidUnitTest(func, f, valid_test, extra, *extras)
6788 invalid_test = """
6789 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
6790 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
6791 SpecializedSetup<cmds::%(name)s, 0>(false);
6792 cmds::%(name)s cmd;
6793 cmd.Init(%(args)s);
6794 GetSharedMemoryAs<%(data_type)s*>()[0] = %(data_value)s;
6795 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
6798 self.WriteInvalidUnitTest(func, f, invalid_test, extra, *extras)
6800 def WriteImmediateServiceUnitTest(self, func, f, *extras):
6801 """Writes the service unit test for a command."""
6802 valid_test = """
6803 TEST_P(%(test_name)s, %(name)sValidArgs) {
6804 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
6805 SpecializedSetup<cmds::%(name)s, 0>(true);
6806 %(data_type)s temp[%(data_count)s] = { %(data_value)s, };
6807 cmd.Init(%(gl_args)s, &temp[0]);
6808 EXPECT_CALL(
6809 *gl_,
6810 %(gl_func_name)s(%(gl_args)s, %(data_ref)sreinterpret_cast<
6811 %(data_type)s*>(ImmediateDataAddress(&cmd))));"""
6812 if func.IsUnsafe():
6813 valid_test += """
6814 decoder_->set_unsafe_es3_apis_enabled(true);"""
6815 valid_test += """
6816 EXPECT_EQ(error::kNoError,
6817 ExecuteImmediateCmd(cmd, sizeof(temp)));
6818 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
6819 if func.IsUnsafe():
6820 valid_test += """
6821 decoder_->set_unsafe_es3_apis_enabled(false);
6822 EXPECT_EQ(error::kUnknownCommand,
6823 ExecuteImmediateCmd(cmd, sizeof(temp)));"""
6824 valid_test += """
6827 gl_arg_strings = [
6828 arg.GetValidGLArg(func) for arg in func.GetOriginalArgs()[0:-1]
6830 gl_any_strings = ["_"] * len(gl_arg_strings)
6832 extra = {
6833 'data_ref': ("*" if func.GetInfo('first_element_only') else ""),
6834 'data_type': self.GetArrayType(func),
6835 'data_count': self.GetArrayCount(func),
6836 'data_value': func.GetInfo('data_value') or '0',
6837 'gl_args': ", ".join(gl_arg_strings),
6838 'gl_any_args': ", ".join(gl_any_strings),
6840 self.WriteValidUnitTest(func, f, valid_test, extra, *extras)
6842 invalid_test = """
6843 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
6844 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();"""
6845 if func.IsUnsafe():
6846 invalid_test += """
6847 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_any_args)s, _)).Times(1);
6849 else:
6850 invalid_test += """
6851 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_any_args)s, _)).Times(0);
6853 invalid_test += """
6854 SpecializedSetup<cmds::%(name)s, 0>(false);
6855 %(data_type)s temp[%(data_count)s] = { %(data_value)s, };
6856 cmd.Init(%(all_but_last_args)s, &temp[0]);"""
6857 if func.IsUnsafe():
6858 invalid_test += """
6859 decoder_->set_unsafe_es3_apis_enabled(true);
6860 EXPECT_EQ(error::%(parse_result)s,
6861 ExecuteImmediateCmd(cmd, sizeof(temp)));
6862 decoder_->set_unsafe_es3_apis_enabled(false);
6865 else:
6866 invalid_test += """
6867 EXPECT_EQ(error::%(parse_result)s,
6868 ExecuteImmediateCmd(cmd, sizeof(temp)));
6869 %(gl_error_test)s
6872 self.WriteInvalidUnitTest(func, f, invalid_test, extra, *extras)
6874 def WriteGetDataSizeCode(self, func, f):
6875 """Overrriden from TypeHandler."""
6876 code = """ uint32_t data_size;
6877 if (!ComputeDataSize(1, sizeof(%s), %d, &data_size)) {
6878 return error::kOutOfBounds;
6881 f.write(code % (self.GetArrayType(func), self.GetArrayCount(func)))
6882 if func.IsImmediate():
6883 f.write(" if (data_size > immediate_data_size) {\n")
6884 f.write(" return error::kOutOfBounds;\n")
6885 f.write(" }\n")
6887 def __NeedsToCalcDataCount(self, func):
6888 use_count_func = func.GetInfo('use_count_func')
6889 return use_count_func != None and use_count_func != False
6891 def WriteGLES2Implementation(self, func, f):
6892 """Overrriden from TypeHandler."""
6893 impl_func = func.GetInfo('impl_func')
6894 if (impl_func != None and impl_func != True):
6895 return;
6896 f.write("%s GLES2Implementation::%s(%s) {\n" %
6897 (func.return_type, func.original_name,
6898 func.MakeTypedOriginalArgString("")))
6899 f.write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
6900 func.WriteDestinationInitalizationValidation(f)
6901 self.WriteClientGLCallLog(func, f)
6903 if self.__NeedsToCalcDataCount(func):
6904 f.write(" size_t count = GLES2Util::Calc%sDataCount(%s);\n" %
6905 (func.name, func.GetOriginalArgs()[0].name))
6906 f.write(" DCHECK_LE(count, %du);\n" % self.GetArrayCount(func))
6907 else:
6908 f.write(" size_t count = %d;" % self.GetArrayCount(func))
6909 f.write(" for (size_t ii = 0; ii < count; ++ii)\n")
6910 f.write(' GPU_CLIENT_LOG("value[" << ii << "]: " << %s[ii]);\n' %
6911 func.GetLastOriginalArg().name)
6912 for arg in func.GetOriginalArgs():
6913 arg.WriteClientSideValidationCode(f, func)
6914 f.write(" helper_->%sImmediate(%s);\n" %
6915 (func.name, func.MakeOriginalArgString("")))
6916 f.write(" CheckGLError();\n")
6917 f.write("}\n")
6918 f.write("\n")
6920 def WriteGLES2ImplementationUnitTest(self, func, f):
6921 """Writes the GLES2 Implemention unit test."""
6922 client_test = func.GetInfo('client_test')
6923 if (client_test != None and client_test != True):
6924 return;
6925 code = """
6926 TEST_F(GLES2ImplementationTest, %(name)s) {
6927 %(type)s data[%(count)d] = {0};
6928 struct Cmds {
6929 cmds::%(name)sImmediate cmd;
6930 %(type)s data[%(count)d];
6933 for (int jj = 0; jj < %(count)d; ++jj) {
6934 data[jj] = static_cast<%(type)s>(jj);
6936 Cmds expected;
6937 expected.cmd.Init(%(cmd_args)s, &data[0]);
6938 gl_->%(name)s(%(args)s, &data[0]);
6939 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
6942 cmd_arg_strings = [
6943 arg.GetValidClientSideCmdArg(func) for arg in func.GetCmdArgs()[0:-2]
6945 gl_arg_strings = [
6946 arg.GetValidClientSideArg(func) for arg in func.GetOriginalArgs()[0:-1]
6949 f.write(code % {
6950 'name': func.name,
6951 'type': self.GetArrayType(func),
6952 'count': self.GetArrayCount(func),
6953 'args': ", ".join(gl_arg_strings),
6954 'cmd_args': ", ".join(cmd_arg_strings),
6957 def WriteImmediateCmdComputeSize(self, func, f):
6958 """Overrriden from TypeHandler."""
6959 f.write(" static uint32_t ComputeDataSize() {\n")
6960 f.write(" return static_cast<uint32_t>(\n")
6961 f.write(" sizeof(%s) * %d);\n" %
6962 (self.GetArrayType(func), self.GetArrayCount(func)))
6963 f.write(" }\n")
6964 f.write("\n")
6965 if self.__NeedsToCalcDataCount(func):
6966 f.write(" static uint32_t ComputeEffectiveDataSize(%s %s) {\n" %
6967 (func.GetOriginalArgs()[0].type,
6968 func.GetOriginalArgs()[0].name))
6969 f.write(" return static_cast<uint32_t>(\n")
6970 f.write(" sizeof(%s) * GLES2Util::Calc%sDataCount(%s));\n" %
6971 (self.GetArrayType(func), func.original_name,
6972 func.GetOriginalArgs()[0].name))
6973 f.write(" }\n")
6974 f.write("\n")
6975 f.write(" static uint32_t ComputeSize() {\n")
6976 f.write(" return static_cast<uint32_t>(\n")
6977 f.write(
6978 " sizeof(ValueType) + ComputeDataSize());\n")
6979 f.write(" }\n")
6980 f.write("\n")
6982 def WriteImmediateCmdSetHeader(self, func, f):
6983 """Overrriden from TypeHandler."""
6984 f.write(" void SetHeader() {\n")
6985 f.write(
6986 " header.SetCmdByTotalSize<ValueType>(ComputeSize());\n")
6987 f.write(" }\n")
6988 f.write("\n")
6990 def WriteImmediateCmdInit(self, func, f):
6991 """Overrriden from TypeHandler."""
6992 last_arg = func.GetLastOriginalArg()
6993 f.write(" void Init(%s, %s _%s) {\n" %
6994 (func.MakeTypedCmdArgString("_"),
6995 last_arg.type, last_arg.name))
6996 f.write(" SetHeader();\n")
6997 args = func.GetCmdArgs()
6998 for arg in args:
6999 f.write(" %s = _%s;\n" % (arg.name, arg.name))
7000 f.write(" memcpy(ImmediateDataAddress(this),\n")
7001 if self.__NeedsToCalcDataCount(func):
7002 f.write(" _%s, ComputeEffectiveDataSize(%s));" %
7003 (last_arg.name, func.GetOriginalArgs()[0].name))
7004 f.write("""
7005 DCHECK_GE(ComputeDataSize(), ComputeEffectiveDataSize(%(arg)s));
7006 char* pointer = reinterpret_cast<char*>(ImmediateDataAddress(this)) +
7007 ComputeEffectiveDataSize(%(arg)s);
7008 memset(pointer, 0, ComputeDataSize() - ComputeEffectiveDataSize(%(arg)s));
7009 """ % { 'arg': func.GetOriginalArgs()[0].name, })
7010 else:
7011 f.write(" _%s, ComputeDataSize());\n" % last_arg.name)
7012 f.write(" }\n")
7013 f.write("\n")
7015 def WriteImmediateCmdSet(self, func, f):
7016 """Overrriden from TypeHandler."""
7017 last_arg = func.GetLastOriginalArg()
7018 copy_args = func.MakeCmdArgString("_", False)
7019 f.write(" void* Set(void* cmd%s, %s _%s) {\n" %
7020 (func.MakeTypedCmdArgString("_", True),
7021 last_arg.type, last_arg.name))
7022 f.write(" static_cast<ValueType*>(cmd)->Init(%s, _%s);\n" %
7023 (copy_args, last_arg.name))
7024 f.write(" const uint32_t size = ComputeSize();\n")
7025 f.write(" return NextImmediateCmdAddressTotalSize<ValueType>("
7026 "cmd, size);\n")
7027 f.write(" }\n")
7028 f.write("\n")
7030 def WriteImmediateCmdHelper(self, func, f):
7031 """Overrriden from TypeHandler."""
7032 code = """ void %(name)s(%(typed_args)s) {
7033 const uint32_t size = gles2::cmds::%(name)s::ComputeSize();
7034 gles2::cmds::%(name)s* c =
7035 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
7036 if (c) {
7037 c->Init(%(args)s);
7042 f.write(code % {
7043 "name": func.name,
7044 "typed_args": func.MakeTypedOriginalArgString(""),
7045 "args": func.MakeOriginalArgString(""),
7048 def WriteImmediateFormatTest(self, func, f):
7049 """Overrriden from TypeHandler."""
7050 f.write("TEST_F(GLES2FormatTest, %s) {\n" % func.name)
7051 f.write(" const int kSomeBaseValueToTestWith = 51;\n")
7052 f.write(" static %s data[] = {\n" % self.GetArrayType(func))
7053 for v in range(0, self.GetArrayCount(func)):
7054 f.write(" static_cast<%s>(kSomeBaseValueToTestWith + %d),\n" %
7055 (self.GetArrayType(func), v))
7056 f.write(" };\n")
7057 f.write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
7058 (func.name, func.name))
7059 f.write(" void* next_cmd = cmd.Set(\n")
7060 f.write(" &cmd")
7061 args = func.GetCmdArgs()
7062 for value, arg in enumerate(args):
7063 f.write(",\n static_cast<%s>(%d)" % (arg.type, value + 11))
7064 f.write(",\n data);\n")
7065 args = func.GetCmdArgs()
7066 f.write(" EXPECT_EQ(static_cast<uint32_t>(cmds::%s::kCmdId),\n"
7067 % func.name)
7068 f.write(" cmd.header.command);\n")
7069 f.write(" EXPECT_EQ(sizeof(cmd) +\n")
7070 f.write(" RoundSizeToMultipleOfEntries(sizeof(data)),\n")
7071 f.write(" cmd.header.size * 4u);\n")
7072 for value, arg in enumerate(args):
7073 f.write(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);\n" %
7074 (arg.type, value + 11, arg.name))
7075 f.write(" CheckBytesWrittenMatchesExpectedSize(\n")
7076 f.write(" next_cmd, sizeof(cmd) +\n")
7077 f.write(" RoundSizeToMultipleOfEntries(sizeof(data)));\n")
7078 f.write(" // TODO(gman): Check that data was inserted;\n")
7079 f.write("}\n")
7080 f.write("\n")
7083 class PUTnHandler(ArrayArgTypeHandler):
7084 """Handler for PUTn 'glUniform__v' type functions."""
7086 def WriteServiceUnitTest(self, func, f, *extras):
7087 """Overridden from TypeHandler."""
7088 ArrayArgTypeHandler.WriteServiceUnitTest(self, func, f, *extras)
7090 valid_test = """
7091 TEST_P(%(test_name)s, %(name)sValidArgsCountTooLarge) {
7092 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
7093 SpecializedSetup<cmds::%(name)s, 0>(true);
7094 cmds::%(name)s cmd;
7095 cmd.Init(%(args)s);
7096 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
7097 EXPECT_EQ(GL_NO_ERROR, GetGLError());
7100 gl_arg_strings = []
7101 arg_strings = []
7102 for count, arg in enumerate(func.GetOriginalArgs()):
7103 # hardcoded to match unit tests.
7104 if count == 0:
7105 # the location of the second element of the 2nd uniform.
7106 # defined in GLES2DecoderBase::SetupShaderForUniform
7107 gl_arg_strings.append("3")
7108 arg_strings.append("ProgramManager::MakeFakeLocation(1, 1)")
7109 elif count == 1:
7110 # the number of elements that gl will be called with.
7111 gl_arg_strings.append("3")
7112 # the number of elements requested in the command.
7113 arg_strings.append("5")
7114 else:
7115 gl_arg_strings.append(arg.GetValidGLArg(func))
7116 if not arg.IsConstant():
7117 arg_strings.append(arg.GetValidArg(func))
7118 extra = {
7119 'gl_args': ", ".join(gl_arg_strings),
7120 'args': ", ".join(arg_strings),
7122 self.WriteValidUnitTest(func, f, valid_test, extra, *extras)
7124 def WriteImmediateServiceUnitTest(self, func, f, *extras):
7125 """Overridden from TypeHandler."""
7126 valid_test = """
7127 TEST_P(%(test_name)s, %(name)sValidArgs) {
7128 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
7129 EXPECT_CALL(
7130 *gl_,
7131 %(gl_func_name)s(%(gl_args)s,
7132 reinterpret_cast<%(data_type)s*>(ImmediateDataAddress(&cmd))));
7133 SpecializedSetup<cmds::%(name)s, 0>(true);
7134 %(data_type)s temp[%(data_count)s * 2] = { 0, };
7135 cmd.Init(%(args)s, &temp[0]);"""
7136 if func.IsUnsafe():
7137 valid_test += """
7138 decoder_->set_unsafe_es3_apis_enabled(true);"""
7139 valid_test += """
7140 EXPECT_EQ(error::kNoError,
7141 ExecuteImmediateCmd(cmd, sizeof(temp)));
7142 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
7143 if func.IsUnsafe():
7144 valid_test += """
7145 decoder_->set_unsafe_es3_apis_enabled(false);
7146 EXPECT_EQ(error::kUnknownCommand,
7147 ExecuteImmediateCmd(cmd, sizeof(temp)));"""
7148 valid_test += """
7151 gl_arg_strings = []
7152 gl_any_strings = []
7153 arg_strings = []
7154 for arg in func.GetOriginalArgs()[0:-1]:
7155 gl_arg_strings.append(arg.GetValidGLArg(func))
7156 gl_any_strings.append("_")
7157 if not arg.IsConstant():
7158 arg_strings.append(arg.GetValidArg(func))
7159 extra = {
7160 'data_type': self.GetArrayType(func),
7161 'data_count': self.GetArrayCount(func),
7162 'args': ", ".join(arg_strings),
7163 'gl_args': ", ".join(gl_arg_strings),
7164 'gl_any_args': ", ".join(gl_any_strings),
7166 self.WriteValidUnitTest(func, f, valid_test, extra, *extras)
7168 invalid_test = """
7169 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
7170 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
7171 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_any_args)s, _)).Times(0);
7172 SpecializedSetup<cmds::%(name)s, 0>(false);
7173 %(data_type)s temp[%(data_count)s * 2] = { 0, };
7174 cmd.Init(%(all_but_last_args)s, &temp[0]);
7175 EXPECT_EQ(error::%(parse_result)s,
7176 ExecuteImmediateCmd(cmd, sizeof(temp)));%(gl_error_test)s
7179 self.WriteInvalidUnitTest(func, f, invalid_test, extra, *extras)
7181 def WriteGetDataSizeCode(self, func, f):
7182 """Overrriden from TypeHandler."""
7183 code = """ uint32_t data_size;
7184 if (!ComputeDataSize(count, sizeof(%s), %d, &data_size)) {
7185 return error::kOutOfBounds;
7188 f.write(code % (self.GetArrayType(func), self.GetArrayCount(func)))
7189 if func.IsImmediate():
7190 f.write(" if (data_size > immediate_data_size) {\n")
7191 f.write(" return error::kOutOfBounds;\n")
7192 f.write(" }\n")
7194 def WriteGLES2Implementation(self, func, f):
7195 """Overrriden from TypeHandler."""
7196 f.write("%s GLES2Implementation::%s(%s) {\n" %
7197 (func.return_type, func.original_name,
7198 func.MakeTypedOriginalArgString("")))
7199 f.write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
7200 func.WriteDestinationInitalizationValidation(f)
7201 self.WriteClientGLCallLog(func, f)
7202 last_pointer_name = func.GetLastOriginalPointerArg().name
7203 f.write(""" GPU_CLIENT_LOG_CODE_BLOCK({
7204 for (GLsizei i = 0; i < count; ++i) {
7205 """)
7206 values_str = ' << ", " << '.join(
7207 ["%s[%d + i * %d]" % (
7208 last_pointer_name, ndx, self.GetArrayCount(func)) for ndx in range(
7209 0, self.GetArrayCount(func))])
7210 f.write(' GPU_CLIENT_LOG(" " << i << ": " << %s);\n' % values_str)
7211 f.write(" }\n });\n")
7212 for arg in func.GetOriginalArgs():
7213 arg.WriteClientSideValidationCode(f, func)
7214 f.write(" helper_->%sImmediate(%s);\n" %
7215 (func.name, func.MakeInitString("")))
7216 f.write(" CheckGLError();\n")
7217 f.write("}\n")
7218 f.write("\n")
7220 def WriteGLES2ImplementationUnitTest(self, func, f):
7221 """Writes the GLES2 Implemention unit test."""
7222 code = """
7223 TEST_F(GLES2ImplementationTest, %(name)s) {
7224 %(type)s data[%(count_param)d][%(count)d] = {{0}};
7225 struct Cmds {
7226 cmds::%(name)sImmediate cmd;
7227 %(type)s data[%(count_param)d][%(count)d];
7230 Cmds expected;
7231 for (int ii = 0; ii < %(count_param)d; ++ii) {
7232 for (int jj = 0; jj < %(count)d; ++jj) {
7233 data[ii][jj] = static_cast<%(type)s>(ii * %(count)d + jj);
7236 expected.cmd.Init(%(cmd_args)s);
7237 gl_->%(name)s(%(args)s);
7238 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
7241 cmd_arg_strings = []
7242 for arg in func.GetCmdArgs():
7243 if arg.name.endswith("_shm_id"):
7244 cmd_arg_strings.append("&data[0][0]")
7245 elif arg.name.endswith("_shm_offset"):
7246 continue
7247 else:
7248 cmd_arg_strings.append(arg.GetValidClientSideCmdArg(func))
7249 gl_arg_strings = []
7250 count_param = 0
7251 for arg in func.GetOriginalArgs():
7252 if arg.IsPointer():
7253 valid_value = "&data[0][0]"
7254 else:
7255 valid_value = arg.GetValidClientSideArg(func)
7256 gl_arg_strings.append(valid_value)
7257 if arg.name == "count":
7258 count_param = int(valid_value)
7259 f.write(code % {
7260 'name': func.name,
7261 'type': self.GetArrayType(func),
7262 'count': self.GetArrayCount(func),
7263 'args': ", ".join(gl_arg_strings),
7264 'cmd_args': ", ".join(cmd_arg_strings),
7265 'count_param': count_param,
7268 # Test constants for invalid values, as they are not tested by the
7269 # service.
7270 constants = [
7271 arg for arg in func.GetOriginalArgs()[0:-1] if arg.IsConstant()
7273 if not constants:
7274 return
7276 code = """
7277 TEST_F(GLES2ImplementationTest, %(name)sInvalidConstantArg%(invalid_index)d) {
7278 %(type)s data[%(count_param)d][%(count)d] = {{0}};
7279 for (int ii = 0; ii < %(count_param)d; ++ii) {
7280 for (int jj = 0; jj < %(count)d; ++jj) {
7281 data[ii][jj] = static_cast<%(type)s>(ii * %(count)d + jj);
7284 gl_->%(name)s(%(args)s);
7285 EXPECT_TRUE(NoCommandsWritten());
7286 EXPECT_EQ(%(gl_error)s, CheckError());
7289 for invalid_arg in constants:
7290 gl_arg_strings = []
7291 invalid = invalid_arg.GetInvalidArg(func)
7292 for arg in func.GetOriginalArgs():
7293 if arg is invalid_arg:
7294 gl_arg_strings.append(invalid[0])
7295 elif arg.IsPointer():
7296 gl_arg_strings.append("&data[0][0]")
7297 else:
7298 valid_value = arg.GetValidClientSideArg(func)
7299 gl_arg_strings.append(valid_value)
7300 if arg.name == "count":
7301 count_param = int(valid_value)
7303 f.write(code % {
7304 'name': func.name,
7305 'invalid_index': func.GetOriginalArgs().index(invalid_arg),
7306 'type': self.GetArrayType(func),
7307 'count': self.GetArrayCount(func),
7308 'args': ", ".join(gl_arg_strings),
7309 'gl_error': invalid[2],
7310 'count_param': count_param,
7314 def WriteImmediateCmdComputeSize(self, func, f):
7315 """Overrriden from TypeHandler."""
7316 f.write(" static uint32_t ComputeDataSize(GLsizei count) {\n")
7317 f.write(" return static_cast<uint32_t>(\n")
7318 f.write(" sizeof(%s) * %d * count); // NOLINT\n" %
7319 (self.GetArrayType(func), self.GetArrayCount(func)))
7320 f.write(" }\n")
7321 f.write("\n")
7322 f.write(" static uint32_t ComputeSize(GLsizei count) {\n")
7323 f.write(" return static_cast<uint32_t>(\n")
7324 f.write(
7325 " sizeof(ValueType) + ComputeDataSize(count)); // NOLINT\n")
7326 f.write(" }\n")
7327 f.write("\n")
7329 def WriteImmediateCmdSetHeader(self, func, f):
7330 """Overrriden from TypeHandler."""
7331 f.write(" void SetHeader(GLsizei count) {\n")
7332 f.write(
7333 " header.SetCmdByTotalSize<ValueType>(ComputeSize(count));\n")
7334 f.write(" }\n")
7335 f.write("\n")
7337 def WriteImmediateCmdInit(self, func, f):
7338 """Overrriden from TypeHandler."""
7339 f.write(" void Init(%s) {\n" %
7340 func.MakeTypedInitString("_"))
7341 f.write(" SetHeader(_count);\n")
7342 args = func.GetCmdArgs()
7343 for arg in args:
7344 f.write(" %s = _%s;\n" % (arg.name, arg.name))
7345 f.write(" memcpy(ImmediateDataAddress(this),\n")
7346 pointer_arg = func.GetLastOriginalPointerArg()
7347 f.write(" _%s, ComputeDataSize(_count));\n" % pointer_arg.name)
7348 f.write(" }\n")
7349 f.write("\n")
7351 def WriteImmediateCmdSet(self, func, f):
7352 """Overrriden from TypeHandler."""
7353 f.write(" void* Set(void* cmd%s) {\n" %
7354 func.MakeTypedInitString("_", True))
7355 f.write(" static_cast<ValueType*>(cmd)->Init(%s);\n" %
7356 func.MakeInitString("_"))
7357 f.write(" const uint32_t size = ComputeSize(_count);\n")
7358 f.write(" return NextImmediateCmdAddressTotalSize<ValueType>("
7359 "cmd, size);\n")
7360 f.write(" }\n")
7361 f.write("\n")
7363 def WriteImmediateCmdHelper(self, func, f):
7364 """Overrriden from TypeHandler."""
7365 code = """ void %(name)s(%(typed_args)s) {
7366 const uint32_t size = gles2::cmds::%(name)s::ComputeSize(count);
7367 gles2::cmds::%(name)s* c =
7368 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
7369 if (c) {
7370 c->Init(%(args)s);
7375 f.write(code % {
7376 "name": func.name,
7377 "typed_args": func.MakeTypedInitString(""),
7378 "args": func.MakeInitString("")
7381 def WriteImmediateFormatTest(self, func, f):
7382 """Overrriden from TypeHandler."""
7383 args = func.GetOriginalArgs()
7384 count_param = 0
7385 for arg in args:
7386 if arg.name == "count":
7387 count_param = int(arg.GetValidClientSideCmdArg(func))
7388 f.write("TEST_F(GLES2FormatTest, %s) {\n" % func.name)
7389 f.write(" const int kSomeBaseValueToTestWith = 51;\n")
7390 f.write(" static %s data[] = {\n" % self.GetArrayType(func))
7391 for v in range(0, self.GetArrayCount(func) * count_param):
7392 f.write(" static_cast<%s>(kSomeBaseValueToTestWith + %d),\n" %
7393 (self.GetArrayType(func), v))
7394 f.write(" };\n")
7395 f.write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
7396 (func.name, func.name))
7397 f.write(" const GLsizei kNumElements = %d;\n" % count_param)
7398 f.write(" const size_t kExpectedCmdSize =\n")
7399 f.write(" sizeof(cmd) + kNumElements * sizeof(%s) * %d;\n" %
7400 (self.GetArrayType(func), self.GetArrayCount(func)))
7401 f.write(" void* next_cmd = cmd.Set(\n")
7402 f.write(" &cmd")
7403 for value, arg in enumerate(args):
7404 if arg.IsPointer():
7405 f.write(",\n data")
7406 elif arg.IsConstant():
7407 continue
7408 else:
7409 f.write(",\n static_cast<%s>(%d)" % (arg.type, value + 1))
7410 f.write(");\n")
7411 f.write(" EXPECT_EQ(static_cast<uint32_t>(cmds::%s::kCmdId),\n" %
7412 func.name)
7413 f.write(" cmd.header.command);\n")
7414 f.write(" EXPECT_EQ(kExpectedCmdSize, cmd.header.size * 4u);\n")
7415 for value, arg in enumerate(args):
7416 if arg.IsPointer() or arg.IsConstant():
7417 continue
7418 f.write(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);\n" %
7419 (arg.type, value + 1, arg.name))
7420 f.write(" CheckBytesWrittenMatchesExpectedSize(\n")
7421 f.write(" next_cmd, sizeof(cmd) +\n")
7422 f.write(" RoundSizeToMultipleOfEntries(sizeof(data)));\n")
7423 f.write(" // TODO(gman): Check that data was inserted;\n")
7424 f.write("}\n")
7425 f.write("\n")
7427 class PUTSTRHandler(ArrayArgTypeHandler):
7428 """Handler for functions that pass a string array."""
7430 def __GetDataArg(self, func):
7431 """Return the argument that points to the 2D char arrays"""
7432 for arg in func.GetOriginalArgs():
7433 if arg.IsPointer2D():
7434 return arg
7435 return None
7437 def __GetLengthArg(self, func):
7438 """Return the argument that holds length for each char array"""
7439 for arg in func.GetOriginalArgs():
7440 if arg.IsPointer() and not arg.IsPointer2D():
7441 return arg
7442 return None
7444 def WriteGLES2Implementation(self, func, f):
7445 """Overrriden from TypeHandler."""
7446 f.write("%s GLES2Implementation::%s(%s) {\n" %
7447 (func.return_type, func.original_name,
7448 func.MakeTypedOriginalArgString("")))
7449 f.write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
7450 func.WriteDestinationInitalizationValidation(f)
7451 self.WriteClientGLCallLog(func, f)
7452 data_arg = self.__GetDataArg(func)
7453 length_arg = self.__GetLengthArg(func)
7454 log_code_block = """ GPU_CLIENT_LOG_CODE_BLOCK({
7455 for (GLsizei ii = 0; ii < count; ++ii) {
7456 if (%(data)s[ii]) {"""
7457 if length_arg == None:
7458 log_code_block += """
7459 GPU_CLIENT_LOG(" " << ii << ": ---\\n" << %(data)s[ii] << "\\n---");"""
7460 else:
7461 log_code_block += """
7462 if (%(length)s && %(length)s[ii] >= 0) {
7463 const std::string my_str(%(data)s[ii], %(length)s[ii]);
7464 GPU_CLIENT_LOG(" " << ii << ": ---\\n" << my_str << "\\n---");
7465 } else {
7466 GPU_CLIENT_LOG(" " << ii << ": ---\\n" << %(data)s[ii] << "\\n---");
7467 }"""
7468 log_code_block += """
7469 } else {
7470 GPU_CLIENT_LOG(" " << ii << ": NULL");
7475 f.write(log_code_block % {
7476 'data': data_arg.name,
7477 'length': length_arg.name if not length_arg == None else ''
7479 for arg in func.GetOriginalArgs():
7480 arg.WriteClientSideValidationCode(f, func)
7482 bucket_args = []
7483 for arg in func.GetOriginalArgs():
7484 if arg.name == 'count' or arg == self.__GetLengthArg(func):
7485 continue
7486 if arg == self.__GetDataArg(func):
7487 bucket_args.append('kResultBucketId')
7488 else:
7489 bucket_args.append(arg.name)
7490 code_block = """
7491 if (!PackStringsToBucket(count, %(data)s, %(length)s, "gl%(func_name)s")) {
7492 return;
7494 helper_->%(func_name)sBucket(%(bucket_args)s);
7495 helper_->SetBucketSize(kResultBucketId, 0);
7496 CheckGLError();
7500 f.write(code_block % {
7501 'data': data_arg.name,
7502 'length': length_arg.name if not length_arg == None else 'NULL',
7503 'func_name': func.name,
7504 'bucket_args': ', '.join(bucket_args),
7507 def WriteGLES2ImplementationUnitTest(self, func, f):
7508 """Overrriden from TypeHandler."""
7509 code = """
7510 TEST_F(GLES2ImplementationTest, %(name)s) {
7511 const uint32 kBucketId = GLES2Implementation::kResultBucketId;
7512 const char* kString1 = "happy";
7513 const char* kString2 = "ending";
7514 const size_t kString1Size = ::strlen(kString1) + 1;
7515 const size_t kString2Size = ::strlen(kString2) + 1;
7516 const size_t kHeaderSize = sizeof(GLint) * 3;
7517 const size_t kSourceSize = kHeaderSize + kString1Size + kString2Size;
7518 const size_t kPaddedHeaderSize =
7519 transfer_buffer_->RoundToAlignment(kHeaderSize);
7520 const size_t kPaddedString1Size =
7521 transfer_buffer_->RoundToAlignment(kString1Size);
7522 const size_t kPaddedString2Size =
7523 transfer_buffer_->RoundToAlignment(kString2Size);
7524 struct Cmds {
7525 cmd::SetBucketSize set_bucket_size;
7526 cmd::SetBucketData set_bucket_header;
7527 cmd::SetToken set_token1;
7528 cmd::SetBucketData set_bucket_data1;
7529 cmd::SetToken set_token2;
7530 cmd::SetBucketData set_bucket_data2;
7531 cmd::SetToken set_token3;
7532 cmds::%(name)sBucket cmd_bucket;
7533 cmd::SetBucketSize clear_bucket_size;
7536 ExpectedMemoryInfo mem0 = GetExpectedMemory(kPaddedHeaderSize);
7537 ExpectedMemoryInfo mem1 = GetExpectedMemory(kPaddedString1Size);
7538 ExpectedMemoryInfo mem2 = GetExpectedMemory(kPaddedString2Size);
7540 Cmds expected;
7541 expected.set_bucket_size.Init(kBucketId, kSourceSize);
7542 expected.set_bucket_header.Init(
7543 kBucketId, 0, kHeaderSize, mem0.id, mem0.offset);
7544 expected.set_token1.Init(GetNextToken());
7545 expected.set_bucket_data1.Init(
7546 kBucketId, kHeaderSize, kString1Size, mem1.id, mem1.offset);
7547 expected.set_token2.Init(GetNextToken());
7548 expected.set_bucket_data2.Init(
7549 kBucketId, kHeaderSize + kString1Size, kString2Size, mem2.id,
7550 mem2.offset);
7551 expected.set_token3.Init(GetNextToken());
7552 expected.cmd_bucket.Init(%(bucket_args)s);
7553 expected.clear_bucket_size.Init(kBucketId, 0);
7554 const char* kStrings[] = { kString1, kString2 };
7555 gl_->%(name)s(%(gl_args)s);
7556 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
7559 gl_args = []
7560 bucket_args = []
7561 for arg in func.GetOriginalArgs():
7562 if arg == self.__GetDataArg(func):
7563 gl_args.append('kStrings')
7564 bucket_args.append('kBucketId')
7565 elif arg == self.__GetLengthArg(func):
7566 gl_args.append('NULL')
7567 elif arg.name == 'count':
7568 gl_args.append('2')
7569 else:
7570 gl_args.append(arg.GetValidClientSideArg(func))
7571 bucket_args.append(arg.GetValidClientSideArg(func))
7572 f.write(code % {
7573 'name': func.name,
7574 'gl_args': ", ".join(gl_args),
7575 'bucket_args': ", ".join(bucket_args),
7578 if self.__GetLengthArg(func) == None:
7579 return
7580 code = """
7581 TEST_F(GLES2ImplementationTest, %(name)sWithLength) {
7582 const uint32 kBucketId = GLES2Implementation::kResultBucketId;
7583 const char* kString = "foobar******";
7584 const size_t kStringSize = 6; // We only need "foobar".
7585 const size_t kHeaderSize = sizeof(GLint) * 2;
7586 const size_t kSourceSize = kHeaderSize + kStringSize + 1;
7587 const size_t kPaddedHeaderSize =
7588 transfer_buffer_->RoundToAlignment(kHeaderSize);
7589 const size_t kPaddedStringSize =
7590 transfer_buffer_->RoundToAlignment(kStringSize + 1);
7591 struct Cmds {
7592 cmd::SetBucketSize set_bucket_size;
7593 cmd::SetBucketData set_bucket_header;
7594 cmd::SetToken set_token1;
7595 cmd::SetBucketData set_bucket_data;
7596 cmd::SetToken set_token2;
7597 cmds::ShaderSourceBucket shader_source_bucket;
7598 cmd::SetBucketSize clear_bucket_size;
7601 ExpectedMemoryInfo mem0 = GetExpectedMemory(kPaddedHeaderSize);
7602 ExpectedMemoryInfo mem1 = GetExpectedMemory(kPaddedStringSize);
7604 Cmds expected;
7605 expected.set_bucket_size.Init(kBucketId, kSourceSize);
7606 expected.set_bucket_header.Init(
7607 kBucketId, 0, kHeaderSize, mem0.id, mem0.offset);
7608 expected.set_token1.Init(GetNextToken());
7609 expected.set_bucket_data.Init(
7610 kBucketId, kHeaderSize, kStringSize + 1, mem1.id, mem1.offset);
7611 expected.set_token2.Init(GetNextToken());
7612 expected.shader_source_bucket.Init(%(bucket_args)s);
7613 expected.clear_bucket_size.Init(kBucketId, 0);
7614 const char* kStrings[] = { kString };
7615 const GLint kLength[] = { kStringSize };
7616 gl_->%(name)s(%(gl_args)s);
7617 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
7620 gl_args = []
7621 for arg in func.GetOriginalArgs():
7622 if arg == self.__GetDataArg(func):
7623 gl_args.append('kStrings')
7624 elif arg == self.__GetLengthArg(func):
7625 gl_args.append('kLength')
7626 elif arg.name == 'count':
7627 gl_args.append('1')
7628 else:
7629 gl_args.append(arg.GetValidClientSideArg(func))
7630 f.write(code % {
7631 'name': func.name,
7632 'gl_args': ", ".join(gl_args),
7633 'bucket_args': ", ".join(bucket_args),
7636 def WriteBucketServiceUnitTest(self, func, f, *extras):
7637 """Overrriden from TypeHandler."""
7638 cmd_args = []
7639 cmd_args_with_invalid_id = []
7640 gl_args = []
7641 for index, arg in enumerate(func.GetOriginalArgs()):
7642 if arg == self.__GetLengthArg(func):
7643 gl_args.append('_')
7644 elif arg.name == 'count':
7645 gl_args.append('1')
7646 elif arg == self.__GetDataArg(func):
7647 cmd_args.append('kBucketId')
7648 cmd_args_with_invalid_id.append('kBucketId')
7649 gl_args.append('_')
7650 elif index == 0: # Resource ID arg
7651 cmd_args.append(arg.GetValidArg(func))
7652 cmd_args_with_invalid_id.append('kInvalidClientId')
7653 gl_args.append(arg.GetValidGLArg(func))
7654 else:
7655 cmd_args.append(arg.GetValidArg(func))
7656 cmd_args_with_invalid_id.append(arg.GetValidArg(func))
7657 gl_args.append(arg.GetValidGLArg(func))
7659 test = """
7660 TEST_P(%(test_name)s, %(name)sValidArgs) {
7661 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
7662 const uint32 kBucketId = 123;
7663 const char kSource0[] = "hello";
7664 const char* kSource[] = { kSource0 };
7665 const char kValidStrEnd = 0;
7666 SetBucketAsCStrings(kBucketId, 1, kSource, 1, kValidStrEnd);
7667 cmds::%(name)s cmd;
7668 cmd.Init(%(cmd_args)s);
7669 decoder_->set_unsafe_es3_apis_enabled(true);
7670 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));"""
7671 if func.IsUnsafe():
7672 test += """
7673 decoder_->set_unsafe_es3_apis_enabled(false);
7674 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));
7676 test += """
7679 self.WriteValidUnitTest(func, f, test, {
7680 'cmd_args': ", ".join(cmd_args),
7681 'gl_args': ", ".join(gl_args),
7682 }, *extras)
7684 test = """
7685 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
7686 const uint32 kBucketId = 123;
7687 const char kSource0[] = "hello";
7688 const char* kSource[] = { kSource0 };
7689 const char kValidStrEnd = 0;
7690 decoder_->set_unsafe_es3_apis_enabled(true);
7691 cmds::%(name)s cmd;
7692 // Test no bucket.
7693 cmd.Init(%(cmd_args)s);
7694 EXPECT_NE(error::kNoError, ExecuteCmd(cmd));
7695 // Test invalid client.
7696 SetBucketAsCStrings(kBucketId, 1, kSource, 1, kValidStrEnd);
7697 cmd.Init(%(cmd_args_with_invalid_id)s);
7698 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
7699 EXPECT_EQ(GL_INVALID_VALUE, GetGLError());
7702 self.WriteValidUnitTest(func, f, test, {
7703 'cmd_args': ", ".join(cmd_args),
7704 'cmd_args_with_invalid_id': ", ".join(cmd_args_with_invalid_id),
7705 }, *extras)
7707 test = """
7708 TEST_P(%(test_name)s, %(name)sInvalidHeader) {
7709 const uint32 kBucketId = 123;
7710 const char kSource0[] = "hello";
7711 const char* kSource[] = { kSource0 };
7712 const char kValidStrEnd = 0;
7713 const GLsizei kCount = static_cast<GLsizei>(arraysize(kSource));
7714 const GLsizei kTests[] = {
7715 kCount + 1,
7717 std::numeric_limits<GLsizei>::max(),
7720 decoder_->set_unsafe_es3_apis_enabled(true);
7721 for (size_t ii = 0; ii < arraysize(kTests); ++ii) {
7722 SetBucketAsCStrings(kBucketId, 1, kSource, kTests[ii], kValidStrEnd);
7723 cmds::%(name)s cmd;
7724 cmd.Init(%(cmd_args)s);
7725 EXPECT_EQ(error::kInvalidArguments, ExecuteCmd(cmd));
7729 self.WriteValidUnitTest(func, f, test, {
7730 'cmd_args': ", ".join(cmd_args),
7731 }, *extras)
7733 test = """
7734 TEST_P(%(test_name)s, %(name)sInvalidStringEnding) {
7735 const uint32 kBucketId = 123;
7736 const char kSource0[] = "hello";
7737 const char* kSource[] = { kSource0 };
7738 const char kInvalidStrEnd = '*';
7739 SetBucketAsCStrings(kBucketId, 1, kSource, 1, kInvalidStrEnd);
7740 cmds::%(name)s cmd;
7741 cmd.Init(%(cmd_args)s);
7742 decoder_->set_unsafe_es3_apis_enabled(true);
7743 EXPECT_EQ(error::kInvalidArguments, ExecuteCmd(cmd));
7746 self.WriteValidUnitTest(func, f, test, {
7747 'cmd_args': ", ".join(cmd_args),
7748 }, *extras)
7751 class PUTXnHandler(ArrayArgTypeHandler):
7752 """Handler for glUniform?f functions."""
7754 def WriteHandlerImplementation(self, func, f):
7755 """Overrriden from TypeHandler."""
7756 code = """ %(type)s temp[%(count)s] = { %(values)s};
7757 Do%(name)sv(%(location)s, 1, &temp[0]);
7759 values = ""
7760 args = func.GetOriginalArgs()
7761 count = int(self.GetArrayCount(func))
7762 num_args = len(args)
7763 for ii in range(count):
7764 values += "%s, " % args[len(args) - count + ii].name
7766 f.write(code % {
7767 'name': func.name,
7768 'count': self.GetArrayCount(func),
7769 'type': self.GetArrayType(func),
7770 'location': args[0].name,
7771 'args': func.MakeOriginalArgString(""),
7772 'values': values,
7775 def WriteServiceUnitTest(self, func, f, *extras):
7776 """Overrriden from TypeHandler."""
7777 valid_test = """
7778 TEST_P(%(test_name)s, %(name)sValidArgs) {
7779 EXPECT_CALL(*gl_, %(name)sv(%(local_args)s));
7780 SpecializedSetup<cmds::%(name)s, 0>(true);
7781 cmds::%(name)s cmd;
7782 cmd.Init(%(args)s);"""
7783 if func.IsUnsafe():
7784 valid_test += """
7785 decoder_->set_unsafe_es3_apis_enabled(true);"""
7786 valid_test += """
7787 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
7788 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
7789 if func.IsUnsafe():
7790 valid_test += """
7791 decoder_->set_unsafe_es3_apis_enabled(false);
7792 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));"""
7793 valid_test += """
7796 args = func.GetOriginalArgs()
7797 local_args = "%s, 1, _" % args[0].GetValidGLArg(func)
7798 self.WriteValidUnitTest(func, f, valid_test, {
7799 'name': func.name,
7800 'count': self.GetArrayCount(func),
7801 'local_args': local_args,
7802 }, *extras)
7804 invalid_test = """
7805 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
7806 EXPECT_CALL(*gl_, %(name)sv(_, _, _).Times(0);
7807 SpecializedSetup<cmds::%(name)s, 0>(false);
7808 cmds::%(name)s cmd;
7809 cmd.Init(%(args)s);
7810 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
7813 self.WriteInvalidUnitTest(func, f, invalid_test, {
7814 'name': func.GetInfo('name'),
7815 'count': self.GetArrayCount(func),
7819 class GLcharHandler(CustomHandler):
7820 """Handler for functions that pass a single string ."""
7822 def WriteImmediateCmdComputeSize(self, func, f):
7823 """Overrriden from TypeHandler."""
7824 f.write(" static uint32_t ComputeSize(uint32_t data_size) {\n")
7825 f.write(" return static_cast<uint32_t>(\n")
7826 f.write(" sizeof(ValueType) + data_size); // NOLINT\n")
7827 f.write(" }\n")
7829 def WriteImmediateCmdSetHeader(self, func, f):
7830 """Overrriden from TypeHandler."""
7831 code = """
7832 void SetHeader(uint32_t data_size) {
7833 header.SetCmdBySize<ValueType>(data_size);
7836 f.write(code)
7838 def WriteImmediateCmdInit(self, func, f):
7839 """Overrriden from TypeHandler."""
7840 last_arg = func.GetLastOriginalArg()
7841 args = func.GetCmdArgs()
7842 set_code = []
7843 for arg in args:
7844 set_code.append(" %s = _%s;" % (arg.name, arg.name))
7845 code = """
7846 void Init(%(typed_args)s, uint32_t _data_size) {
7847 SetHeader(_data_size);
7848 %(set_code)s
7849 memcpy(ImmediateDataAddress(this), _%(last_arg)s, _data_size);
7853 f.write(code % {
7854 "typed_args": func.MakeTypedArgString("_"),
7855 "set_code": "\n".join(set_code),
7856 "last_arg": last_arg.name
7859 def WriteImmediateCmdSet(self, func, f):
7860 """Overrriden from TypeHandler."""
7861 last_arg = func.GetLastOriginalArg()
7862 f.write(" void* Set(void* cmd%s, uint32_t _data_size) {\n" %
7863 func.MakeTypedCmdArgString("_", True))
7864 f.write(" static_cast<ValueType*>(cmd)->Init(%s, _data_size);\n" %
7865 func.MakeCmdArgString("_"))
7866 f.write(" return NextImmediateCmdAddress<ValueType>("
7867 "cmd, _data_size);\n")
7868 f.write(" }\n")
7869 f.write("\n")
7871 def WriteImmediateCmdHelper(self, func, f):
7872 """Overrriden from TypeHandler."""
7873 code = """ void %(name)s(%(typed_args)s) {
7874 const uint32_t data_size = strlen(name);
7875 gles2::cmds::%(name)s* c =
7876 GetImmediateCmdSpace<gles2::cmds::%(name)s>(data_size);
7877 if (c) {
7878 c->Init(%(args)s, data_size);
7883 f.write(code % {
7884 "name": func.name,
7885 "typed_args": func.MakeTypedOriginalArgString(""),
7886 "args": func.MakeOriginalArgString(""),
7890 def WriteImmediateFormatTest(self, func, f):
7891 """Overrriden from TypeHandler."""
7892 init_code = []
7893 check_code = []
7894 all_but_last_arg = func.GetCmdArgs()[:-1]
7895 for value, arg in enumerate(all_but_last_arg):
7896 init_code.append(" static_cast<%s>(%d)," % (arg.type, value + 11))
7897 for value, arg in enumerate(all_but_last_arg):
7898 check_code.append(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);" %
7899 (arg.type, value + 11, arg.name))
7900 code = """
7901 TEST_F(GLES2FormatTest, %(func_name)s) {
7902 cmds::%(func_name)s& cmd = *GetBufferAs<cmds::%(func_name)s>();
7903 static const char* const test_str = \"test string\";
7904 void* next_cmd = cmd.Set(
7905 &cmd,
7906 %(init_code)s
7907 test_str,
7908 strlen(test_str));
7909 EXPECT_EQ(static_cast<uint32_t>(cmds::%(func_name)s::kCmdId),
7910 cmd.header.command);
7911 EXPECT_EQ(sizeof(cmd) +
7912 RoundSizeToMultipleOfEntries(strlen(test_str)),
7913 cmd.header.size * 4u);
7914 EXPECT_EQ(static_cast<char*>(next_cmd),
7915 reinterpret_cast<char*>(&cmd) + sizeof(cmd) +
7916 RoundSizeToMultipleOfEntries(strlen(test_str)));
7917 %(check_code)s
7918 EXPECT_EQ(static_cast<uint32_t>(strlen(test_str)), cmd.data_size);
7919 EXPECT_EQ(0, memcmp(test_str, ImmediateDataAddress(&cmd), strlen(test_str)));
7920 CheckBytesWritten(
7921 next_cmd,
7922 sizeof(cmd) + RoundSizeToMultipleOfEntries(strlen(test_str)),
7923 sizeof(cmd) + strlen(test_str));
7927 f.write(code % {
7928 'func_name': func.name,
7929 'init_code': "\n".join(init_code),
7930 'check_code': "\n".join(check_code),
7934 class GLcharNHandler(CustomHandler):
7935 """Handler for functions that pass a single string with an optional len."""
7937 def InitFunction(self, func):
7938 """Overrriden from TypeHandler."""
7939 func.cmd_args = []
7940 func.AddCmdArg(Argument('bucket_id', 'GLuint'))
7942 def NeedsDataTransferFunction(self, func):
7943 """Overriden from TypeHandler."""
7944 return False
7946 def WriteServiceImplementation(self, func, f):
7947 """Overrriden from TypeHandler."""
7948 self.WriteServiceHandlerFunctionHeader(func, f)
7949 f.write("""
7950 GLuint bucket_id = static_cast<GLuint>(c.%(bucket_id)s);
7951 Bucket* bucket = GetBucket(bucket_id);
7952 if (!bucket || bucket->size() == 0) {
7953 return error::kInvalidArguments;
7955 std::string str;
7956 if (!bucket->GetAsString(&str)) {
7957 return error::kInvalidArguments;
7959 %(gl_func_name)s(0, str.c_str());
7960 return error::kNoError;
7963 """ % {
7964 'name': func.name,
7965 'gl_func_name': func.GetGLFunctionName(),
7966 'bucket_id': func.cmd_args[0].name,
7970 class IsHandler(TypeHandler):
7971 """Handler for glIs____ type and glGetError functions."""
7973 def InitFunction(self, func):
7974 """Overrriden from TypeHandler."""
7975 func.AddCmdArg(Argument("result_shm_id", 'uint32_t'))
7976 func.AddCmdArg(Argument("result_shm_offset", 'uint32_t'))
7977 if func.GetInfo('result') == None:
7978 func.AddInfo('result', ['uint32_t'])
7980 def WriteServiceUnitTest(self, func, f, *extras):
7981 """Overrriden from TypeHandler."""
7982 valid_test = """
7983 TEST_P(%(test_name)s, %(name)sValidArgs) {
7984 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
7985 SpecializedSetup<cmds::%(name)s, 0>(true);
7986 cmds::%(name)s cmd;
7987 cmd.Init(%(args)s%(comma)sshared_memory_id_, shared_memory_offset_);"""
7988 if func.IsUnsafe():
7989 valid_test += """
7990 decoder_->set_unsafe_es3_apis_enabled(true);"""
7991 valid_test += """
7992 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
7993 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
7994 if func.IsUnsafe():
7995 valid_test += """
7996 decoder_->set_unsafe_es3_apis_enabled(false);
7997 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));"""
7998 valid_test += """
8001 comma = ""
8002 if len(func.GetOriginalArgs()):
8003 comma =", "
8004 self.WriteValidUnitTest(func, f, valid_test, {
8005 'comma': comma,
8006 }, *extras)
8008 invalid_test = """
8009 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
8010 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
8011 SpecializedSetup<cmds::%(name)s, 0>(false);
8012 cmds::%(name)s cmd;
8013 cmd.Init(%(args)s%(comma)sshared_memory_id_, shared_memory_offset_);
8014 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
8017 self.WriteInvalidUnitTest(func, f, invalid_test, {
8018 'comma': comma,
8019 }, *extras)
8021 invalid_test = """
8022 TEST_P(%(test_name)s, %(name)sInvalidArgsBadSharedMemoryId) {
8023 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
8024 SpecializedSetup<cmds::%(name)s, 0>(false);"""
8025 if func.IsUnsafe():
8026 invalid_test += """
8027 decoder_->set_unsafe_es3_apis_enabled(true);"""
8028 invalid_test += """
8029 cmds::%(name)s cmd;
8030 cmd.Init(%(args)s%(comma)skInvalidSharedMemoryId, shared_memory_offset_);
8031 EXPECT_EQ(error::kOutOfBounds, ExecuteCmd(cmd));
8032 cmd.Init(%(args)s%(comma)sshared_memory_id_, kInvalidSharedMemoryOffset);
8033 EXPECT_EQ(error::kOutOfBounds, ExecuteCmd(cmd));"""
8034 if func.IsUnsafe():
8035 invalid_test += """
8036 decoder_->set_unsafe_es3_apis_enabled(true);"""
8037 invalid_test += """
8040 self.WriteValidUnitTest(func, f, invalid_test, {
8041 'comma': comma,
8042 }, *extras)
8044 def WriteServiceImplementation(self, func, f):
8045 """Overrriden from TypeHandler."""
8046 self.WriteServiceHandlerFunctionHeader(func, f)
8047 self.WriteHandlerExtensionCheck(func, f)
8048 args = func.GetOriginalArgs()
8049 for arg in args:
8050 arg.WriteGetCode(f)
8052 code = """ typedef cmds::%(func_name)s::Result Result;
8053 Result* result_dst = GetSharedMemoryAs<Result*>(
8054 c.result_shm_id, c.result_shm_offset, sizeof(*result_dst));
8055 if (!result_dst) {
8056 return error::kOutOfBounds;
8059 f.write(code % {'func_name': func.name})
8060 func.WriteHandlerValidation(f)
8061 if func.IsUnsafe():
8062 assert func.GetInfo('id_mapping')
8063 assert len(func.GetInfo('id_mapping')) == 1
8064 assert len(args) == 1
8065 id_type = func.GetInfo('id_mapping')[0]
8066 f.write(" %s service_%s = 0;\n" % (args[0].type, id_type.lower()))
8067 f.write(" *result_dst = group_->Get%sServiceId(%s, &service_%s);\n" %
8068 (id_type, id_type.lower(), id_type.lower()))
8069 else:
8070 f.write(" *result_dst = %s(%s);\n" %
8071 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
8072 f.write(" return error::kNoError;\n")
8073 f.write("}\n")
8074 f.write("\n")
8076 def WriteGLES2Implementation(self, func, f):
8077 """Overrriden from TypeHandler."""
8078 impl_func = func.GetInfo('impl_func')
8079 if impl_func == None or impl_func == True:
8080 error_value = func.GetInfo("error_value") or "GL_FALSE"
8081 f.write("%s GLES2Implementation::%s(%s) {\n" %
8082 (func.return_type, func.original_name,
8083 func.MakeTypedOriginalArgString("")))
8084 f.write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
8085 self.WriteTraceEvent(func, f)
8086 func.WriteDestinationInitalizationValidation(f)
8087 self.WriteClientGLCallLog(func, f)
8088 f.write(" typedef cmds::%s::Result Result;\n" % func.name)
8089 f.write(" Result* result = GetResultAs<Result*>();\n")
8090 f.write(" if (!result) {\n")
8091 f.write(" return %s;\n" % error_value)
8092 f.write(" }\n")
8093 f.write(" *result = 0;\n")
8094 assert len(func.GetOriginalArgs()) == 1
8095 id_arg = func.GetOriginalArgs()[0]
8096 if id_arg.type == 'GLsync':
8097 arg_string = "ToGLuint(%s)" % func.MakeOriginalArgString("")
8098 else:
8099 arg_string = func.MakeOriginalArgString("")
8100 f.write(
8101 " helper_->%s(%s, GetResultShmId(), GetResultShmOffset());\n" %
8102 (func.name, arg_string))
8103 f.write(" WaitForCmd();\n")
8104 f.write(" %s result_value = *result" % func.return_type)
8105 if func.return_type == "GLboolean":
8106 f.write(" != 0")
8107 f.write(';\n GPU_CLIENT_LOG("returned " << result_value);\n')
8108 f.write(" CheckGLError();\n")
8109 f.write(" return result_value;\n")
8110 f.write("}\n")
8111 f.write("\n")
8113 def WriteGLES2ImplementationUnitTest(self, func, f):
8114 """Overrriden from TypeHandler."""
8115 client_test = func.GetInfo('client_test')
8116 if client_test == None or client_test == True:
8117 code = """
8118 TEST_F(GLES2ImplementationTest, %(name)s) {
8119 struct Cmds {
8120 cmds::%(name)s cmd;
8123 Cmds expected;
8124 ExpectedMemoryInfo result1 =
8125 GetExpectedResultMemory(sizeof(cmds::%(name)s::Result));
8126 expected.cmd.Init(%(cmd_id_value)s, result1.id, result1.offset);
8128 EXPECT_CALL(*command_buffer(), OnFlush())
8129 .WillOnce(SetMemory(result1.ptr, uint32_t(GL_TRUE)))
8130 .RetiresOnSaturation();
8132 GLboolean result = gl_->%(name)s(%(gl_id_value)s);
8133 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
8134 EXPECT_TRUE(result);
8137 args = func.GetOriginalArgs()
8138 assert len(args) == 1
8139 f.write(code % {
8140 'name': func.name,
8141 'cmd_id_value': args[0].GetValidClientSideCmdArg(func),
8142 'gl_id_value': args[0].GetValidClientSideArg(func) })
8145 class STRnHandler(TypeHandler):
8146 """Handler for GetProgramInfoLog, GetShaderInfoLog, GetShaderSource, and
8147 GetTranslatedShaderSourceANGLE."""
8149 def InitFunction(self, func):
8150 """Overrriden from TypeHandler."""
8151 # remove all but the first cmd args.
8152 cmd_args = func.GetCmdArgs()
8153 func.ClearCmdArgs()
8154 func.AddCmdArg(cmd_args[0])
8155 # add on a bucket id.
8156 func.AddCmdArg(Argument('bucket_id', 'uint32_t'))
8158 def WriteGLES2Implementation(self, func, f):
8159 """Overrriden from TypeHandler."""
8160 code_1 = """%(return_type)s GLES2Implementation::%(func_name)s(%(args)s) {
8161 GPU_CLIENT_SINGLE_THREAD_CHECK();
8163 code_2 = """ GPU_CLIENT_LOG("[" << GetLogPrefix()
8164 << "] gl%(func_name)s" << "("
8165 << %(arg0)s << ", "
8166 << %(arg1)s << ", "
8167 << static_cast<void*>(%(arg2)s) << ", "
8168 << static_cast<void*>(%(arg3)s) << ")");
8169 helper_->SetBucketSize(kResultBucketId, 0);
8170 helper_->%(func_name)s(%(id_name)s, kResultBucketId);
8171 std::string str;
8172 GLsizei max_size = 0;
8173 if (GetBucketAsString(kResultBucketId, &str)) {
8174 if (bufsize > 0) {
8175 max_size =
8176 std::min(static_cast<size_t>(%(bufsize_name)s) - 1, str.size());
8177 memcpy(%(dest_name)s, str.c_str(), max_size);
8178 %(dest_name)s[max_size] = '\\0';
8179 GPU_CLIENT_LOG("------\\n" << %(dest_name)s << "\\n------");
8182 if (%(length_name)s != NULL) {
8183 *%(length_name)s = max_size;
8185 CheckGLError();
8188 args = func.GetOriginalArgs()
8189 str_args = {
8190 'return_type': func.return_type,
8191 'func_name': func.original_name,
8192 'args': func.MakeTypedOriginalArgString(""),
8193 'id_name': args[0].name,
8194 'bufsize_name': args[1].name,
8195 'length_name': args[2].name,
8196 'dest_name': args[3].name,
8197 'arg0': args[0].name,
8198 'arg1': args[1].name,
8199 'arg2': args[2].name,
8200 'arg3': args[3].name,
8202 f.write(code_1 % str_args)
8203 func.WriteDestinationInitalizationValidation(f)
8204 f.write(code_2 % str_args)
8206 def WriteServiceUnitTest(self, func, f, *extras):
8207 """Overrriden from TypeHandler."""
8208 valid_test = """
8209 TEST_P(%(test_name)s, %(name)sValidArgs) {
8210 const char* kInfo = "hello";
8211 const uint32_t kBucketId = 123;
8212 SpecializedSetup<cmds::%(name)s, 0>(true);
8213 %(expect_len_code)s
8214 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s))
8215 .WillOnce(DoAll(SetArgumentPointee<2>(strlen(kInfo)),
8216 SetArrayArgument<3>(kInfo, kInfo + strlen(kInfo) + 1)));
8217 cmds::%(name)s cmd;
8218 cmd.Init(%(args)s);
8219 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
8220 CommonDecoder::Bucket* bucket = decoder_->GetBucket(kBucketId);
8221 ASSERT_TRUE(bucket != NULL);
8222 EXPECT_EQ(strlen(kInfo) + 1, bucket->size());
8223 EXPECT_EQ(0, memcmp(bucket->GetData(0, bucket->size()), kInfo,
8224 bucket->size()));
8225 EXPECT_EQ(GL_NO_ERROR, GetGLError());
8228 args = func.GetOriginalArgs()
8229 id_name = args[0].GetValidGLArg(func)
8230 get_len_func = func.GetInfo('get_len_func')
8231 get_len_enum = func.GetInfo('get_len_enum')
8232 sub = {
8233 'id_name': id_name,
8234 'get_len_func': get_len_func,
8235 'get_len_enum': get_len_enum,
8236 'gl_args': '%s, strlen(kInfo) + 1, _, _' %
8237 args[0].GetValidGLArg(func),
8238 'args': '%s, kBucketId' % args[0].GetValidArg(func),
8239 'expect_len_code': '',
8241 if get_len_func and get_len_func[0:2] == 'gl':
8242 sub['expect_len_code'] = (
8243 " EXPECT_CALL(*gl_, %s(%s, %s, _))\n"
8244 " .WillOnce(SetArgumentPointee<2>(strlen(kInfo) + 1));") % (
8245 get_len_func[2:], id_name, get_len_enum)
8246 self.WriteValidUnitTest(func, f, valid_test, sub, *extras)
8248 invalid_test = """
8249 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
8250 const uint32_t kBucketId = 123;
8251 EXPECT_CALL(*gl_, %(gl_func_name)s(_, _, _, _))
8252 .Times(0);
8253 cmds::%(name)s cmd;
8254 cmd.Init(kInvalidClientId, kBucketId);
8255 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
8256 EXPECT_EQ(GL_INVALID_VALUE, GetGLError());
8259 self.WriteValidUnitTest(func, f, invalid_test, *extras)
8261 def WriteServiceImplementation(self, func, f):
8262 """Overrriden from TypeHandler."""
8263 pass
8265 class NamedType(object):
8266 """A class that represents a type of an argument in a client function.
8268 A type of an argument that is to be passed through in the command buffer
8269 command. Currently used only for the arguments that are specificly named in
8270 the 'cmd_buffer_functions.txt' f, mostly enums.
8273 def __init__(self, info):
8274 assert not 'is_complete' in info or info['is_complete'] == True
8275 self.info = info
8276 self.valid = info['valid']
8277 if 'invalid' in info:
8278 self.invalid = info['invalid']
8279 else:
8280 self.invalid = []
8281 if 'valid_es3' in info:
8282 self.valid_es3 = info['valid_es3']
8283 else:
8284 self.valid_es3 = []
8285 if 'deprecated_es3' in info:
8286 self.deprecated_es3 = info['deprecated_es3']
8287 else:
8288 self.deprecated_es3 = []
8290 def GetType(self):
8291 return self.info['type']
8293 def GetInvalidValues(self):
8294 return self.invalid
8296 def GetValidValues(self):
8297 return self.valid
8299 def GetValidValuesES3(self):
8300 return self.valid_es3
8302 def GetDeprecatedValuesES3(self):
8303 return self.deprecated_es3
8305 def IsConstant(self):
8306 if not 'is_complete' in self.info:
8307 return False
8309 return len(self.GetValidValues()) == 1
8311 def GetConstantValue(self):
8312 return self.GetValidValues()[0]
8314 class Argument(object):
8315 """A class that represents a function argument."""
8317 cmd_type_map_ = {
8318 'GLenum': 'uint32_t',
8319 'GLint': 'int32_t',
8320 'GLintptr': 'int32_t',
8321 'GLsizei': 'int32_t',
8322 'GLsizeiptr': 'int32_t',
8323 'GLfloat': 'float',
8324 'GLclampf': 'float',
8326 need_validation_ = ['GLsizei*', 'GLboolean*', 'GLenum*', 'GLint*']
8328 def __init__(self, name, type):
8329 self.name = name
8330 self.optional = type.endswith("Optional*")
8331 if self.optional:
8332 type = type[:-9] + "*"
8333 self.type = type
8335 if type in self.cmd_type_map_:
8336 self.cmd_type = self.cmd_type_map_[type]
8337 else:
8338 self.cmd_type = 'uint32_t'
8340 def IsPointer(self):
8341 """Returns true if argument is a pointer."""
8342 return False
8344 def IsPointer2D(self):
8345 """Returns true if argument is a 2D pointer."""
8346 return False
8348 def IsConstant(self):
8349 """Returns true if the argument has only one valid value."""
8350 return False
8352 def AddCmdArgs(self, args):
8353 """Adds command arguments for this argument to the given list."""
8354 if not self.IsConstant():
8355 return args.append(self)
8357 def AddInitArgs(self, args):
8358 """Adds init arguments for this argument to the given list."""
8359 if not self.IsConstant():
8360 return args.append(self)
8362 def GetValidArg(self, func):
8363 """Gets a valid value for this argument."""
8364 valid_arg = func.GetValidArg(self)
8365 if valid_arg != None:
8366 return valid_arg
8368 index = func.GetOriginalArgs().index(self)
8369 return str(index + 1)
8371 def GetValidClientSideArg(self, func):
8372 """Gets a valid value for this argument."""
8373 valid_arg = func.GetValidArg(self)
8374 if valid_arg != None:
8375 return valid_arg
8377 if self.IsPointer():
8378 return 'nullptr'
8379 index = func.GetOriginalArgs().index(self)
8380 if self.type == 'GLsync':
8381 return ("reinterpret_cast<GLsync>(%d)" % (index + 1))
8382 return str(index + 1)
8384 def GetValidClientSideCmdArg(self, func):
8385 """Gets a valid value for this argument."""
8386 valid_arg = func.GetValidArg(self)
8387 if valid_arg != None:
8388 return valid_arg
8389 try:
8390 index = func.GetOriginalArgs().index(self)
8391 return str(index + 1)
8392 except ValueError:
8393 pass
8394 index = func.GetCmdArgs().index(self)
8395 return str(index + 1)
8397 def GetValidGLArg(self, func):
8398 """Gets a valid GL value for this argument."""
8399 value = self.GetValidArg(func)
8400 if self.type == 'GLsync':
8401 return ("reinterpret_cast<GLsync>(%s)" % value)
8402 return value
8404 def GetValidNonCachedClientSideArg(self, func):
8405 """Returns a valid value for this argument in a GL call.
8406 Using the value will produce a command buffer service invocation.
8407 Returns None if there is no such value."""
8408 value = '123'
8409 if self.type == 'GLsync':
8410 return ("reinterpret_cast<GLsync>(%s)" % value)
8411 return value
8413 def GetValidNonCachedClientSideCmdArg(self, func):
8414 """Returns a valid value for this argument in a command buffer command.
8415 Calling the GL function with the value returned by
8416 GetValidNonCachedClientSideArg will result in a command buffer command
8417 that contains the value returned by this function. """
8418 return '123'
8420 def GetNumInvalidValues(self, func):
8421 """returns the number of invalid values to be tested."""
8422 return 0
8424 def GetInvalidArg(self, index):
8425 """returns an invalid value and expected parse result by index."""
8426 return ("---ERROR0---", "---ERROR2---", None)
8428 def GetLogArg(self):
8429 """Get argument appropriate for LOG macro."""
8430 if self.type == 'GLboolean':
8431 return 'GLES2Util::GetStringBool(%s)' % self.name
8432 if self.type == 'GLenum':
8433 return 'GLES2Util::GetStringEnum(%s)' % self.name
8434 return self.name
8436 def WriteGetCode(self, f):
8437 """Writes the code to get an argument from a command structure."""
8438 if self.type == 'GLsync':
8439 my_type = 'GLuint'
8440 else:
8441 my_type = self.type
8442 f.write(" %s %s = static_cast<%s>(c.%s);\n" %
8443 (my_type, self.name, my_type, self.name))
8445 def WriteValidationCode(self, f, func):
8446 """Writes the validation code for an argument."""
8447 pass
8449 def WriteClientSideValidationCode(self, f, func):
8450 """Writes the validation code for an argument."""
8451 pass
8453 def WriteDestinationInitalizationValidation(self, f, func):
8454 """Writes the client side destintion initialization validation."""
8455 pass
8457 def WriteDestinationInitalizationValidatationIfNeeded(self, f, func):
8458 """Writes the client side destintion initialization validation if needed."""
8459 parts = self.type.split(" ")
8460 if len(parts) > 1:
8461 return
8462 if parts[0] in self.need_validation_:
8463 f.write(
8464 " GPU_CLIENT_VALIDATE_DESTINATION_%sINITALIZATION(%s, %s);\n" %
8465 ("OPTIONAL_" if self.optional else "", self.type[:-1], self.name))
8467 def GetImmediateVersion(self):
8468 """Gets the immediate version of this argument."""
8469 return self
8471 def GetBucketVersion(self):
8472 """Gets the bucket version of this argument."""
8473 return self
8476 class BoolArgument(Argument):
8477 """class for GLboolean"""
8479 def __init__(self, name, type):
8480 Argument.__init__(self, name, 'GLboolean')
8482 def GetValidArg(self, func):
8483 """Gets a valid value for this argument."""
8484 return 'true'
8486 def GetValidClientSideArg(self, func):
8487 """Gets a valid value for this argument."""
8488 return 'true'
8490 def GetValidClientSideCmdArg(self, func):
8491 """Gets a valid value for this argument."""
8492 return 'true'
8494 def GetValidGLArg(self, func):
8495 """Gets a valid GL value for this argument."""
8496 return 'true'
8499 class UniformLocationArgument(Argument):
8500 """class for uniform locations."""
8502 def __init__(self, name):
8503 Argument.__init__(self, name, "GLint")
8505 def WriteGetCode(self, f):
8506 """Writes the code to get an argument from a command structure."""
8507 code = """ %s %s = static_cast<%s>(c.%s);
8509 f.write(code % (self.type, self.name, self.type, self.name))
8511 class DataSizeArgument(Argument):
8512 """class for data_size which Bucket commands do not need."""
8514 def __init__(self, name):
8515 Argument.__init__(self, name, "uint32_t")
8517 def GetBucketVersion(self):
8518 return None
8521 class SizeArgument(Argument):
8522 """class for GLsizei and GLsizeiptr."""
8524 def GetNumInvalidValues(self, func):
8525 """overridden from Argument."""
8526 if func.IsImmediate():
8527 return 0
8528 return 1
8530 def GetInvalidArg(self, index):
8531 """overridden from Argument."""
8532 return ("-1", "kNoError", "GL_INVALID_VALUE")
8534 def WriteValidationCode(self, f, func):
8535 """overridden from Argument."""
8536 if func.IsUnsafe():
8537 return
8538 code = """ if (%(var_name)s < 0) {
8539 LOCAL_SET_GL_ERROR(GL_INVALID_VALUE, "gl%(func_name)s", "%(var_name)s < 0");
8540 return error::kNoError;
8543 f.write(code % {
8544 "var_name": self.name,
8545 "func_name": func.original_name,
8548 def WriteClientSideValidationCode(self, f, func):
8549 """overridden from Argument."""
8550 code = """ if (%(var_name)s < 0) {
8551 SetGLError(GL_INVALID_VALUE, "gl%(func_name)s", "%(var_name)s < 0");
8552 return;
8555 f.write(code % {
8556 "var_name": self.name,
8557 "func_name": func.original_name,
8561 class SizeNotNegativeArgument(SizeArgument):
8562 """class for GLsizeiNotNegative. It's NEVER allowed to be negative"""
8564 def __init__(self, name, type, gl_type):
8565 SizeArgument.__init__(self, name, gl_type)
8567 def GetInvalidArg(self, index):
8568 """overridden from SizeArgument."""
8569 return ("-1", "kOutOfBounds", "GL_NO_ERROR")
8571 def WriteValidationCode(self, f, func):
8572 """overridden from SizeArgument."""
8573 pass
8576 class EnumBaseArgument(Argument):
8577 """Base class for EnumArgument, IntArgument, BitfieldArgument, and
8578 ValidatedBoolArgument."""
8580 def __init__(self, name, gl_type, type, gl_error):
8581 Argument.__init__(self, name, gl_type)
8583 self.gl_error = gl_error
8584 name = type[len(gl_type):]
8585 self.type_name = name
8586 self.named_type = NamedType(_NAMED_TYPE_INFO[name])
8588 def IsConstant(self):
8589 return self.named_type.IsConstant()
8591 def GetConstantValue(self):
8592 return self.named_type.GetConstantValue()
8594 def WriteValidationCode(self, f, func):
8595 if func.IsUnsafe():
8596 return
8597 if self.named_type.IsConstant():
8598 return
8599 f.write(" if (!validators_->%s.IsValid(%s)) {\n" %
8600 (ToUnderscore(self.type_name), self.name))
8601 if self.gl_error == "GL_INVALID_ENUM":
8602 f.write(
8603 " LOCAL_SET_GL_ERROR_INVALID_ENUM(\"gl%s\", %s, \"%s\");\n" %
8604 (func.original_name, self.name, self.name))
8605 else:
8606 f.write(
8607 " LOCAL_SET_GL_ERROR(%s, \"gl%s\", \"%s %s\");\n" %
8608 (self.gl_error, func.original_name, self.name, self.gl_error))
8609 f.write(" return error::kNoError;\n")
8610 f.write(" }\n")
8612 def WriteClientSideValidationCode(self, f, func):
8613 if not self.named_type.IsConstant():
8614 return
8615 f.write(" if (%s != %s) {" % (self.name,
8616 self.GetConstantValue()))
8617 f.write(
8618 " SetGLError(%s, \"gl%s\", \"%s %s\");\n" %
8619 (self.gl_error, func.original_name, self.name, self.gl_error))
8620 if func.return_type == "void":
8621 f.write(" return;\n")
8622 else:
8623 f.write(" return %s;\n" % func.GetErrorReturnString())
8624 f.write(" }\n")
8626 def GetValidArg(self, func):
8627 valid_arg = func.GetValidArg(self)
8628 if valid_arg != None:
8629 return valid_arg
8630 valid = self.named_type.GetValidValues()
8631 if valid:
8632 return valid[0]
8634 index = func.GetOriginalArgs().index(self)
8635 return str(index + 1)
8637 def GetValidClientSideArg(self, func):
8638 """Gets a valid value for this argument."""
8639 return self.GetValidArg(func)
8641 def GetValidClientSideCmdArg(self, func):
8642 """Gets a valid value for this argument."""
8643 valid_arg = func.GetValidArg(self)
8644 if valid_arg != None:
8645 return valid_arg
8647 valid = self.named_type.GetValidValues()
8648 if valid:
8649 return valid[0]
8651 try:
8652 index = func.GetOriginalArgs().index(self)
8653 return str(index + 1)
8654 except ValueError:
8655 pass
8656 index = func.GetCmdArgs().index(self)
8657 return str(index + 1)
8659 def GetValidGLArg(self, func):
8660 """Gets a valid value for this argument."""
8661 return self.GetValidArg(func)
8663 def GetNumInvalidValues(self, func):
8664 """returns the number of invalid values to be tested."""
8665 return len(self.named_type.GetInvalidValues())
8667 def GetInvalidArg(self, index):
8668 """returns an invalid value by index."""
8669 invalid = self.named_type.GetInvalidValues()
8670 if invalid:
8671 num_invalid = len(invalid)
8672 if index >= num_invalid:
8673 index = num_invalid - 1
8674 return (invalid[index], "kNoError", self.gl_error)
8675 return ("---ERROR1---", "kNoError", self.gl_error)
8678 class EnumArgument(EnumBaseArgument):
8679 """A class that represents a GLenum argument"""
8681 def __init__(self, name, type):
8682 EnumBaseArgument.__init__(self, name, "GLenum", type, "GL_INVALID_ENUM")
8684 def GetLogArg(self):
8685 """Overridden from Argument."""
8686 return ("GLES2Util::GetString%s(%s)" %
8687 (self.type_name, self.name))
8690 class IntArgument(EnumBaseArgument):
8691 """A class for a GLint argument that can only accept specific values.
8693 For example glTexImage2D takes a GLint for its internalformat
8694 argument instead of a GLenum.
8697 def __init__(self, name, type):
8698 EnumBaseArgument.__init__(self, name, "GLint", type, "GL_INVALID_VALUE")
8701 class ValidatedBoolArgument(EnumBaseArgument):
8702 """A class for a GLboolean argument that can only accept specific values.
8704 For example glUniformMatrix takes a GLboolean for it's transpose but it
8705 must be false.
8708 def __init__(self, name, type):
8709 EnumBaseArgument.__init__(self, name, "GLboolean", type, "GL_INVALID_VALUE")
8711 def GetLogArg(self):
8712 """Overridden from Argument."""
8713 return 'GLES2Util::GetStringBool(%s)' % self.name
8716 class BitFieldArgument(EnumBaseArgument):
8717 """A class for a GLbitfield argument that can only accept specific values.
8719 For example glFenceSync takes a GLbitfield for its flags argument bit it
8720 must be 0.
8723 def __init__(self, name, type):
8724 EnumBaseArgument.__init__(self, name, "GLbitfield", type,
8725 "GL_INVALID_VALUE")
8728 class ImmediatePointerArgument(Argument):
8729 """A class that represents an immediate argument to a function.
8731 An immediate argument is one where the data follows the command.
8734 def IsPointer(self):
8735 return True
8737 def GetPointedType(self):
8738 match = re.match('(const\s+)?(?P<element_type>[\w]+)\s*\*', self.type)
8739 assert match
8740 return match.groupdict()['element_type']
8742 def AddCmdArgs(self, args):
8743 """Overridden from Argument."""
8744 pass
8746 def WriteGetCode(self, f):
8747 """Overridden from Argument."""
8748 f.write(
8749 " %s %s = GetImmediateDataAs<%s>(\n" %
8750 (self.type, self.name, self.type))
8751 f.write(" c, data_size, immediate_data_size);\n")
8753 def WriteValidationCode(self, f, func):
8754 """Overridden from Argument."""
8755 if self.optional:
8756 return
8757 f.write(" if (%s == NULL) {\n" % self.name)
8758 f.write(" return error::kOutOfBounds;\n")
8759 f.write(" }\n")
8761 def GetImmediateVersion(self):
8762 """Overridden from Argument."""
8763 return None
8765 def WriteDestinationInitalizationValidation(self, f, func):
8766 """Overridden from Argument."""
8767 self.WriteDestinationInitalizationValidatationIfNeeded(f, func)
8769 def GetLogArg(self):
8770 """Overridden from Argument."""
8771 return "static_cast<const void*>(%s)" % self.name
8774 class PointerArgument(Argument):
8775 """A class that represents a pointer argument to a function."""
8777 def IsPointer(self):
8778 """Overridden from Argument."""
8779 return True
8781 def IsPointer2D(self):
8782 """Overridden from Argument."""
8783 return self.type.count('*') == 2
8785 def GetPointedType(self):
8786 match = re.match('(const\s+)?(?P<element_type>[\w]+)\s*\*', self.type)
8787 assert match
8788 return match.groupdict()['element_type']
8790 def GetValidArg(self, func):
8791 """Overridden from Argument."""
8792 return "shared_memory_id_, shared_memory_offset_"
8794 def GetValidGLArg(self, func):
8795 """Overridden from Argument."""
8796 return "reinterpret_cast<%s>(shared_memory_address_)" % self.type
8798 def GetNumInvalidValues(self, func):
8799 """Overridden from Argument."""
8800 return 2
8802 def GetInvalidArg(self, index):
8803 """Overridden from Argument."""
8804 if index == 0:
8805 return ("kInvalidSharedMemoryId, 0", "kOutOfBounds", None)
8806 else:
8807 return ("shared_memory_id_, kInvalidSharedMemoryOffset",
8808 "kOutOfBounds", None)
8810 def GetLogArg(self):
8811 """Overridden from Argument."""
8812 return "static_cast<const void*>(%s)" % self.name
8814 def AddCmdArgs(self, args):
8815 """Overridden from Argument."""
8816 args.append(Argument("%s_shm_id" % self.name, 'uint32_t'))
8817 args.append(Argument("%s_shm_offset" % self.name, 'uint32_t'))
8819 def WriteGetCode(self, f):
8820 """Overridden from Argument."""
8821 f.write(
8822 " %s %s = GetSharedMemoryAs<%s>(\n" %
8823 (self.type, self.name, self.type))
8824 f.write(
8825 " c.%s_shm_id, c.%s_shm_offset, data_size);\n" %
8826 (self.name, self.name))
8828 def WriteValidationCode(self, f, func):
8829 """Overridden from Argument."""
8830 if self.optional:
8831 return
8832 f.write(" if (%s == NULL) {\n" % self.name)
8833 f.write(" return error::kOutOfBounds;\n")
8834 f.write(" }\n")
8836 def GetImmediateVersion(self):
8837 """Overridden from Argument."""
8838 return ImmediatePointerArgument(self.name, self.type)
8840 def GetBucketVersion(self):
8841 """Overridden from Argument."""
8842 if self.type.find('char') >= 0:
8843 if self.IsPointer2D():
8844 return InputStringArrayBucketArgument(self.name, self.type)
8845 return InputStringBucketArgument(self.name, self.type)
8846 return BucketPointerArgument(self.name, self.type)
8848 def WriteDestinationInitalizationValidation(self, f, func):
8849 """Overridden from Argument."""
8850 self.WriteDestinationInitalizationValidatationIfNeeded(f, func)
8853 class BucketPointerArgument(PointerArgument):
8854 """A class that represents an bucket argument to a function."""
8856 def AddCmdArgs(self, args):
8857 """Overridden from Argument."""
8858 pass
8860 def WriteGetCode(self, f):
8861 """Overridden from Argument."""
8862 f.write(
8863 " %s %s = bucket->GetData(0, data_size);\n" %
8864 (self.type, self.name))
8866 def WriteValidationCode(self, f, func):
8867 """Overridden from Argument."""
8868 pass
8870 def GetImmediateVersion(self):
8871 """Overridden from Argument."""
8872 return None
8874 def WriteDestinationInitalizationValidation(self, f, func):
8875 """Overridden from Argument."""
8876 self.WriteDestinationInitalizationValidatationIfNeeded(f, func)
8878 def GetLogArg(self):
8879 """Overridden from Argument."""
8880 return "static_cast<const void*>(%s)" % self.name
8883 class InputStringBucketArgument(Argument):
8884 """A string input argument where the string is passed in a bucket."""
8886 def __init__(self, name, type):
8887 Argument.__init__(self, name + "_bucket_id", "uint32_t")
8889 def IsPointer(self):
8890 """Overridden from Argument."""
8891 return True
8893 def IsPointer2D(self):
8894 """Overridden from Argument."""
8895 return False
8898 class InputStringArrayBucketArgument(Argument):
8899 """A string array input argument where the strings are passed in a bucket."""
8901 def __init__(self, name, type):
8902 Argument.__init__(self, name + "_bucket_id", "uint32_t")
8903 self._original_name = name
8905 def WriteGetCode(self, f):
8906 """Overridden from Argument."""
8907 code = """
8908 Bucket* bucket = GetBucket(c.%(name)s);
8909 if (!bucket) {
8910 return error::kInvalidArguments;
8912 GLsizei count = 0;
8913 std::vector<char*> strs;
8914 std::vector<GLint> len;
8915 if (!bucket->GetAsStrings(&count, &strs, &len)) {
8916 return error::kInvalidArguments;
8918 const char** %(original_name)s =
8919 strs.size() > 0 ? const_cast<const char**>(&strs[0]) : NULL;
8920 const GLint* length =
8921 len.size() > 0 ? const_cast<const GLint*>(&len[0]) : NULL;
8922 (void)length;
8924 f.write(code % {
8925 'name': self.name,
8926 'original_name': self._original_name,
8929 def GetValidArg(self, func):
8930 return "kNameBucketId"
8932 def GetValidGLArg(self, func):
8933 return "_"
8935 def IsPointer(self):
8936 """Overridden from Argument."""
8937 return True
8939 def IsPointer2D(self):
8940 """Overridden from Argument."""
8941 return True
8944 class ResourceIdArgument(Argument):
8945 """A class that represents a resource id argument to a function."""
8947 def __init__(self, name, type):
8948 match = re.match("(GLid\w+)", type)
8949 self.resource_type = match.group(1)[4:]
8950 if self.resource_type == "Sync":
8951 type = type.replace(match.group(1), "GLsync")
8952 else:
8953 type = type.replace(match.group(1), "GLuint")
8954 Argument.__init__(self, name, type)
8956 def WriteGetCode(self, f):
8957 """Overridden from Argument."""
8958 if self.type == "GLsync":
8959 my_type = "GLuint"
8960 else:
8961 my_type = self.type
8962 f.write(" %s %s = c.%s;\n" % (my_type, self.name, self.name))
8964 def GetValidArg(self, func):
8965 return "client_%s_id_" % self.resource_type.lower()
8967 def GetValidGLArg(self, func):
8968 if self.resource_type == "Sync":
8969 return "reinterpret_cast<GLsync>(kService%sId)" % self.resource_type
8970 return "kService%sId" % self.resource_type
8973 class ResourceIdBindArgument(Argument):
8974 """Represents a resource id argument to a bind function."""
8976 def __init__(self, name, type):
8977 match = re.match("(GLidBind\w+)", type)
8978 self.resource_type = match.group(1)[8:]
8979 type = type.replace(match.group(1), "GLuint")
8980 Argument.__init__(self, name, type)
8982 def WriteGetCode(self, f):
8983 """Overridden from Argument."""
8984 code = """ %(type)s %(name)s = c.%(name)s;
8986 f.write(code % {'type': self.type, 'name': self.name})
8988 def GetValidArg(self, func):
8989 return "client_%s_id_" % self.resource_type.lower()
8991 def GetValidGLArg(self, func):
8992 return "kService%sId" % self.resource_type
8995 class ResourceIdZeroArgument(Argument):
8996 """Represents a resource id argument to a function that can be zero."""
8998 def __init__(self, name, type):
8999 match = re.match("(GLidZero\w+)", type)
9000 self.resource_type = match.group(1)[8:]
9001 type = type.replace(match.group(1), "GLuint")
9002 Argument.__init__(self, name, type)
9004 def WriteGetCode(self, f):
9005 """Overridden from Argument."""
9006 f.write(" %s %s = c.%s;\n" % (self.type, self.name, self.name))
9008 def GetValidArg(self, func):
9009 return "client_%s_id_" % self.resource_type.lower()
9011 def GetValidGLArg(self, func):
9012 return "kService%sId" % self.resource_type
9014 def GetNumInvalidValues(self, func):
9015 """returns the number of invalid values to be tested."""
9016 return 1
9018 def GetInvalidArg(self, index):
9019 """returns an invalid value by index."""
9020 return ("kInvalidClientId", "kNoError", "GL_INVALID_VALUE")
9023 class Function(object):
9024 """A class that represents a function."""
9026 type_handlers = {
9027 '': TypeHandler(),
9028 'Bind': BindHandler(),
9029 'Create': CreateHandler(),
9030 'Custom': CustomHandler(),
9031 'Data': DataHandler(),
9032 'Delete': DeleteHandler(),
9033 'DELn': DELnHandler(),
9034 'GENn': GENnHandler(),
9035 'GETn': GETnHandler(),
9036 'GLchar': GLcharHandler(),
9037 'GLcharN': GLcharNHandler(),
9038 'HandWritten': HandWrittenHandler(),
9039 'Is': IsHandler(),
9040 'Manual': ManualHandler(),
9041 'PUT': PUTHandler(),
9042 'PUTn': PUTnHandler(),
9043 'PUTSTR': PUTSTRHandler(),
9044 'PUTXn': PUTXnHandler(),
9045 'StateSet': StateSetHandler(),
9046 'StateSetRGBAlpha': StateSetRGBAlphaHandler(),
9047 'StateSetFrontBack': StateSetFrontBackHandler(),
9048 'StateSetFrontBackSeparate': StateSetFrontBackSeparateHandler(),
9049 'StateSetNamedParameter': StateSetNamedParameter(),
9050 'STRn': STRnHandler(),
9053 def __init__(self, name, info):
9054 self.name = name
9055 self.original_name = info['original_name']
9057 self.original_args = self.ParseArgs(info['original_args'])
9059 if 'cmd_args' in info:
9060 self.args_for_cmds = self.ParseArgs(info['cmd_args'])
9061 else:
9062 self.args_for_cmds = self.original_args[:]
9064 self.return_type = info['return_type']
9065 if self.return_type != 'void':
9066 self.return_arg = CreateArg(info['return_type'] + " result")
9067 else:
9068 self.return_arg = None
9070 self.num_pointer_args = sum(
9071 [1 for arg in self.args_for_cmds if arg.IsPointer()])
9072 if self.num_pointer_args > 0:
9073 for arg in reversed(self.original_args):
9074 if arg.IsPointer():
9075 self.last_original_pointer_arg = arg
9076 break
9077 else:
9078 self.last_original_pointer_arg = None
9079 self.info = info
9080 self.type_handler = self.type_handlers[info['type']]
9081 self.can_auto_generate = (self.num_pointer_args == 0 and
9082 info['return_type'] == "void")
9083 self.InitFunction()
9085 def ParseArgs(self, arg_string):
9086 """Parses a function arg string."""
9087 args = []
9088 parts = arg_string.split(',')
9089 for arg_string in parts:
9090 arg = CreateArg(arg_string)
9091 if arg:
9092 args.append(arg)
9093 return args
9095 def IsType(self, type_name):
9096 """Returns true if function is a certain type."""
9097 return self.info['type'] == type_name
9099 def InitFunction(self):
9100 """Creates command args and calls the init function for the type handler.
9102 Creates argument lists for command buffer commands, eg. self.cmd_args and
9103 self.init_args.
9104 Calls the type function initialization.
9105 Override to create different kind of command buffer command argument lists.
9107 self.cmd_args = []
9108 for arg in self.args_for_cmds:
9109 arg.AddCmdArgs(self.cmd_args)
9111 self.init_args = []
9112 for arg in self.args_for_cmds:
9113 arg.AddInitArgs(self.init_args)
9115 if self.return_arg:
9116 self.init_args.append(self.return_arg)
9118 self.type_handler.InitFunction(self)
9120 def IsImmediate(self):
9121 """Returns whether the function is immediate data function or not."""
9122 return False
9124 def IsUnsafe(self):
9125 """Returns whether the function has service side validation or not."""
9126 return self.GetInfo('unsafe', False)
9128 def GetInfo(self, name, default = None):
9129 """Returns a value from the function info for this function."""
9130 if name in self.info:
9131 return self.info[name]
9132 return default
9134 def GetValidArg(self, arg):
9135 """Gets a valid argument value for the parameter arg from the function info
9136 if one exists."""
9137 try:
9138 index = self.GetOriginalArgs().index(arg)
9139 except ValueError:
9140 return None
9142 valid_args = self.GetInfo('valid_args')
9143 if valid_args and str(index) in valid_args:
9144 return valid_args[str(index)]
9145 return None
9147 def AddInfo(self, name, value):
9148 """Adds an info."""
9149 self.info[name] = value
9151 def IsExtension(self):
9152 return self.GetInfo('extension') or self.GetInfo('extension_flag')
9154 def IsCoreGLFunction(self):
9155 return (not self.IsExtension() and
9156 not self.GetInfo('pepper_interface') and
9157 not self.IsUnsafe())
9159 def InPepperInterface(self, interface):
9160 ext = self.GetInfo('pepper_interface')
9161 if not interface.GetName():
9162 return self.IsCoreGLFunction()
9163 return ext == interface.GetName()
9165 def InAnyPepperExtension(self):
9166 return self.IsCoreGLFunction() or self.GetInfo('pepper_interface')
9168 def GetErrorReturnString(self):
9169 if self.GetInfo("error_return"):
9170 return self.GetInfo("error_return")
9171 elif self.return_type == "GLboolean":
9172 return "GL_FALSE"
9173 elif "*" in self.return_type:
9174 return "NULL"
9175 return "0"
9177 def GetGLFunctionName(self):
9178 """Gets the function to call to execute GL for this command."""
9179 if self.GetInfo('decoder_func'):
9180 return self.GetInfo('decoder_func')
9181 return "gl%s" % self.original_name
9183 def GetGLTestFunctionName(self):
9184 gl_func_name = self.GetInfo('gl_test_func')
9185 if gl_func_name == None:
9186 gl_func_name = self.GetGLFunctionName()
9187 if gl_func_name.startswith("gl"):
9188 gl_func_name = gl_func_name[2:]
9189 else:
9190 gl_func_name = self.original_name
9191 return gl_func_name
9193 def GetDataTransferMethods(self):
9194 return self.GetInfo('data_transfer_methods',
9195 ['immediate' if self.num_pointer_args == 1 else 'shm'])
9197 def AddCmdArg(self, arg):
9198 """Adds a cmd argument to this function."""
9199 self.cmd_args.append(arg)
9201 def GetCmdArgs(self):
9202 """Gets the command args for this function."""
9203 return self.cmd_args
9205 def ClearCmdArgs(self):
9206 """Clears the command args for this function."""
9207 self.cmd_args = []
9209 def GetCmdConstants(self):
9210 """Gets the constants for this function."""
9211 return [arg for arg in self.args_for_cmds if arg.IsConstant()]
9213 def GetInitArgs(self):
9214 """Gets the init args for this function."""
9215 return self.init_args
9217 def GetOriginalArgs(self):
9218 """Gets the original arguments to this function."""
9219 return self.original_args
9221 def GetLastOriginalArg(self):
9222 """Gets the last original argument to this function."""
9223 return self.original_args[len(self.original_args) - 1]
9225 def GetLastOriginalPointerArg(self):
9226 return self.last_original_pointer_arg
9228 def GetResourceIdArg(self):
9229 for arg in self.original_args:
9230 if hasattr(arg, 'resource_type'):
9231 return arg
9232 return None
9234 def _MaybePrependComma(self, arg_string, add_comma):
9235 """Adds a comma if arg_string is not empty and add_comma is true."""
9236 comma = ""
9237 if add_comma and len(arg_string):
9238 comma = ", "
9239 return "%s%s" % (comma, arg_string)
9241 def MakeTypedOriginalArgString(self, prefix, add_comma = False):
9242 """Gets a list of arguments as they are in GL."""
9243 args = self.GetOriginalArgs()
9244 arg_string = ", ".join(
9245 ["%s %s%s" % (arg.type, prefix, arg.name) for arg in args])
9246 return self._MaybePrependComma(arg_string, add_comma)
9248 def MakeOriginalArgString(self, prefix, add_comma = False, separator = ", "):
9249 """Gets the list of arguments as they are in GL."""
9250 args = self.GetOriginalArgs()
9251 arg_string = separator.join(
9252 ["%s%s" % (prefix, arg.name) for arg in args])
9253 return self._MaybePrependComma(arg_string, add_comma)
9255 def MakeHelperArgString(self, prefix, add_comma = False, separator = ", "):
9256 """Gets a list of GL arguments after removing unneeded arguments."""
9257 args = self.GetOriginalArgs()
9258 arg_string = separator.join(
9259 ["%s%s" % (prefix, arg.name)
9260 for arg in args if not arg.IsConstant()])
9261 return self._MaybePrependComma(arg_string, add_comma)
9263 def MakeTypedPepperArgString(self, prefix):
9264 """Gets a list of arguments as they need to be for Pepper."""
9265 if self.GetInfo("pepper_args"):
9266 return self.GetInfo("pepper_args")
9267 else:
9268 return self.MakeTypedOriginalArgString(prefix, False)
9270 def MapCTypeToPepperIdlType(self, ctype, is_for_return_type=False):
9271 """Converts a C type name to the corresponding Pepper IDL type."""
9272 idltype = {
9273 'char*': '[out] str_t',
9274 'const GLchar* const*': '[out] cstr_t',
9275 'const char*': 'cstr_t',
9276 'const void*': 'mem_t',
9277 'void*': '[out] mem_t',
9278 'void**': '[out] mem_ptr_t',
9279 }.get(ctype, ctype)
9280 # We use "GLxxx_ptr_t" for "GLxxx*".
9281 matched = re.match(r'(const )?(GL\w+)\*$', ctype)
9282 if matched:
9283 idltype = matched.group(2) + '_ptr_t'
9284 if not matched.group(1):
9285 idltype = '[out] ' + idltype
9286 # If an in/out specifier is not specified yet, prepend [in].
9287 if idltype[0] != '[':
9288 idltype = '[in] ' + idltype
9289 # Strip the in/out specifier for a return type.
9290 if is_for_return_type:
9291 idltype = re.sub(r'\[\w+\] ', '', idltype)
9292 return idltype
9294 def MakeTypedPepperIdlArgStrings(self):
9295 """Gets a list of arguments as they need to be for Pepper IDL."""
9296 args = self.GetOriginalArgs()
9297 return ["%s %s" % (self.MapCTypeToPepperIdlType(arg.type), arg.name)
9298 for arg in args]
9300 def GetPepperName(self):
9301 if self.GetInfo("pepper_name"):
9302 return self.GetInfo("pepper_name")
9303 return self.name
9305 def MakeTypedCmdArgString(self, prefix, add_comma = False):
9306 """Gets a typed list of arguments as they need to be for command buffers."""
9307 args = self.GetCmdArgs()
9308 arg_string = ", ".join(
9309 ["%s %s%s" % (arg.type, prefix, arg.name) for arg in args])
9310 return self._MaybePrependComma(arg_string, add_comma)
9312 def MakeCmdArgString(self, prefix, add_comma = False):
9313 """Gets the list of arguments as they need to be for command buffers."""
9314 args = self.GetCmdArgs()
9315 arg_string = ", ".join(
9316 ["%s%s" % (prefix, arg.name) for arg in args])
9317 return self._MaybePrependComma(arg_string, add_comma)
9319 def MakeTypedInitString(self, prefix, add_comma = False):
9320 """Gets a typed list of arguments as they need to be for cmd Init/Set."""
9321 args = self.GetInitArgs()
9322 arg_string = ", ".join(
9323 ["%s %s%s" % (arg.type, prefix, arg.name) for arg in args])
9324 return self._MaybePrependComma(arg_string, add_comma)
9326 def MakeInitString(self, prefix, add_comma = False):
9327 """Gets the list of arguments as they need to be for cmd Init/Set."""
9328 args = self.GetInitArgs()
9329 arg_string = ", ".join(
9330 ["%s%s" % (prefix, arg.name) for arg in args])
9331 return self._MaybePrependComma(arg_string, add_comma)
9333 def MakeLogArgString(self):
9334 """Makes a string of the arguments for the LOG macros"""
9335 args = self.GetOriginalArgs()
9336 return ' << ", " << '.join([arg.GetLogArg() for arg in args])
9338 def WriteHandlerValidation(self, f):
9339 """Writes validation code for the function."""
9340 for arg in self.GetOriginalArgs():
9341 arg.WriteValidationCode(f, self)
9342 self.WriteValidationCode(f)
9344 def WriteHandlerImplementation(self, f):
9345 """Writes the handler implementation for this command."""
9346 self.type_handler.WriteHandlerImplementation(self, f)
9348 def WriteValidationCode(self, f):
9349 """Writes the validation code for a command."""
9350 pass
9352 def WriteCmdFlag(self, f):
9353 """Writes the cmd cmd_flags constant."""
9354 flags = []
9355 # By default trace only at the highest level 3.
9356 trace_level = int(self.GetInfo('trace_level', default = 3))
9357 if trace_level not in xrange(0, 4):
9358 raise KeyError("Unhandled trace_level: %d" % trace_level)
9360 flags.append('CMD_FLAG_SET_TRACE_LEVEL(%d)' % trace_level)
9362 if len(flags) > 0:
9363 cmd_flags = ' | '.join(flags)
9364 else:
9365 cmd_flags = 0
9367 f.write(" static const uint8 cmd_flags = %s;\n" % cmd_flags)
9370 def WriteCmdArgFlag(self, f):
9371 """Writes the cmd kArgFlags constant."""
9372 f.write(" static const cmd::ArgFlags kArgFlags = cmd::kFixed;\n")
9374 def WriteCmdComputeSize(self, f):
9375 """Writes the ComputeSize function for the command."""
9376 f.write(" static uint32_t ComputeSize() {\n")
9377 f.write(
9378 " return static_cast<uint32_t>(sizeof(ValueType)); // NOLINT\n")
9379 f.write(" }\n")
9380 f.write("\n")
9382 def WriteCmdSetHeader(self, f):
9383 """Writes the cmd's SetHeader function."""
9384 f.write(" void SetHeader() {\n")
9385 f.write(" header.SetCmd<ValueType>();\n")
9386 f.write(" }\n")
9387 f.write("\n")
9389 def WriteCmdInit(self, f):
9390 """Writes the cmd's Init function."""
9391 f.write(" void Init(%s) {\n" % self.MakeTypedCmdArgString("_"))
9392 f.write(" SetHeader();\n")
9393 args = self.GetCmdArgs()
9394 for arg in args:
9395 f.write(" %s = _%s;\n" % (arg.name, arg.name))
9396 f.write(" }\n")
9397 f.write("\n")
9399 def WriteCmdSet(self, f):
9400 """Writes the cmd's Set function."""
9401 copy_args = self.MakeCmdArgString("_", False)
9402 f.write(" void* Set(void* cmd%s) {\n" %
9403 self.MakeTypedCmdArgString("_", True))
9404 f.write(" static_cast<ValueType*>(cmd)->Init(%s);\n" % copy_args)
9405 f.write(" return NextCmdAddress<ValueType>(cmd);\n")
9406 f.write(" }\n")
9407 f.write("\n")
9409 def WriteStruct(self, f):
9410 self.type_handler.WriteStruct(self, f)
9412 def WriteDocs(self, f):
9413 self.type_handler.WriteDocs(self, f)
9415 def WriteCmdHelper(self, f):
9416 """Writes the cmd's helper."""
9417 self.type_handler.WriteCmdHelper(self, f)
9419 def WriteServiceImplementation(self, f):
9420 """Writes the service implementation for a command."""
9421 self.type_handler.WriteServiceImplementation(self, f)
9423 def WriteServiceUnitTest(self, f, *extras):
9424 """Writes the service implementation for a command."""
9425 self.type_handler.WriteServiceUnitTest(self, f, *extras)
9427 def WriteGLES2CLibImplementation(self, f):
9428 """Writes the GLES2 C Lib Implemention."""
9429 self.type_handler.WriteGLES2CLibImplementation(self, f)
9431 def WriteGLES2InterfaceHeader(self, f):
9432 """Writes the GLES2 Interface declaration."""
9433 self.type_handler.WriteGLES2InterfaceHeader(self, f)
9435 def WriteMojoGLES2ImplHeader(self, f):
9436 """Writes the Mojo GLES2 implementation header declaration."""
9437 self.type_handler.WriteMojoGLES2ImplHeader(self, f)
9439 def WriteMojoGLES2Impl(self, f):
9440 """Writes the Mojo GLES2 implementation declaration."""
9441 self.type_handler.WriteMojoGLES2Impl(self, f)
9443 def WriteGLES2InterfaceStub(self, f):
9444 """Writes the GLES2 Interface Stub declaration."""
9445 self.type_handler.WriteGLES2InterfaceStub(self, f)
9447 def WriteGLES2InterfaceStubImpl(self, f):
9448 """Writes the GLES2 Interface Stub declaration."""
9449 self.type_handler.WriteGLES2InterfaceStubImpl(self, f)
9451 def WriteGLES2ImplementationHeader(self, f):
9452 """Writes the GLES2 Implemention declaration."""
9453 self.type_handler.WriteGLES2ImplementationHeader(self, f)
9455 def WriteGLES2Implementation(self, f):
9456 """Writes the GLES2 Implemention definition."""
9457 self.type_handler.WriteGLES2Implementation(self, f)
9459 def WriteGLES2TraceImplementationHeader(self, f):
9460 """Writes the GLES2 Trace Implemention declaration."""
9461 self.type_handler.WriteGLES2TraceImplementationHeader(self, f)
9463 def WriteGLES2TraceImplementation(self, f):
9464 """Writes the GLES2 Trace Implemention definition."""
9465 self.type_handler.WriteGLES2TraceImplementation(self, f)
9467 def WriteGLES2Header(self, f):
9468 """Writes the GLES2 Implemention unit test."""
9469 self.type_handler.WriteGLES2Header(self, f)
9471 def WriteGLES2ImplementationUnitTest(self, f):
9472 """Writes the GLES2 Implemention unit test."""
9473 self.type_handler.WriteGLES2ImplementationUnitTest(self, f)
9475 def WriteDestinationInitalizationValidation(self, f):
9476 """Writes the client side destintion initialization validation."""
9477 self.type_handler.WriteDestinationInitalizationValidation(self, f)
9479 def WriteFormatTest(self, f):
9480 """Writes the cmd's format test."""
9481 self.type_handler.WriteFormatTest(self, f)
9484 class PepperInterface(object):
9485 """A class that represents a function."""
9487 def __init__(self, info):
9488 self.name = info["name"]
9489 self.dev = info["dev"]
9491 def GetName(self):
9492 return self.name
9494 def GetInterfaceName(self):
9495 upperint = ""
9496 dev = ""
9497 if self.name:
9498 upperint = "_" + self.name.upper()
9499 if self.dev:
9500 dev = "_DEV"
9501 return "PPB_OPENGLES2%s%s_INTERFACE" % (upperint, dev)
9503 def GetStructName(self):
9504 dev = ""
9505 if self.dev:
9506 dev = "_Dev"
9507 return "PPB_OpenGLES2%s%s" % (self.name, dev)
9510 class ImmediateFunction(Function):
9511 """A class that represnets an immediate function command."""
9513 def __init__(self, func):
9514 Function.__init__(
9515 self,
9516 "%sImmediate" % func.name,
9517 func.info)
9519 def InitFunction(self):
9520 # Override args in original_args and args_for_cmds with immediate versions
9521 # of the args.
9523 new_original_args = []
9524 for arg in self.original_args:
9525 new_arg = arg.GetImmediateVersion()
9526 if new_arg:
9527 new_original_args.append(new_arg)
9528 self.original_args = new_original_args
9530 new_args_for_cmds = []
9531 for arg in self.args_for_cmds:
9532 new_arg = arg.GetImmediateVersion()
9533 if new_arg:
9534 new_args_for_cmds.append(new_arg)
9536 self.args_for_cmds = new_args_for_cmds
9538 Function.InitFunction(self)
9540 def IsImmediate(self):
9541 return True
9543 def WriteServiceImplementation(self, f):
9544 """Overridden from Function"""
9545 self.type_handler.WriteImmediateServiceImplementation(self, f)
9547 def WriteHandlerImplementation(self, f):
9548 """Overridden from Function"""
9549 self.type_handler.WriteImmediateHandlerImplementation(self, f)
9551 def WriteServiceUnitTest(self, f, *extras):
9552 """Writes the service implementation for a command."""
9553 self.type_handler.WriteImmediateServiceUnitTest(self, f, *extras)
9555 def WriteValidationCode(self, f):
9556 """Overridden from Function"""
9557 self.type_handler.WriteImmediateValidationCode(self, f)
9559 def WriteCmdArgFlag(self, f):
9560 """Overridden from Function"""
9561 f.write(" static const cmd::ArgFlags kArgFlags = cmd::kAtLeastN;\n")
9563 def WriteCmdComputeSize(self, f):
9564 """Overridden from Function"""
9565 self.type_handler.WriteImmediateCmdComputeSize(self, f)
9567 def WriteCmdSetHeader(self, f):
9568 """Overridden from Function"""
9569 self.type_handler.WriteImmediateCmdSetHeader(self, f)
9571 def WriteCmdInit(self, f):
9572 """Overridden from Function"""
9573 self.type_handler.WriteImmediateCmdInit(self, f)
9575 def WriteCmdSet(self, f):
9576 """Overridden from Function"""
9577 self.type_handler.WriteImmediateCmdSet(self, f)
9579 def WriteCmdHelper(self, f):
9580 """Overridden from Function"""
9581 self.type_handler.WriteImmediateCmdHelper(self, f)
9583 def WriteFormatTest(self, f):
9584 """Overridden from Function"""
9585 self.type_handler.WriteImmediateFormatTest(self, f)
9588 class BucketFunction(Function):
9589 """A class that represnets a bucket version of a function command."""
9591 def __init__(self, func):
9592 Function.__init__(
9593 self,
9594 "%sBucket" % func.name,
9595 func.info)
9597 def InitFunction(self):
9598 # Override args in original_args and args_for_cmds with bucket versions
9599 # of the args.
9601 new_original_args = []
9602 for arg in self.original_args:
9603 new_arg = arg.GetBucketVersion()
9604 if new_arg:
9605 new_original_args.append(new_arg)
9606 self.original_args = new_original_args
9608 new_args_for_cmds = []
9609 for arg in self.args_for_cmds:
9610 new_arg = arg.GetBucketVersion()
9611 if new_arg:
9612 new_args_for_cmds.append(new_arg)
9614 self.args_for_cmds = new_args_for_cmds
9616 Function.InitFunction(self)
9618 def WriteServiceImplementation(self, f):
9619 """Overridden from Function"""
9620 self.type_handler.WriteBucketServiceImplementation(self, f)
9622 def WriteHandlerImplementation(self, f):
9623 """Overridden from Function"""
9624 self.type_handler.WriteBucketHandlerImplementation(self, f)
9626 def WriteServiceUnitTest(self, f, *extras):
9627 """Overridden from Function"""
9628 self.type_handler.WriteBucketServiceUnitTest(self, f, *extras)
9630 def MakeOriginalArgString(self, prefix, add_comma = False, separator = ", "):
9631 """Overridden from Function"""
9632 args = self.GetOriginalArgs()
9633 arg_string = separator.join(
9634 ["%s%s" % (prefix, arg.name[0:-10] if arg.name.endswith("_bucket_id")
9635 else arg.name) for arg in args])
9636 return super(BucketFunction, self)._MaybePrependComma(arg_string, add_comma)
9639 def CreateArg(arg_string):
9640 """Creates an Argument."""
9641 arg_parts = arg_string.split()
9642 if len(arg_parts) == 1 and arg_parts[0] == 'void':
9643 return None
9644 # Is this a pointer argument?
9645 elif arg_string.find('*') >= 0:
9646 return PointerArgument(
9647 arg_parts[-1],
9648 " ".join(arg_parts[0:-1]))
9649 # Is this a resource argument? Must come after pointer check.
9650 elif arg_parts[0].startswith('GLidBind'):
9651 return ResourceIdBindArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
9652 elif arg_parts[0].startswith('GLidZero'):
9653 return ResourceIdZeroArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
9654 elif arg_parts[0].startswith('GLid'):
9655 return ResourceIdArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
9656 elif arg_parts[0].startswith('GLenum') and len(arg_parts[0]) > 6:
9657 return EnumArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
9658 elif arg_parts[0].startswith('GLbitfield') and len(arg_parts[0]) > 10:
9659 return BitFieldArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
9660 elif arg_parts[0].startswith('GLboolean') and len(arg_parts[0]) > 9:
9661 return ValidatedBoolArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
9662 elif arg_parts[0].startswith('GLboolean'):
9663 return BoolArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
9664 elif arg_parts[0].startswith('GLintUniformLocation'):
9665 return UniformLocationArgument(arg_parts[-1])
9666 elif (arg_parts[0].startswith('GLint') and len(arg_parts[0]) > 5 and
9667 not arg_parts[0].startswith('GLintptr')):
9668 return IntArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
9669 elif (arg_parts[0].startswith('GLsizeiNotNegative') or
9670 arg_parts[0].startswith('GLintptrNotNegative')):
9671 return SizeNotNegativeArgument(arg_parts[-1],
9672 " ".join(arg_parts[0:-1]),
9673 arg_parts[0][0:-11])
9674 elif arg_parts[0].startswith('GLsize'):
9675 return SizeArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
9676 else:
9677 return Argument(arg_parts[-1], " ".join(arg_parts[0:-1]))
9680 class GLGenerator(object):
9681 """A class to generate GL command buffers."""
9683 _function_re = re.compile(r'GL_APICALL(.*?)GL_APIENTRY (.*?) \((.*?)\);')
9685 def __init__(self, verbose):
9686 self.original_functions = []
9687 self.functions = []
9688 self.verbose = verbose
9689 self.errors = 0
9690 self.pepper_interfaces = []
9691 self.interface_info = {}
9692 self.generated_cpp_filenames = []
9694 for interface in _PEPPER_INTERFACES:
9695 interface = PepperInterface(interface)
9696 self.pepper_interfaces.append(interface)
9697 self.interface_info[interface.GetName()] = interface
9699 def AddFunction(self, func):
9700 """Adds a function."""
9701 self.functions.append(func)
9703 def GetFunctionInfo(self, name):
9704 """Gets a type info for the given function name."""
9705 if name in _FUNCTION_INFO:
9706 func_info = _FUNCTION_INFO[name].copy()
9707 else:
9708 func_info = {}
9710 if not 'type' in func_info:
9711 func_info['type'] = ''
9713 return func_info
9715 def Log(self, msg):
9716 """Prints something if verbose is true."""
9717 if self.verbose:
9718 print msg
9720 def Error(self, msg):
9721 """Prints an error."""
9722 print "Error: %s" % msg
9723 self.errors += 1
9725 def ParseGLH(self, filename):
9726 """Parses the cmd_buffer_functions.txt file and extracts the functions"""
9727 with open(filename, "r") as f:
9728 functions = f.read()
9729 for line in functions.splitlines():
9730 match = self._function_re.match(line)
9731 if match:
9732 func_name = match.group(2)[2:]
9733 func_info = self.GetFunctionInfo(func_name)
9734 if func_info['type'] == 'Noop':
9735 continue
9737 parsed_func_info = {
9738 'original_name': func_name,
9739 'original_args': match.group(3),
9740 'return_type': match.group(1).strip(),
9743 for k in parsed_func_info.keys():
9744 if not k in func_info:
9745 func_info[k] = parsed_func_info[k]
9747 f = Function(func_name, func_info)
9748 self.original_functions.append(f)
9750 #for arg in f.GetOriginalArgs():
9751 # if not isinstance(arg, EnumArgument) and arg.type == 'GLenum':
9752 # self.Log("%s uses bare GLenum %s." % (func_name, arg.name))
9754 gen_cmd = f.GetInfo('gen_cmd')
9755 if gen_cmd == True or gen_cmd == None:
9756 if f.type_handler.NeedsDataTransferFunction(f):
9757 methods = f.GetDataTransferMethods()
9758 if 'immediate' in methods:
9759 self.AddFunction(ImmediateFunction(f))
9760 if 'bucket' in methods:
9761 self.AddFunction(BucketFunction(f))
9762 if 'shm' in methods:
9763 self.AddFunction(f)
9764 else:
9765 self.AddFunction(f)
9767 self.Log("Auto Generated Functions : %d" %
9768 len([f for f in self.functions if f.can_auto_generate or
9769 (not f.IsType('') and not f.IsType('Custom') and
9770 not f.IsType('Todo'))]))
9772 funcs = [f for f in self.functions if not f.can_auto_generate and
9773 (f.IsType('') or f.IsType('Custom') or f.IsType('Todo'))]
9774 self.Log("Non Auto Generated Functions: %d" % len(funcs))
9776 for f in funcs:
9777 self.Log(" %-10s %-20s gl%s" % (f.info['type'], f.return_type, f.name))
9779 def WriteCommandIds(self, filename):
9780 """Writes the command buffer format"""
9781 with CHeaderWriter(filename) as f:
9782 f.write("#define GLES2_COMMAND_LIST(OP) \\\n")
9783 id = 256
9784 for func in self.functions:
9785 f.write(" %-60s /* %d */ \\\n" %
9786 ("OP(%s)" % func.name, id))
9787 id += 1
9788 f.write("\n")
9790 f.write("enum CommandId {\n")
9791 f.write(" kStartPoint = cmd::kLastCommonId, "
9792 "// All GLES2 commands start after this.\n")
9793 f.write("#define GLES2_CMD_OP(name) k ## name,\n")
9794 f.write(" GLES2_COMMAND_LIST(GLES2_CMD_OP)\n")
9795 f.write("#undef GLES2_CMD_OP\n")
9796 f.write(" kNumCommands\n")
9797 f.write("};\n")
9798 f.write("\n")
9799 self.generated_cpp_filenames.append(filename)
9801 def WriteFormat(self, filename):
9802 """Writes the command buffer format"""
9803 with CHeaderWriter(filename) as f:
9804 # Forward declaration of a few enums used in constant argument
9805 # to avoid including GL header files.
9806 enum_defines = {
9807 'GL_SYNC_GPU_COMMANDS_COMPLETE': '0x9117',
9808 'GL_SYNC_FLUSH_COMMANDS_BIT': '0x00000001',
9810 f.write('\n')
9811 for enum in enum_defines:
9812 f.write("#define %s %s\n" % (enum, enum_defines[enum]))
9813 f.write('\n')
9814 for func in self.functions:
9815 if True:
9816 #gen_cmd = func.GetInfo('gen_cmd')
9817 #if gen_cmd == True or gen_cmd == None:
9818 func.WriteStruct(f)
9819 f.write("\n")
9820 self.generated_cpp_filenames.append(filename)
9822 def WriteDocs(self, filename):
9823 """Writes the command buffer doc version of the commands"""
9824 with CHeaderWriter(filename) as f:
9825 for func in self.functions:
9826 if True:
9827 #gen_cmd = func.GetInfo('gen_cmd')
9828 #if gen_cmd == True or gen_cmd == None:
9829 func.WriteDocs(f)
9830 f.write("\n")
9831 self.generated_cpp_filenames.append(filename)
9833 def WriteFormatTest(self, filename):
9834 """Writes the command buffer format test."""
9835 comment = ("// This file contains unit tests for gles2 commmands\n"
9836 "// It is included by gles2_cmd_format_test.cc\n\n")
9837 with CHeaderWriter(filename, comment) as f:
9838 for func in self.functions:
9839 if True:
9840 #gen_cmd = func.GetInfo('gen_cmd')
9841 #if gen_cmd == True or gen_cmd == None:
9842 func.WriteFormatTest(f)
9843 self.generated_cpp_filenames.append(filename)
9845 def WriteCmdHelperHeader(self, filename):
9846 """Writes the gles2 command helper."""
9847 with CHeaderWriter(filename) as f:
9848 for func in self.functions:
9849 if True:
9850 #gen_cmd = func.GetInfo('gen_cmd')
9851 #if gen_cmd == True or gen_cmd == None:
9852 func.WriteCmdHelper(f)
9853 self.generated_cpp_filenames.append(filename)
9855 def WriteServiceContextStateHeader(self, filename):
9856 """Writes the service context state header."""
9857 comment = "// It is included by context_state.h\n"
9858 with CHeaderWriter(filename, comment) as f:
9859 f.write("struct EnableFlags {\n")
9860 f.write(" EnableFlags();\n")
9861 for capability in _CAPABILITY_FLAGS:
9862 f.write(" bool %s;\n" % capability['name'])
9863 f.write(" bool cached_%s;\n" % capability['name'])
9864 f.write("};\n\n")
9866 for state_name in sorted(_STATES.keys()):
9867 state = _STATES[state_name]
9868 for item in state['states']:
9869 if isinstance(item['default'], list):
9870 f.write("%s %s[%d];\n" % (item['type'], item['name'],
9871 len(item['default'])))
9872 else:
9873 f.write("%s %s;\n" % (item['type'], item['name']))
9875 if item.get('cached', False):
9876 if isinstance(item['default'], list):
9877 f.write("%s cached_%s[%d];\n" % (item['type'], item['name'],
9878 len(item['default'])))
9879 else:
9880 f.write("%s cached_%s;\n" % (item['type'], item['name']))
9882 f.write("\n")
9883 f.write("""
9884 inline void SetDeviceCapabilityState(GLenum cap, bool enable) {
9885 switch (cap) {
9886 """)
9887 for capability in _CAPABILITY_FLAGS:
9888 f.write("""\
9889 case GL_%s:
9890 """ % capability['name'].upper())
9891 f.write("""\
9892 if (enable_flags.cached_%(name)s == enable &&
9893 !ignore_cached_state)
9894 return;
9895 enable_flags.cached_%(name)s = enable;
9896 break;
9897 """ % capability)
9899 f.write("""\
9900 default:
9901 NOTREACHED();
9902 return;
9904 if (enable)
9905 glEnable(cap);
9906 else
9907 glDisable(cap);
9909 """)
9910 self.generated_cpp_filenames.append(filename)
9912 def WriteClientContextStateHeader(self, filename):
9913 """Writes the client context state header."""
9914 comment = "// It is included by client_context_state.h\n"
9915 with CHeaderWriter(filename, comment) as f:
9916 f.write("struct EnableFlags {\n")
9917 f.write(" EnableFlags();\n")
9918 for capability in _CAPABILITY_FLAGS:
9919 f.write(" bool %s;\n" % capability['name'])
9920 f.write("};\n\n")
9921 self.generated_cpp_filenames.append(filename)
9923 def WriteContextStateGetters(self, f, class_name):
9924 """Writes the state getters."""
9925 for gl_type in ["GLint", "GLfloat"]:
9926 f.write("""
9927 bool %s::GetStateAs%s(
9928 GLenum pname, %s* params, GLsizei* num_written) const {
9929 switch (pname) {
9930 """ % (class_name, gl_type, gl_type))
9931 for state_name in sorted(_STATES.keys()):
9932 state = _STATES[state_name]
9933 if 'enum' in state:
9934 f.write(" case %s:\n" % state['enum'])
9935 f.write(" *num_written = %d;\n" % len(state['states']))
9936 f.write(" if (params) {\n")
9937 for ndx,item in enumerate(state['states']):
9938 f.write(" params[%d] = static_cast<%s>(%s);\n" %
9939 (ndx, gl_type, item['name']))
9940 f.write(" }\n")
9941 f.write(" return true;\n")
9942 else:
9943 for item in state['states']:
9944 f.write(" case %s:\n" % item['enum'])
9945 if isinstance(item['default'], list):
9946 item_len = len(item['default'])
9947 f.write(" *num_written = %d;\n" % item_len)
9948 f.write(" if (params) {\n")
9949 if item['type'] == gl_type:
9950 f.write(" memcpy(params, %s, sizeof(%s) * %d);\n" %
9951 (item['name'], item['type'], item_len))
9952 else:
9953 f.write(" for (size_t i = 0; i < %s; ++i) {\n" %
9954 item_len)
9955 f.write(" params[i] = %s;\n" %
9956 (GetGLGetTypeConversion(gl_type, item['type'],
9957 "%s[i]" % item['name'])))
9958 f.write(" }\n");
9959 else:
9960 f.write(" *num_written = 1;\n")
9961 f.write(" if (params) {\n")
9962 f.write(" params[0] = %s;\n" %
9963 (GetGLGetTypeConversion(gl_type, item['type'],
9964 item['name'])))
9965 f.write(" }\n")
9966 f.write(" return true;\n")
9967 for capability in _CAPABILITY_FLAGS:
9968 f.write(" case GL_%s:\n" % capability['name'].upper())
9969 f.write(" *num_written = 1;\n")
9970 f.write(" if (params) {\n")
9971 f.write(
9972 " params[0] = static_cast<%s>(enable_flags.%s);\n" %
9973 (gl_type, capability['name']))
9974 f.write(" }\n")
9975 f.write(" return true;\n")
9976 f.write(""" default:
9977 return false;
9980 """)
9982 def WriteServiceContextStateImpl(self, filename):
9983 """Writes the context state service implementation."""
9984 comment = "// It is included by context_state.cc\n"
9985 with CHeaderWriter(filename, comment) as f:
9986 code = []
9987 for capability in _CAPABILITY_FLAGS:
9988 code.append("%s(%s)" %
9989 (capability['name'],
9990 ('false', 'true')['default' in capability]))
9991 code.append("cached_%s(%s)" %
9992 (capability['name'],
9993 ('false', 'true')['default' in capability]))
9994 f.write("ContextState::EnableFlags::EnableFlags()\n : %s {\n}\n" %
9995 ",\n ".join(code))
9996 f.write("\n")
9998 f.write("void ContextState::Initialize() {\n")
9999 for state_name in sorted(_STATES.keys()):
10000 state = _STATES[state_name]
10001 for item in state['states']:
10002 if isinstance(item['default'], list):
10003 for ndx, value in enumerate(item['default']):
10004 f.write(" %s[%d] = %s;\n" % (item['name'], ndx, value))
10005 else:
10006 f.write(" %s = %s;\n" % (item['name'], item['default']))
10007 if item.get('cached', False):
10008 if isinstance(item['default'], list):
10009 for ndx, value in enumerate(item['default']):
10010 f.write(" cached_%s[%d] = %s;\n" % (item['name'], ndx, value))
10011 else:
10012 f.write(" cached_%s = %s;\n" % (item['name'], item['default']))
10013 f.write("}\n")
10015 f.write("""
10016 void ContextState::InitCapabilities(const ContextState* prev_state) const {
10017 """)
10018 def WriteCapabilities(test_prev, es3_caps):
10019 for capability in _CAPABILITY_FLAGS:
10020 capability_name = capability['name']
10021 capability_es3 = 'es3' in capability and capability['es3'] == True
10022 if capability_es3 and not es3_caps or not capability_es3 and es3_caps:
10023 continue
10024 if test_prev:
10025 f.write(""" if (prev_state->enable_flags.cached_%s !=
10026 enable_flags.cached_%s) {\n""" %
10027 (capability_name, capability_name))
10028 f.write(" EnableDisable(GL_%s, enable_flags.cached_%s);\n" %
10029 (capability_name.upper(), capability_name))
10030 if test_prev:
10031 f.write(" }")
10033 f.write(" if (prev_state) {")
10034 WriteCapabilities(True, False)
10035 f.write(" if (feature_info_->IsES3Capable()) {\n")
10036 WriteCapabilities(True, True)
10037 f.write(" }\n")
10038 f.write(" } else {")
10039 WriteCapabilities(False, False)
10040 f.write(" if (feature_info_->IsES3Capable()) {\n")
10041 WriteCapabilities(False, True)
10042 f.write(" }\n")
10043 f.write(" }")
10044 f.write("""}
10046 void ContextState::InitState(const ContextState *prev_state) const {
10047 """)
10049 def WriteStates(test_prev):
10050 # We need to sort the keys so the expectations match
10051 for state_name in sorted(_STATES.keys()):
10052 state = _STATES[state_name]
10053 if state['type'] == 'FrontBack':
10054 num_states = len(state['states'])
10055 for ndx, group in enumerate(Grouper(num_states / 2,
10056 state['states'])):
10057 if test_prev:
10058 f.write(" if (")
10059 args = []
10060 for place, item in enumerate(group):
10061 item_name = CachedStateName(item)
10062 args.append('%s' % item_name)
10063 if test_prev:
10064 if place > 0:
10065 f.write(' ||\n')
10066 f.write("(%s != prev_state->%s)" % (item_name, item_name))
10067 if test_prev:
10068 f.write(")\n")
10069 f.write(
10070 " gl%s(%s, %s);\n" %
10071 (state['func'], ('GL_FRONT', 'GL_BACK')[ndx],
10072 ", ".join(args)))
10073 elif state['type'] == 'NamedParameter':
10074 for item in state['states']:
10075 item_name = CachedStateName(item)
10077 if 'extension_flag' in item:
10078 f.write(" if (feature_info_->feature_flags().%s) {\n " %
10079 item['extension_flag'])
10080 if test_prev:
10081 if isinstance(item['default'], list):
10082 f.write(" if (memcmp(prev_state->%s, %s, "
10083 "sizeof(%s) * %d)) {\n" %
10084 (item_name, item_name, item['type'],
10085 len(item['default'])))
10086 else:
10087 f.write(" if (prev_state->%s != %s) {\n " %
10088 (item_name, item_name))
10089 if 'gl_version_flag' in item:
10090 item_name = item['gl_version_flag']
10091 inverted = ''
10092 if item_name[0] == '!':
10093 inverted = '!'
10094 item_name = item_name[1:]
10095 f.write(" if (%sfeature_info_->gl_version_info().%s) {\n" %
10096 (inverted, item_name))
10097 f.write(" gl%s(%s, %s);\n" %
10098 (state['func'],
10099 (item['enum_set']
10100 if 'enum_set' in item else item['enum']),
10101 item['name']))
10102 if 'gl_version_flag' in item:
10103 f.write(" }\n")
10104 if test_prev:
10105 if 'extension_flag' in item:
10106 f.write(" ")
10107 f.write(" }")
10108 if 'extension_flag' in item:
10109 f.write(" }")
10110 else:
10111 if 'extension_flag' in state:
10112 f.write(" if (feature_info_->feature_flags().%s)\n " %
10113 state['extension_flag'])
10114 if test_prev:
10115 f.write(" if (")
10116 args = []
10117 for place, item in enumerate(state['states']):
10118 item_name = CachedStateName(item)
10119 args.append('%s' % item_name)
10120 if test_prev:
10121 if place > 0:
10122 f.write(' ||\n')
10123 f.write("(%s != prev_state->%s)" %
10124 (item_name, item_name))
10125 if test_prev:
10126 f.write(" )\n")
10127 f.write(" gl%s(%s);\n" % (state['func'], ", ".join(args)))
10129 f.write(" if (prev_state) {")
10130 WriteStates(True)
10131 f.write(" } else {")
10132 WriteStates(False)
10133 f.write(" }")
10134 f.write("}\n")
10136 f.write("""bool ContextState::GetEnabled(GLenum cap) const {
10137 switch (cap) {
10138 """)
10139 for capability in _CAPABILITY_FLAGS:
10140 f.write(" case GL_%s:\n" % capability['name'].upper())
10141 f.write(" return enable_flags.%s;\n" % capability['name'])
10142 f.write(""" default:
10143 NOTREACHED();
10144 return false;
10147 """)
10148 self.WriteContextStateGetters(f, "ContextState")
10149 self.generated_cpp_filenames.append(filename)
10151 def WriteClientContextStateImpl(self, filename):
10152 """Writes the context state client side implementation."""
10153 comment = "// It is included by client_context_state.cc\n"
10154 with CHeaderWriter(filename, comment) as f:
10155 code = []
10156 for capability in _CAPABILITY_FLAGS:
10157 code.append("%s(%s)" %
10158 (capability['name'],
10159 ('false', 'true')['default' in capability]))
10160 f.write(
10161 "ClientContextState::EnableFlags::EnableFlags()\n : %s {\n}\n" %
10162 ",\n ".join(code))
10163 f.write("\n")
10165 f.write("""
10166 bool ClientContextState::SetCapabilityState(
10167 GLenum cap, bool enabled, bool* changed) {
10168 *changed = false;
10169 switch (cap) {
10170 """)
10171 for capability in _CAPABILITY_FLAGS:
10172 f.write(" case GL_%s:\n" % capability['name'].upper())
10173 f.write(""" if (enable_flags.%(name)s != enabled) {
10174 *changed = true;
10175 enable_flags.%(name)s = enabled;
10177 return true;
10178 """ % capability)
10179 f.write(""" default:
10180 return false;
10183 """)
10184 f.write("""bool ClientContextState::GetEnabled(
10185 GLenum cap, bool* enabled) const {
10186 switch (cap) {
10187 """)
10188 for capability in _CAPABILITY_FLAGS:
10189 f.write(" case GL_%s:\n" % capability['name'].upper())
10190 f.write(" *enabled = enable_flags.%s;\n" % capability['name'])
10191 f.write(" return true;\n")
10192 f.write(""" default:
10193 return false;
10196 """)
10197 self.generated_cpp_filenames.append(filename)
10199 def WriteServiceImplementation(self, filename):
10200 """Writes the service decorder implementation."""
10201 comment = "// It is included by gles2_cmd_decoder.cc\n"
10202 with CHeaderWriter(filename, comment) as f:
10203 for func in self.functions:
10204 if True:
10205 #gen_cmd = func.GetInfo('gen_cmd')
10206 #if gen_cmd == True or gen_cmd == None:
10207 func.WriteServiceImplementation(f)
10209 f.write("""
10210 bool GLES2DecoderImpl::SetCapabilityState(GLenum cap, bool enabled) {
10211 switch (cap) {
10212 """)
10213 for capability in _CAPABILITY_FLAGS:
10214 f.write(" case GL_%s:\n" % capability['name'].upper())
10215 if 'state_flag' in capability:
10217 f.write("""\
10218 state_.enable_flags.%(name)s = enabled;
10219 if (state_.enable_flags.cached_%(name)s != enabled
10220 || state_.ignore_cached_state) {
10221 %(state_flag)s = true;
10223 return false;
10224 """ % capability)
10225 else:
10226 f.write("""\
10227 state_.enable_flags.%(name)s = enabled;
10228 if (state_.enable_flags.cached_%(name)s != enabled
10229 || state_.ignore_cached_state) {
10230 state_.enable_flags.cached_%(name)s = enabled;
10231 return true;
10233 return false;
10234 """ % capability)
10235 f.write(""" default:
10236 NOTREACHED();
10237 return false;
10240 """)
10241 self.generated_cpp_filenames.append(filename)
10243 def WriteServiceUnitTests(self, filename_pattern):
10244 """Writes the service decorder unit tests."""
10245 num_tests = len(self.functions)
10246 FUNCTIONS_PER_FILE = 98 # hard code this so it doesn't change.
10247 count = 0
10248 for test_num in range(0, num_tests, FUNCTIONS_PER_FILE):
10249 count += 1
10250 filename = filename_pattern % count
10251 comment = "// It is included by gles2_cmd_decoder_unittest_%d.cc\n" \
10252 % count
10253 with CHeaderWriter(filename, comment) as f:
10254 test_name = 'GLES2DecoderTest%d' % count
10255 end = test_num + FUNCTIONS_PER_FILE
10256 if end > num_tests:
10257 end = num_tests
10258 for idx in range(test_num, end):
10259 func = self.functions[idx]
10261 # Do any filtering of the functions here, so that the functions
10262 # will not move between the numbered files if filtering properties
10263 # are changed.
10264 if func.GetInfo('extension_flag'):
10265 continue
10267 if True:
10268 #gen_cmd = func.GetInfo('gen_cmd')
10269 #if gen_cmd == True or gen_cmd == None:
10270 if func.GetInfo('unit_test') == False:
10271 f.write("// TODO(gman): %s\n" % func.name)
10272 else:
10273 func.WriteServiceUnitTest(f, {
10274 'test_name': test_name
10276 self.generated_cpp_filenames.append(filename)
10278 comment = "// It is included by gles2_cmd_decoder_unittest_base.cc\n"
10279 filename = filename_pattern % 0
10280 with CHeaderWriter(filename, comment) as f:
10281 f.write(
10282 """void GLES2DecoderTestBase::SetupInitCapabilitiesExpectations(
10283 bool es3_capable) {""")
10284 for capability in _CAPABILITY_FLAGS:
10285 capability_es3 = 'es3' in capability and capability['es3'] == True
10286 if not capability_es3:
10287 f.write(" ExpectEnableDisable(GL_%s, %s);\n" %
10288 (capability['name'].upper(),
10289 ('false', 'true')['default' in capability]))
10291 f.write(" if (es3_capable) {")
10292 for capability in _CAPABILITY_FLAGS:
10293 capability_es3 = 'es3' in capability and capability['es3'] == True
10294 if capability_es3:
10295 f.write(" ExpectEnableDisable(GL_%s, %s);\n" %
10296 (capability['name'].upper(),
10297 ('false', 'true')['default' in capability]))
10298 f.write(""" }
10301 void GLES2DecoderTestBase::SetupInitStateExpectations() {
10302 """)
10303 # We need to sort the keys so the expectations match
10304 for state_name in sorted(_STATES.keys()):
10305 state = _STATES[state_name]
10306 if state['type'] == 'FrontBack':
10307 num_states = len(state['states'])
10308 for ndx, group in enumerate(Grouper(num_states / 2, state['states'])):
10309 args = []
10310 for item in group:
10311 if 'expected' in item:
10312 args.append(item['expected'])
10313 else:
10314 args.append(item['default'])
10315 f.write(
10316 " EXPECT_CALL(*gl_, %s(%s, %s))\n" %
10317 (state['func'], ('GL_FRONT', 'GL_BACK')[ndx], ", ".join(args)))
10318 f.write(" .Times(1)\n")
10319 f.write(" .RetiresOnSaturation();\n")
10320 elif state['type'] == 'NamedParameter':
10321 for item in state['states']:
10322 if 'extension_flag' in item:
10323 f.write(" if (group_->feature_info()->feature_flags().%s) {\n" %
10324 item['extension_flag'])
10325 f.write(" ")
10326 expect_value = item['default']
10327 if isinstance(expect_value, list):
10328 # TODO: Currently we do not check array values.
10329 expect_value = "_"
10331 f.write(
10332 " EXPECT_CALL(*gl_, %s(%s, %s))\n" %
10333 (state['func'],
10334 (item['enum_set']
10335 if 'enum_set' in item else item['enum']),
10336 expect_value))
10337 f.write(" .Times(1)\n")
10338 f.write(" .RetiresOnSaturation();\n")
10339 if 'extension_flag' in item:
10340 f.write(" }\n")
10341 else:
10342 if 'extension_flag' in state:
10343 f.write(" if (group_->feature_info()->feature_flags().%s) {\n" %
10344 state['extension_flag'])
10345 f.write(" ")
10346 args = []
10347 for item in state['states']:
10348 if 'expected' in item:
10349 args.append(item['expected'])
10350 else:
10351 args.append(item['default'])
10352 # TODO: Currently we do not check array values.
10353 args = ["_" if isinstance(arg, list) else arg for arg in args]
10354 f.write(" EXPECT_CALL(*gl_, %s(%s))\n" %
10355 (state['func'], ", ".join(args)))
10356 f.write(" .Times(1)\n")
10357 f.write(" .RetiresOnSaturation();\n")
10358 if 'extension_flag' in state:
10359 f.write(" }\n")
10360 f.write("}\n")
10361 self.generated_cpp_filenames.append(filename)
10363 def WriteServiceUnitTestsForExtensions(self, filename):
10364 """Writes the service decorder unit tests for functions with extension_flag.
10366 The functions are special in that they need a specific unit test
10367 baseclass to turn on the extension.
10369 functions = [f for f in self.functions if f.GetInfo('extension_flag')]
10370 comment = "// It is included by gles2_cmd_decoder_unittest_extensions.cc\n"
10371 with CHeaderWriter(filename, comment) as f:
10372 for func in functions:
10373 if True:
10374 if func.GetInfo('unit_test') == False:
10375 f.write("// TODO(gman): %s\n" % func.name)
10376 else:
10377 extension = ToCamelCase(
10378 ToGLExtensionString(func.GetInfo('extension_flag')))
10379 func.WriteServiceUnitTest(f, {
10380 'test_name': 'GLES2DecoderTestWith%s' % extension
10382 self.generated_cpp_filenames.append(filename)
10384 def WriteGLES2Header(self, filename):
10385 """Writes the GLES2 header."""
10386 comment = "// This file contains Chromium-specific GLES2 declarations.\n\n"
10387 with CHeaderWriter(filename, comment) as f:
10388 for func in self.original_functions:
10389 func.WriteGLES2Header(f)
10390 f.write("\n")
10391 self.generated_cpp_filenames.append(filename)
10393 def WriteGLES2CLibImplementation(self, filename):
10394 """Writes the GLES2 c lib implementation."""
10395 comment = "// These functions emulate GLES2 over command buffers.\n"
10396 with CHeaderWriter(filename, comment) as f:
10397 for func in self.original_functions:
10398 func.WriteGLES2CLibImplementation(f)
10399 f.write("""
10400 namespace gles2 {
10402 extern const NameToFunc g_gles2_function_table[] = {
10403 """)
10404 for func in self.original_functions:
10405 f.write(
10406 ' { "gl%s", reinterpret_cast<GLES2FunctionPointer>(gl%s), },\n' %
10407 (func.name, func.name))
10408 f.write(""" { NULL, NULL, },
10411 } // namespace gles2
10412 """)
10413 self.generated_cpp_filenames.append(filename)
10415 def WriteGLES2InterfaceHeader(self, filename):
10416 """Writes the GLES2 interface header."""
10417 comment = ("// This file is included by gles2_interface.h to declare the\n"
10418 "// GL api functions.\n")
10419 with CHeaderWriter(filename, comment) as f:
10420 for func in self.original_functions:
10421 func.WriteGLES2InterfaceHeader(f)
10422 self.generated_cpp_filenames.append(filename)
10424 def WriteMojoGLES2ImplHeader(self, filename):
10425 """Writes the Mojo GLES2 implementation header."""
10426 comment = ("// This file is included by gles2_interface.h to declare the\n"
10427 "// GL api functions.\n")
10428 code = """
10429 #include "gpu/command_buffer/client/gles2_interface.h"
10430 #include "third_party/mojo/src/mojo/public/c/gles2/gles2.h"
10432 namespace mojo {
10434 class MojoGLES2Impl : public gpu::gles2::GLES2Interface {
10435 public:
10436 explicit MojoGLES2Impl(MojoGLES2Context context) {
10437 context_ = context;
10439 ~MojoGLES2Impl() override {}
10441 with CHeaderWriter(filename, comment) as f:
10442 f.write(code);
10443 for func in self.original_functions:
10444 func.WriteMojoGLES2ImplHeader(f)
10445 code = """
10446 private:
10447 MojoGLES2Context context_;
10450 } // namespace mojo
10452 f.write(code);
10453 self.generated_cpp_filenames.append(filename)
10455 def WriteMojoGLES2Impl(self, filename):
10456 """Writes the Mojo GLES2 implementation."""
10457 code = """
10458 #include "mojo/gpu/mojo_gles2_impl_autogen.h"
10460 #include "base/logging.h"
10461 #include "third_party/mojo/src/mojo/public/c/gles2/chromium_copy_texture.h"
10462 #include "third_party/mojo/src/mojo/public/c/gles2/chromium_framebuffer_multisample.h"
10463 #include "third_party/mojo/src/mojo/public/c/gles2/chromium_image.h"
10464 #include "third_party/mojo/src/mojo/public/c/gles2/chromium_miscellaneous.h"
10465 #include "third_party/mojo/src/mojo/public/c/gles2/chromium_pixel_transfer_buffer_object.h"
10466 #include "third_party/mojo/src/mojo/public/c/gles2/chromium_sub_image.h"
10467 #include "third_party/mojo/src/mojo/public/c/gles2/chromium_sync_point.h"
10468 #include "third_party/mojo/src/mojo/public/c/gles2/chromium_texture_mailbox.h"
10469 #include "third_party/mojo/src/mojo/public/c/gles2/gles2.h"
10470 #include "third_party/mojo/src/mojo/public/c/gles2/occlusion_query_ext.h"
10472 namespace mojo {
10475 with CWriter(filename) as f:
10476 f.write(code);
10477 for func in self.original_functions:
10478 func.WriteMojoGLES2Impl(f)
10479 code = """
10481 } // namespace mojo
10483 f.write(code);
10484 self.generated_cpp_filenames.append(filename)
10486 def WriteGLES2InterfaceStub(self, filename):
10487 """Writes the GLES2 interface stub header."""
10488 comment = "// This file is included by gles2_interface_stub.h.\n"
10489 with CHeaderWriter(filename, comment) as f:
10490 for func in self.original_functions:
10491 func.WriteGLES2InterfaceStub(f)
10492 self.generated_cpp_filenames.append(filename)
10494 def WriteGLES2InterfaceStubImpl(self, filename):
10495 """Writes the GLES2 interface header."""
10496 comment = "// This file is included by gles2_interface_stub.cc.\n"
10497 with CHeaderWriter(filename, comment) as f:
10498 for func in self.original_functions:
10499 func.WriteGLES2InterfaceStubImpl(f)
10500 self.generated_cpp_filenames.append(filename)
10502 def WriteGLES2ImplementationHeader(self, filename):
10503 """Writes the GLES2 Implementation header."""
10504 comment = \
10505 ("// This file is included by gles2_implementation.h to declare the\n"
10506 "// GL api functions.\n")
10507 with CHeaderWriter(filename, comment) as f:
10508 for func in self.original_functions:
10509 func.WriteGLES2ImplementationHeader(f)
10510 self.generated_cpp_filenames.append(filename)
10512 def WriteGLES2Implementation(self, filename):
10513 """Writes the GLES2 Implementation."""
10514 comment = \
10515 ("// This file is included by gles2_implementation.cc to define the\n"
10516 "// GL api functions.\n")
10517 with CHeaderWriter(filename, comment) as f:
10518 for func in self.original_functions:
10519 func.WriteGLES2Implementation(f)
10520 self.generated_cpp_filenames.append(filename)
10522 def WriteGLES2TraceImplementationHeader(self, filename):
10523 """Writes the GLES2 Trace Implementation header."""
10524 comment = "// This file is included by gles2_trace_implementation.h\n"
10525 with CHeaderWriter(filename, comment) as f:
10526 for func in self.original_functions:
10527 func.WriteGLES2TraceImplementationHeader(f)
10528 self.generated_cpp_filenames.append(filename)
10530 def WriteGLES2TraceImplementation(self, filename):
10531 """Writes the GLES2 Trace Implementation."""
10532 comment = "// This file is included by gles2_trace_implementation.cc\n"
10533 with CHeaderWriter(filename, comment) as f:
10534 for func in self.original_functions:
10535 func.WriteGLES2TraceImplementation(f)
10536 self.generated_cpp_filenames.append(filename)
10538 def WriteGLES2ImplementationUnitTests(self, filename):
10539 """Writes the GLES2 helper header."""
10540 comment = \
10541 ("// This file is included by gles2_implementation.h to declare the\n"
10542 "// GL api functions.\n")
10543 with CHeaderWriter(filename, comment) as f:
10544 for func in self.original_functions:
10545 func.WriteGLES2ImplementationUnitTest(f)
10546 self.generated_cpp_filenames.append(filename)
10548 def WriteServiceUtilsHeader(self, filename):
10549 """Writes the gles2 auto generated utility header."""
10550 with CHeaderWriter(filename) as f:
10551 for name in sorted(_NAMED_TYPE_INFO.keys()):
10552 named_type = NamedType(_NAMED_TYPE_INFO[name])
10553 if named_type.IsConstant():
10554 continue
10555 f.write("ValueValidator<%s> %s;\n" %
10556 (named_type.GetType(), ToUnderscore(name)))
10557 f.write("\n")
10558 self.generated_cpp_filenames.append(filename)
10560 def WriteServiceUtilsImplementation(self, filename):
10561 """Writes the gles2 auto generated utility implementation."""
10562 with CHeaderWriter(filename) as f:
10563 names = sorted(_NAMED_TYPE_INFO.keys())
10564 for name in names:
10565 named_type = NamedType(_NAMED_TYPE_INFO[name])
10566 if named_type.IsConstant():
10567 continue
10568 if named_type.GetValidValues():
10569 f.write("static const %s valid_%s_table[] = {\n" %
10570 (named_type.GetType(), ToUnderscore(name)))
10571 for value in named_type.GetValidValues():
10572 f.write(" %s,\n" % value)
10573 f.write("};\n")
10574 f.write("\n")
10575 if named_type.GetValidValuesES3():
10576 f.write("static const %s valid_%s_table_es3[] = {\n" %
10577 (named_type.GetType(), ToUnderscore(name)))
10578 for value in named_type.GetValidValuesES3():
10579 f.write(" %s,\n" % value)
10580 f.write("};\n")
10581 f.write("\n")
10582 if named_type.GetDeprecatedValuesES3():
10583 f.write("static const %s deprecated_%s_table_es3[] = {\n" %
10584 (named_type.GetType(), ToUnderscore(name)))
10585 for value in named_type.GetDeprecatedValuesES3():
10586 f.write(" %s,\n" % value)
10587 f.write("};\n")
10588 f.write("\n")
10589 f.write("Validators::Validators()")
10590 pre = ' : '
10591 for count, name in enumerate(names):
10592 named_type = NamedType(_NAMED_TYPE_INFO[name])
10593 if named_type.IsConstant():
10594 continue
10595 if named_type.GetValidValues():
10596 code = """%(pre)s%(name)s(
10597 valid_%(name)s_table, arraysize(valid_%(name)s_table))"""
10598 else:
10599 code = "%(pre)s%(name)s()"
10600 f.write(code % {
10601 'name': ToUnderscore(name),
10602 'pre': pre,
10604 pre = ',\n '
10605 f.write(" {\n");
10606 f.write("}\n\n");
10608 f.write("void Validators::UpdateValuesES3() {\n")
10609 for name in names:
10610 named_type = NamedType(_NAMED_TYPE_INFO[name])
10611 if named_type.GetDeprecatedValuesES3():
10612 code = """ %(name)s.RemoveValues(
10613 deprecated_%(name)s_table_es3, arraysize(deprecated_%(name)s_table_es3));
10615 f.write(code % {
10616 'name': ToUnderscore(name),
10618 if named_type.GetValidValuesES3():
10619 code = """ %(name)s.AddValues(
10620 valid_%(name)s_table_es3, arraysize(valid_%(name)s_table_es3));
10622 f.write(code % {
10623 'name': ToUnderscore(name),
10625 f.write("}\n\n");
10626 self.generated_cpp_filenames.append(filename)
10628 def WriteCommonUtilsHeader(self, filename):
10629 """Writes the gles2 common utility header."""
10630 with CHeaderWriter(filename) as f:
10631 type_infos = sorted(_NAMED_TYPE_INFO.keys())
10632 for type_info in type_infos:
10633 if _NAMED_TYPE_INFO[type_info]['type'] == 'GLenum':
10634 f.write("static std::string GetString%s(uint32_t value);\n" %
10635 type_info)
10636 f.write("\n")
10637 self.generated_cpp_filenames.append(filename)
10639 def WriteCommonUtilsImpl(self, filename):
10640 """Writes the gles2 common utility header."""
10641 enum_re = re.compile(r'\#define\s+(GL_[a-zA-Z0-9_]+)\s+([0-9A-Fa-fx]+)')
10642 dict = {}
10643 for fname in ['third_party/khronos/GLES2/gl2.h',
10644 'third_party/khronos/GLES2/gl2ext.h',
10645 'third_party/khronos/GLES3/gl3.h',
10646 'gpu/GLES2/gl2chromium.h',
10647 'gpu/GLES2/gl2extchromium.h']:
10648 lines = open(fname).readlines()
10649 for line in lines:
10650 m = enum_re.match(line)
10651 if m:
10652 name = m.group(1)
10653 value = m.group(2)
10654 if len(value) <= 10:
10655 if not value in dict:
10656 dict[value] = name
10657 # check our own _CHROMIUM macro conflicts with khronos GL headers.
10658 elif dict[value] != name and (name.endswith('_CHROMIUM') or
10659 dict[value].endswith('_CHROMIUM')):
10660 self.Error("code collision: %s and %s have the same code %s" %
10661 (dict[value], name, value))
10663 with CHeaderWriter(filename) as f:
10664 f.write("static const GLES2Util::EnumToString "
10665 "enum_to_string_table[] = {\n")
10666 for value in dict:
10667 f.write(' { %s, "%s", },\n' % (value, dict[value]))
10668 f.write("""};
10670 const GLES2Util::EnumToString* const GLES2Util::enum_to_string_table_ =
10671 enum_to_string_table;
10672 const size_t GLES2Util::enum_to_string_table_len_ =
10673 sizeof(enum_to_string_table) / sizeof(enum_to_string_table[0]);
10675 """)
10677 enums = sorted(_NAMED_TYPE_INFO.keys())
10678 for enum in enums:
10679 if _NAMED_TYPE_INFO[enum]['type'] == 'GLenum':
10680 f.write("std::string GLES2Util::GetString%s(uint32_t value) {\n" %
10681 enum)
10682 valid_list = _NAMED_TYPE_INFO[enum]['valid']
10683 if 'valid_es3' in _NAMED_TYPE_INFO[enum]:
10684 valid_list = valid_list + _NAMED_TYPE_INFO[enum]['valid_es3']
10685 assert len(valid_list) == len(set(valid_list))
10686 if len(valid_list) > 0:
10687 f.write(" static const EnumToString string_table[] = {\n")
10688 for value in valid_list:
10689 f.write(' { %s, "%s" },\n' % (value, value))
10690 f.write(""" };
10691 return GLES2Util::GetQualifiedEnumString(
10692 string_table, arraysize(string_table), value);
10695 """)
10696 else:
10697 f.write(""" return GLES2Util::GetQualifiedEnumString(
10698 NULL, 0, value);
10701 """)
10702 self.generated_cpp_filenames.append(filename)
10704 def WritePepperGLES2Interface(self, filename, dev):
10705 """Writes the Pepper OpenGLES interface definition."""
10706 with CWriter(filename) as f:
10707 f.write("label Chrome {\n")
10708 f.write(" M39 = 1.0\n")
10709 f.write("};\n\n")
10711 if not dev:
10712 # Declare GL types.
10713 f.write("[version=1.0]\n")
10714 f.write("describe {\n")
10715 for gltype in ['GLbitfield', 'GLboolean', 'GLbyte', 'GLclampf',
10716 'GLclampx', 'GLenum', 'GLfixed', 'GLfloat', 'GLint',
10717 'GLintptr', 'GLshort', 'GLsizei', 'GLsizeiptr',
10718 'GLubyte', 'GLuint', 'GLushort']:
10719 f.write(" %s;\n" % gltype)
10720 f.write(" %s_ptr_t;\n" % gltype)
10721 f.write("};\n\n")
10723 # C level typedefs.
10724 f.write("#inline c\n")
10725 f.write("#include \"ppapi/c/pp_resource.h\"\n")
10726 if dev:
10727 f.write("#include \"ppapi/c/ppb_opengles2.h\"\n\n")
10728 else:
10729 f.write("\n#ifndef __gl2_h_\n")
10730 for (k, v) in _GL_TYPES.iteritems():
10731 f.write("typedef %s %s;\n" % (v, k))
10732 f.write("#ifdef _WIN64\n")
10733 for (k, v) in _GL_TYPES_64.iteritems():
10734 f.write("typedef %s %s;\n" % (v, k))
10735 f.write("#else\n")
10736 for (k, v) in _GL_TYPES_32.iteritems():
10737 f.write("typedef %s %s;\n" % (v, k))
10738 f.write("#endif // _WIN64\n")
10739 f.write("#endif // __gl2_h_\n\n")
10740 f.write("#endinl\n")
10742 for interface in self.pepper_interfaces:
10743 if interface.dev != dev:
10744 continue
10745 # Historically, we provide OpenGLES2 interfaces with struct
10746 # namespace. Not to break code which uses the interface as
10747 # "struct OpenGLES2", we put it in struct namespace.
10748 f.write('\n[macro="%s", force_struct_namespace]\n' %
10749 interface.GetInterfaceName())
10750 f.write("interface %s {\n" % interface.GetStructName())
10751 for func in self.original_functions:
10752 if not func.InPepperInterface(interface):
10753 continue
10755 ret_type = func.MapCTypeToPepperIdlType(func.return_type,
10756 is_for_return_type=True)
10757 func_prefix = " %s %s(" % (ret_type, func.GetPepperName())
10758 f.write(func_prefix)
10759 f.write("[in] PP_Resource context")
10760 for arg in func.MakeTypedPepperIdlArgStrings():
10761 f.write(",\n" + " " * len(func_prefix) + arg)
10762 f.write(");\n")
10763 f.write("};\n\n")
10765 def WritePepperGLES2Implementation(self, filename):
10766 """Writes the Pepper OpenGLES interface implementation."""
10767 with CWriter(filename) as f:
10768 f.write("#include \"ppapi/shared_impl/ppb_opengles2_shared.h\"\n\n")
10769 f.write("#include \"base/logging.h\"\n")
10770 f.write("#include \"gpu/command_buffer/client/gles2_implementation.h\"\n")
10771 f.write("#include \"ppapi/shared_impl/ppb_graphics_3d_shared.h\"\n")
10772 f.write("#include \"ppapi/thunk/enter.h\"\n\n")
10774 f.write("namespace ppapi {\n\n")
10775 f.write("namespace {\n\n")
10777 f.write("typedef thunk::EnterResource<thunk::PPB_Graphics3D_API>"
10778 " Enter3D;\n\n")
10780 f.write("gpu::gles2::GLES2Implementation* ToGles2Impl(Enter3D*"
10781 " enter) {\n")
10782 f.write(" DCHECK(enter);\n")
10783 f.write(" DCHECK(enter->succeeded());\n")
10784 f.write(" return static_cast<PPB_Graphics3D_Shared*>(enter->object())->"
10785 "gles2_impl();\n");
10786 f.write("}\n\n");
10788 for func in self.original_functions:
10789 if not func.InAnyPepperExtension():
10790 continue
10792 original_arg = func.MakeTypedPepperArgString("")
10793 context_arg = "PP_Resource context_id"
10794 if len(original_arg):
10795 arg = context_arg + ", " + original_arg
10796 else:
10797 arg = context_arg
10798 f.write("%s %s(%s) {\n" %
10799 (func.return_type, func.GetPepperName(), arg))
10800 f.write(" Enter3D enter(context_id, true);\n")
10801 f.write(" if (enter.succeeded()) {\n")
10803 return_str = "" if func.return_type == "void" else "return "
10804 f.write(" %sToGles2Impl(&enter)->%s(%s);\n" %
10805 (return_str, func.original_name,
10806 func.MakeOriginalArgString("")))
10807 f.write(" }")
10808 if func.return_type == "void":
10809 f.write("\n")
10810 else:
10811 f.write(" else {\n")
10812 f.write(" return %s;\n" % func.GetErrorReturnString())
10813 f.write(" }\n")
10814 f.write("}\n\n")
10816 f.write("} // namespace\n")
10818 for interface in self.pepper_interfaces:
10819 f.write("const %s* PPB_OpenGLES2_Shared::Get%sInterface() {\n" %
10820 (interface.GetStructName(), interface.GetName()))
10821 f.write(" static const struct %s "
10822 "ppb_opengles2 = {\n" % interface.GetStructName())
10823 f.write(" &")
10824 f.write(",\n &".join(
10825 f.GetPepperName() for f in self.original_functions
10826 if f.InPepperInterface(interface)))
10827 f.write("\n")
10829 f.write(" };\n")
10830 f.write(" return &ppb_opengles2;\n")
10831 f.write("}\n")
10833 f.write("} // namespace ppapi\n")
10834 self.generated_cpp_filenames.append(filename)
10836 def WriteGLES2ToPPAPIBridge(self, filename):
10837 """Connects GLES2 helper library to PPB_OpenGLES2 interface"""
10838 with CWriter(filename) as f:
10839 f.write("#ifndef GL_GLEXT_PROTOTYPES\n")
10840 f.write("#define GL_GLEXT_PROTOTYPES\n")
10841 f.write("#endif\n")
10842 f.write("#include <GLES2/gl2.h>\n")
10843 f.write("#include <GLES2/gl2ext.h>\n")
10844 f.write("#include \"ppapi/lib/gl/gles2/gl2ext_ppapi.h\"\n\n")
10846 for func in self.original_functions:
10847 if not func.InAnyPepperExtension():
10848 continue
10850 interface = self.interface_info[func.GetInfo('pepper_interface') or '']
10852 f.write("%s GL_APIENTRY gl%s(%s) {\n" %
10853 (func.return_type, func.GetPepperName(),
10854 func.MakeTypedPepperArgString("")))
10855 return_str = "" if func.return_type == "void" else "return "
10856 interface_str = "glGet%sInterfacePPAPI()" % interface.GetName()
10857 original_arg = func.MakeOriginalArgString("")
10858 context_arg = "glGetCurrentContextPPAPI()"
10859 if len(original_arg):
10860 arg = context_arg + ", " + original_arg
10861 else:
10862 arg = context_arg
10863 if interface.GetName():
10864 f.write(" const struct %s* ext = %s;\n" %
10865 (interface.GetStructName(), interface_str))
10866 f.write(" if (ext)\n")
10867 f.write(" %sext->%s(%s);\n" %
10868 (return_str, func.GetPepperName(), arg))
10869 if return_str:
10870 f.write(" %s0;\n" % return_str)
10871 else:
10872 f.write(" %s%s->%s(%s);\n" %
10873 (return_str, interface_str, func.GetPepperName(), arg))
10874 f.write("}\n\n")
10875 self.generated_cpp_filenames.append(filename)
10877 def WriteMojoGLCallVisitor(self, filename):
10878 """Provides the GL implementation for mojo"""
10879 with CWriter(filename) as f:
10880 for func in self.original_functions:
10881 if not func.IsCoreGLFunction():
10882 continue
10883 f.write("VISIT_GL_CALL(%s, %s, (%s), (%s))\n" %
10884 (func.name, func.return_type,
10885 func.MakeTypedOriginalArgString(""),
10886 func.MakeOriginalArgString("")))
10887 self.generated_cpp_filenames.append(filename)
10889 def WriteMojoGLCallVisitorForExtension(self, filename, extension):
10890 """Provides the GL implementation for mojo for a particular extension"""
10891 with CWriter(filename) as f:
10892 for func in self.original_functions:
10893 if func.GetInfo("extension") != extension:
10894 continue
10895 f.write("VISIT_GL_CALL(%s, %s, (%s), (%s))\n" %
10896 (func.name, func.return_type,
10897 func.MakeTypedOriginalArgString(""),
10898 func.MakeOriginalArgString("")))
10899 self.generated_cpp_filenames.append(filename)
10901 def Format(generated_files):
10902 formatter = "clang-format"
10903 if platform.system() == "Windows":
10904 formatter += ".bat"
10905 for filename in generated_files:
10906 call([formatter, "-i", "-style=chromium", filename])
10908 def main(argv):
10909 """This is the main function."""
10910 parser = OptionParser()
10911 parser.add_option(
10912 "--output-dir",
10913 help="base directory for resulting files, under chrome/src. default is "
10914 "empty. Use this if you want the result stored under gen.")
10915 parser.add_option(
10916 "-v", "--verbose", action="store_true",
10917 help="prints more output.")
10919 (options, args) = parser.parse_args(args=argv)
10921 # Add in states and capabilites to GLState
10922 gl_state_valid = _NAMED_TYPE_INFO['GLState']['valid']
10923 for state_name in sorted(_STATES.keys()):
10924 state = _STATES[state_name]
10925 if 'extension_flag' in state:
10926 continue
10927 if 'enum' in state:
10928 if not state['enum'] in gl_state_valid:
10929 gl_state_valid.append(state['enum'])
10930 else:
10931 for item in state['states']:
10932 if 'extension_flag' in item:
10933 continue
10934 if not item['enum'] in gl_state_valid:
10935 gl_state_valid.append(item['enum'])
10936 for capability in _CAPABILITY_FLAGS:
10937 valid_value = "GL_%s" % capability['name'].upper()
10938 if not valid_value in gl_state_valid:
10939 gl_state_valid.append(valid_value)
10941 # This script lives under gpu/command_buffer, cd to base directory.
10942 os.chdir(os.path.dirname(__file__) + "/../..")
10943 base_dir = os.getcwd()
10944 gen = GLGenerator(options.verbose)
10945 gen.ParseGLH("gpu/command_buffer/cmd_buffer_functions.txt")
10947 # Support generating files under gen/
10948 if options.output_dir != None:
10949 os.chdir(options.output_dir)
10951 gen.WritePepperGLES2Interface("ppapi/api/ppb_opengles2.idl", False)
10952 gen.WritePepperGLES2Interface("ppapi/api/dev/ppb_opengles2ext_dev.idl", True)
10953 gen.WriteGLES2ToPPAPIBridge("ppapi/lib/gl/gles2/gles2.c")
10954 gen.WritePepperGLES2Implementation(
10955 "ppapi/shared_impl/ppb_opengles2_shared.cc")
10956 os.chdir(base_dir)
10957 gen.WriteCommandIds("gpu/command_buffer/common/gles2_cmd_ids_autogen.h")
10958 gen.WriteFormat("gpu/command_buffer/common/gles2_cmd_format_autogen.h")
10959 gen.WriteFormatTest(
10960 "gpu/command_buffer/common/gles2_cmd_format_test_autogen.h")
10961 gen.WriteGLES2InterfaceHeader(
10962 "gpu/command_buffer/client/gles2_interface_autogen.h")
10963 gen.WriteMojoGLES2ImplHeader(
10964 "mojo/gpu/mojo_gles2_impl_autogen.h")
10965 gen.WriteMojoGLES2Impl(
10966 "mojo/gpu/mojo_gles2_impl_autogen.cc")
10967 gen.WriteGLES2InterfaceStub(
10968 "gpu/command_buffer/client/gles2_interface_stub_autogen.h")
10969 gen.WriteGLES2InterfaceStubImpl(
10970 "gpu/command_buffer/client/gles2_interface_stub_impl_autogen.h")
10971 gen.WriteGLES2ImplementationHeader(
10972 "gpu/command_buffer/client/gles2_implementation_autogen.h")
10973 gen.WriteGLES2Implementation(
10974 "gpu/command_buffer/client/gles2_implementation_impl_autogen.h")
10975 gen.WriteGLES2ImplementationUnitTests(
10976 "gpu/command_buffer/client/gles2_implementation_unittest_autogen.h")
10977 gen.WriteGLES2TraceImplementationHeader(
10978 "gpu/command_buffer/client/gles2_trace_implementation_autogen.h")
10979 gen.WriteGLES2TraceImplementation(
10980 "gpu/command_buffer/client/gles2_trace_implementation_impl_autogen.h")
10981 gen.WriteGLES2CLibImplementation(
10982 "gpu/command_buffer/client/gles2_c_lib_autogen.h")
10983 gen.WriteCmdHelperHeader(
10984 "gpu/command_buffer/client/gles2_cmd_helper_autogen.h")
10985 gen.WriteServiceImplementation(
10986 "gpu/command_buffer/service/gles2_cmd_decoder_autogen.h")
10987 gen.WriteServiceContextStateHeader(
10988 "gpu/command_buffer/service/context_state_autogen.h")
10989 gen.WriteServiceContextStateImpl(
10990 "gpu/command_buffer/service/context_state_impl_autogen.h")
10991 gen.WriteClientContextStateHeader(
10992 "gpu/command_buffer/client/client_context_state_autogen.h")
10993 gen.WriteClientContextStateImpl(
10994 "gpu/command_buffer/client/client_context_state_impl_autogen.h")
10995 gen.WriteServiceUnitTests(
10996 "gpu/command_buffer/service/gles2_cmd_decoder_unittest_%d_autogen.h")
10997 gen.WriteServiceUnitTestsForExtensions(
10998 "gpu/command_buffer/service/"
10999 "gles2_cmd_decoder_unittest_extensions_autogen.h")
11000 gen.WriteServiceUtilsHeader(
11001 "gpu/command_buffer/service/gles2_cmd_validation_autogen.h")
11002 gen.WriteServiceUtilsImplementation(
11003 "gpu/command_buffer/service/"
11004 "gles2_cmd_validation_implementation_autogen.h")
11005 gen.WriteCommonUtilsHeader(
11006 "gpu/command_buffer/common/gles2_cmd_utils_autogen.h")
11007 gen.WriteCommonUtilsImpl(
11008 "gpu/command_buffer/common/gles2_cmd_utils_implementation_autogen.h")
11009 gen.WriteGLES2Header("gpu/GLES2/gl2chromium_autogen.h")
11010 mojo_gles2_prefix = ("third_party/mojo/src/mojo/public/c/gles2/"
11011 "gles2_call_visitor")
11012 gen.WriteMojoGLCallVisitor(mojo_gles2_prefix + "_autogen.h")
11013 gen.WriteMojoGLCallVisitorForExtension(
11014 mojo_gles2_prefix + "_chromium_texture_mailbox_autogen.h",
11015 "CHROMIUM_texture_mailbox")
11016 gen.WriteMojoGLCallVisitorForExtension(
11017 mojo_gles2_prefix + "_chromium_sync_point_autogen.h",
11018 "CHROMIUM_sync_point")
11019 gen.WriteMojoGLCallVisitorForExtension(
11020 mojo_gles2_prefix + "_chromium_sub_image_autogen.h",
11021 "CHROMIUM_sub_image")
11022 gen.WriteMojoGLCallVisitorForExtension(
11023 mojo_gles2_prefix + "_chromium_miscellaneous_autogen.h",
11024 "CHROMIUM_miscellaneous")
11025 gen.WriteMojoGLCallVisitorForExtension(
11026 mojo_gles2_prefix + "_occlusion_query_ext_autogen.h",
11027 "occlusion_query_EXT")
11028 gen.WriteMojoGLCallVisitorForExtension(
11029 mojo_gles2_prefix + "_chromium_image_autogen.h",
11030 "CHROMIUM_image")
11031 gen.WriteMojoGLCallVisitorForExtension(
11032 mojo_gles2_prefix + "_chromium_copy_texture_autogen.h",
11033 "CHROMIUM_copy_texture")
11034 gen.WriteMojoGLCallVisitorForExtension(
11035 mojo_gles2_prefix + "_chromium_pixel_transfer_buffer_object_autogen.h",
11036 "CHROMIUM_pixel_transfer_buffer_object")
11037 gen.WriteMojoGLCallVisitorForExtension(
11038 mojo_gles2_prefix + "_chromium_framebuffer_multisample_autogen.h",
11039 "chromium_framebuffer_multisample")
11041 Format(gen.generated_cpp_filenames)
11043 if gen.errors > 0:
11044 print "%d errors" % gen.errors
11045 return 1
11046 return 0
11049 if __name__ == '__main__':
11050 sys.exit(main(sys.argv[1:]))