Revert "Reland c91b178b07b0d - Delete dead signin code (SigninGlobalError)"
[chromium-blink-merge.git] / gpu / command_buffer / build_gles2_cmd_buffer.py
blob79629552293414ee17f0cda2f0fc68584e05609b
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',
1149 'BackbufferAttachment': {
1150 'type': 'GLenum',
1151 'valid': [
1152 'GL_COLOR_EXT',
1153 'GL_DEPTH_EXT',
1154 'GL_STENCIL_EXT',
1157 'BufferParameter': {
1158 'type': 'GLenum',
1159 'valid': [
1160 'GL_BUFFER_SIZE',
1161 'GL_BUFFER_USAGE',
1163 'valid_es3': [
1164 'GL_BUFFER_ACCESS_FLAGS',
1165 'GL_BUFFER_MAPPED',
1167 'invalid': [
1168 'GL_PIXEL_PACK_BUFFER',
1171 'BufferParameter64': {
1172 'type': 'GLenum',
1173 'valid': [
1174 'GL_BUFFER_SIZE',
1175 'GL_BUFFER_MAP_LENGTH',
1176 'GL_BUFFER_MAP_OFFSET',
1178 'invalid': [
1179 'GL_PIXEL_PACK_BUFFER',
1182 'BufferMode': {
1183 'type': 'GLenum',
1184 'valid': [
1185 'GL_INTERLEAVED_ATTRIBS',
1186 'GL_SEPARATE_ATTRIBS',
1188 'invalid': [
1189 'GL_PIXEL_PACK_BUFFER',
1192 'FrameBufferParameter': {
1193 'type': 'GLenum',
1194 'valid': [
1195 'GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE',
1196 'GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME',
1197 'GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL',
1198 'GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE',
1200 'valid_es3': [
1201 'GL_FRAMEBUFFER_ATTACHMENT_RED_SIZE',
1202 'GL_FRAMEBUFFER_ATTACHMENT_GREEN_SIZE',
1203 'GL_FRAMEBUFFER_ATTACHMENT_BLUE_SIZE',
1204 'GL_FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE',
1205 'GL_FRAMEBUFFER_ATTACHMENT_DEPTH_SIZE',
1206 'GL_FRAMEBUFFER_ATTACHMENT_STENCIL_SIZE',
1207 'GL_FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE',
1208 'GL_FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING',
1209 'GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER',
1212 'MatrixMode': {
1213 'type': 'GLenum',
1214 'valid': [
1215 'GL_PATH_PROJECTION_CHROMIUM',
1216 'GL_PATH_MODELVIEW_CHROMIUM',
1219 'ProgramParameter': {
1220 'type': 'GLenum',
1221 'valid': [
1222 'GL_DELETE_STATUS',
1223 'GL_LINK_STATUS',
1224 'GL_VALIDATE_STATUS',
1225 'GL_INFO_LOG_LENGTH',
1226 'GL_ATTACHED_SHADERS',
1227 'GL_ACTIVE_ATTRIBUTES',
1228 'GL_ACTIVE_ATTRIBUTE_MAX_LENGTH',
1229 'GL_ACTIVE_UNIFORMS',
1230 'GL_ACTIVE_UNIFORM_MAX_LENGTH',
1232 'valid_es3': [
1233 'GL_ACTIVE_UNIFORM_BLOCKS',
1234 'GL_ACTIVE_UNIFORM_BLOCK_MAX_NAME_LENGTH',
1235 'GL_TRANSFORM_FEEDBACK_BUFFER_MODE',
1236 'GL_TRANSFORM_FEEDBACK_VARYINGS',
1237 'GL_TRANSFORM_FEEDBACK_VARYING_MAX_LENGTH',
1239 'invalid': [
1240 'GL_PROGRAM_BINARY_RETRIEVABLE_HINT', # not supported in Chromium.
1243 'QueryObjectParameter': {
1244 'type': 'GLenum',
1245 'valid': [
1246 'GL_QUERY_RESULT_EXT',
1247 'GL_QUERY_RESULT_AVAILABLE_EXT',
1250 'QueryParameter': {
1251 'type': 'GLenum',
1252 'valid': [
1253 'GL_CURRENT_QUERY_EXT',
1256 'QueryTarget': {
1257 'type': 'GLenum',
1258 'valid': [
1259 'GL_ANY_SAMPLES_PASSED_EXT',
1260 'GL_ANY_SAMPLES_PASSED_CONSERVATIVE_EXT',
1261 'GL_COMMANDS_ISSUED_CHROMIUM',
1262 'GL_LATENCY_QUERY_CHROMIUM',
1263 'GL_ASYNC_PIXEL_UNPACK_COMPLETED_CHROMIUM',
1264 'GL_ASYNC_PIXEL_PACK_COMPLETED_CHROMIUM',
1265 'GL_COMMANDS_COMPLETED_CHROMIUM',
1268 'RenderBufferParameter': {
1269 'type': 'GLenum',
1270 'valid': [
1271 'GL_RENDERBUFFER_RED_SIZE',
1272 'GL_RENDERBUFFER_GREEN_SIZE',
1273 'GL_RENDERBUFFER_BLUE_SIZE',
1274 'GL_RENDERBUFFER_ALPHA_SIZE',
1275 'GL_RENDERBUFFER_DEPTH_SIZE',
1276 'GL_RENDERBUFFER_STENCIL_SIZE',
1277 'GL_RENDERBUFFER_WIDTH',
1278 'GL_RENDERBUFFER_HEIGHT',
1279 'GL_RENDERBUFFER_INTERNAL_FORMAT',
1281 'valid_es3': [
1282 'GL_RENDERBUFFER_SAMPLES',
1285 'InternalFormatParameter': {
1286 'type': 'GLenum',
1287 'valid': [
1288 'GL_NUM_SAMPLE_COUNTS',
1289 'GL_SAMPLES',
1292 'SamplerParameter': {
1293 'type': 'GLenum',
1294 'valid': [
1295 'GL_TEXTURE_MAG_FILTER',
1296 'GL_TEXTURE_MIN_FILTER',
1297 'GL_TEXTURE_MIN_LOD',
1298 'GL_TEXTURE_MAX_LOD',
1299 'GL_TEXTURE_WRAP_S',
1300 'GL_TEXTURE_WRAP_T',
1301 'GL_TEXTURE_WRAP_R',
1302 'GL_TEXTURE_COMPARE_MODE',
1303 'GL_TEXTURE_COMPARE_FUNC',
1305 'invalid': [
1306 'GL_GENERATE_MIPMAP',
1309 'ShaderParameter': {
1310 'type': 'GLenum',
1311 'valid': [
1312 'GL_SHADER_TYPE',
1313 'GL_DELETE_STATUS',
1314 'GL_COMPILE_STATUS',
1315 'GL_INFO_LOG_LENGTH',
1316 'GL_SHADER_SOURCE_LENGTH',
1317 'GL_TRANSLATED_SHADER_SOURCE_LENGTH_ANGLE',
1320 'ShaderPrecision': {
1321 'type': 'GLenum',
1322 'valid': [
1323 'GL_LOW_FLOAT',
1324 'GL_MEDIUM_FLOAT',
1325 'GL_HIGH_FLOAT',
1326 'GL_LOW_INT',
1327 'GL_MEDIUM_INT',
1328 'GL_HIGH_INT',
1331 'StringType': {
1332 'type': 'GLenum',
1333 'valid': [
1334 'GL_VENDOR',
1335 'GL_RENDERER',
1336 'GL_VERSION',
1337 'GL_SHADING_LANGUAGE_VERSION',
1338 'GL_EXTENSIONS',
1341 'TextureParameter': {
1342 'type': 'GLenum',
1343 'valid': [
1344 'GL_TEXTURE_MAG_FILTER',
1345 'GL_TEXTURE_MIN_FILTER',
1346 'GL_TEXTURE_POOL_CHROMIUM',
1347 'GL_TEXTURE_WRAP_S',
1348 'GL_TEXTURE_WRAP_T',
1350 'valid_es3': [
1351 'GL_TEXTURE_BASE_LEVEL',
1352 'GL_TEXTURE_COMPARE_FUNC',
1353 'GL_TEXTURE_COMPARE_MODE',
1354 'GL_TEXTURE_IMMUTABLE_FORMAT',
1355 'GL_TEXTURE_IMMUTABLE_LEVELS',
1356 'GL_TEXTURE_MAX_LEVEL',
1357 'GL_TEXTURE_MAX_LOD',
1358 'GL_TEXTURE_MIN_LOD',
1359 'GL_TEXTURE_WRAP_R',
1361 'invalid': [
1362 'GL_GENERATE_MIPMAP',
1365 'TexturePool': {
1366 'type': 'GLenum',
1367 'valid': [
1368 'GL_TEXTURE_POOL_MANAGED_CHROMIUM',
1369 'GL_TEXTURE_POOL_UNMANAGED_CHROMIUM',
1372 'TextureWrapMode': {
1373 'type': 'GLenum',
1374 'valid': [
1375 'GL_CLAMP_TO_EDGE',
1376 'GL_MIRRORED_REPEAT',
1377 'GL_REPEAT',
1380 'TextureMinFilterMode': {
1381 'type': 'GLenum',
1382 'valid': [
1383 'GL_NEAREST',
1384 'GL_LINEAR',
1385 'GL_NEAREST_MIPMAP_NEAREST',
1386 'GL_LINEAR_MIPMAP_NEAREST',
1387 'GL_NEAREST_MIPMAP_LINEAR',
1388 'GL_LINEAR_MIPMAP_LINEAR',
1391 'TextureMagFilterMode': {
1392 'type': 'GLenum',
1393 'valid': [
1394 'GL_NEAREST',
1395 'GL_LINEAR',
1398 'TextureCompareFunc': {
1399 'type': 'GLenum',
1400 'valid': [
1401 'GL_LEQUAL',
1402 'GL_GEQUAL',
1403 'GL_LESS',
1404 'GL_GREATER',
1405 'GL_EQUAL',
1406 'GL_NOTEQUAL',
1407 'GL_ALWAYS',
1408 'GL_NEVER',
1411 'TextureCompareMode': {
1412 'type': 'GLenum',
1413 'valid': [
1414 'GL_NONE',
1415 'GL_COMPARE_REF_TO_TEXTURE',
1418 'TextureUsage': {
1419 'type': 'GLenum',
1420 'valid': [
1421 'GL_NONE',
1422 'GL_FRAMEBUFFER_ATTACHMENT_ANGLE',
1425 'VertexAttribute': {
1426 'type': 'GLenum',
1427 'valid': [
1428 # some enum that the decoder actually passes through to GL needs
1429 # to be the first listed here since it's used in unit tests.
1430 'GL_VERTEX_ATTRIB_ARRAY_NORMALIZED',
1431 'GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING',
1432 'GL_VERTEX_ATTRIB_ARRAY_ENABLED',
1433 'GL_VERTEX_ATTRIB_ARRAY_SIZE',
1434 'GL_VERTEX_ATTRIB_ARRAY_STRIDE',
1435 'GL_VERTEX_ATTRIB_ARRAY_TYPE',
1436 'GL_CURRENT_VERTEX_ATTRIB',
1438 'valid_es3': [
1439 'GL_VERTEX_ATTRIB_ARRAY_INTEGER',
1440 'GL_VERTEX_ATTRIB_ARRAY_DIVISOR',
1443 'VertexPointer': {
1444 'type': 'GLenum',
1445 'valid': [
1446 'GL_VERTEX_ATTRIB_ARRAY_POINTER',
1449 'HintTarget': {
1450 'type': 'GLenum',
1451 'valid': [
1452 'GL_GENERATE_MIPMAP_HINT',
1454 'valid_es3': [
1455 'GL_FRAGMENT_SHADER_DERIVATIVE_HINT',
1457 'invalid': [
1458 'GL_PERSPECTIVE_CORRECTION_HINT',
1461 'HintMode': {
1462 'type': 'GLenum',
1463 'valid': [
1464 'GL_FASTEST',
1465 'GL_NICEST',
1466 'GL_DONT_CARE',
1469 'PixelStore': {
1470 'type': 'GLenum',
1471 'valid': [
1472 'GL_PACK_ALIGNMENT',
1473 'GL_UNPACK_ALIGNMENT',
1475 'valid_es3': [
1476 'GL_PACK_ROW_LENGTH',
1477 'GL_PACK_SKIP_PIXELS',
1478 'GL_PACK_SKIP_ROWS',
1479 'GL_UNPACK_ROW_LENGTH',
1480 'GL_UNPACK_IMAGE_HEIGHT',
1481 'GL_UNPACK_SKIP_PIXELS',
1482 'GL_UNPACK_SKIP_ROWS',
1483 'GL_UNPACK_SKIP_IMAGES',
1485 'invalid': [
1486 'GL_PACK_SWAP_BYTES',
1487 'GL_UNPACK_SWAP_BYTES',
1490 'PixelStoreAlignment': {
1491 'type': 'GLint',
1492 'valid': [
1493 '1',
1494 '2',
1495 '4',
1496 '8',
1498 'invalid': [
1499 '3',
1500 '9',
1503 'ReadPixelFormat': {
1504 'type': 'GLenum',
1505 'valid': [
1506 'GL_ALPHA',
1507 'GL_RGB',
1508 'GL_RGBA',
1510 'valid_es3': [
1511 'GL_RGBA_INTEGER',
1513 'deprecated_es3': [
1514 'GL_ALPHA',
1515 'GL_RGB',
1518 'PixelType': {
1519 'type': 'GLenum',
1520 'valid': [
1521 'GL_UNSIGNED_BYTE',
1522 'GL_UNSIGNED_SHORT_5_6_5',
1523 'GL_UNSIGNED_SHORT_4_4_4_4',
1524 'GL_UNSIGNED_SHORT_5_5_5_1',
1526 'valid_es3': [
1527 'GL_BYTE',
1528 'GL_UNSIGNED_SHORT',
1529 'GL_SHORT',
1530 'GL_UNSIGNED_INT',
1531 'GL_INT',
1532 'GL_HALF_FLOAT',
1533 'GL_FLOAT',
1534 'GL_UNSIGNED_INT_2_10_10_10_REV',
1535 'GL_UNSIGNED_INT_10F_11F_11F_REV',
1536 'GL_UNSIGNED_INT_5_9_9_9_REV',
1537 'GL_UNSIGNED_INT_24_8',
1538 'GL_FLOAT_32_UNSIGNED_INT_24_8_REV',
1540 'invalid': [
1541 'GL_UNSIGNED_BYTE_3_3_2',
1544 'PathCoordType': {
1545 'type': 'GLenum',
1546 'valid': [
1547 'GL_BYTE',
1548 'GL_UNSIGNED_BYTE',
1549 'GL_SHORT',
1550 'GL_UNSIGNED_SHORT',
1551 'GL_FLOAT',
1554 'PathCoverMode': {
1555 'type': 'GLenum',
1556 'valid': [
1557 'GL_CONVEX_HULL_CHROMIUM',
1558 'GL_BOUNDING_BOX_CHROMIUM',
1561 'PathFillMode': {
1562 'type': 'GLenum',
1563 'valid': [
1564 'GL_INVERT',
1565 'GL_COUNT_UP_CHROMIUM',
1566 'GL_COUNT_DOWN_CHROMIUM',
1569 'PathParameter': {
1570 'type': 'GLenum',
1571 'valid': [
1572 'GL_PATH_STROKE_WIDTH_CHROMIUM',
1573 'GL_PATH_END_CAPS_CHROMIUM',
1574 'GL_PATH_JOIN_STYLE_CHROMIUM',
1575 'GL_PATH_MITER_LIMIT_CHROMIUM',
1576 'GL_PATH_STROKE_BOUND_CHROMIUM',
1579 'PathParameterCapValues': {
1580 'type': 'GLint',
1581 'valid': [
1582 'GL_FLAT',
1583 'GL_SQUARE_CHROMIUM',
1584 'GL_ROUND_CHROMIUM',
1587 'PathParameterJoinValues': {
1588 'type': 'GLint',
1589 'valid': [
1590 'GL_MITER_REVERT_CHROMIUM',
1591 'GL_BEVEL_CHROMIUM',
1592 'GL_ROUND_CHROMIUM',
1595 'ReadPixelType': {
1596 'type': 'GLenum',
1597 'valid': [
1598 'GL_UNSIGNED_BYTE',
1599 'GL_UNSIGNED_SHORT_5_6_5',
1600 'GL_UNSIGNED_SHORT_4_4_4_4',
1601 'GL_UNSIGNED_SHORT_5_5_5_1',
1603 'invalid': [
1604 'GL_SHORT',
1606 'valid_es3': [
1607 'GL_UNSIGNED_INT',
1608 'GL_INT',
1609 'GL_FLOAT',
1610 'GL_UNSIGNED_INT_2_10_10_10_REV',
1612 'deprecated_es3': [
1613 'GL_UNSIGNED_SHORT_5_6_5',
1614 'GL_UNSIGNED_SHORT_4_4_4_4',
1615 'GL_UNSIGNED_SHORT_5_5_5_1',
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_RGBA',
1868 'ImageUsage': {
1869 'type': 'GLenum',
1870 'valid': [
1871 'GL_MAP_CHROMIUM',
1872 'GL_SCANOUT_CHROMIUM'
1875 'ValueBufferTarget': {
1876 'type': 'GLenum',
1877 'valid': [
1878 'GL_SUBSCRIBED_VALUES_BUFFER_CHROMIUM',
1881 'SubscriptionTarget': {
1882 'type': 'GLenum',
1883 'valid': [
1884 'GL_MOUSE_POSITION_CHROMIUM',
1887 'UniformParameter': {
1888 'type': 'GLenum',
1889 'valid': [
1890 'GL_UNIFORM_SIZE',
1891 'GL_UNIFORM_TYPE',
1892 'GL_UNIFORM_NAME_LENGTH',
1893 'GL_UNIFORM_BLOCK_INDEX',
1894 'GL_UNIFORM_OFFSET',
1895 'GL_UNIFORM_ARRAY_STRIDE',
1896 'GL_UNIFORM_MATRIX_STRIDE',
1897 'GL_UNIFORM_IS_ROW_MAJOR',
1899 'invalid': [
1900 'GL_UNIFORM_BLOCK_NAME_LENGTH',
1903 'UniformBlockParameter': {
1904 'type': 'GLenum',
1905 'valid': [
1906 'GL_UNIFORM_BLOCK_BINDING',
1907 'GL_UNIFORM_BLOCK_DATA_SIZE',
1908 'GL_UNIFORM_BLOCK_NAME_LENGTH',
1909 'GL_UNIFORM_BLOCK_ACTIVE_UNIFORMS',
1910 'GL_UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES',
1911 'GL_UNIFORM_BLOCK_REFERENCED_BY_VERTEX_SHADER',
1912 'GL_UNIFORM_BLOCK_REFERENCED_BY_FRAGMENT_SHADER',
1914 'invalid': [
1915 'GL_NEAREST',
1918 'VertexAttribType': {
1919 'type': 'GLenum',
1920 'valid': [
1921 'GL_BYTE',
1922 'GL_UNSIGNED_BYTE',
1923 'GL_SHORT',
1924 'GL_UNSIGNED_SHORT',
1925 # 'GL_FIXED', // This is not available on Desktop GL.
1926 'GL_FLOAT',
1928 'valid_es3': [
1929 'GL_INT',
1930 'GL_UNSIGNED_INT',
1931 'GL_HALF_FLOAT',
1932 'GL_INT_2_10_10_10_REV',
1933 'GL_UNSIGNED_INT_2_10_10_10_REV',
1935 'invalid': [
1936 'GL_DOUBLE',
1939 'VertexAttribIType': {
1940 'type': 'GLenum',
1941 'valid': [
1942 'GL_BYTE',
1943 'GL_UNSIGNED_BYTE',
1944 'GL_SHORT',
1945 'GL_UNSIGNED_SHORT',
1946 'GL_INT',
1947 'GL_UNSIGNED_INT',
1949 'invalid': [
1950 'GL_FLOAT',
1951 'GL_DOUBLE',
1954 'TextureBorder': {
1955 'type': 'GLint',
1956 'is_complete': True,
1957 'valid': [
1958 '0',
1960 'invalid': [
1961 '1',
1964 'VertexAttribSize': {
1965 'type': 'GLint',
1966 'valid': [
1967 '1',
1968 '2',
1969 '3',
1970 '4',
1972 'invalid': [
1973 '0',
1974 '5',
1977 'ZeroOnly': {
1978 'type': 'GLint',
1979 'is_complete': True,
1980 'valid': [
1981 '0',
1983 'invalid': [
1984 '1',
1987 'FalseOnly': {
1988 'type': 'GLboolean',
1989 'is_complete': True,
1990 'valid': [
1991 'false',
1993 'invalid': [
1994 'true',
1997 'ResetStatus': {
1998 'type': 'GLenum',
1999 'valid': [
2000 'GL_GUILTY_CONTEXT_RESET_ARB',
2001 'GL_INNOCENT_CONTEXT_RESET_ARB',
2002 'GL_UNKNOWN_CONTEXT_RESET_ARB',
2005 'SyncCondition': {
2006 'type': 'GLenum',
2007 'is_complete': True,
2008 'valid': [
2009 'GL_SYNC_GPU_COMMANDS_COMPLETE',
2011 'invalid': [
2012 '0',
2015 'SyncFlags': {
2016 'type': 'GLbitfield',
2017 'is_complete': True,
2018 'valid': [
2019 '0',
2021 'invalid': [
2022 '1',
2025 'SyncFlushFlags': {
2026 'type': 'GLbitfield',
2027 'valid': [
2028 'GL_SYNC_FLUSH_COMMANDS_BIT',
2029 '0',
2031 'invalid': [
2032 '0xFFFFFFFF',
2035 'SyncParameter': {
2036 'type': 'GLenum',
2037 'valid': [
2038 'GL_SYNC_STATUS', # This needs to be the 1st; all others are cached.
2039 'GL_OBJECT_TYPE',
2040 'GL_SYNC_CONDITION',
2041 'GL_SYNC_FLAGS',
2043 'invalid': [
2044 'GL_SYNC_FENCE',
2049 # This table specifies the different pepper interfaces that are supported for
2050 # GL commands. 'dev' is true if it's a dev interface.
2051 _PEPPER_INTERFACES = [
2052 {'name': '', 'dev': False},
2053 {'name': 'InstancedArrays', 'dev': False},
2054 {'name': 'FramebufferBlit', 'dev': False},
2055 {'name': 'FramebufferMultisample', 'dev': False},
2056 {'name': 'ChromiumEnableFeature', 'dev': False},
2057 {'name': 'ChromiumMapSub', 'dev': False},
2058 {'name': 'Query', 'dev': False},
2059 {'name': 'VertexArrayObject', 'dev': False},
2060 {'name': 'DrawBuffers', 'dev': True},
2063 # A function info object specifies the type and other special data for the
2064 # command that will be generated. A base function info object is generated by
2065 # parsing the "cmd_buffer_functions.txt", one for each function in the
2066 # file. These function info objects can be augmented and their values can be
2067 # overridden by adding an object to the table below.
2069 # Must match function names specified in "cmd_buffer_functions.txt".
2071 # cmd_comment: A comment added to the cmd format.
2072 # type: defines which handler will be used to generate code.
2073 # decoder_func: defines which function to call in the decoder to execute the
2074 # corresponding GL command. If not specified the GL command will
2075 # be called directly.
2076 # gl_test_func: GL function that is expected to be called when testing.
2077 # cmd_args: The arguments to use for the command. This overrides generating
2078 # them based on the GL function arguments.
2079 # gen_cmd: Whether or not this function geneates a command. Default = True.
2080 # data_transfer_methods: Array of methods that are used for transfering the
2081 # pointer data. Possible values: 'immediate', 'shm', 'bucket'.
2082 # The default is 'immediate' if the command has one pointer
2083 # argument, otherwise 'shm'. One command is generated for each
2084 # transfer method. Affects only commands which are not of type
2085 # 'HandWritten', 'GETn' or 'GLcharN'.
2086 # Note: the command arguments that affect this are the final args,
2087 # taking cmd_args override into consideration.
2088 # impl_func: Whether or not to generate the GLES2Implementation part of this
2089 # command.
2090 # impl_decl: Whether or not to generate the GLES2Implementation declaration
2091 # for this command.
2092 # needs_size: If True a data_size field is added to the command.
2093 # count: The number of units per element. For PUTn or PUT types.
2094 # use_count_func: If True the actual data count needs to be computed; the count
2095 # argument specifies the maximum count.
2096 # unit_test: If False no service side unit test will be generated.
2097 # client_test: If False no client side unit test will be generated.
2098 # expectation: If False the unit test will have no expected calls.
2099 # gen_func: Name of function that generates GL resource for corresponding
2100 # bind function.
2101 # states: array of states that get set by this function corresponding to
2102 # the given arguments
2103 # state_flag: name of flag that is set to true when function is called.
2104 # no_gl: no GL function is called.
2105 # valid_args: A dictionary of argument indices to args to use in unit tests
2106 # when they can not be automatically determined.
2107 # pepper_interface: The pepper interface that is used for this extension
2108 # pepper_name: The name of the function as exposed to pepper.
2109 # pepper_args: A string representing the argument list (what would appear in
2110 # C/C++ between the parentheses for the function declaration)
2111 # that the Pepper API expects for this function. Use this only if
2112 # the stable Pepper API differs from the GLES2 argument list.
2113 # invalid_test: False if no invalid test needed.
2114 # shadowed: True = the value is shadowed so no glGetXXX call will be made.
2115 # first_element_only: For PUT types, True if only the first element of an
2116 # array is used and we end up calling the single value
2117 # corresponding function. eg. TexParameteriv -> TexParameteri
2118 # extension: Function is an extension to GL and should not be exposed to
2119 # pepper unless pepper_interface is defined.
2120 # extension_flag: Function is an extension and should be enabled only when
2121 # the corresponding feature info flag is enabled. Implies
2122 # 'extension': True.
2123 # not_shared: For GENn types, True if objects can't be shared between contexts
2124 # unsafe: True = no validation is implemented on the service side and the
2125 # command is only available with --enable-unsafe-es3-apis.
2126 # id_mapping: A list of resource type names whose client side IDs need to be
2127 # mapped to service side IDs. This is only used for unsafe APIs.
2129 _FUNCTION_INFO = {
2130 'ActiveTexture': {
2131 'decoder_func': 'DoActiveTexture',
2132 'unit_test': False,
2133 'impl_func': False,
2134 'client_test': False,
2136 'AttachShader': {'decoder_func': 'DoAttachShader'},
2137 'BindAttribLocation': {
2138 'type': 'GLchar',
2139 'data_transfer_methods': ['bucket'],
2140 'needs_size': True,
2142 'BindBuffer': {
2143 'type': 'Bind',
2144 'decoder_func': 'DoBindBuffer',
2145 'gen_func': 'GenBuffersARB',
2147 'BindBufferBase': {
2148 'type': 'Bind',
2149 'id_mapping': [ 'Buffer' ],
2150 'gen_func': 'GenBuffersARB',
2151 'unsafe': True,
2153 'BindBufferRange': {
2154 'type': 'Bind',
2155 'id_mapping': [ 'Buffer' ],
2156 'gen_func': 'GenBuffersARB',
2157 'valid_args': {
2158 '3': '4',
2159 '4': '4'
2161 'unsafe': True,
2163 'BindFramebuffer': {
2164 'type': 'Bind',
2165 'decoder_func': 'DoBindFramebuffer',
2166 'gl_test_func': 'glBindFramebufferEXT',
2167 'gen_func': 'GenFramebuffersEXT',
2168 'trace_level': 1,
2170 'BindRenderbuffer': {
2171 'type': 'Bind',
2172 'decoder_func': 'DoBindRenderbuffer',
2173 'gl_test_func': 'glBindRenderbufferEXT',
2174 'gen_func': 'GenRenderbuffersEXT',
2176 'BindSampler': {
2177 'type': 'Bind',
2178 'id_mapping': [ 'Sampler' ],
2179 'unsafe': True,
2181 'BindTexture': {
2182 'type': 'Bind',
2183 'decoder_func': 'DoBindTexture',
2184 'gen_func': 'GenTextures',
2185 # TODO(gman): remove this once client side caching works.
2186 'client_test': False,
2187 'trace_level': 2,
2189 'BindTransformFeedback': {
2190 'type': 'Bind',
2191 'id_mapping': [ 'TransformFeedback' ],
2192 'unsafe': True,
2194 'BlitFramebufferCHROMIUM': {
2195 'decoder_func': 'DoBlitFramebufferCHROMIUM',
2196 'unit_test': False,
2197 'extension_flag': 'chromium_framebuffer_multisample',
2198 'pepper_interface': 'FramebufferBlit',
2199 'pepper_name': 'BlitFramebufferEXT',
2200 'defer_reads': True,
2201 'defer_draws': True,
2202 'trace_level': 1,
2204 'BufferData': {
2205 'type': 'Manual',
2206 'data_transfer_methods': ['shm'],
2207 'client_test': False,
2208 'trace_level': 2,
2210 'BufferSubData': {
2211 'type': 'Data',
2212 'client_test': False,
2213 'decoder_func': 'DoBufferSubData',
2214 'data_transfer_methods': ['shm'],
2215 'trace_level': 2,
2217 'CheckFramebufferStatus': {
2218 'type': 'Is',
2219 'decoder_func': 'DoCheckFramebufferStatus',
2220 'gl_test_func': 'glCheckFramebufferStatusEXT',
2221 'error_value': 'GL_FRAMEBUFFER_UNSUPPORTED',
2222 'result': ['GLenum'],
2224 'Clear': {
2225 'decoder_func': 'DoClear',
2226 'defer_draws': True,
2227 'trace_level': 2,
2229 'ClearBufferiv': {
2230 'type': 'PUT',
2231 'use_count_func': True,
2232 'count': 4,
2233 'unsafe': True,
2234 'trace_level': 2,
2236 'ClearBufferuiv': {
2237 'type': 'PUT',
2238 'count': 4,
2239 'unsafe': True,
2240 'trace_level': 2,
2242 'ClearBufferfv': {
2243 'type': 'PUT',
2244 'use_count_func': True,
2245 'count': 4,
2246 'unsafe': True,
2247 'trace_level': 2,
2249 'ClearBufferfi': {
2250 'unsafe': True,
2251 'trace_level': 2,
2253 'ClearColor': {
2254 'type': 'StateSet',
2255 'state': 'ClearColor',
2257 'ClearDepthf': {
2258 'type': 'StateSet',
2259 'state': 'ClearDepthf',
2260 'decoder_func': 'glClearDepth',
2261 'gl_test_func': 'glClearDepth',
2262 'valid_args': {
2263 '0': '0.5f'
2266 'ClientWaitSync': {
2267 'type': 'Custom',
2268 'data_transfer_methods': ['shm'],
2269 'cmd_args': 'GLuint sync, GLbitfieldSyncFlushFlags flags, '
2270 'GLuint timeout_0, GLuint timeout_1, GLenum* result',
2271 'unsafe': True,
2272 'result': ['GLenum'],
2273 'trace_level': 2,
2275 'ColorMask': {
2276 'type': 'StateSet',
2277 'state': 'ColorMask',
2278 'no_gl': True,
2279 'expectation': False,
2281 'ConsumeTextureCHROMIUM': {
2282 'decoder_func': 'DoConsumeTextureCHROMIUM',
2283 'impl_func': False,
2284 'type': 'PUT',
2285 'count': 64, # GL_MAILBOX_SIZE_CHROMIUM
2286 'unit_test': False,
2287 'client_test': False,
2288 'extension': "CHROMIUM_texture_mailbox",
2289 'chromium': True,
2290 'trace_level': 2,
2292 'CopyBufferSubData': {
2293 'unsafe': True,
2295 'CreateAndConsumeTextureCHROMIUM': {
2296 'decoder_func': 'DoCreateAndConsumeTextureCHROMIUM',
2297 'impl_func': False,
2298 'type': 'HandWritten',
2299 'data_transfer_methods': ['immediate'],
2300 'unit_test': False,
2301 'client_test': False,
2302 'extension': "CHROMIUM_texture_mailbox",
2303 'chromium': True,
2304 'trace_level': 2,
2306 'GenValuebuffersCHROMIUM': {
2307 'type': 'GENn',
2308 'gl_test_func': 'glGenValuebuffersCHROMIUM',
2309 'resource_type': 'Valuebuffer',
2310 'resource_types': 'Valuebuffers',
2311 'unit_test': False,
2312 'extension': True,
2313 'chromium': True,
2315 'DeleteValuebuffersCHROMIUM': {
2316 'type': 'DELn',
2317 'gl_test_func': 'glDeleteValuebuffersCHROMIUM',
2318 'resource_type': 'Valuebuffer',
2319 'resource_types': 'Valuebuffers',
2320 'unit_test': False,
2321 'extension': True,
2322 'chromium': True,
2324 'IsValuebufferCHROMIUM': {
2325 'type': 'Is',
2326 'decoder_func': 'DoIsValuebufferCHROMIUM',
2327 'expectation': False,
2328 'extension': True,
2329 'chromium': True,
2331 'BindValuebufferCHROMIUM': {
2332 'type': 'Bind',
2333 'decoder_func': 'DoBindValueBufferCHROMIUM',
2334 'gen_func': 'GenValueBuffersCHROMIUM',
2335 'unit_test': False,
2336 'extension': True,
2337 'chromium': True,
2339 'SubscribeValueCHROMIUM': {
2340 'decoder_func': 'DoSubscribeValueCHROMIUM',
2341 'unit_test': False,
2342 'extension': True,
2343 'chromium': True,
2345 'PopulateSubscribedValuesCHROMIUM': {
2346 'decoder_func': 'DoPopulateSubscribedValuesCHROMIUM',
2347 'unit_test': False,
2348 'extension': True,
2349 'chromium': True,
2351 'UniformValuebufferCHROMIUM': {
2352 'decoder_func': 'DoUniformValueBufferCHROMIUM',
2353 'unit_test': False,
2354 'extension': True,
2355 'chromium': True,
2357 'ClearStencil': {
2358 'type': 'StateSet',
2359 'state': 'ClearStencil',
2361 'EnableFeatureCHROMIUM': {
2362 'type': 'Custom',
2363 'data_transfer_methods': ['shm'],
2364 'decoder_func': 'DoEnableFeatureCHROMIUM',
2365 'expectation': False,
2366 'cmd_args': 'GLuint bucket_id, GLint* result',
2367 'result': ['GLint'],
2368 'extension': True,
2369 'chromium': True,
2370 'pepper_interface': 'ChromiumEnableFeature',
2372 'CompileShader': {'decoder_func': 'DoCompileShader', 'unit_test': False},
2373 'CompressedTexImage2D': {
2374 'type': 'Manual',
2375 'data_transfer_methods': ['bucket', 'shm'],
2376 'trace_level': 1,
2378 'CompressedTexSubImage2D': {
2379 'type': 'Data',
2380 'data_transfer_methods': ['bucket', 'shm'],
2381 'decoder_func': 'DoCompressedTexSubImage2D',
2382 'trace_level': 1,
2384 'CopyTexImage2D': {
2385 'decoder_func': 'DoCopyTexImage2D',
2386 'unit_test': False,
2387 'defer_reads': True,
2388 'trace_level': 1,
2390 'CopyTexSubImage2D': {
2391 'decoder_func': 'DoCopyTexSubImage2D',
2392 'defer_reads': True,
2393 'trace_level': 1,
2395 'CompressedTexImage3D': {
2396 'type': 'Manual',
2397 'data_transfer_methods': ['bucket', 'shm'],
2398 'unsafe': True,
2399 'trace_level': 1,
2401 'CompressedTexSubImage3D': {
2402 'type': 'Data',
2403 'data_transfer_methods': ['bucket', 'shm'],
2404 'decoder_func': 'DoCompressedTexSubImage3D',
2405 'unsafe': True,
2406 'trace_level': 1,
2408 'CopyTexSubImage3D': {
2409 'defer_reads': True,
2410 'unsafe': True,
2411 'trace_level': 1,
2413 'CreateImageCHROMIUM': {
2414 'type': 'Manual',
2415 'cmd_args':
2416 'ClientBuffer buffer, GLsizei width, GLsizei height, '
2417 'GLenum internalformat',
2418 'result': ['GLuint'],
2419 'client_test': False,
2420 'gen_cmd': False,
2421 'expectation': False,
2422 'extension': "CHROMIUM_image",
2423 'chromium': True,
2424 'trace_level': 1,
2426 'DestroyImageCHROMIUM': {
2427 'type': 'Manual',
2428 'client_test': False,
2429 'gen_cmd': False,
2430 'extension': "CHROMIUM_image",
2431 'chromium': True,
2432 'trace_level': 1,
2434 'CreateGpuMemoryBufferImageCHROMIUM': {
2435 'type': 'Manual',
2436 'cmd_args':
2437 'GLsizei width, GLsizei height, GLenum internalformat, GLenum usage',
2438 'result': ['GLuint'],
2439 'client_test': False,
2440 'gen_cmd': False,
2441 'expectation': False,
2442 'extension': "CHROMIUM_image",
2443 'chromium': True,
2444 'trace_level': 1,
2446 'CreateProgram': {
2447 'type': 'Create',
2448 'client_test': False,
2450 'CreateShader': {
2451 'type': 'Create',
2452 'client_test': False,
2454 'BlendColor': {
2455 'type': 'StateSet',
2456 'state': 'BlendColor',
2458 'BlendEquation': {
2459 'type': 'StateSetRGBAlpha',
2460 'state': 'BlendEquation',
2461 'valid_args': {
2462 '0': 'GL_FUNC_SUBTRACT'
2465 'BlendEquationSeparate': {
2466 'type': 'StateSet',
2467 'state': 'BlendEquation',
2468 'valid_args': {
2469 '0': 'GL_FUNC_SUBTRACT'
2472 'BlendFunc': {
2473 'type': 'StateSetRGBAlpha',
2474 'state': 'BlendFunc',
2476 'BlendFuncSeparate': {
2477 'type': 'StateSet',
2478 'state': 'BlendFunc',
2480 'BlendBarrierKHR': {
2481 'gl_test_func': 'glBlendBarrierKHR',
2482 'extension': True,
2483 'extension_flag': 'blend_equation_advanced',
2484 'client_test': False,
2486 'SampleCoverage': {'decoder_func': 'DoSampleCoverage'},
2487 'StencilFunc': {
2488 'type': 'StateSetFrontBack',
2489 'state': 'StencilFunc',
2491 'StencilFuncSeparate': {
2492 'type': 'StateSetFrontBackSeparate',
2493 'state': 'StencilFunc',
2495 'StencilOp': {
2496 'type': 'StateSetFrontBack',
2497 'state': 'StencilOp',
2498 'valid_args': {
2499 '1': 'GL_INCR'
2502 'StencilOpSeparate': {
2503 'type': 'StateSetFrontBackSeparate',
2504 'state': 'StencilOp',
2505 'valid_args': {
2506 '1': 'GL_INCR'
2509 'Hint': {
2510 'type': 'StateSetNamedParameter',
2511 'state': 'Hint',
2513 'CullFace': {'type': 'StateSet', 'state': 'CullFace'},
2514 'FrontFace': {'type': 'StateSet', 'state': 'FrontFace'},
2515 'DepthFunc': {'type': 'StateSet', 'state': 'DepthFunc'},
2516 'LineWidth': {
2517 'type': 'StateSet',
2518 'state': 'LineWidth',
2519 'valid_args': {
2520 '0': '0.5f'
2523 'PolygonOffset': {
2524 'type': 'StateSet',
2525 'state': 'PolygonOffset',
2527 'DeleteBuffers': {
2528 'type': 'DELn',
2529 'gl_test_func': 'glDeleteBuffersARB',
2530 'resource_type': 'Buffer',
2531 'resource_types': 'Buffers',
2533 'DeleteFramebuffers': {
2534 'type': 'DELn',
2535 'gl_test_func': 'glDeleteFramebuffersEXT',
2536 'resource_type': 'Framebuffer',
2537 'resource_types': 'Framebuffers',
2538 'trace_level': 2,
2540 'DeleteProgram': { 'type': 'Delete' },
2541 'DeleteRenderbuffers': {
2542 'type': 'DELn',
2543 'gl_test_func': 'glDeleteRenderbuffersEXT',
2544 'resource_type': 'Renderbuffer',
2545 'resource_types': 'Renderbuffers',
2546 'trace_level': 2,
2548 'DeleteSamplers': {
2549 'type': 'DELn',
2550 'resource_type': 'Sampler',
2551 'resource_types': 'Samplers',
2552 'unsafe': True,
2554 'DeleteShader': { 'type': 'Delete' },
2555 'DeleteSync': {
2556 'type': 'Delete',
2557 'cmd_args': 'GLuint sync',
2558 'resource_type': 'Sync',
2559 'unsafe': True,
2561 'DeleteTextures': {
2562 'type': 'DELn',
2563 'resource_type': 'Texture',
2564 'resource_types': 'Textures',
2566 'DeleteTransformFeedbacks': {
2567 'type': 'DELn',
2568 'resource_type': 'TransformFeedback',
2569 'resource_types': 'TransformFeedbacks',
2570 'unsafe': True,
2572 'DepthRangef': {
2573 'decoder_func': 'DoDepthRangef',
2574 'gl_test_func': 'glDepthRange',
2576 'DepthMask': {
2577 'type': 'StateSet',
2578 'state': 'DepthMask',
2579 'no_gl': True,
2580 'expectation': False,
2582 'DetachShader': {'decoder_func': 'DoDetachShader'},
2583 'Disable': {
2584 'decoder_func': 'DoDisable',
2585 'impl_func': False,
2586 'client_test': False,
2588 'DisableVertexAttribArray': {
2589 'decoder_func': 'DoDisableVertexAttribArray',
2590 'impl_decl': False,
2592 'DrawArrays': {
2593 'type': 'Manual',
2594 'cmd_args': 'GLenumDrawMode mode, GLint first, GLsizei count',
2595 'defer_draws': True,
2596 'trace_level': 2,
2598 'DrawElements': {
2599 'type': 'Manual',
2600 'cmd_args': 'GLenumDrawMode mode, GLsizei count, '
2601 'GLenumIndexType type, GLuint index_offset',
2602 'client_test': False,
2603 'defer_draws': True,
2604 'trace_level': 2,
2606 'DrawRangeElements': {
2607 'type': 'Manual',
2608 'gen_cmd': 'False',
2609 'unsafe': True,
2611 'Enable': {
2612 'decoder_func': 'DoEnable',
2613 'impl_func': False,
2614 'client_test': False,
2616 'EnableVertexAttribArray': {
2617 'decoder_func': 'DoEnableVertexAttribArray',
2618 'impl_decl': False,
2620 'FenceSync': {
2621 'type': 'Create',
2622 'client_test': False,
2623 'unsafe': True,
2624 'trace_level': 1,
2626 'Finish': {
2627 'impl_func': False,
2628 'client_test': False,
2629 'decoder_func': 'DoFinish',
2630 'defer_reads': True,
2631 'trace_level': 1,
2633 'Flush': {
2634 'impl_func': False,
2635 'decoder_func': 'DoFlush',
2636 'trace_level': 1,
2638 'FramebufferRenderbuffer': {
2639 'decoder_func': 'DoFramebufferRenderbuffer',
2640 'gl_test_func': 'glFramebufferRenderbufferEXT',
2641 'trace_level': 1,
2643 'FramebufferTexture2D': {
2644 'decoder_func': 'DoFramebufferTexture2D',
2645 'gl_test_func': 'glFramebufferTexture2DEXT',
2646 'trace_level': 1,
2648 'FramebufferTexture2DMultisampleEXT': {
2649 'decoder_func': 'DoFramebufferTexture2DMultisample',
2650 'gl_test_func': 'glFramebufferTexture2DMultisampleEXT',
2651 'expectation': False,
2652 'unit_test': False,
2653 'extension_flag': 'multisampled_render_to_texture',
2654 'trace_level': 1,
2656 'FramebufferTextureLayer': {
2657 'decoder_func': 'DoFramebufferTextureLayer',
2658 'unsafe': True,
2659 'trace_level': 1,
2661 'GenerateMipmap': {
2662 'decoder_func': 'DoGenerateMipmap',
2663 'gl_test_func': 'glGenerateMipmapEXT',
2664 'trace_level': 1,
2666 'GenBuffers': {
2667 'type': 'GENn',
2668 'gl_test_func': 'glGenBuffersARB',
2669 'resource_type': 'Buffer',
2670 'resource_types': 'Buffers',
2672 'GenMailboxCHROMIUM': {
2673 'type': 'HandWritten',
2674 'impl_func': False,
2675 'extension': "CHROMIUM_texture_mailbox",
2676 'chromium': True,
2678 'GenFramebuffers': {
2679 'type': 'GENn',
2680 'gl_test_func': 'glGenFramebuffersEXT',
2681 'resource_type': 'Framebuffer',
2682 'resource_types': 'Framebuffers',
2684 'GenRenderbuffers': {
2685 'type': 'GENn', 'gl_test_func': 'glGenRenderbuffersEXT',
2686 'resource_type': 'Renderbuffer',
2687 'resource_types': 'Renderbuffers',
2689 'GenSamplers': {
2690 'type': 'GENn',
2691 'gl_test_func': 'glGenSamplers',
2692 'resource_type': 'Sampler',
2693 'resource_types': 'Samplers',
2694 'unsafe': True,
2696 'GenTextures': {
2697 'type': 'GENn',
2698 'gl_test_func': 'glGenTextures',
2699 'resource_type': 'Texture',
2700 'resource_types': 'Textures',
2702 'GenTransformFeedbacks': {
2703 'type': 'GENn',
2704 'gl_test_func': 'glGenTransformFeedbacks',
2705 'resource_type': 'TransformFeedback',
2706 'resource_types': 'TransformFeedbacks',
2707 'unsafe': True,
2709 'GetActiveAttrib': {
2710 'type': 'Custom',
2711 'data_transfer_methods': ['shm'],
2712 'cmd_args':
2713 'GLidProgram program, GLuint index, uint32_t name_bucket_id, '
2714 'void* result',
2715 'result': [
2716 'int32_t success',
2717 'int32_t size',
2718 'uint32_t type',
2721 'GetActiveUniform': {
2722 'type': 'Custom',
2723 'data_transfer_methods': ['shm'],
2724 'cmd_args':
2725 'GLidProgram program, GLuint index, uint32_t name_bucket_id, '
2726 'void* result',
2727 'result': [
2728 'int32_t success',
2729 'int32_t size',
2730 'uint32_t type',
2733 'GetActiveUniformBlockiv': {
2734 'type': 'Custom',
2735 'data_transfer_methods': ['shm'],
2736 'result': ['SizedResult<GLint>'],
2737 'unsafe': True,
2739 'GetActiveUniformBlockName': {
2740 'type': 'Custom',
2741 'data_transfer_methods': ['shm'],
2742 'cmd_args':
2743 'GLidProgram program, GLuint index, uint32_t name_bucket_id, '
2744 'void* result',
2745 'result': ['int32_t'],
2746 'unsafe': True,
2748 'GetActiveUniformsiv': {
2749 'type': 'Custom',
2750 'data_transfer_methods': ['shm'],
2751 'cmd_args':
2752 'GLidProgram program, uint32_t indices_bucket_id, GLenum pname, '
2753 'GLint* params',
2754 'result': ['SizedResult<GLint>'],
2755 'unsafe': True,
2757 'GetAttachedShaders': {
2758 'type': 'Custom',
2759 'data_transfer_methods': ['shm'],
2760 'cmd_args': 'GLidProgram program, void* result, uint32_t result_size',
2761 'result': ['SizedResult<GLuint>'],
2763 'GetAttribLocation': {
2764 'type': 'Custom',
2765 'data_transfer_methods': ['shm'],
2766 'cmd_args':
2767 'GLidProgram program, uint32_t name_bucket_id, GLint* location',
2768 'result': ['GLint'],
2769 'error_return': -1,
2771 'GetFragDataLocation': {
2772 'type': 'Custom',
2773 'data_transfer_methods': ['shm'],
2774 'cmd_args':
2775 'GLidProgram program, uint32_t name_bucket_id, GLint* location',
2776 'result': ['GLint'],
2777 'error_return': -1,
2778 'unsafe': True,
2780 'GetBooleanv': {
2781 'type': 'GETn',
2782 'result': ['SizedResult<GLboolean>'],
2783 'decoder_func': 'DoGetBooleanv',
2784 'gl_test_func': 'glGetBooleanv',
2786 'GetBufferParameteri64v': {
2787 'type': 'GETn',
2788 'result': ['SizedResult<GLint64>'],
2789 'decoder_func': 'DoGetBufferParameteri64v',
2790 'expectation': False,
2791 'shadowed': True,
2792 'unsafe': True,
2794 'GetBufferParameteriv': {
2795 'type': 'GETn',
2796 'result': ['SizedResult<GLint>'],
2797 'decoder_func': 'DoGetBufferParameteriv',
2798 'expectation': False,
2799 'shadowed': True,
2801 'GetError': {
2802 'type': 'Is',
2803 'decoder_func': 'GetErrorState()->GetGLError',
2804 'impl_func': False,
2805 'result': ['GLenum'],
2806 'client_test': False,
2808 'GetFloatv': {
2809 'type': 'GETn',
2810 'result': ['SizedResult<GLfloat>'],
2811 'decoder_func': 'DoGetFloatv',
2812 'gl_test_func': 'glGetFloatv',
2814 'GetFramebufferAttachmentParameteriv': {
2815 'type': 'GETn',
2816 'decoder_func': 'DoGetFramebufferAttachmentParameteriv',
2817 'gl_test_func': 'glGetFramebufferAttachmentParameterivEXT',
2818 'result': ['SizedResult<GLint>'],
2820 'GetGraphicsResetStatusKHR': {
2821 'extension': True,
2822 'client_test': False,
2823 'gen_cmd': False,
2824 'trace_level': 1,
2826 'GetInteger64v': {
2827 'type': 'GETn',
2828 'result': ['SizedResult<GLint64>'],
2829 'client_test': False,
2830 'decoder_func': 'DoGetInteger64v',
2831 'unsafe': True
2833 'GetIntegerv': {
2834 'type': 'GETn',
2835 'result': ['SizedResult<GLint>'],
2836 'decoder_func': 'DoGetIntegerv',
2837 'client_test': False,
2839 'GetInteger64i_v': {
2840 'type': 'GETn',
2841 'result': ['SizedResult<GLint64>'],
2842 'client_test': False,
2843 'unsafe': True
2845 'GetIntegeri_v': {
2846 'type': 'GETn',
2847 'result': ['SizedResult<GLint>'],
2848 'client_test': False,
2849 'unsafe': True
2851 'GetInternalformativ': {
2852 'type': 'Custom',
2853 'data_transfer_methods': ['shm'],
2854 'result': ['SizedResult<GLint>'],
2855 'cmd_args':
2856 'GLenumRenderBufferTarget target, GLenumRenderBufferFormat format, '
2857 'GLenumInternalFormatParameter pname, GLint* params',
2858 'unsafe': True,
2860 'GetMaxValueInBufferCHROMIUM': {
2861 'type': 'Is',
2862 'decoder_func': 'DoGetMaxValueInBufferCHROMIUM',
2863 'result': ['GLuint'],
2864 'unit_test': False,
2865 'client_test': False,
2866 'extension': True,
2867 'chromium': True,
2868 'impl_func': False,
2870 'GetProgramiv': {
2871 'type': 'GETn',
2872 'decoder_func': 'DoGetProgramiv',
2873 'result': ['SizedResult<GLint>'],
2874 'expectation': False,
2876 'GetProgramInfoCHROMIUM': {
2877 'type': 'Custom',
2878 'expectation': False,
2879 'impl_func': False,
2880 'extension': True,
2881 'chromium': True,
2882 'client_test': False,
2883 'cmd_args': 'GLidProgram program, uint32_t bucket_id',
2884 'result': [
2885 'uint32_t link_status',
2886 'uint32_t num_attribs',
2887 'uint32_t num_uniforms',
2890 'GetProgramInfoLog': {
2891 'type': 'STRn',
2892 'expectation': False,
2894 'GetRenderbufferParameteriv': {
2895 'type': 'GETn',
2896 'decoder_func': 'DoGetRenderbufferParameteriv',
2897 'gl_test_func': 'glGetRenderbufferParameterivEXT',
2898 'result': ['SizedResult<GLint>'],
2900 'GetSamplerParameterfv': {
2901 'type': 'GETn',
2902 'result': ['SizedResult<GLfloat>'],
2903 'id_mapping': [ 'Sampler' ],
2904 'unsafe': True,
2906 'GetSamplerParameteriv': {
2907 'type': 'GETn',
2908 'result': ['SizedResult<GLint>'],
2909 'id_mapping': [ 'Sampler' ],
2910 'unsafe': True,
2912 'GetShaderiv': {
2913 'type': 'GETn',
2914 'decoder_func': 'DoGetShaderiv',
2915 'result': ['SizedResult<GLint>'],
2917 'GetShaderInfoLog': {
2918 'type': 'STRn',
2919 'get_len_func': 'glGetShaderiv',
2920 'get_len_enum': 'GL_INFO_LOG_LENGTH',
2921 'unit_test': False,
2923 'GetShaderPrecisionFormat': {
2924 'type': 'Custom',
2925 'data_transfer_methods': ['shm'],
2926 'cmd_args':
2927 'GLenumShaderType shadertype, GLenumShaderPrecision precisiontype, '
2928 'void* result',
2929 'result': [
2930 'int32_t success',
2931 'int32_t min_range',
2932 'int32_t max_range',
2933 'int32_t precision',
2936 'GetShaderSource': {
2937 'type': 'STRn',
2938 'get_len_func': 'DoGetShaderiv',
2939 'get_len_enum': 'GL_SHADER_SOURCE_LENGTH',
2940 'unit_test': False,
2941 'client_test': False,
2943 'GetString': {
2944 'type': 'Custom',
2945 'client_test': False,
2946 'cmd_args': 'GLenumStringType name, uint32_t bucket_id',
2948 'GetSynciv': {
2949 'type': 'GETn',
2950 'cmd_args': 'GLuint sync, GLenumSyncParameter pname, void* values',
2951 'result': ['SizedResult<GLint>'],
2952 'id_mapping': ['Sync'],
2953 'unsafe': True,
2955 'GetTexParameterfv': {
2956 'type': 'GETn',
2957 'decoder_func': 'DoGetTexParameterfv',
2958 'result': ['SizedResult<GLfloat>']
2960 'GetTexParameteriv': {
2961 'type': 'GETn',
2962 'decoder_func': 'DoGetTexParameteriv',
2963 'result': ['SizedResult<GLint>']
2965 'GetTranslatedShaderSourceANGLE': {
2966 'type': 'STRn',
2967 'get_len_func': 'DoGetShaderiv',
2968 'get_len_enum': 'GL_TRANSLATED_SHADER_SOURCE_LENGTH_ANGLE',
2969 'unit_test': False,
2970 'extension': True,
2972 'GetUniformBlockIndex': {
2973 'type': 'Custom',
2974 'data_transfer_methods': ['shm'],
2975 'cmd_args':
2976 'GLidProgram program, uint32_t name_bucket_id, GLuint* index',
2977 'result': ['GLuint'],
2978 'error_return': 'GL_INVALID_INDEX',
2979 'unsafe': True,
2981 'GetUniformBlocksCHROMIUM': {
2982 'type': 'Custom',
2983 'expectation': False,
2984 'impl_func': False,
2985 'extension': True,
2986 'chromium': True,
2987 'client_test': False,
2988 'cmd_args': 'GLidProgram program, uint32_t bucket_id',
2989 'result': ['uint32_t'],
2990 'unsafe': True,
2992 'GetUniformsES3CHROMIUM': {
2993 'type': 'Custom',
2994 'expectation': False,
2995 'impl_func': False,
2996 'extension': True,
2997 'chromium': True,
2998 'client_test': False,
2999 'cmd_args': 'GLidProgram program, uint32_t bucket_id',
3000 'result': ['uint32_t'],
3001 'unsafe': True,
3003 'GetTransformFeedbackVarying': {
3004 'type': 'Custom',
3005 'data_transfer_methods': ['shm'],
3006 'cmd_args':
3007 'GLidProgram program, GLuint index, uint32_t name_bucket_id, '
3008 'void* result',
3009 'result': [
3010 'int32_t success',
3011 'int32_t size',
3012 'uint32_t type',
3014 'unsafe': True,
3016 'GetTransformFeedbackVaryingsCHROMIUM': {
3017 'type': 'Custom',
3018 'expectation': False,
3019 'impl_func': False,
3020 'extension': True,
3021 'chromium': True,
3022 'client_test': False,
3023 'cmd_args': 'GLidProgram program, uint32_t bucket_id',
3024 'result': ['uint32_t'],
3025 'unsafe': True,
3027 'GetUniformfv': {
3028 'type': 'Custom',
3029 'data_transfer_methods': ['shm'],
3030 'result': ['SizedResult<GLfloat>'],
3032 'GetUniformiv': {
3033 'type': 'Custom',
3034 'data_transfer_methods': ['shm'],
3035 'result': ['SizedResult<GLint>'],
3037 'GetUniformuiv': {
3038 'type': 'Custom',
3039 'data_transfer_methods': ['shm'],
3040 'result': ['SizedResult<GLuint>'],
3041 'unsafe': True,
3043 'GetUniformIndices': {
3044 'type': 'Custom',
3045 'data_transfer_methods': ['shm'],
3046 'result': ['SizedResult<GLuint>'],
3047 'cmd_args': 'GLidProgram program, uint32_t names_bucket_id, '
3048 'GLuint* indices',
3049 'unsafe': True,
3051 'GetUniformLocation': {
3052 'type': 'Custom',
3053 'data_transfer_methods': ['shm'],
3054 'cmd_args':
3055 'GLidProgram program, uint32_t name_bucket_id, GLint* location',
3056 'result': ['GLint'],
3057 'error_return': -1, # http://www.opengl.org/sdk/docs/man/xhtml/glGetUniformLocation.xml
3059 'GetVertexAttribfv': {
3060 'type': 'GETn',
3061 'result': ['SizedResult<GLfloat>'],
3062 'impl_decl': False,
3063 'decoder_func': 'DoGetVertexAttribfv',
3064 'expectation': False,
3065 'client_test': False,
3067 'GetVertexAttribiv': {
3068 'type': 'GETn',
3069 'result': ['SizedResult<GLint>'],
3070 'impl_decl': False,
3071 'decoder_func': 'DoGetVertexAttribiv',
3072 'expectation': False,
3073 'client_test': False,
3075 'GetVertexAttribIiv': {
3076 'type': 'GETn',
3077 'result': ['SizedResult<GLint>'],
3078 'impl_decl': False,
3079 'decoder_func': 'DoGetVertexAttribIiv',
3080 'expectation': False,
3081 'client_test': False,
3082 'unsafe': True,
3084 'GetVertexAttribIuiv': {
3085 'type': 'GETn',
3086 'result': ['SizedResult<GLuint>'],
3087 'impl_decl': False,
3088 'decoder_func': 'DoGetVertexAttribIuiv',
3089 'expectation': False,
3090 'client_test': False,
3091 'unsafe': True,
3093 'GetVertexAttribPointerv': {
3094 'type': 'Custom',
3095 'data_transfer_methods': ['shm'],
3096 'result': ['SizedResult<GLuint>'],
3097 'client_test': False,
3099 'InvalidateFramebuffer': {
3100 'type': 'PUTn',
3101 'count': 1,
3102 'client_test': False,
3103 'unit_test': False,
3104 'unsafe': True,
3106 'InvalidateSubFramebuffer': {
3107 'type': 'PUTn',
3108 'count': 1,
3109 'client_test': False,
3110 'unit_test': False,
3111 'unsafe': True,
3113 'IsBuffer': {
3114 'type': 'Is',
3115 'decoder_func': 'DoIsBuffer',
3116 'expectation': False,
3118 'IsEnabled': {
3119 'type': 'Is',
3120 'decoder_func': 'DoIsEnabled',
3121 'client_test': False,
3122 'impl_func': False,
3123 'expectation': False,
3125 'IsFramebuffer': {
3126 'type': 'Is',
3127 'decoder_func': 'DoIsFramebuffer',
3128 'expectation': False,
3130 'IsProgram': {
3131 'type': 'Is',
3132 'decoder_func': 'DoIsProgram',
3133 'expectation': False,
3135 'IsRenderbuffer': {
3136 'type': 'Is',
3137 'decoder_func': 'DoIsRenderbuffer',
3138 'expectation': False,
3140 'IsShader': {
3141 'type': 'Is',
3142 'decoder_func': 'DoIsShader',
3143 'expectation': False,
3145 'IsSampler': {
3146 'type': 'Is',
3147 'id_mapping': [ 'Sampler' ],
3148 'expectation': False,
3149 'unsafe': True,
3151 'IsSync': {
3152 'type': 'Is',
3153 'id_mapping': [ 'Sync' ],
3154 'cmd_args': 'GLuint sync',
3155 'expectation': False,
3156 'unsafe': True,
3158 'IsTexture': {
3159 'type': 'Is',
3160 'decoder_func': 'DoIsTexture',
3161 'expectation': False,
3163 'IsTransformFeedback': {
3164 'type': 'Is',
3165 'id_mapping': [ 'TransformFeedback' ],
3166 'expectation': False,
3167 'unsafe': True,
3169 'LinkProgram': {
3170 'decoder_func': 'DoLinkProgram',
3171 'impl_func': False,
3172 'trace_level': 1,
3174 'MapBufferCHROMIUM': {
3175 'gen_cmd': False,
3176 'extension': "CHROMIUM_pixel_transfer_buffer_object",
3177 'chromium': True,
3178 'client_test': False,
3179 'trace_level': 1,
3181 'MapBufferSubDataCHROMIUM': {
3182 'gen_cmd': False,
3183 'extension': True,
3184 'chromium': True,
3185 'client_test': False,
3186 'pepper_interface': 'ChromiumMapSub',
3187 'trace_level': 1,
3189 'MapTexSubImage2DCHROMIUM': {
3190 'gen_cmd': False,
3191 'extension': "CHROMIUM_sub_image",
3192 'chromium': True,
3193 'client_test': False,
3194 'pepper_interface': 'ChromiumMapSub',
3195 'trace_level': 1,
3197 'MapBufferRange': {
3198 'type': 'Custom',
3199 'data_transfer_methods': ['shm'],
3200 'cmd_args': 'GLenumBufferTarget target, GLintptrNotNegative offset, '
3201 'GLsizeiptr size, GLbitfieldMapBufferAccess access, '
3202 'uint32_t data_shm_id, uint32_t data_shm_offset, '
3203 'uint32_t result_shm_id, uint32_t result_shm_offset',
3204 'unsafe': True,
3205 'result': ['uint32_t'],
3206 'trace_level': 1,
3208 'PauseTransformFeedback': {
3209 'unsafe': True,
3211 'PixelStorei': {'type': 'Manual'},
3212 'PostSubBufferCHROMIUM': {
3213 'type': 'Custom',
3214 'impl_func': False,
3215 'unit_test': False,
3216 'client_test': False,
3217 'extension': True,
3218 'chromium': True,
3220 'ProduceTextureCHROMIUM': {
3221 'decoder_func': 'DoProduceTextureCHROMIUM',
3222 'impl_func': False,
3223 'type': 'PUT',
3224 'count': 64, # GL_MAILBOX_SIZE_CHROMIUM
3225 'unit_test': False,
3226 'client_test': False,
3227 'extension': "CHROMIUM_texture_mailbox",
3228 'chromium': True,
3229 'trace_level': 1,
3231 'ProduceTextureDirectCHROMIUM': {
3232 'decoder_func': 'DoProduceTextureDirectCHROMIUM',
3233 'impl_func': False,
3234 'type': 'PUT',
3235 'count': 64, # GL_MAILBOX_SIZE_CHROMIUM
3236 'unit_test': False,
3237 'client_test': False,
3238 'extension': "CHROMIUM_texture_mailbox",
3239 'chromium': True,
3240 'trace_level': 1,
3242 'RenderbufferStorage': {
3243 'decoder_func': 'DoRenderbufferStorage',
3244 'gl_test_func': 'glRenderbufferStorageEXT',
3245 'expectation': False,
3246 'trace_level': 1,
3248 'RenderbufferStorageMultisampleCHROMIUM': {
3249 'cmd_comment':
3250 '// GL_CHROMIUM_framebuffer_multisample\n',
3251 'decoder_func': 'DoRenderbufferStorageMultisampleCHROMIUM',
3252 'gl_test_func': 'glRenderbufferStorageMultisampleCHROMIUM',
3253 'expectation': False,
3254 'unit_test': False,
3255 'extension_flag': 'chromium_framebuffer_multisample',
3256 'pepper_interface': 'FramebufferMultisample',
3257 'pepper_name': 'RenderbufferStorageMultisampleEXT',
3258 'trace_level': 1,
3260 'RenderbufferStorageMultisampleEXT': {
3261 'cmd_comment':
3262 '// GL_EXT_multisampled_render_to_texture\n',
3263 'decoder_func': 'DoRenderbufferStorageMultisampleEXT',
3264 'gl_test_func': 'glRenderbufferStorageMultisampleEXT',
3265 'expectation': False,
3266 'unit_test': False,
3267 'extension_flag': 'multisampled_render_to_texture',
3268 'trace_level': 1,
3270 'ReadBuffer': {
3271 'unsafe': True,
3272 'decoder_func': 'DoReadBuffer',
3273 'trace_level': 1,
3275 'ReadPixels': {
3276 'cmd_comment':
3277 '// ReadPixels has the result separated from the pixel buffer so that\n'
3278 '// it is easier to specify the result going to some specific place\n'
3279 '// that exactly fits the rectangle of pixels.\n',
3280 'type': 'Custom',
3281 'data_transfer_methods': ['shm'],
3282 'impl_func': False,
3283 'client_test': False,
3284 'cmd_args':
3285 'GLint x, GLint y, GLsizei width, GLsizei height, '
3286 'GLenumReadPixelFormat format, GLenumReadPixelType type, '
3287 'uint32_t pixels_shm_id, uint32_t pixels_shm_offset, '
3288 'uint32_t result_shm_id, uint32_t result_shm_offset, '
3289 'GLboolean async',
3290 'result': ['uint32_t'],
3291 'defer_reads': True,
3292 'trace_level': 1,
3294 'ReleaseShaderCompiler': {
3295 'decoder_func': 'DoReleaseShaderCompiler',
3296 'unit_test': False,
3298 'ResumeTransformFeedback': {
3299 'unsafe': True,
3301 'SamplerParameterf': {
3302 'valid_args': {
3303 '2': 'GL_NEAREST'
3305 'id_mapping': [ 'Sampler' ],
3306 'unsafe': True,
3308 'SamplerParameterfv': {
3309 'type': 'PUT',
3310 'data_value': 'GL_NEAREST',
3311 'count': 1,
3312 'gl_test_func': 'glSamplerParameterf',
3313 'decoder_func': 'DoSamplerParameterfv',
3314 'first_element_only': True,
3315 'id_mapping': [ 'Sampler' ],
3316 'unsafe': True,
3318 'SamplerParameteri': {
3319 'valid_args': {
3320 '2': 'GL_NEAREST'
3322 'id_mapping': [ 'Sampler' ],
3323 'unsafe': True,
3325 'SamplerParameteriv': {
3326 'type': 'PUT',
3327 'data_value': 'GL_NEAREST',
3328 'count': 1,
3329 'gl_test_func': 'glSamplerParameteri',
3330 'decoder_func': 'DoSamplerParameteriv',
3331 'first_element_only': True,
3332 'unsafe': True,
3334 'ShaderBinary': {
3335 'type': 'Custom',
3336 'client_test': False,
3338 'ShaderSource': {
3339 'type': 'PUTSTR',
3340 'decoder_func': 'DoShaderSource',
3341 'expectation': False,
3342 'data_transfer_methods': ['bucket'],
3343 'cmd_args':
3344 'GLuint shader, const char** str',
3345 'pepper_args':
3346 'GLuint shader, GLsizei count, const char** str, const GLint* length',
3348 'StencilMask': {
3349 'type': 'StateSetFrontBack',
3350 'state': 'StencilMask',
3351 'no_gl': True,
3352 'expectation': False,
3354 'StencilMaskSeparate': {
3355 'type': 'StateSetFrontBackSeparate',
3356 'state': 'StencilMask',
3357 'no_gl': True,
3358 'expectation': False,
3360 'SwapBuffers': {
3361 'impl_func': False,
3362 'decoder_func': 'DoSwapBuffers',
3363 'unit_test': False,
3364 'client_test': False,
3365 'extension': True,
3366 'trace_level': 1,
3368 'SwapInterval': {
3369 'impl_func': False,
3370 'decoder_func': 'DoSwapInterval',
3371 'unit_test': False,
3372 'client_test': False,
3373 'extension': True,
3374 'trace_level': 1,
3376 'TexImage2D': {
3377 'type': 'Manual',
3378 'data_transfer_methods': ['shm'],
3379 'client_test': False,
3380 'trace_level': 2,
3382 'TexImage3D': {
3383 'type': 'Manual',
3384 'data_transfer_methods': ['shm'],
3385 'client_test': False,
3386 'unsafe': True,
3387 'trace_level': 2,
3389 'TexParameterf': {
3390 'decoder_func': 'DoTexParameterf',
3391 'valid_args': {
3392 '2': 'GL_NEAREST'
3395 'TexParameteri': {
3396 'decoder_func': 'DoTexParameteri',
3397 'valid_args': {
3398 '2': 'GL_NEAREST'
3401 'TexParameterfv': {
3402 'type': 'PUT',
3403 'data_value': 'GL_NEAREST',
3404 'count': 1,
3405 'decoder_func': 'DoTexParameterfv',
3406 'gl_test_func': 'glTexParameterf',
3407 'first_element_only': True,
3409 'TexParameteriv': {
3410 'type': 'PUT',
3411 'data_value': 'GL_NEAREST',
3412 'count': 1,
3413 'decoder_func': 'DoTexParameteriv',
3414 'gl_test_func': 'glTexParameteri',
3415 'first_element_only': True,
3417 'TexStorage3D': {
3418 'unsafe': True,
3419 'trace_level': 2,
3421 'TexSubImage2D': {
3422 'type': 'Manual',
3423 'data_transfer_methods': ['shm'],
3424 'client_test': False,
3425 'trace_level': 2,
3426 'cmd_args': 'GLenumTextureTarget target, GLint level, '
3427 'GLint xoffset, GLint yoffset, '
3428 'GLsizei width, GLsizei height, '
3429 'GLenumTextureFormat format, GLenumPixelType type, '
3430 'const void* pixels, GLboolean internal'
3432 'TexSubImage3D': {
3433 'type': 'Manual',
3434 'data_transfer_methods': ['shm'],
3435 'client_test': False,
3436 'trace_level': 2,
3437 'cmd_args': 'GLenumTextureTarget target, GLint level, '
3438 'GLint xoffset, GLint yoffset, GLint zoffset, '
3439 'GLsizei width, GLsizei height, GLsizei depth, '
3440 'GLenumTextureFormat format, GLenumPixelType type, '
3441 'const void* pixels, GLboolean internal',
3442 'unsafe': True,
3444 'TransformFeedbackVaryings': {
3445 'type': 'PUTSTR',
3446 'data_transfer_methods': ['bucket'],
3447 'decoder_func': 'DoTransformFeedbackVaryings',
3448 'cmd_args':
3449 'GLuint program, const char** varyings, GLenum buffermode',
3450 'unsafe': True,
3452 'Uniform1f': {'type': 'PUTXn', 'count': 1},
3453 'Uniform1fv': {
3454 'type': 'PUTn',
3455 'count': 1,
3456 'decoder_func': 'DoUniform1fv',
3458 'Uniform1i': {'decoder_func': 'DoUniform1i', 'unit_test': False},
3459 'Uniform1iv': {
3460 'type': 'PUTn',
3461 'count': 1,
3462 'decoder_func': 'DoUniform1iv',
3463 'unit_test': False,
3465 'Uniform1ui': {
3466 'type': 'PUTXn',
3467 'count': 1,
3468 'unsafe': True,
3470 'Uniform1uiv': {
3471 'type': 'PUTn',
3472 'count': 1,
3473 'unsafe': True,
3475 'Uniform2i': {'type': 'PUTXn', 'count': 2},
3476 'Uniform2f': {'type': 'PUTXn', 'count': 2},
3477 'Uniform2fv': {
3478 'type': 'PUTn',
3479 'count': 2,
3480 'decoder_func': 'DoUniform2fv',
3482 'Uniform2iv': {
3483 'type': 'PUTn',
3484 'count': 2,
3485 'decoder_func': 'DoUniform2iv',
3487 'Uniform2ui': {
3488 'type': 'PUTXn',
3489 'count': 2,
3490 'unsafe': True,
3492 'Uniform2uiv': {
3493 'type': 'PUTn',
3494 'count': 2,
3495 'unsafe': True,
3497 'Uniform3i': {'type': 'PUTXn', 'count': 3},
3498 'Uniform3f': {'type': 'PUTXn', 'count': 3},
3499 'Uniform3fv': {
3500 'type': 'PUTn',
3501 'count': 3,
3502 'decoder_func': 'DoUniform3fv',
3504 'Uniform3iv': {
3505 'type': 'PUTn',
3506 'count': 3,
3507 'decoder_func': 'DoUniform3iv',
3509 'Uniform3ui': {
3510 'type': 'PUTXn',
3511 'count': 3,
3512 'unsafe': True,
3514 'Uniform3uiv': {
3515 'type': 'PUTn',
3516 'count': 3,
3517 'unsafe': True,
3519 'Uniform4i': {'type': 'PUTXn', 'count': 4},
3520 'Uniform4f': {'type': 'PUTXn', 'count': 4},
3521 'Uniform4fv': {
3522 'type': 'PUTn',
3523 'count': 4,
3524 'decoder_func': 'DoUniform4fv',
3526 'Uniform4iv': {
3527 'type': 'PUTn',
3528 'count': 4,
3529 'decoder_func': 'DoUniform4iv',
3531 'Uniform4ui': {
3532 'type': 'PUTXn',
3533 'count': 4,
3534 'unsafe': True,
3536 'Uniform4uiv': {
3537 'type': 'PUTn',
3538 'count': 4,
3539 'unsafe': True,
3541 'UniformMatrix2fv': {
3542 'type': 'PUTn',
3543 'count': 4,
3544 'decoder_func': 'DoUniformMatrix2fv',
3546 'UniformMatrix2x3fv': {
3547 'type': 'PUTn',
3548 'count': 6,
3549 'unsafe': True,
3551 'UniformMatrix2x4fv': {
3552 'type': 'PUTn',
3553 'count': 8,
3554 'unsafe': True,
3556 'UniformMatrix3fv': {
3557 'type': 'PUTn',
3558 'count': 9,
3559 'decoder_func': 'DoUniformMatrix3fv',
3561 'UniformMatrix3x2fv': {
3562 'type': 'PUTn',
3563 'count': 6,
3564 'unsafe': True,
3566 'UniformMatrix3x4fv': {
3567 'type': 'PUTn',
3568 'count': 12,
3569 'unsafe': True,
3571 'UniformMatrix4fv': {
3572 'type': 'PUTn',
3573 'count': 16,
3574 'decoder_func': 'DoUniformMatrix4fv',
3576 'UniformMatrix4x2fv': {
3577 'type': 'PUTn',
3578 'count': 8,
3579 'unsafe': True,
3581 'UniformMatrix4x3fv': {
3582 'type': 'PUTn',
3583 'count': 12,
3584 'unsafe': True,
3586 'UniformBlockBinding': {
3587 'type': 'Custom',
3588 'impl_func': False,
3589 'unsafe': True,
3591 'UnmapBufferCHROMIUM': {
3592 'gen_cmd': False,
3593 'extension': "CHROMIUM_pixel_transfer_buffer_object",
3594 'chromium': True,
3595 'client_test': False,
3596 'trace_level': 1,
3598 'UnmapBufferSubDataCHROMIUM': {
3599 'gen_cmd': False,
3600 'extension': True,
3601 'chromium': True,
3602 'client_test': False,
3603 'pepper_interface': 'ChromiumMapSub',
3604 'trace_level': 1,
3606 'UnmapBuffer': {
3607 'type': 'Custom',
3608 'unsafe': True,
3609 'trace_level': 1,
3611 'UnmapTexSubImage2DCHROMIUM': {
3612 'gen_cmd': False,
3613 'extension': "CHROMIUM_sub_image",
3614 'chromium': True,
3615 'client_test': False,
3616 'pepper_interface': 'ChromiumMapSub',
3617 'trace_level': 1,
3619 'UseProgram': {
3620 'type': 'Bind',
3621 'decoder_func': 'DoUseProgram',
3623 'ValidateProgram': {'decoder_func': 'DoValidateProgram'},
3624 'VertexAttrib1f': {'decoder_func': 'DoVertexAttrib1f'},
3625 'VertexAttrib1fv': {
3626 'type': 'PUT',
3627 'count': 1,
3628 'decoder_func': 'DoVertexAttrib1fv',
3630 'VertexAttrib2f': {'decoder_func': 'DoVertexAttrib2f'},
3631 'VertexAttrib2fv': {
3632 'type': 'PUT',
3633 'count': 2,
3634 'decoder_func': 'DoVertexAttrib2fv',
3636 'VertexAttrib3f': {'decoder_func': 'DoVertexAttrib3f'},
3637 'VertexAttrib3fv': {
3638 'type': 'PUT',
3639 'count': 3,
3640 'decoder_func': 'DoVertexAttrib3fv',
3642 'VertexAttrib4f': {'decoder_func': 'DoVertexAttrib4f'},
3643 'VertexAttrib4fv': {
3644 'type': 'PUT',
3645 'count': 4,
3646 'decoder_func': 'DoVertexAttrib4fv',
3648 'VertexAttribI4i': {
3649 'unsafe': True,
3650 'decoder_func': 'DoVertexAttribI4i',
3652 'VertexAttribI4iv': {
3653 'type': 'PUT',
3654 'count': 4,
3655 'unsafe': True,
3656 'decoder_func': 'DoVertexAttribI4iv',
3658 'VertexAttribI4ui': {
3659 'unsafe': True,
3660 'decoder_func': 'DoVertexAttribI4ui',
3662 'VertexAttribI4uiv': {
3663 'type': 'PUT',
3664 'count': 4,
3665 'unsafe': True,
3666 'decoder_func': 'DoVertexAttribI4uiv',
3668 'VertexAttribIPointer': {
3669 'type': 'Manual',
3670 'cmd_args': 'GLuint indx, GLintVertexAttribSize size, '
3671 'GLenumVertexAttribIType type, GLsizei stride, '
3672 'GLuint offset',
3673 'client_test': False,
3674 'unsafe': True,
3676 'VertexAttribPointer': {
3677 'type': 'Manual',
3678 'cmd_args': 'GLuint indx, GLintVertexAttribSize size, '
3679 'GLenumVertexAttribType type, GLboolean normalized, '
3680 'GLsizei stride, GLuint offset',
3681 'client_test': False,
3683 'WaitSync': {
3684 'type': 'Custom',
3685 'cmd_args': 'GLuint sync, GLbitfieldSyncFlushFlags flags, '
3686 'GLuint timeout_0, GLuint timeout_1',
3687 'impl_func': False,
3688 'client_test': False,
3689 'unsafe': True,
3690 'trace_level': 1,
3692 'Scissor': {
3693 'type': 'StateSet',
3694 'state': 'Scissor',
3696 'Viewport': {
3697 'decoder_func': 'DoViewport',
3699 'ResizeCHROMIUM': {
3700 'type': 'Custom',
3701 'impl_func': False,
3702 'unit_test': False,
3703 'extension': True,
3704 'chromium': True,
3705 'trace_level': 1,
3707 'GetRequestableExtensionsCHROMIUM': {
3708 'type': 'Custom',
3709 'impl_func': False,
3710 'cmd_args': 'uint32_t bucket_id',
3711 'extension': True,
3712 'chromium': True,
3714 'RequestExtensionCHROMIUM': {
3715 'type': 'Custom',
3716 'impl_func': False,
3717 'client_test': False,
3718 'cmd_args': 'uint32_t bucket_id',
3719 'extension': True,
3720 'chromium': True,
3722 'RateLimitOffscreenContextCHROMIUM': {
3723 'gen_cmd': False,
3724 'extension': True,
3725 'chromium': True,
3726 'client_test': False,
3728 'CreateStreamTextureCHROMIUM': {
3729 'type': 'HandWritten',
3730 'impl_func': False,
3731 'gen_cmd': False,
3732 'extension': True,
3733 'chromium': True,
3734 'trace_level': 1,
3736 'TexImageIOSurface2DCHROMIUM': {
3737 'decoder_func': 'DoTexImageIOSurface2DCHROMIUM',
3738 'unit_test': False,
3739 'extension': True,
3740 'chromium': True,
3741 'trace_level': 1,
3743 'CopyTextureCHROMIUM': {
3744 'decoder_func': 'DoCopyTextureCHROMIUM',
3745 'unit_test': False,
3746 'extension': "CHROMIUM_copy_texture",
3747 'chromium': True,
3748 'trace_level': 2,
3750 'CopySubTextureCHROMIUM': {
3751 'decoder_func': 'DoCopySubTextureCHROMIUM',
3752 'unit_test': False,
3753 'extension': "CHROMIUM_copy_texture",
3754 'chromium': True,
3755 'trace_level': 2,
3757 'CompressedCopyTextureCHROMIUM': {
3758 'decoder_func': 'DoCompressedCopyTextureCHROMIUM',
3759 'unit_test': False,
3760 'extension': True,
3761 'chromium': True,
3763 'CompressedCopySubTextureCHROMIUM': {
3764 'decoder_func': 'DoCompressedCopySubTextureCHROMIUM',
3765 'unit_test': False,
3766 'extension': True,
3767 'chromium': True,
3769 'TexStorage2DEXT': {
3770 'unit_test': False,
3771 'extension': True,
3772 'decoder_func': 'DoTexStorage2DEXT',
3773 'trace_level': 2,
3775 'DrawArraysInstancedANGLE': {
3776 'type': 'Manual',
3777 'cmd_args': 'GLenumDrawMode mode, GLint first, GLsizei count, '
3778 'GLsizei primcount',
3779 'extension': True,
3780 'unit_test': False,
3781 'pepper_interface': 'InstancedArrays',
3782 'defer_draws': True,
3783 'trace_level': 2,
3785 'DrawBuffersEXT': {
3786 'type': 'PUTn',
3787 'decoder_func': 'DoDrawBuffersEXT',
3788 'count': 1,
3789 'client_test': False,
3790 'unit_test': False,
3791 # could use 'extension_flag': 'ext_draw_buffers' but currently expected to
3792 # work without.
3793 'extension': True,
3794 'pepper_interface': 'DrawBuffers',
3795 'trace_level': 2,
3797 'DrawElementsInstancedANGLE': {
3798 'type': 'Manual',
3799 'cmd_args': 'GLenumDrawMode mode, GLsizei count, '
3800 'GLenumIndexType type, GLuint index_offset, GLsizei primcount',
3801 'extension': True,
3802 'unit_test': False,
3803 'client_test': False,
3804 'pepper_interface': 'InstancedArrays',
3805 'defer_draws': True,
3806 'trace_level': 2,
3808 'VertexAttribDivisorANGLE': {
3809 'type': 'Manual',
3810 'cmd_args': 'GLuint index, GLuint divisor',
3811 'extension': True,
3812 'unit_test': False,
3813 'pepper_interface': 'InstancedArrays',
3815 'GenQueriesEXT': {
3816 'type': 'GENn',
3817 'gl_test_func': 'glGenQueriesARB',
3818 'resource_type': 'Query',
3819 'resource_types': 'Queries',
3820 'unit_test': False,
3821 'pepper_interface': 'Query',
3822 'not_shared': 'True',
3823 'extension': "occlusion_query_EXT",
3825 'DeleteQueriesEXT': {
3826 'type': 'DELn',
3827 'gl_test_func': 'glDeleteQueriesARB',
3828 'resource_type': 'Query',
3829 'resource_types': 'Queries',
3830 'unit_test': False,
3831 'pepper_interface': 'Query',
3832 'extension': "occlusion_query_EXT",
3834 'IsQueryEXT': {
3835 'gen_cmd': False,
3836 'client_test': False,
3837 'pepper_interface': 'Query',
3838 'extension': "occlusion_query_EXT",
3840 'BeginQueryEXT': {
3841 'type': 'Manual',
3842 'cmd_args': 'GLenumQueryTarget target, GLidQuery id, void* sync_data',
3843 'data_transfer_methods': ['shm'],
3844 'gl_test_func': 'glBeginQuery',
3845 'pepper_interface': 'Query',
3846 'extension': "occlusion_query_EXT",
3848 'BeginTransformFeedback': {
3849 'unsafe': True,
3851 'EndQueryEXT': {
3852 'type': 'Manual',
3853 'cmd_args': 'GLenumQueryTarget target, GLuint submit_count',
3854 'gl_test_func': 'glEndnQuery',
3855 'client_test': False,
3856 'pepper_interface': 'Query',
3857 'extension': "occlusion_query_EXT",
3859 'EndTransformFeedback': {
3860 'unsafe': True,
3862 'FlushDriverCachesCHROMIUM': {
3863 'decoder_func': 'DoFlushDriverCachesCHROMIUM',
3864 'unit_test': False,
3865 'extension': True,
3866 'chromium': True,
3867 'trace_level': 1,
3869 'GetQueryivEXT': {
3870 'gen_cmd': False,
3871 'client_test': False,
3872 'gl_test_func': 'glGetQueryiv',
3873 'pepper_interface': 'Query',
3874 'extension': "occlusion_query_EXT",
3876 'QueryCounterEXT' : {
3877 'type': 'Manual',
3878 'cmd_args': 'GLidQuery id, GLenumQueryTarget target, '
3879 'void* sync_data, GLuint submit_count',
3880 'data_transfer_methods': ['shm'],
3881 'gl_test_func': 'glQueryCounter',
3882 'extension': "disjoint_timer_query_EXT",
3884 'GetQueryObjectivEXT': {
3885 'gen_cmd': False,
3886 'client_test': False,
3887 'gl_test_func': 'glGetQueryObjectiv',
3888 'extension': "disjoint_timer_query_EXT",
3890 'GetQueryObjectuivEXT': {
3891 'gen_cmd': False,
3892 'client_test': False,
3893 'gl_test_func': 'glGetQueryObjectuiv',
3894 'pepper_interface': 'Query',
3895 'extension': "occlusion_query_EXT",
3897 'GetQueryObjecti64vEXT': {
3898 'gen_cmd': False,
3899 'client_test': False,
3900 'gl_test_func': 'glGetQueryObjecti64v',
3901 'extension': "disjoint_timer_query_EXT",
3903 'GetQueryObjectui64vEXT': {
3904 'gen_cmd': False,
3905 'client_test': False,
3906 'gl_test_func': 'glGetQueryObjectui64v',
3907 'extension': "disjoint_timer_query_EXT",
3909 'SetDisjointValueSyncCHROMIUM': {
3910 'type': 'Manual',
3911 'data_transfer_methods': ['shm'],
3912 'client_test': False,
3913 'cmd_args': 'void* sync_data',
3914 'extension': True,
3915 'chromium': True,
3917 'BindUniformLocationCHROMIUM': {
3918 'type': 'GLchar',
3919 'extension': True,
3920 'data_transfer_methods': ['bucket'],
3921 'needs_size': True,
3922 'gl_test_func': 'DoBindUniformLocationCHROMIUM',
3924 'InsertEventMarkerEXT': {
3925 'type': 'GLcharN',
3926 'decoder_func': 'DoInsertEventMarkerEXT',
3927 'expectation': False,
3928 'extension': True,
3930 'PushGroupMarkerEXT': {
3931 'type': 'GLcharN',
3932 'decoder_func': 'DoPushGroupMarkerEXT',
3933 'expectation': False,
3934 'extension': True,
3936 'PopGroupMarkerEXT': {
3937 'decoder_func': 'DoPopGroupMarkerEXT',
3938 'expectation': False,
3939 'extension': True,
3940 'impl_func': False,
3943 'GenVertexArraysOES': {
3944 'type': 'GENn',
3945 'extension': True,
3946 'gl_test_func': 'glGenVertexArraysOES',
3947 'resource_type': 'VertexArray',
3948 'resource_types': 'VertexArrays',
3949 'unit_test': False,
3950 'pepper_interface': 'VertexArrayObject',
3952 'BindVertexArrayOES': {
3953 'type': 'Bind',
3954 'extension': True,
3955 'gl_test_func': 'glBindVertexArrayOES',
3956 'decoder_func': 'DoBindVertexArrayOES',
3957 'gen_func': 'GenVertexArraysOES',
3958 'unit_test': False,
3959 'client_test': False,
3960 'pepper_interface': 'VertexArrayObject',
3962 'DeleteVertexArraysOES': {
3963 'type': 'DELn',
3964 'extension': True,
3965 'gl_test_func': 'glDeleteVertexArraysOES',
3966 'resource_type': 'VertexArray',
3967 'resource_types': 'VertexArrays',
3968 'unit_test': False,
3969 'pepper_interface': 'VertexArrayObject',
3971 'IsVertexArrayOES': {
3972 'type': 'Is',
3973 'extension': True,
3974 'gl_test_func': 'glIsVertexArrayOES',
3975 'decoder_func': 'DoIsVertexArrayOES',
3976 'expectation': False,
3977 'unit_test': False,
3978 'pepper_interface': 'VertexArrayObject',
3980 'BindTexImage2DCHROMIUM': {
3981 'decoder_func': 'DoBindTexImage2DCHROMIUM',
3982 'unit_test': False,
3983 'extension': "CHROMIUM_image",
3984 'chromium': True,
3986 'ReleaseTexImage2DCHROMIUM': {
3987 'decoder_func': 'DoReleaseTexImage2DCHROMIUM',
3988 'unit_test': False,
3989 'extension': "CHROMIUM_image",
3990 'chromium': True,
3992 'ShallowFinishCHROMIUM': {
3993 'impl_func': False,
3994 'gen_cmd': False,
3995 'extension': True,
3996 'chromium': True,
3997 'client_test': False,
3999 'ShallowFlushCHROMIUM': {
4000 'impl_func': False,
4001 'gen_cmd': False,
4002 'extension': "CHROMIUM_miscellaneous",
4003 'chromium': True,
4004 'client_test': False,
4006 'OrderingBarrierCHROMIUM': {
4007 'impl_func': False,
4008 'gen_cmd': False,
4009 'extension': "CHROMIUM_miscellaneous",
4010 'chromium': True,
4011 'client_test': False,
4013 'TraceBeginCHROMIUM': {
4014 'type': 'Custom',
4015 'impl_func': False,
4016 'client_test': False,
4017 'cmd_args': 'GLuint category_bucket_id, GLuint name_bucket_id',
4018 'extension': True,
4019 'chromium': True,
4021 'TraceEndCHROMIUM': {
4022 'impl_func': False,
4023 'client_test': False,
4024 'decoder_func': 'DoTraceEndCHROMIUM',
4025 'unit_test': False,
4026 'extension': True,
4027 'chromium': True,
4029 'AsyncTexImage2DCHROMIUM': {
4030 'type': 'Manual',
4031 'data_transfer_methods': ['shm'],
4032 'client_test': False,
4033 'cmd_args': 'GLenumTextureTarget target, GLint level, '
4034 'GLintTextureInternalFormat internalformat, '
4035 'GLsizei width, GLsizei height, '
4036 'GLintTextureBorder border, '
4037 'GLenumTextureFormat format, GLenumPixelType type, '
4038 'const void* pixels, '
4039 'uint32_t async_upload_token, '
4040 'void* sync_data',
4041 'extension': True,
4042 'chromium': True,
4043 'trace_level': 2,
4045 'AsyncTexSubImage2DCHROMIUM': {
4046 'type': 'Manual',
4047 'data_transfer_methods': ['shm'],
4048 'client_test': False,
4049 'cmd_args': 'GLenumTextureTarget target, GLint level, '
4050 'GLint xoffset, GLint yoffset, '
4051 'GLsizei width, GLsizei height, '
4052 'GLenumTextureFormat format, GLenumPixelType type, '
4053 'const void* data, '
4054 'uint32_t async_upload_token, '
4055 'void* sync_data',
4056 'extension': True,
4057 'chromium': True,
4058 'trace_level': 2,
4060 'WaitAsyncTexImage2DCHROMIUM': {
4061 'type': 'Manual',
4062 'client_test': False,
4063 'extension': True,
4064 'chromium': True,
4065 'trace_level': 1,
4067 'WaitAllAsyncTexImage2DCHROMIUM': {
4068 'type': 'Manual',
4069 'client_test': False,
4070 'extension': True,
4071 'chromium': True,
4072 'trace_level': 1,
4074 'DiscardFramebufferEXT': {
4075 'type': 'PUTn',
4076 'count': 1,
4077 'decoder_func': 'DoDiscardFramebufferEXT',
4078 'unit_test': False,
4079 'client_test': False,
4080 'extension_flag': 'ext_discard_framebuffer',
4081 'trace_level': 2,
4083 'LoseContextCHROMIUM': {
4084 'decoder_func': 'DoLoseContextCHROMIUM',
4085 'unit_test': False,
4086 'extension': True,
4087 'chromium': True,
4088 'trace_level': 1,
4090 'InsertSyncPointCHROMIUM': {
4091 'type': 'HandWritten',
4092 'impl_func': False,
4093 'extension': "CHROMIUM_sync_point",
4094 'chromium': True,
4095 'trace_level': 1,
4097 'WaitSyncPointCHROMIUM': {
4098 'type': 'Custom',
4099 'impl_func': True,
4100 'extension': "CHROMIUM_sync_point",
4101 'chromium': True,
4102 'trace_level': 1,
4104 'DiscardBackbufferCHROMIUM': {
4105 'type': 'Custom',
4106 'impl_func': True,
4107 'extension': True,
4108 'chromium': True,
4109 'trace_level': 2,
4111 'ScheduleOverlayPlaneCHROMIUM': {
4112 'type': 'Custom',
4113 'impl_func': True,
4114 'unit_test': False,
4115 'client_test': False,
4116 'extension': True,
4117 'chromium': True,
4119 'MatrixLoadfCHROMIUM': {
4120 'type': 'PUT',
4121 'count': 16,
4122 'data_type': 'GLfloat',
4123 'decoder_func': 'DoMatrixLoadfCHROMIUM',
4124 'gl_test_func': 'glMatrixLoadfEXT',
4125 'chromium': True,
4126 'extension': True,
4127 'extension_flag': 'chromium_path_rendering',
4129 'MatrixLoadIdentityCHROMIUM': {
4130 'decoder_func': 'DoMatrixLoadIdentityCHROMIUM',
4131 'gl_test_func': 'glMatrixLoadIdentityEXT',
4132 'chromium': True,
4133 'extension': True,
4134 'extension_flag': 'chromium_path_rendering',
4136 'GenPathsCHROMIUM': {
4137 'type': 'Custom',
4138 'cmd_args': 'GLuint first_client_id, GLsizei range',
4139 'chromium': True,
4140 'extension': True,
4141 'extension_flag': 'chromium_path_rendering',
4143 'DeletePathsCHROMIUM': {
4144 'type': 'Custom',
4145 'cmd_args': 'GLuint first_client_id, GLsizei range',
4146 'impl_func': False,
4147 'unit_test': False,
4148 'chromium': True,
4149 'extension': True,
4150 'extension_flag': 'chromium_path_rendering',
4152 'IsPathCHROMIUM': {
4153 'type': 'Is',
4154 'decoder_func': 'DoIsPathCHROMIUM',
4155 'gl_test_func': 'glIsPathNV',
4156 'chromium': True,
4157 'extension': True,
4158 'extension_flag': 'chromium_path_rendering',
4160 'PathCommandsCHROMIUM': {
4161 'type': 'Manual',
4162 'immediate': False,
4163 'chromium': True,
4164 'extension': True,
4165 'extension_flag': 'chromium_path_rendering',
4167 'PathParameterfCHROMIUM': {
4168 'type': 'Custom',
4169 'chromium': True,
4170 'extension': True,
4171 'extension_flag': 'chromium_path_rendering',
4173 'PathParameteriCHROMIUM': {
4174 'type': 'Custom',
4175 'chromium': True,
4176 'extension': True,
4177 'extension_flag': 'chromium_path_rendering',
4179 'PathStencilFuncCHROMIUM': {
4180 'type': 'StateSet',
4181 'state': 'PathStencilFuncCHROMIUM',
4182 'decoder_func': 'glPathStencilFuncNV',
4183 'chromium': True,
4184 'extension': True,
4185 'extension_flag': 'chromium_path_rendering',
4187 'StencilFillPathCHROMIUM': {
4188 'type': 'Custom',
4189 'chromium': True,
4190 'extension': True,
4191 'extension_flag': 'chromium_path_rendering',
4193 'StencilStrokePathCHROMIUM': {
4194 'type': 'Custom',
4195 'chromium': True,
4196 'extension': True,
4197 'extension_flag': 'chromium_path_rendering',
4199 'CoverFillPathCHROMIUM': {
4200 'type': 'Custom',
4201 'chromium': True,
4202 'extension': True,
4203 'extension_flag': 'chromium_path_rendering',
4205 'CoverStrokePathCHROMIUM': {
4206 'type': 'Custom',
4207 'chromium': True,
4208 'extension': True,
4209 'extension_flag': 'chromium_path_rendering',
4211 'StencilThenCoverFillPathCHROMIUM': {
4212 'type': 'Custom',
4213 'chromium': True,
4214 'extension': True,
4215 'extension_flag': 'chromium_path_rendering',
4217 'StencilThenCoverStrokePathCHROMIUM': {
4218 'type': 'Custom',
4219 'chromium': True,
4220 'extension': True,
4221 'extension_flag': 'chromium_path_rendering',
4227 def Grouper(n, iterable, fillvalue=None):
4228 """Collect data into fixed-length chunks or blocks"""
4229 args = [iter(iterable)] * n
4230 return itertools.izip_longest(fillvalue=fillvalue, *args)
4233 def SplitWords(input_string):
4234 """Split by '_' if found, otherwise split at uppercase/numeric chars.
4236 Will split "some_TEXT" into ["some", "TEXT"], "CamelCase" into ["Camel",
4237 "Case"], and "Vector3" into ["Vector", "3"].
4239 if input_string.find('_') > -1:
4240 # 'some_TEXT_' -> 'some TEXT'
4241 return input_string.replace('_', ' ').strip().split()
4242 else:
4243 if re.search('[A-Z]', input_string) and re.search('[a-z]', input_string):
4244 # mixed case.
4245 # look for capitalization to cut input_strings
4246 # 'SomeText' -> 'Some Text'
4247 input_string = re.sub('([A-Z])', r' \1', input_string).strip()
4248 # 'Vector3' -> 'Vector 3'
4249 input_string = re.sub('([^0-9])([0-9])', r'\1 \2', input_string)
4250 return input_string.split()
4252 def ToUnderscore(input_string):
4253 """converts CamelCase to camel_case."""
4254 words = SplitWords(input_string)
4255 return '_'.join([word.lower() for word in words])
4257 def CachedStateName(item):
4258 if item.get('cached', False):
4259 return 'cached_' + item['name']
4260 return item['name']
4262 def ToGLExtensionString(extension_flag):
4263 """Returns GL-type extension string of a extension flag."""
4264 if extension_flag == "oes_compressed_etc1_rgb8_texture":
4265 return "OES_compressed_ETC1_RGB8_texture" # Fixup inconsitency with rgb8,
4266 # unfortunate.
4267 uppercase_words = [ 'img', 'ext', 'arb', 'chromium', 'oes', 'amd', 'bgra8888',
4268 'egl', 'atc', 'etc1', 'angle']
4269 parts = extension_flag.split('_')
4270 return "_".join(
4271 [part.upper() if part in uppercase_words else part for part in parts])
4273 def ToCamelCase(input_string):
4274 """converts ABC_underscore_case to ABCUnderscoreCase."""
4275 return ''.join(w[0].upper() + w[1:] for w in input_string.split('_'))
4277 def GetGLGetTypeConversion(result_type, value_type, value):
4278 """Makes a gl compatible type conversion string for accessing state variables.
4280 Useful when accessing state variables through glGetXXX calls.
4281 glGet documetation (for example, the manual pages):
4282 [...] If glGetIntegerv is called, [...] most floating-point values are
4283 rounded to the nearest integer value. [...]
4285 Args:
4286 result_type: the gl type to be obtained
4287 value_type: the GL type of the state variable
4288 value: the name of the state variable
4290 Returns:
4291 String that converts the state variable to desired GL type according to GL
4292 rules.
4295 if result_type == 'GLint':
4296 if value_type == 'GLfloat':
4297 return 'static_cast<GLint>(round(%s))' % value
4298 return 'static_cast<%s>(%s)' % (result_type, value)
4301 class CWriter(object):
4302 """Context manager that creates a C source file.
4304 To be used with the `with` statement. Returns a normal `file` type, open only
4305 for writing - any existing files with that name will be overwritten. It will
4306 automatically write the contents of `_LICENSE` and `_DO_NOT_EDIT_WARNING`
4307 at the beginning.
4309 Example:
4310 with CWriter("file.cpp") as myfile:
4311 myfile.write("hello")
4312 # type(myfile) == file
4314 def __init__(self, filename):
4315 self.filename = filename
4316 self._file = open(filename, 'w')
4317 self._ENTER_MSG = _LICENSE + _DO_NOT_EDIT_WARNING
4318 self._EXIT_MSG = ""
4320 def __enter__(self):
4321 self._file.write(self._ENTER_MSG)
4322 return self._file
4324 def __exit__(self, exc_type, exc_value, traceback):
4325 self._file.write(self._EXIT_MSG)
4326 self._file.close()
4329 class CHeaderWriter(CWriter):
4330 """Context manager that creates a C header file.
4332 Works the same way as CWriter, except it will also add the #ifdef guard
4333 around it. If `file_comment` is set, it will write that before the #ifdef
4334 guard.
4336 def __init__(self, filename, file_comment=None):
4337 super(CHeaderWriter, self).__init__(filename)
4338 guard = self._get_guard()
4339 if file_comment is None:
4340 file_comment = ""
4341 self._ENTER_MSG = self._ENTER_MSG + file_comment \
4342 + "#ifndef %s\n#define %s\n\n" % (guard, guard)
4343 self._EXIT_MSG = self._EXIT_MSG + "#endif // %s\n" % guard
4345 def _get_guard(self):
4346 non_alnum_re = re.compile(r'[^a-zA-Z0-9]')
4347 base = os.path.abspath(self.filename)
4348 while os.path.basename(base) != 'src':
4349 new_base = os.path.dirname(base)
4350 assert new_base != base # Prevent infinite loop.
4351 base = new_base
4352 hpath = os.path.relpath(self.filename, base)
4353 return non_alnum_re.sub('_', hpath).upper() + '_'
4356 class TypeHandler(object):
4357 """This class emits code for a particular type of function."""
4359 _remove_expected_call_re = re.compile(r' EXPECT_CALL.*?;\n', re.S)
4361 def InitFunction(self, func):
4362 """Add or adjust anything type specific for this function."""
4363 if func.GetInfo('needs_size') and not func.name.endswith('Bucket'):
4364 func.AddCmdArg(DataSizeArgument('data_size'))
4366 def NeedsDataTransferFunction(self, func):
4367 """Overriden from TypeHandler."""
4368 return func.num_pointer_args >= 1
4370 def WriteStruct(self, func, f):
4371 """Writes a structure that matches the arguments to a function."""
4372 comment = func.GetInfo('cmd_comment')
4373 if not comment == None:
4374 f.write(comment)
4375 f.write("struct %s {\n" % func.name)
4376 f.write(" typedef %s ValueType;\n" % func.name)
4377 f.write(" static const CommandId kCmdId = k%s;\n" % func.name)
4378 func.WriteCmdArgFlag(f)
4379 func.WriteCmdFlag(f)
4380 f.write("\n")
4381 result = func.GetInfo('result')
4382 if not result == None:
4383 if len(result) == 1:
4384 f.write(" typedef %s Result;\n\n" % result[0])
4385 else:
4386 f.write(" struct Result {\n")
4387 for line in result:
4388 f.write(" %s;\n" % line)
4389 f.write(" };\n\n")
4391 func.WriteCmdComputeSize(f)
4392 func.WriteCmdSetHeader(f)
4393 func.WriteCmdInit(f)
4394 func.WriteCmdSet(f)
4396 f.write(" gpu::CommandHeader header;\n")
4397 args = func.GetCmdArgs()
4398 for arg in args:
4399 f.write(" %s %s;\n" % (arg.cmd_type, arg.name))
4401 consts = func.GetCmdConstants()
4402 for const in consts:
4403 f.write(" static const %s %s = %s;\n" %
4404 (const.cmd_type, const.name, const.GetConstantValue()))
4406 f.write("};\n")
4407 f.write("\n")
4409 size = len(args) * _SIZE_OF_UINT32 + _SIZE_OF_COMMAND_HEADER
4410 f.write("static_assert(sizeof(%s) == %d,\n" % (func.name, size))
4411 f.write(" \"size of %s should be %d\");\n" %
4412 (func.name, size))
4413 f.write("static_assert(offsetof(%s, header) == 0,\n" % func.name)
4414 f.write(" \"offset of %s header should be 0\");\n" %
4415 func.name)
4416 offset = _SIZE_OF_COMMAND_HEADER
4417 for arg in args:
4418 f.write("static_assert(offsetof(%s, %s) == %d,\n" %
4419 (func.name, arg.name, offset))
4420 f.write(" \"offset of %s %s should be %d\");\n" %
4421 (func.name, arg.name, offset))
4422 offset += _SIZE_OF_UINT32
4423 if not result == None and len(result) > 1:
4424 offset = 0;
4425 for line in result:
4426 parts = line.split()
4427 name = parts[-1]
4428 check = """
4429 static_assert(offsetof(%(cmd_name)s::Result, %(field_name)s) == %(offset)d,
4430 "offset of %(cmd_name)s Result %(field_name)s should be "
4431 "%(offset)d");
4433 f.write((check.strip() + "\n") % {
4434 'cmd_name': func.name,
4435 'field_name': name,
4436 'offset': offset,
4438 offset += _SIZE_OF_UINT32
4439 f.write("\n")
4441 def WriteHandlerImplementation(self, func, f):
4442 """Writes the handler implementation for this command."""
4443 if func.IsUnsafe() and func.GetInfo('id_mapping'):
4444 code_no_gen = """ if (!group_->Get%(type)sServiceId(
4445 %(var)s, &%(service_var)s)) {
4446 LOCAL_SET_GL_ERROR(GL_INVALID_OPERATION, "%(func)s", "invalid %(var)s id");
4447 return error::kNoError;
4450 code_gen = """ if (!group_->Get%(type)sServiceId(
4451 %(var)s, &%(service_var)s)) {
4452 if (!group_->bind_generates_resource()) {
4453 LOCAL_SET_GL_ERROR(
4454 GL_INVALID_OPERATION, "%(func)s", "invalid %(var)s id");
4455 return error::kNoError;
4457 GLuint client_id = %(var)s;
4458 gl%(gen_func)s(1, &%(service_var)s);
4459 Create%(type)s(client_id, %(service_var)s);
4462 gen_func = func.GetInfo('gen_func')
4463 for id_type in func.GetInfo('id_mapping'):
4464 service_var = id_type.lower()
4465 if id_type == 'Sync':
4466 service_var = "service_%s" % service_var
4467 f.write(" GLsync %s = 0;\n" % service_var)
4468 if id_type == 'Sampler' and func.IsType('Bind'):
4469 # No error generated when binding a reserved zero sampler.
4470 args = [arg.name for arg in func.GetOriginalArgs()]
4471 f.write(""" if(%(var)s == 0) {
4472 %(func)s(%(args)s);
4473 return error::kNoError;
4474 }""" % { 'var': id_type.lower(),
4475 'func': func.GetGLFunctionName(),
4476 'args': ", ".join(args) })
4477 if gen_func and id_type in gen_func:
4478 f.write(code_gen % { 'type': id_type,
4479 'var': id_type.lower(),
4480 'service_var': service_var,
4481 'func': func.GetGLFunctionName(),
4482 'gen_func': gen_func })
4483 else:
4484 f.write(code_no_gen % { 'type': id_type,
4485 'var': id_type.lower(),
4486 'service_var': service_var,
4487 'func': func.GetGLFunctionName() })
4488 args = []
4489 for arg in func.GetOriginalArgs():
4490 if arg.type == "GLsync":
4491 args.append("service_%s" % arg.name)
4492 elif arg.name.endswith("size") and arg.type == "GLsizei":
4493 args.append("num_%s" % func.GetLastOriginalArg().name)
4494 elif arg.name == "length":
4495 args.append("nullptr")
4496 else:
4497 args.append(arg.name)
4498 f.write(" %s(%s);\n" %
4499 (func.GetGLFunctionName(), ", ".join(args)))
4501 def WriteCmdSizeTest(self, func, f):
4502 """Writes the size test for a command."""
4503 f.write(" EXPECT_EQ(sizeof(cmd), cmd.header.size * 4u);\n")
4505 def WriteFormatTest(self, func, f):
4506 """Writes a format test for a command."""
4507 f.write("TEST_F(GLES2FormatTest, %s) {\n" % func.name)
4508 f.write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
4509 (func.name, func.name))
4510 f.write(" void* next_cmd = cmd.Set(\n")
4511 f.write(" &cmd")
4512 args = func.GetCmdArgs()
4513 for value, arg in enumerate(args):
4514 f.write(",\n static_cast<%s>(%d)" % (arg.type, value + 11))
4515 f.write(");\n")
4516 f.write(" EXPECT_EQ(static_cast<uint32_t>(cmds::%s::kCmdId),\n" %
4517 func.name)
4518 f.write(" cmd.header.command);\n")
4519 func.type_handler.WriteCmdSizeTest(func, f)
4520 for value, arg in enumerate(args):
4521 f.write(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);\n" %
4522 (arg.type, value + 11, arg.name))
4523 f.write(" CheckBytesWrittenMatchesExpectedSize(\n")
4524 f.write(" next_cmd, sizeof(cmd));\n")
4525 f.write("}\n")
4526 f.write("\n")
4528 def WriteImmediateFormatTest(self, func, f):
4529 """Writes a format test for an immediate version of a command."""
4530 pass
4532 def WriteGetDataSizeCode(self, func, f):
4533 """Writes the code to set data_size used in validation"""
4534 pass
4536 def __WriteIdMapping(self, func, f):
4537 """Writes client side / service side ID mapping."""
4538 if not func.IsUnsafe() or not func.GetInfo('id_mapping'):
4539 return
4540 for id_type in func.GetInfo('id_mapping'):
4541 f.write(" group_->Get%sServiceId(%s, &%s);\n" %
4542 (id_type, id_type.lower(), id_type.lower()))
4544 def WriteImmediateHandlerImplementation (self, func, f):
4545 """Writes the handler impl for the immediate version of a command."""
4546 self.__WriteIdMapping(func, f)
4547 f.write(" %s(%s);\n" %
4548 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
4550 def WriteBucketHandlerImplementation (self, func, f):
4551 """Writes the handler impl for the bucket version of a command."""
4552 self.__WriteIdMapping(func, f)
4553 f.write(" %s(%s);\n" %
4554 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
4556 def WriteServiceHandlerFunctionHeader(self, func, f):
4557 """Writes function header for service implementation handlers."""
4558 f.write("""error::Error GLES2DecoderImpl::Handle%(name)s(
4559 uint32_t immediate_data_size, const void* cmd_data) {
4560 """ % {'name': func.name})
4561 if func.IsUnsafe():
4562 f.write("""if (!unsafe_es3_apis_enabled())
4563 return error::kUnknownCommand;
4564 """)
4565 f.write("""const gles2::cmds::%(name)s& c =
4566 *static_cast<const gles2::cmds::%(name)s*>(cmd_data);
4567 (void)c;
4568 """ % {'name': func.name})
4570 def WriteServiceImplementation(self, func, f):
4571 """Writes the service implementation for a command."""
4572 self.WriteServiceHandlerFunctionHeader(func, f)
4573 self.WriteHandlerExtensionCheck(func, f)
4574 self.WriteHandlerDeferReadWrite(func, f);
4575 if len(func.GetOriginalArgs()) > 0:
4576 last_arg = func.GetLastOriginalArg()
4577 all_but_last_arg = func.GetOriginalArgs()[:-1]
4578 for arg in all_but_last_arg:
4579 arg.WriteGetCode(f)
4580 self.WriteGetDataSizeCode(func, f)
4581 last_arg.WriteGetCode(f)
4582 func.WriteHandlerValidation(f)
4583 func.WriteHandlerImplementation(f)
4584 f.write(" return error::kNoError;\n")
4585 f.write("}\n")
4586 f.write("\n")
4588 def WriteImmediateServiceImplementation(self, func, f):
4589 """Writes the service implementation for an immediate version of command."""
4590 self.WriteServiceHandlerFunctionHeader(func, f)
4591 self.WriteHandlerExtensionCheck(func, f)
4592 self.WriteHandlerDeferReadWrite(func, f);
4593 for arg in func.GetOriginalArgs():
4594 if arg.IsPointer():
4595 self.WriteGetDataSizeCode(func, f)
4596 arg.WriteGetCode(f)
4597 func.WriteHandlerValidation(f)
4598 func.WriteHandlerImplementation(f)
4599 f.write(" return error::kNoError;\n")
4600 f.write("}\n")
4601 f.write("\n")
4603 def WriteBucketServiceImplementation(self, func, f):
4604 """Writes the service implementation for a bucket version of command."""
4605 self.WriteServiceHandlerFunctionHeader(func, f)
4606 self.WriteHandlerExtensionCheck(func, f)
4607 self.WriteHandlerDeferReadWrite(func, f);
4608 for arg in func.GetCmdArgs():
4609 arg.WriteGetCode(f)
4610 func.WriteHandlerValidation(f)
4611 func.WriteHandlerImplementation(f)
4612 f.write(" return error::kNoError;\n")
4613 f.write("}\n")
4614 f.write("\n")
4616 def WriteHandlerExtensionCheck(self, func, f):
4617 if func.GetInfo('extension_flag'):
4618 f.write(" if (!features().%s) {\n" % func.GetInfo('extension_flag'))
4619 f.write(" LOCAL_SET_GL_ERROR(GL_INVALID_OPERATION, \"gl%s\","
4620 " \"function not available\");\n" % func.original_name)
4621 f.write(" return error::kNoError;")
4622 f.write(" }\n\n")
4624 def WriteHandlerDeferReadWrite(self, func, f):
4625 """Writes the code to handle deferring reads or writes."""
4626 defer_draws = func.GetInfo('defer_draws')
4627 defer_reads = func.GetInfo('defer_reads')
4628 if defer_draws or defer_reads:
4629 f.write(" error::Error error;\n")
4630 if defer_draws:
4631 f.write(" error = WillAccessBoundFramebufferForDraw();\n")
4632 f.write(" if (error != error::kNoError)\n")
4633 f.write(" return error;\n")
4634 if defer_reads:
4635 f.write(" error = WillAccessBoundFramebufferForRead();\n")
4636 f.write(" if (error != error::kNoError)\n")
4637 f.write(" return error;\n")
4639 def WriteValidUnitTest(self, func, f, test, *extras):
4640 """Writes a valid unit test for the service implementation."""
4641 if func.GetInfo('expectation') == False:
4642 test = self._remove_expected_call_re.sub('', test)
4643 name = func.name
4644 arg_strings = [
4645 arg.GetValidArg(func) \
4646 for arg in func.GetOriginalArgs() if not arg.IsConstant()
4648 gl_arg_strings = [
4649 arg.GetValidGLArg(func) \
4650 for arg in func.GetOriginalArgs()
4652 gl_func_name = func.GetGLTestFunctionName()
4653 vars = {
4654 'name':name,
4655 'gl_func_name': gl_func_name,
4656 'args': ", ".join(arg_strings),
4657 'gl_args': ", ".join(gl_arg_strings),
4659 for extra in extras:
4660 vars.update(extra)
4661 old_test = ""
4662 while (old_test != test):
4663 old_test = test
4664 test = test % vars
4665 f.write(test % vars)
4667 def WriteInvalidUnitTest(self, func, f, test, *extras):
4668 """Writes an invalid unit test for the service implementation."""
4669 if func.IsUnsafe():
4670 return
4671 for invalid_arg_index, invalid_arg in enumerate(func.GetOriginalArgs()):
4672 # Service implementation does not test constants, as they are not part of
4673 # the call in the service side.
4674 if invalid_arg.IsConstant():
4675 continue
4677 num_invalid_values = invalid_arg.GetNumInvalidValues(func)
4678 for value_index in range(0, num_invalid_values):
4679 arg_strings = []
4680 parse_result = "kNoError"
4681 gl_error = None
4682 for arg in func.GetOriginalArgs():
4683 if arg.IsConstant():
4684 continue
4685 if invalid_arg is arg:
4686 (arg_string, parse_result, gl_error) = arg.GetInvalidArg(
4687 value_index)
4688 else:
4689 arg_string = arg.GetValidArg(func)
4690 arg_strings.append(arg_string)
4691 gl_arg_strings = []
4692 for arg in func.GetOriginalArgs():
4693 gl_arg_strings.append("_")
4694 gl_func_name = func.GetGLTestFunctionName()
4695 gl_error_test = ''
4696 if not gl_error == None:
4697 gl_error_test = '\n EXPECT_EQ(%s, GetGLError());' % gl_error
4699 vars = {
4700 'name': func.name,
4701 'arg_index': invalid_arg_index,
4702 'value_index': value_index,
4703 'gl_func_name': gl_func_name,
4704 'args': ", ".join(arg_strings),
4705 'all_but_last_args': ", ".join(arg_strings[:-1]),
4706 'gl_args': ", ".join(gl_arg_strings),
4707 'parse_result': parse_result,
4708 'gl_error_test': gl_error_test,
4710 for extra in extras:
4711 vars.update(extra)
4712 f.write(test % vars)
4714 def WriteServiceUnitTest(self, func, f, *extras):
4715 """Writes the service unit test for a command."""
4717 if func.name == 'Enable':
4718 valid_test = """
4719 TEST_P(%(test_name)s, %(name)sValidArgs) {
4720 SetupExpectationsForEnableDisable(%(gl_args)s, true);
4721 SpecializedSetup<cmds::%(name)s, 0>(true);
4722 cmds::%(name)s cmd;
4723 cmd.Init(%(args)s);"""
4724 elif func.name == 'Disable':
4725 valid_test = """
4726 TEST_P(%(test_name)s, %(name)sValidArgs) {
4727 SetupExpectationsForEnableDisable(%(gl_args)s, false);
4728 SpecializedSetup<cmds::%(name)s, 0>(true);
4729 cmds::%(name)s cmd;
4730 cmd.Init(%(args)s);"""
4731 else:
4732 valid_test = """
4733 TEST_P(%(test_name)s, %(name)sValidArgs) {
4734 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
4735 SpecializedSetup<cmds::%(name)s, 0>(true);
4736 cmds::%(name)s cmd;
4737 cmd.Init(%(args)s);"""
4738 if func.IsUnsafe():
4739 valid_test += """
4740 decoder_->set_unsafe_es3_apis_enabled(true);
4741 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4742 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4743 decoder_->set_unsafe_es3_apis_enabled(false);
4744 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));
4747 else:
4748 valid_test += """
4749 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4750 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4753 self.WriteValidUnitTest(func, f, valid_test, *extras)
4755 if not func.IsUnsafe():
4756 invalid_test = """
4757 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
4758 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
4759 SpecializedSetup<cmds::%(name)s, 0>(false);
4760 cmds::%(name)s cmd;
4761 cmd.Init(%(args)s);
4762 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
4765 self.WriteInvalidUnitTest(func, f, invalid_test, *extras)
4767 def WriteImmediateServiceUnitTest(self, func, f, *extras):
4768 """Writes the service unit test for an immediate command."""
4769 f.write("// TODO(gman): %s\n" % func.name)
4771 def WriteImmediateValidationCode(self, func, f):
4772 """Writes the validation code for an immediate version of a command."""
4773 pass
4775 def WriteBucketServiceUnitTest(self, func, f, *extras):
4776 """Writes the service unit test for a bucket command."""
4777 f.write("// TODO(gman): %s\n" % func.name)
4779 def WriteGLES2ImplementationDeclaration(self, func, f):
4780 """Writes the GLES2 Implemention declaration."""
4781 impl_decl = func.GetInfo('impl_decl')
4782 if impl_decl == None or impl_decl == True:
4783 f.write("%s %s(%s) override;\n" %
4784 (func.return_type, func.original_name,
4785 func.MakeTypedOriginalArgString("")))
4786 f.write("\n")
4788 def WriteGLES2CLibImplementation(self, func, f):
4789 f.write("%s GL_APIENTRY GLES2%s(%s) {\n" %
4790 (func.return_type, func.name,
4791 func.MakeTypedOriginalArgString("")))
4792 result_string = "return "
4793 if func.return_type == "void":
4794 result_string = ""
4795 f.write(" %sgles2::GetGLContext()->%s(%s);\n" %
4796 (result_string, func.original_name,
4797 func.MakeOriginalArgString("")))
4798 f.write("}\n")
4800 def WriteGLES2Header(self, func, f):
4801 """Writes a re-write macro for GLES"""
4802 f.write("#define gl%s GLES2_GET_FUN(%s)\n" %(func.name, func.name))
4804 def WriteClientGLCallLog(self, func, f):
4805 """Writes a logging macro for the client side code."""
4806 comma = ""
4807 if len(func.GetOriginalArgs()):
4808 comma = " << "
4809 f.write(
4810 ' GPU_CLIENT_LOG("[" << GetLogPrefix() << "] gl%s("%s%s << ")");\n' %
4811 (func.original_name, comma, func.MakeLogArgString()))
4813 def WriteClientGLReturnLog(self, func, f):
4814 """Writes the return value logging code."""
4815 if func.return_type != "void":
4816 f.write(' GPU_CLIENT_LOG("return:" << result)\n')
4818 def WriteGLES2ImplementationHeader(self, func, f):
4819 """Writes the GLES2 Implemention."""
4820 self.WriteGLES2ImplementationDeclaration(func, f)
4822 def WriteGLES2TraceImplementationHeader(self, func, f):
4823 """Writes the GLES2 Trace Implemention header."""
4824 f.write("%s %s(%s) override;\n" %
4825 (func.return_type, func.original_name,
4826 func.MakeTypedOriginalArgString("")))
4828 def WriteGLES2TraceImplementation(self, func, f):
4829 """Writes the GLES2 Trace Implemention."""
4830 f.write("%s GLES2TraceImplementation::%s(%s) {\n" %
4831 (func.return_type, func.original_name,
4832 func.MakeTypedOriginalArgString("")))
4833 result_string = "return "
4834 if func.return_type == "void":
4835 result_string = ""
4836 f.write(' TRACE_EVENT_BINARY_EFFICIENT0("gpu", "GLES2Trace::%s");\n' %
4837 func.name)
4838 f.write(" %sgl_->%s(%s);\n" %
4839 (result_string, func.name, func.MakeOriginalArgString("")))
4840 f.write("}\n")
4841 f.write("\n")
4843 def WriteGLES2Implementation(self, func, f):
4844 """Writes the GLES2 Implemention."""
4845 impl_func = func.GetInfo('impl_func')
4846 impl_decl = func.GetInfo('impl_decl')
4847 gen_cmd = func.GetInfo('gen_cmd')
4848 if (func.can_auto_generate and
4849 (impl_func == None or impl_func == True) and
4850 (impl_decl == None or impl_decl == True) and
4851 (gen_cmd == None or gen_cmd == True)):
4852 f.write("%s GLES2Implementation::%s(%s) {\n" %
4853 (func.return_type, func.original_name,
4854 func.MakeTypedOriginalArgString("")))
4855 f.write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
4856 self.WriteClientGLCallLog(func, f)
4857 func.WriteDestinationInitalizationValidation(f)
4858 for arg in func.GetOriginalArgs():
4859 arg.WriteClientSideValidationCode(f, func)
4860 f.write(" helper_->%s(%s);\n" %
4861 (func.name, func.MakeHelperArgString("")))
4862 f.write(" CheckGLError();\n")
4863 self.WriteClientGLReturnLog(func, f)
4864 f.write("}\n")
4865 f.write("\n")
4867 def WriteGLES2InterfaceHeader(self, func, f):
4868 """Writes the GLES2 Interface."""
4869 f.write("virtual %s %s(%s) = 0;\n" %
4870 (func.return_type, func.original_name,
4871 func.MakeTypedOriginalArgString("")))
4873 def WriteMojoGLES2ImplHeader(self, func, f):
4874 """Writes the Mojo GLES2 implementation header."""
4875 f.write("%s %s(%s) override;\n" %
4876 (func.return_type, func.original_name,
4877 func.MakeTypedOriginalArgString("")))
4879 def WriteMojoGLES2Impl(self, func, f):
4880 """Writes the Mojo GLES2 implementation."""
4881 f.write("%s MojoGLES2Impl::%s(%s) {\n" %
4882 (func.return_type, func.original_name,
4883 func.MakeTypedOriginalArgString("")))
4884 extensions = ["CHROMIUM_sync_point", "CHROMIUM_texture_mailbox",
4885 "CHROMIUM_sub_image", "CHROMIUM_miscellaneous",
4886 "occlusion_query_EXT", "CHROMIUM_image",
4887 "CHROMIUM_copy_texture",
4888 "CHROMIUM_pixel_transfer_buffer_object"]
4889 if func.IsCoreGLFunction() or func.GetInfo("extension") in extensions:
4890 f.write("MojoGLES2MakeCurrent(context_);");
4891 func_return = "gl" + func.original_name + "(" + \
4892 func.MakeOriginalArgString("") + ");"
4893 if func.return_type == "void":
4894 f.write(func_return);
4895 else:
4896 f.write("return " + func_return);
4897 else:
4898 f.write("NOTREACHED() << \"Unimplemented %s.\";\n" %
4899 func.original_name);
4900 if func.return_type != "void":
4901 f.write("return 0;")
4902 f.write("}")
4904 def WriteGLES2InterfaceStub(self, func, f):
4905 """Writes the GLES2 Interface stub declaration."""
4906 f.write("%s %s(%s) override;\n" %
4907 (func.return_type, func.original_name,
4908 func.MakeTypedOriginalArgString("")))
4910 def WriteGLES2InterfaceStubImpl(self, func, f):
4911 """Writes the GLES2 Interface stub declaration."""
4912 args = func.GetOriginalArgs()
4913 arg_string = ", ".join(
4914 ["%s /* %s */" % (arg.type, arg.name) for arg in args])
4915 f.write("%s GLES2InterfaceStub::%s(%s) {\n" %
4916 (func.return_type, func.original_name, arg_string))
4917 if func.return_type != "void":
4918 f.write(" return 0;\n")
4919 f.write("}\n")
4921 def WriteGLES2ImplementationUnitTest(self, func, f):
4922 """Writes the GLES2 Implemention unit test."""
4923 client_test = func.GetInfo('client_test')
4924 if (func.can_auto_generate and
4925 (client_test == None or client_test == True)):
4926 code = """
4927 TEST_F(GLES2ImplementationTest, %(name)s) {
4928 struct Cmds {
4929 cmds::%(name)s cmd;
4931 Cmds expected;
4932 expected.cmd.Init(%(cmd_args)s);
4934 gl_->%(name)s(%(args)s);
4935 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
4938 cmd_arg_strings = [
4939 arg.GetValidClientSideCmdArg(func) for arg in func.GetCmdArgs()
4942 gl_arg_strings = [
4943 arg.GetValidClientSideArg(func) for arg in func.GetOriginalArgs()
4946 f.write(code % {
4947 'name': func.name,
4948 'args': ", ".join(gl_arg_strings),
4949 'cmd_args': ", ".join(cmd_arg_strings),
4952 # Test constants for invalid values, as they are not tested by the
4953 # service.
4954 constants = [arg for arg in func.GetOriginalArgs() if arg.IsConstant()]
4955 if constants:
4956 code = """
4957 TEST_F(GLES2ImplementationTest, %(name)sInvalidConstantArg%(invalid_index)d) {
4958 gl_->%(name)s(%(args)s);
4959 EXPECT_TRUE(NoCommandsWritten());
4960 EXPECT_EQ(%(gl_error)s, CheckError());
4963 for invalid_arg in constants:
4964 gl_arg_strings = []
4965 invalid = invalid_arg.GetInvalidArg(func)
4966 for arg in func.GetOriginalArgs():
4967 if arg is invalid_arg:
4968 gl_arg_strings.append(invalid[0])
4969 else:
4970 gl_arg_strings.append(arg.GetValidClientSideArg(func))
4972 f.write(code % {
4973 'name': func.name,
4974 'invalid_index': func.GetOriginalArgs().index(invalid_arg),
4975 'args': ", ".join(gl_arg_strings),
4976 'gl_error': invalid[2],
4978 else:
4979 if client_test != False:
4980 f.write("// TODO(zmo): Implement unit test for %s\n" % func.name)
4982 def WriteDestinationInitalizationValidation(self, func, f):
4983 """Writes the client side destintion initialization validation."""
4984 for arg in func.GetOriginalArgs():
4985 arg.WriteDestinationInitalizationValidation(f, func)
4987 def WriteTraceEvent(self, func, f):
4988 f.write(' TRACE_EVENT0("gpu", "GLES2Implementation::%s");\n' %
4989 func.original_name)
4991 def WriteImmediateCmdComputeSize(self, func, f):
4992 """Writes the size computation code for the immediate version of a cmd."""
4993 f.write(" static uint32_t ComputeSize(uint32_t size_in_bytes) {\n")
4994 f.write(" return static_cast<uint32_t>(\n")
4995 f.write(" sizeof(ValueType) + // NOLINT\n")
4996 f.write(" RoundSizeToMultipleOfEntries(size_in_bytes));\n")
4997 f.write(" }\n")
4998 f.write("\n")
5000 def WriteImmediateCmdSetHeader(self, func, f):
5001 """Writes the SetHeader function for the immediate version of a cmd."""
5002 f.write(" void SetHeader(uint32_t size_in_bytes) {\n")
5003 f.write(" header.SetCmdByTotalSize<ValueType>(size_in_bytes);\n")
5004 f.write(" }\n")
5005 f.write("\n")
5007 def WriteImmediateCmdInit(self, func, f):
5008 """Writes the Init function for the immediate version of a command."""
5009 raise NotImplementedError(func.name)
5011 def WriteImmediateCmdSet(self, func, f):
5012 """Writes the Set function for the immediate version of a command."""
5013 raise NotImplementedError(func.name)
5015 def WriteCmdHelper(self, func, f):
5016 """Writes the cmd helper definition for a cmd."""
5017 code = """ void %(name)s(%(typed_args)s) {
5018 gles2::cmds::%(name)s* c = GetCmdSpace<gles2::cmds::%(name)s>();
5019 if (c) {
5020 c->Init(%(args)s);
5025 f.write(code % {
5026 "name": func.name,
5027 "typed_args": func.MakeTypedCmdArgString(""),
5028 "args": func.MakeCmdArgString(""),
5031 def WriteImmediateCmdHelper(self, func, f):
5032 """Writes the cmd helper definition for the immediate version of a cmd."""
5033 code = """ void %(name)s(%(typed_args)s) {
5034 const uint32_t s = 0; // TODO(gman): compute correct size
5035 gles2::cmds::%(name)s* c =
5036 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(s);
5037 if (c) {
5038 c->Init(%(args)s);
5043 f.write(code % {
5044 "name": func.name,
5045 "typed_args": func.MakeTypedCmdArgString(""),
5046 "args": func.MakeCmdArgString(""),
5050 class StateSetHandler(TypeHandler):
5051 """Handler for commands that simply set state."""
5053 def WriteHandlerImplementation(self, func, f):
5054 """Overrriden from TypeHandler."""
5055 state_name = func.GetInfo('state')
5056 state = _STATES[state_name]
5057 states = state['states']
5058 args = func.GetOriginalArgs()
5059 for ndx,item in enumerate(states):
5060 code = []
5061 if 'range_checks' in item:
5062 for range_check in item['range_checks']:
5063 code.append("%s %s" % (args[ndx].name, range_check['check']))
5064 if 'nan_check' in item:
5065 # Drivers might generate an INVALID_VALUE error when a value is set
5066 # to NaN. This is allowed behavior under GLES 3.0 section 2.1.1 or
5067 # OpenGL 4.5 section 2.3.4.1 - providing NaN allows undefined results.
5068 # Make this behavior consistent within Chromium, and avoid leaking GL
5069 # errors by generating the error in the command buffer instead of
5070 # letting the GL driver generate it.
5071 code.append("std::isnan(%s)" % args[ndx].name)
5072 if len(code):
5073 f.write(" if (%s) {\n" % " ||\n ".join(code))
5074 f.write(
5075 ' LOCAL_SET_GL_ERROR(GL_INVALID_VALUE,'
5076 ' "%s", "%s out of range");\n' %
5077 (func.name, args[ndx].name))
5078 f.write(" return error::kNoError;\n")
5079 f.write(" }\n")
5080 code = []
5081 for ndx,item in enumerate(states):
5082 code.append("state_.%s != %s" % (item['name'], args[ndx].name))
5083 f.write(" if (%s) {\n" % " ||\n ".join(code))
5084 for ndx,item in enumerate(states):
5085 f.write(" state_.%s = %s;\n" % (item['name'], args[ndx].name))
5086 if 'state_flag' in state:
5087 f.write(" %s = true;\n" % state['state_flag'])
5088 if not func.GetInfo("no_gl"):
5089 for ndx,item in enumerate(states):
5090 if item.get('cached', False):
5091 f.write(" state_.%s = %s;\n" %
5092 (CachedStateName(item), args[ndx].name))
5093 f.write(" %s(%s);\n" %
5094 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
5095 f.write(" }\n")
5097 def WriteServiceUnitTest(self, func, f, *extras):
5098 """Overrriden from TypeHandler."""
5099 TypeHandler.WriteServiceUnitTest(self, func, f, *extras)
5100 state_name = func.GetInfo('state')
5101 state = _STATES[state_name]
5102 states = state['states']
5103 for ndx,item in enumerate(states):
5104 if 'range_checks' in item:
5105 for check_ndx, range_check in enumerate(item['range_checks']):
5106 valid_test = """
5107 TEST_P(%(test_name)s, %(name)sInvalidValue%(ndx)d_%(check_ndx)d) {
5108 SpecializedSetup<cmds::%(name)s, 0>(false);
5109 cmds::%(name)s cmd;
5110 cmd.Init(%(args)s);
5111 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5112 EXPECT_EQ(GL_INVALID_VALUE, GetGLError());
5115 name = func.name
5116 arg_strings = [
5117 arg.GetValidArg(func) \
5118 for arg in func.GetOriginalArgs() if not arg.IsConstant()
5121 arg_strings[ndx] = range_check['test_value']
5122 vars = {
5123 'name': name,
5124 'ndx': ndx,
5125 'check_ndx': check_ndx,
5126 'args': ", ".join(arg_strings),
5128 for extra in extras:
5129 vars.update(extra)
5130 f.write(valid_test % vars)
5131 if 'nan_check' in item:
5132 valid_test = """
5133 TEST_P(%(test_name)s, %(name)sNaNValue%(ndx)d) {
5134 SpecializedSetup<cmds::%(name)s, 0>(false);
5135 cmds::%(name)s cmd;
5136 cmd.Init(%(args)s);
5137 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5138 EXPECT_EQ(GL_INVALID_VALUE, GetGLError());
5141 name = func.name
5142 arg_strings = [
5143 arg.GetValidArg(func) \
5144 for arg in func.GetOriginalArgs() if not arg.IsConstant()
5147 arg_strings[ndx] = 'nanf("")'
5148 vars = {
5149 'name': name,
5150 'ndx': ndx,
5151 'args': ", ".join(arg_strings),
5153 for extra in extras:
5154 vars.update(extra)
5155 f.write(valid_test % vars)
5158 class StateSetRGBAlphaHandler(TypeHandler):
5159 """Handler for commands that simply set state that have rgb/alpha."""
5161 def WriteHandlerImplementation(self, func, f):
5162 """Overrriden from TypeHandler."""
5163 state_name = func.GetInfo('state')
5164 state = _STATES[state_name]
5165 states = state['states']
5166 args = func.GetOriginalArgs()
5167 num_args = len(args)
5168 code = []
5169 for ndx,item in enumerate(states):
5170 code.append("state_.%s != %s" % (item['name'], args[ndx % num_args].name))
5171 f.write(" if (%s) {\n" % " ||\n ".join(code))
5172 for ndx, item in enumerate(states):
5173 f.write(" state_.%s = %s;\n" %
5174 (item['name'], args[ndx % num_args].name))
5175 if 'state_flag' in state:
5176 f.write(" %s = true;\n" % state['state_flag'])
5177 if not func.GetInfo("no_gl"):
5178 f.write(" %s(%s);\n" %
5179 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
5180 f.write(" }\n")
5183 class StateSetFrontBackSeparateHandler(TypeHandler):
5184 """Handler for commands that simply set state that have front/back."""
5186 def WriteHandlerImplementation(self, func, f):
5187 """Overrriden from TypeHandler."""
5188 state_name = func.GetInfo('state')
5189 state = _STATES[state_name]
5190 states = state['states']
5191 args = func.GetOriginalArgs()
5192 face = args[0].name
5193 num_args = len(args)
5194 f.write(" bool changed = false;\n")
5195 for group_ndx, group in enumerate(Grouper(num_args - 1, states)):
5196 f.write(" if (%s == %s || %s == GL_FRONT_AND_BACK) {\n" %
5197 (face, ('GL_FRONT', 'GL_BACK')[group_ndx], face))
5198 code = []
5199 for ndx, item in enumerate(group):
5200 code.append("state_.%s != %s" % (item['name'], args[ndx + 1].name))
5201 f.write(" changed |= %s;\n" % " ||\n ".join(code))
5202 f.write(" }\n")
5203 f.write(" if (changed) {\n")
5204 for group_ndx, group in enumerate(Grouper(num_args - 1, states)):
5205 f.write(" if (%s == %s || %s == GL_FRONT_AND_BACK) {\n" %
5206 (face, ('GL_FRONT', 'GL_BACK')[group_ndx], face))
5207 for ndx, item in enumerate(group):
5208 f.write(" state_.%s = %s;\n" %
5209 (item['name'], args[ndx + 1].name))
5210 f.write(" }\n")
5211 if 'state_flag' in state:
5212 f.write(" %s = true;\n" % state['state_flag'])
5213 if not func.GetInfo("no_gl"):
5214 f.write(" %s(%s);\n" %
5215 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
5216 f.write(" }\n")
5219 class StateSetFrontBackHandler(TypeHandler):
5220 """Handler for commands that simply set state that set both front/back."""
5222 def WriteHandlerImplementation(self, func, f):
5223 """Overrriden from TypeHandler."""
5224 state_name = func.GetInfo('state')
5225 state = _STATES[state_name]
5226 states = state['states']
5227 args = func.GetOriginalArgs()
5228 num_args = len(args)
5229 code = []
5230 for group_ndx, group in enumerate(Grouper(num_args, states)):
5231 for ndx, item in enumerate(group):
5232 code.append("state_.%s != %s" % (item['name'], args[ndx].name))
5233 f.write(" if (%s) {\n" % " ||\n ".join(code))
5234 for group_ndx, group in enumerate(Grouper(num_args, states)):
5235 for ndx, item in enumerate(group):
5236 f.write(" state_.%s = %s;\n" % (item['name'], args[ndx].name))
5237 if 'state_flag' in state:
5238 f.write(" %s = true;\n" % state['state_flag'])
5239 if not func.GetInfo("no_gl"):
5240 f.write(" %s(%s);\n" %
5241 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
5242 f.write(" }\n")
5245 class StateSetNamedParameter(TypeHandler):
5246 """Handler for commands that set a state chosen with an enum parameter."""
5248 def WriteHandlerImplementation(self, func, f):
5249 """Overridden from TypeHandler."""
5250 state_name = func.GetInfo('state')
5251 state = _STATES[state_name]
5252 states = state['states']
5253 args = func.GetOriginalArgs()
5254 num_args = len(args)
5255 assert num_args == 2
5256 f.write(" switch (%s) {\n" % args[0].name)
5257 for state in states:
5258 f.write(" case %s:\n" % state['enum'])
5259 f.write(" if (state_.%s != %s) {\n" %
5260 (state['name'], args[1].name))
5261 f.write(" state_.%s = %s;\n" % (state['name'], args[1].name))
5262 if not func.GetInfo("no_gl"):
5263 f.write(" %s(%s);\n" %
5264 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
5265 f.write(" }\n")
5266 f.write(" break;\n")
5267 f.write(" default:\n")
5268 f.write(" NOTREACHED();\n")
5269 f.write(" }\n")
5272 class CustomHandler(TypeHandler):
5273 """Handler for commands that are auto-generated but require minor tweaks."""
5275 def WriteServiceImplementation(self, func, f):
5276 """Overrriden from TypeHandler."""
5277 pass
5279 def WriteImmediateServiceImplementation(self, func, f):
5280 """Overrriden from TypeHandler."""
5281 pass
5283 def WriteBucketServiceImplementation(self, func, f):
5284 """Overrriden from TypeHandler."""
5285 pass
5287 def WriteServiceUnitTest(self, func, f, *extras):
5288 """Overrriden from TypeHandler."""
5289 f.write("// TODO(gman): %s\n\n" % func.name)
5291 def WriteImmediateServiceUnitTest(self, func, f, *extras):
5292 """Overrriden from TypeHandler."""
5293 f.write("// TODO(gman): %s\n\n" % func.name)
5295 def WriteImmediateCmdGetTotalSize(self, func, f):
5296 """Overrriden from TypeHandler."""
5297 f.write(
5298 " uint32_t total_size = 0; // TODO(gman): get correct size.\n")
5300 def WriteImmediateCmdInit(self, func, f):
5301 """Overrriden from TypeHandler."""
5302 f.write(" void Init(%s) {\n" % func.MakeTypedCmdArgString("_"))
5303 self.WriteImmediateCmdGetTotalSize(func, f)
5304 f.write(" SetHeader(total_size);\n")
5305 args = func.GetCmdArgs()
5306 for arg in args:
5307 f.write(" %s = _%s;\n" % (arg.name, arg.name))
5308 f.write(" }\n")
5309 f.write("\n")
5311 def WriteImmediateCmdSet(self, func, f):
5312 """Overrriden from TypeHandler."""
5313 copy_args = func.MakeCmdArgString("_", False)
5314 f.write(" void* Set(void* cmd%s) {\n" %
5315 func.MakeTypedCmdArgString("_", True))
5316 self.WriteImmediateCmdGetTotalSize(func, f)
5317 f.write(" static_cast<ValueType*>(cmd)->Init(%s);\n" % copy_args)
5318 f.write(" return NextImmediateCmdAddressTotalSize<ValueType>("
5319 "cmd, total_size);\n")
5320 f.write(" }\n")
5321 f.write("\n")
5324 class HandWrittenHandler(CustomHandler):
5325 """Handler for comands where everything must be written by hand."""
5327 def InitFunction(self, func):
5328 """Add or adjust anything type specific for this function."""
5329 CustomHandler.InitFunction(self, func)
5330 func.can_auto_generate = False
5332 def NeedsDataTransferFunction(self, func):
5333 """Overriden from TypeHandler."""
5334 # If specified explicitly, force the data transfer method.
5335 if func.GetInfo('data_transfer_methods'):
5336 return True
5337 return False
5339 def WriteStruct(self, func, f):
5340 """Overrriden from TypeHandler."""
5341 pass
5343 def WriteDocs(self, func, f):
5344 """Overrriden from TypeHandler."""
5345 pass
5347 def WriteServiceUnitTest(self, func, f, *extras):
5348 """Overrriden from TypeHandler."""
5349 f.write("// TODO(gman): %s\n\n" % func.name)
5351 def WriteImmediateServiceUnitTest(self, func, f, *extras):
5352 """Overrriden from TypeHandler."""
5353 f.write("// TODO(gman): %s\n\n" % func.name)
5355 def WriteBucketServiceUnitTest(self, func, f, *extras):
5356 """Overrriden from TypeHandler."""
5357 f.write("// TODO(gman): %s\n\n" % func.name)
5359 def WriteServiceImplementation(self, func, f):
5360 """Overrriden from TypeHandler."""
5361 pass
5363 def WriteImmediateServiceImplementation(self, func, f):
5364 """Overrriden from TypeHandler."""
5365 pass
5367 def WriteBucketServiceImplementation(self, func, f):
5368 """Overrriden from TypeHandler."""
5369 pass
5371 def WriteImmediateCmdHelper(self, func, f):
5372 """Overrriden from TypeHandler."""
5373 pass
5375 def WriteCmdHelper(self, func, f):
5376 """Overrriden from TypeHandler."""
5377 pass
5379 def WriteFormatTest(self, func, f):
5380 """Overrriden from TypeHandler."""
5381 f.write("// TODO(gman): Write test for %s\n" % func.name)
5383 def WriteImmediateFormatTest(self, func, f):
5384 """Overrriden from TypeHandler."""
5385 f.write("// TODO(gman): Write test for %s\n" % func.name)
5388 class ManualHandler(CustomHandler):
5389 """Handler for commands who's handlers must be written by hand."""
5391 def InitFunction(self, func):
5392 """Overrriden from TypeHandler."""
5393 if (func.name == 'CompressedTexImage2DBucket' or
5394 func.name == 'CompressedTexImage3DBucket'):
5395 func.cmd_args = func.cmd_args[:-1]
5396 func.AddCmdArg(Argument('bucket_id', 'GLuint'))
5397 else:
5398 CustomHandler.InitFunction(self, func)
5400 def WriteServiceImplementation(self, func, f):
5401 """Overrriden from TypeHandler."""
5402 pass
5404 def WriteBucketServiceImplementation(self, func, f):
5405 """Overrriden from TypeHandler."""
5406 pass
5408 def WriteServiceUnitTest(self, func, f, *extras):
5409 """Overrriden from TypeHandler."""
5410 f.write("// TODO(gman): %s\n\n" % func.name)
5412 def WriteImmediateServiceUnitTest(self, func, f, *extras):
5413 """Overrriden from TypeHandler."""
5414 f.write("// TODO(gman): %s\n\n" % func.name)
5416 def WriteImmediateServiceImplementation(self, func, f):
5417 """Overrriden from TypeHandler."""
5418 pass
5420 def WriteImmediateFormatTest(self, func, f):
5421 """Overrriden from TypeHandler."""
5422 f.write("// TODO(gman): Implement test for %s\n" % func.name)
5424 def WriteGLES2Implementation(self, func, f):
5425 """Overrriden from TypeHandler."""
5426 if func.GetInfo('impl_func'):
5427 super(ManualHandler, self).WriteGLES2Implementation(func, f)
5429 def WriteGLES2ImplementationHeader(self, func, f):
5430 """Overrriden from TypeHandler."""
5431 f.write("%s %s(%s) override;\n" %
5432 (func.return_type, func.original_name,
5433 func.MakeTypedOriginalArgString("")))
5434 f.write("\n")
5436 def WriteImmediateCmdGetTotalSize(self, func, f):
5437 """Overrriden from TypeHandler."""
5438 # TODO(gman): Move this data to _FUNCTION_INFO?
5439 CustomHandler.WriteImmediateCmdGetTotalSize(self, func, f)
5442 class DataHandler(TypeHandler):
5443 """Handler for glBufferData, glBufferSubData, glTexImage*D, glTexSubImage*D,
5444 glCompressedTexImage*D, glCompressedTexImageSub*D."""
5446 def InitFunction(self, func):
5447 """Overrriden from TypeHandler."""
5448 if (func.name == 'CompressedTexSubImage2DBucket' or
5449 func.name == 'CompressedTexSubImage3DBucket'):
5450 func.cmd_args = func.cmd_args[:-1]
5451 func.AddCmdArg(Argument('bucket_id', 'GLuint'))
5453 def WriteGetDataSizeCode(self, func, f):
5454 """Overrriden from TypeHandler."""
5455 # TODO(gman): Move this data to _FUNCTION_INFO?
5456 name = func.name
5457 if name.endswith("Immediate"):
5458 name = name[0:-9]
5459 if name == 'BufferData' or name == 'BufferSubData':
5460 f.write(" uint32_t data_size = size;\n")
5461 elif (name == 'CompressedTexImage2D' or
5462 name == 'CompressedTexSubImage2D' or
5463 name == 'CompressedTexImage3D' or
5464 name == 'CompressedTexSubImage3D'):
5465 f.write(" uint32_t data_size = imageSize;\n")
5466 elif (name == 'CompressedTexSubImage2DBucket' or
5467 name == 'CompressedTexSubImage3DBucket'):
5468 f.write(" Bucket* bucket = GetBucket(c.bucket_id);\n")
5469 f.write(" uint32_t data_size = bucket->size();\n")
5470 f.write(" GLsizei imageSize = data_size;\n")
5471 elif name == 'TexImage2D' or name == 'TexSubImage2D':
5472 code = """ uint32_t data_size;
5473 if (!GLES2Util::ComputeImageDataSize(
5474 width, height, format, type, unpack_alignment_, &data_size)) {
5475 return error::kOutOfBounds;
5478 f.write(code)
5479 else:
5480 f.write(
5481 "// uint32_t data_size = 0; // TODO(gman): get correct size!\n")
5483 def WriteImmediateCmdGetTotalSize(self, func, f):
5484 """Overrriden from TypeHandler."""
5485 pass
5487 def WriteImmediateCmdInit(self, func, f):
5488 """Overrriden from TypeHandler."""
5489 f.write(" void Init(%s) {\n" % func.MakeTypedCmdArgString("_"))
5490 self.WriteImmediateCmdGetTotalSize(func, f)
5491 f.write(" SetHeader(total_size);\n")
5492 args = func.GetCmdArgs()
5493 for arg in args:
5494 f.write(" %s = _%s;\n" % (arg.name, arg.name))
5495 f.write(" }\n")
5496 f.write("\n")
5498 def WriteImmediateCmdSet(self, func, f):
5499 """Overrriden from TypeHandler."""
5500 copy_args = func.MakeCmdArgString("_", False)
5501 f.write(" void* Set(void* cmd%s) {\n" %
5502 func.MakeTypedCmdArgString("_", True))
5503 self.WriteImmediateCmdGetTotalSize(func, f)
5504 f.write(" static_cast<ValueType*>(cmd)->Init(%s);\n" % copy_args)
5505 f.write(" return NextImmediateCmdAddressTotalSize<ValueType>("
5506 "cmd, total_size);\n")
5507 f.write(" }\n")
5508 f.write("\n")
5510 def WriteImmediateFormatTest(self, func, f):
5511 """Overrriden from TypeHandler."""
5512 # TODO(gman): Remove this exception.
5513 f.write("// TODO(gman): Implement test for %s\n" % func.name)
5514 return
5516 def WriteServiceUnitTest(self, func, f, *extras):
5517 """Overrriden from TypeHandler."""
5518 f.write("// TODO(gman): %s\n\n" % func.name)
5520 def WriteImmediateServiceUnitTest(self, func, f, *extras):
5521 """Overrriden from TypeHandler."""
5522 f.write("// TODO(gman): %s\n\n" % func.name)
5524 def WriteBucketServiceImplementation(self, func, f):
5525 """Overrriden from TypeHandler."""
5526 if ((not func.name == 'CompressedTexSubImage2DBucket') and
5527 (not func.name == 'CompressedTexSubImage3DBucket')):
5528 TypeHandler.WriteBucketServiceImplemenation(self, func, f)
5531 class BindHandler(TypeHandler):
5532 """Handler for glBind___ type functions."""
5534 def WriteServiceUnitTest(self, func, f, *extras):
5535 """Overrriden from TypeHandler."""
5537 if len(func.GetOriginalArgs()) == 1:
5538 valid_test = """
5539 TEST_P(%(test_name)s, %(name)sValidArgs) {
5540 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
5541 SpecializedSetup<cmds::%(name)s, 0>(true);
5542 cmds::%(name)s cmd;
5543 cmd.Init(%(args)s);"""
5544 if func.IsUnsafe():
5545 valid_test += """
5546 decoder_->set_unsafe_es3_apis_enabled(true);
5547 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5548 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5549 decoder_->set_unsafe_es3_apis_enabled(false);
5550 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));
5553 else:
5554 valid_test += """
5555 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5556 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5559 if func.GetInfo("gen_func"):
5560 valid_test += """
5561 TEST_P(%(test_name)s, %(name)sValidArgsNewId) {
5562 EXPECT_CALL(*gl_, %(gl_func_name)s(kNewServiceId));
5563 EXPECT_CALL(*gl_, %(gl_gen_func_name)s(1, _))
5564 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
5565 SpecializedSetup<cmds::%(name)s, 0>(true);
5566 cmds::%(name)s cmd;
5567 cmd.Init(kNewClientId);
5568 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5569 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5570 EXPECT_TRUE(Get%(resource_type)s(kNewClientId) != NULL);
5573 self.WriteValidUnitTest(func, f, valid_test, {
5574 'resource_type': func.GetOriginalArgs()[0].resource_type,
5575 'gl_gen_func_name': func.GetInfo("gen_func"),
5576 }, *extras)
5577 else:
5578 valid_test = """
5579 TEST_P(%(test_name)s, %(name)sValidArgs) {
5580 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
5581 SpecializedSetup<cmds::%(name)s, 0>(true);
5582 cmds::%(name)s cmd;
5583 cmd.Init(%(args)s);"""
5584 if func.IsUnsafe():
5585 valid_test += """
5586 decoder_->set_unsafe_es3_apis_enabled(true);
5587 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5588 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5589 decoder_->set_unsafe_es3_apis_enabled(false);
5590 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));
5593 else:
5594 valid_test += """
5595 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5596 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5599 if func.GetInfo("gen_func"):
5600 valid_test += """
5601 TEST_P(%(test_name)s, %(name)sValidArgsNewId) {
5602 EXPECT_CALL(*gl_,
5603 %(gl_func_name)s(%(gl_args_with_new_id)s));
5604 EXPECT_CALL(*gl_, %(gl_gen_func_name)s(1, _))
5605 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
5606 SpecializedSetup<cmds::%(name)s, 0>(true);
5607 cmds::%(name)s cmd;
5608 cmd.Init(%(args_with_new_id)s);"""
5609 if func.IsUnsafe():
5610 valid_test += """
5611 decoder_->set_unsafe_es3_apis_enabled(true);
5612 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5613 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5614 EXPECT_TRUE(Get%(resource_type)s(kNewClientId) != NULL);
5615 decoder_->set_unsafe_es3_apis_enabled(false);
5616 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));
5619 else:
5620 valid_test += """
5621 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5622 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5623 EXPECT_TRUE(Get%(resource_type)s(kNewClientId) != NULL);
5627 gl_args_with_new_id = []
5628 args_with_new_id = []
5629 for arg in func.GetOriginalArgs():
5630 if hasattr(arg, 'resource_type'):
5631 gl_args_with_new_id.append('kNewServiceId')
5632 args_with_new_id.append('kNewClientId')
5633 else:
5634 gl_args_with_new_id.append(arg.GetValidGLArg(func))
5635 args_with_new_id.append(arg.GetValidArg(func))
5636 self.WriteValidUnitTest(func, f, valid_test, {
5637 'args_with_new_id': ", ".join(args_with_new_id),
5638 'gl_args_with_new_id': ", ".join(gl_args_with_new_id),
5639 'resource_type': func.GetResourceIdArg().resource_type,
5640 'gl_gen_func_name': func.GetInfo("gen_func"),
5641 }, *extras)
5643 invalid_test = """
5644 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
5645 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
5646 SpecializedSetup<cmds::%(name)s, 0>(false);
5647 cmds::%(name)s cmd;
5648 cmd.Init(%(args)s);
5649 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
5652 self.WriteInvalidUnitTest(func, f, invalid_test, *extras)
5654 def WriteGLES2Implementation(self, func, f):
5655 """Writes the GLES2 Implemention."""
5657 impl_func = func.GetInfo('impl_func')
5658 impl_decl = func.GetInfo('impl_decl')
5660 if (func.can_auto_generate and
5661 (impl_func == None or impl_func == True) and
5662 (impl_decl == None or impl_decl == True)):
5664 f.write("%s GLES2Implementation::%s(%s) {\n" %
5665 (func.return_type, func.original_name,
5666 func.MakeTypedOriginalArgString("")))
5667 f.write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
5668 func.WriteDestinationInitalizationValidation(f)
5669 self.WriteClientGLCallLog(func, f)
5670 for arg in func.GetOriginalArgs():
5671 arg.WriteClientSideValidationCode(f, func)
5673 code = """ if (Is%(type)sReservedId(%(id)s)) {
5674 SetGLError(GL_INVALID_OPERATION, "%(name)s\", \"%(id)s reserved id");
5675 return;
5677 %(name)sHelper(%(arg_string)s);
5678 CheckGLError();
5682 name_arg = func.GetResourceIdArg()
5683 f.write(code % {
5684 'name': func.name,
5685 'arg_string': func.MakeOriginalArgString(""),
5686 'id': name_arg.name,
5687 'type': name_arg.resource_type,
5688 'lc_type': name_arg.resource_type.lower(),
5691 def WriteGLES2ImplementationUnitTest(self, func, f):
5692 """Overrriden from TypeHandler."""
5693 client_test = func.GetInfo('client_test')
5694 if client_test == False:
5695 return
5696 code = """
5697 TEST_F(GLES2ImplementationTest, %(name)s) {
5698 struct Cmds {
5699 cmds::%(name)s cmd;
5701 Cmds expected;
5702 expected.cmd.Init(%(cmd_args)s);
5704 gl_->%(name)s(%(args)s);
5705 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));"""
5706 if not func.IsUnsafe():
5707 code += """
5708 ClearCommands();
5709 gl_->%(name)s(%(args)s);
5710 EXPECT_TRUE(NoCommandsWritten());"""
5711 code += """
5714 cmd_arg_strings = [
5715 arg.GetValidClientSideCmdArg(func) for arg in func.GetCmdArgs()
5717 gl_arg_strings = [
5718 arg.GetValidClientSideArg(func) for arg in func.GetOriginalArgs()
5721 f.write(code % {
5722 'name': func.name,
5723 'args': ", ".join(gl_arg_strings),
5724 'cmd_args': ", ".join(cmd_arg_strings),
5728 class GENnHandler(TypeHandler):
5729 """Handler for glGen___ type functions."""
5731 def InitFunction(self, func):
5732 """Overrriden from TypeHandler."""
5733 pass
5735 def WriteGetDataSizeCode(self, func, f):
5736 """Overrriden from TypeHandler."""
5737 code = """ uint32_t data_size;
5738 if (!SafeMultiplyUint32(n, sizeof(GLuint), &data_size)) {
5739 return error::kOutOfBounds;
5742 f.write(code)
5744 def WriteHandlerImplementation (self, func, f):
5745 """Overrriden from TypeHandler."""
5746 f.write(" if (!%sHelper(n, %s)) {\n"
5747 " return error::kInvalidArguments;\n"
5748 " }\n" %
5749 (func.name, func.GetLastOriginalArg().name))
5751 def WriteImmediateHandlerImplementation(self, func, f):
5752 """Overrriden from TypeHandler."""
5753 if func.IsUnsafe():
5754 f.write(""" for (GLsizei ii = 0; ii < n; ++ii) {
5755 if (group_->Get%(resource_name)sServiceId(%(last_arg_name)s[ii], NULL)) {
5756 return error::kInvalidArguments;
5759 scoped_ptr<GLuint[]> service_ids(new GLuint[n]);
5760 gl%(func_name)s(n, service_ids.get());
5761 for (GLsizei ii = 0; ii < n; ++ii) {
5762 group_->Add%(resource_name)sId(%(last_arg_name)s[ii], service_ids[ii]);
5764 """ % { 'func_name': func.original_name,
5765 'last_arg_name': func.GetLastOriginalArg().name,
5766 'resource_name': func.GetInfo('resource_type') })
5767 else:
5768 f.write(" if (!%sHelper(n, %s)) {\n"
5769 " return error::kInvalidArguments;\n"
5770 " }\n" %
5771 (func.original_name, func.GetLastOriginalArg().name))
5773 def WriteGLES2Implementation(self, func, f):
5774 """Overrriden from TypeHandler."""
5775 log_code = (""" GPU_CLIENT_LOG_CODE_BLOCK({
5776 for (GLsizei i = 0; i < n; ++i) {
5777 GPU_CLIENT_LOG(" " << i << ": " << %s[i]);
5779 });""" % func.GetOriginalArgs()[1].name)
5780 args = {
5781 'log_code': log_code,
5782 'return_type': func.return_type,
5783 'name': func.original_name,
5784 'typed_args': func.MakeTypedOriginalArgString(""),
5785 'args': func.MakeOriginalArgString(""),
5786 'resource_types': func.GetInfo('resource_types'),
5787 'count_name': func.GetOriginalArgs()[0].name,
5789 f.write(
5790 "%(return_type)s GLES2Implementation::%(name)s(%(typed_args)s) {\n" %
5791 args)
5792 func.WriteDestinationInitalizationValidation(f)
5793 self.WriteClientGLCallLog(func, f)
5794 for arg in func.GetOriginalArgs():
5795 arg.WriteClientSideValidationCode(f, func)
5796 not_shared = func.GetInfo('not_shared')
5797 if not_shared:
5798 alloc_code = (
5800 """ IdAllocator* id_allocator = GetIdAllocator(id_namespaces::k%s);
5801 for (GLsizei ii = 0; ii < n; ++ii)
5802 %s[ii] = id_allocator->AllocateID();""" %
5803 (func.GetInfo('resource_types'), func.GetOriginalArgs()[1].name))
5804 else:
5805 alloc_code = (""" GetIdHandler(id_namespaces::k%(resource_types)s)->
5806 MakeIds(this, 0, %(args)s);""" % args)
5807 args['alloc_code'] = alloc_code
5809 code = """ GPU_CLIENT_SINGLE_THREAD_CHECK();
5810 %(alloc_code)s
5811 %(name)sHelper(%(args)s);
5812 helper_->%(name)sImmediate(%(args)s);
5813 if (share_group_->bind_generates_resource())
5814 helper_->CommandBufferHelper::Flush();
5815 %(log_code)s
5816 CheckGLError();
5820 f.write(code % args)
5822 def WriteGLES2ImplementationUnitTest(self, func, f):
5823 """Overrriden from TypeHandler."""
5824 code = """
5825 TEST_F(GLES2ImplementationTest, %(name)s) {
5826 GLuint ids[2] = { 0, };
5827 struct Cmds {
5828 cmds::%(name)sImmediate gen;
5829 GLuint data[2];
5831 Cmds expected;
5832 expected.gen.Init(arraysize(ids), &ids[0]);
5833 expected.data[0] = k%(types)sStartId;
5834 expected.data[1] = k%(types)sStartId + 1;
5835 gl_->%(name)s(arraysize(ids), &ids[0]);
5836 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
5837 EXPECT_EQ(k%(types)sStartId, ids[0]);
5838 EXPECT_EQ(k%(types)sStartId + 1, ids[1]);
5841 f.write(code % {
5842 'name': func.name,
5843 'types': func.GetInfo('resource_types'),
5846 def WriteServiceUnitTest(self, func, f, *extras):
5847 """Overrriden from TypeHandler."""
5848 valid_test = """
5849 TEST_P(%(test_name)s, %(name)sValidArgs) {
5850 EXPECT_CALL(*gl_, %(gl_func_name)s(1, _))
5851 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
5852 GetSharedMemoryAs<GLuint*>()[0] = kNewClientId;
5853 SpecializedSetup<cmds::%(name)s, 0>(true);
5854 cmds::%(name)s cmd;
5855 cmd.Init(%(args)s);
5856 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5857 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
5858 if func.IsUnsafe():
5859 valid_test += """
5860 GLuint service_id;
5861 EXPECT_TRUE(Get%(resource_name)sServiceId(kNewClientId, &service_id));
5862 EXPECT_EQ(kNewServiceId, service_id)
5865 else:
5866 valid_test += """
5867 EXPECT_TRUE(Get%(resource_name)s(kNewClientId, &service_id) != NULL);
5870 self.WriteValidUnitTest(func, f, valid_test, {
5871 'resource_name': func.GetInfo('resource_type'),
5872 }, *extras)
5873 invalid_test = """
5874 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
5875 EXPECT_CALL(*gl_, %(gl_func_name)s(_, _)).Times(0);
5876 GetSharedMemoryAs<GLuint*>()[0] = client_%(resource_name)s_id_;
5877 SpecializedSetup<cmds::%(name)s, 0>(false);
5878 cmds::%(name)s cmd;
5879 cmd.Init(%(args)s);
5880 EXPECT_EQ(error::kInvalidArguments, ExecuteCmd(cmd));
5883 self.WriteValidUnitTest(func, f, invalid_test, {
5884 'resource_name': func.GetInfo('resource_type').lower(),
5885 }, *extras)
5887 def WriteImmediateServiceUnitTest(self, func, f, *extras):
5888 """Overrriden from TypeHandler."""
5889 valid_test = """
5890 TEST_P(%(test_name)s, %(name)sValidArgs) {
5891 EXPECT_CALL(*gl_, %(gl_func_name)s(1, _))
5892 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
5893 cmds::%(name)s* cmd = GetImmediateAs<cmds::%(name)s>();
5894 GLuint temp = kNewClientId;
5895 SpecializedSetup<cmds::%(name)s, 0>(true);"""
5896 if func.IsUnsafe():
5897 valid_test += """
5898 decoder_->set_unsafe_es3_apis_enabled(true);"""
5899 valid_test += """
5900 cmd->Init(1, &temp);
5901 EXPECT_EQ(error::kNoError,
5902 ExecuteImmediateCmd(*cmd, sizeof(temp)));
5903 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
5904 if func.IsUnsafe():
5905 valid_test += """
5906 GLuint service_id;
5907 EXPECT_TRUE(Get%(resource_name)sServiceId(kNewClientId, &service_id));
5908 EXPECT_EQ(kNewServiceId, service_id);
5909 decoder_->set_unsafe_es3_apis_enabled(false);
5910 EXPECT_EQ(error::kUnknownCommand,
5911 ExecuteImmediateCmd(*cmd, sizeof(temp)));
5914 else:
5915 valid_test += """
5916 EXPECT_TRUE(Get%(resource_name)s(kNewClientId) != NULL);
5919 self.WriteValidUnitTest(func, f, valid_test, {
5920 'resource_name': func.GetInfo('resource_type'),
5921 }, *extras)
5922 invalid_test = """
5923 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
5924 EXPECT_CALL(*gl_, %(gl_func_name)s(_, _)).Times(0);
5925 cmds::%(name)s* cmd = GetImmediateAs<cmds::%(name)s>();
5926 SpecializedSetup<cmds::%(name)s, 0>(false);
5927 cmd->Init(1, &client_%(resource_name)s_id_);"""
5928 if func.IsUnsafe():
5929 invalid_test += """
5930 decoder_->set_unsafe_es3_apis_enabled(true);
5931 EXPECT_EQ(error::kInvalidArguments,
5932 ExecuteImmediateCmd(*cmd, sizeof(&client_%(resource_name)s_id_)));
5933 decoder_->set_unsafe_es3_apis_enabled(false);
5936 else:
5937 invalid_test += """
5938 EXPECT_EQ(error::kInvalidArguments,
5939 ExecuteImmediateCmd(*cmd, sizeof(&client_%(resource_name)s_id_)));
5942 self.WriteValidUnitTest(func, f, invalid_test, {
5943 'resource_name': func.GetInfo('resource_type').lower(),
5944 }, *extras)
5946 def WriteImmediateCmdComputeSize(self, func, f):
5947 """Overrriden from TypeHandler."""
5948 f.write(" static uint32_t ComputeDataSize(GLsizei n) {\n")
5949 f.write(
5950 " return static_cast<uint32_t>(sizeof(GLuint) * n); // NOLINT\n")
5951 f.write(" }\n")
5952 f.write("\n")
5953 f.write(" static uint32_t ComputeSize(GLsizei n) {\n")
5954 f.write(" return static_cast<uint32_t>(\n")
5955 f.write(" sizeof(ValueType) + ComputeDataSize(n)); // NOLINT\n")
5956 f.write(" }\n")
5957 f.write("\n")
5959 def WriteImmediateCmdSetHeader(self, func, f):
5960 """Overrriden from TypeHandler."""
5961 f.write(" void SetHeader(GLsizei n) {\n")
5962 f.write(" header.SetCmdByTotalSize<ValueType>(ComputeSize(n));\n")
5963 f.write(" }\n")
5964 f.write("\n")
5966 def WriteImmediateCmdInit(self, func, f):
5967 """Overrriden from TypeHandler."""
5968 last_arg = func.GetLastOriginalArg()
5969 f.write(" void Init(%s, %s _%s) {\n" %
5970 (func.MakeTypedCmdArgString("_"),
5971 last_arg.type, last_arg.name))
5972 f.write(" SetHeader(_n);\n")
5973 args = func.GetCmdArgs()
5974 for arg in args:
5975 f.write(" %s = _%s;\n" % (arg.name, arg.name))
5976 f.write(" memcpy(ImmediateDataAddress(this),\n")
5977 f.write(" _%s, ComputeDataSize(_n));\n" % last_arg.name)
5978 f.write(" }\n")
5979 f.write("\n")
5981 def WriteImmediateCmdSet(self, func, f):
5982 """Overrriden from TypeHandler."""
5983 last_arg = func.GetLastOriginalArg()
5984 copy_args = func.MakeCmdArgString("_", False)
5985 f.write(" void* Set(void* cmd%s, %s _%s) {\n" %
5986 (func.MakeTypedCmdArgString("_", True),
5987 last_arg.type, last_arg.name))
5988 f.write(" static_cast<ValueType*>(cmd)->Init(%s, _%s);\n" %
5989 (copy_args, last_arg.name))
5990 f.write(" const uint32_t size = ComputeSize(_n);\n")
5991 f.write(" return NextImmediateCmdAddressTotalSize<ValueType>("
5992 "cmd, size);\n")
5993 f.write(" }\n")
5994 f.write("\n")
5996 def WriteImmediateCmdHelper(self, func, f):
5997 """Overrriden from TypeHandler."""
5998 code = """ void %(name)s(%(typed_args)s) {
5999 const uint32_t size = gles2::cmds::%(name)s::ComputeSize(n);
6000 gles2::cmds::%(name)s* c =
6001 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
6002 if (c) {
6003 c->Init(%(args)s);
6008 f.write(code % {
6009 "name": func.name,
6010 "typed_args": func.MakeTypedOriginalArgString(""),
6011 "args": func.MakeOriginalArgString(""),
6014 def WriteImmediateFormatTest(self, func, f):
6015 """Overrriden from TypeHandler."""
6016 f.write("TEST_F(GLES2FormatTest, %s) {\n" % func.name)
6017 f.write(" static GLuint ids[] = { 12, 23, 34, };\n")
6018 f.write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
6019 (func.name, func.name))
6020 f.write(" void* next_cmd = cmd.Set(\n")
6021 f.write(" &cmd, static_cast<GLsizei>(arraysize(ids)), ids);\n")
6022 f.write(" EXPECT_EQ(static_cast<uint32_t>(cmds::%s::kCmdId),\n" %
6023 func.name)
6024 f.write(" cmd.header.command);\n")
6025 f.write(" EXPECT_EQ(sizeof(cmd) +\n")
6026 f.write(" RoundSizeToMultipleOfEntries(cmd.n * 4u),\n")
6027 f.write(" cmd.header.size * 4u);\n")
6028 f.write(" EXPECT_EQ(static_cast<GLsizei>(arraysize(ids)), cmd.n);\n");
6029 f.write(" CheckBytesWrittenMatchesExpectedSize(\n")
6030 f.write(" next_cmd, sizeof(cmd) +\n")
6031 f.write(" RoundSizeToMultipleOfEntries(arraysize(ids) * 4u));\n")
6032 f.write(" // TODO(gman): Check that ids were inserted;\n")
6033 f.write("}\n")
6034 f.write("\n")
6037 class CreateHandler(TypeHandler):
6038 """Handler for glCreate___ type functions."""
6040 def InitFunction(self, func):
6041 """Overrriden from TypeHandler."""
6042 func.AddCmdArg(Argument("client_id", 'uint32_t'))
6044 def __GetResourceType(self, func):
6045 if func.return_type == "GLsync":
6046 return "Sync"
6047 else:
6048 return func.name[6:] # Create*
6050 def WriteServiceUnitTest(self, func, f, *extras):
6051 """Overrriden from TypeHandler."""
6052 valid_test = """
6053 TEST_P(%(test_name)s, %(name)sValidArgs) {
6054 %(id_type_cast)sEXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s))
6055 .WillOnce(Return(%(const_service_id)s));
6056 SpecializedSetup<cmds::%(name)s, 0>(true);
6057 cmds::%(name)s cmd;
6058 cmd.Init(%(args)s%(comma)skNewClientId);"""
6059 if func.IsUnsafe():
6060 valid_test += """
6061 decoder_->set_unsafe_es3_apis_enabled(true);"""
6062 valid_test += """
6063 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
6064 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
6065 if func.IsUnsafe():
6066 valid_test += """
6067 %(return_type)s service_id = 0;
6068 EXPECT_TRUE(Get%(resource_type)sServiceId(kNewClientId, &service_id));
6069 EXPECT_EQ(%(const_service_id)s, service_id);
6070 decoder_->set_unsafe_es3_apis_enabled(false);
6071 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));
6074 else:
6075 valid_test += """
6076 EXPECT_TRUE(Get%(resource_type)s(kNewClientId));
6079 comma = ""
6080 cmd_arg_count = 0
6081 for arg in func.GetOriginalArgs():
6082 if not arg.IsConstant():
6083 cmd_arg_count += 1
6084 if cmd_arg_count:
6085 comma = ", "
6086 if func.return_type == 'GLsync':
6087 id_type_cast = ("const GLsync kNewServiceIdGLuint = reinterpret_cast"
6088 "<GLsync>(kNewServiceId);\n ")
6089 const_service_id = "kNewServiceIdGLuint"
6090 else:
6091 id_type_cast = ""
6092 const_service_id = "kNewServiceId"
6093 self.WriteValidUnitTest(func, f, valid_test, {
6094 'comma': comma,
6095 'resource_type': self.__GetResourceType(func),
6096 'return_type': func.return_type,
6097 'id_type_cast': id_type_cast,
6098 'const_service_id': const_service_id,
6099 }, *extras)
6100 invalid_test = """
6101 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
6102 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
6103 SpecializedSetup<cmds::%(name)s, 0>(false);
6104 cmds::%(name)s cmd;
6105 cmd.Init(%(args)s%(comma)skNewClientId);
6106 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));%(gl_error_test)s
6109 self.WriteInvalidUnitTest(func, f, invalid_test, {
6110 'comma': comma,
6111 }, *extras)
6113 def WriteHandlerImplementation (self, func, f):
6114 """Overrriden from TypeHandler."""
6115 if func.IsUnsafe():
6116 code = """ uint32_t client_id = c.client_id;
6117 %(return_type)s service_id = 0;
6118 if (group_->Get%(resource_name)sServiceId(client_id, &service_id)) {
6119 return error::kInvalidArguments;
6121 service_id = %(gl_func_name)s(%(gl_args)s);
6122 if (service_id) {
6123 group_->Add%(resource_name)sId(client_id, service_id);
6126 else:
6127 code = """ uint32_t client_id = c.client_id;
6128 if (Get%(resource_name)s(client_id)) {
6129 return error::kInvalidArguments;
6131 %(return_type)s service_id = %(gl_func_name)s(%(gl_args)s);
6132 if (service_id) {
6133 Create%(resource_name)s(client_id, service_id%(gl_args_with_comma)s);
6136 f.write(code % {
6137 'resource_name': self.__GetResourceType(func),
6138 'return_type': func.return_type,
6139 'gl_func_name': func.GetGLFunctionName(),
6140 'gl_args': func.MakeOriginalArgString(""),
6141 'gl_args_with_comma': func.MakeOriginalArgString("", True) })
6143 def WriteGLES2Implementation(self, func, f):
6144 """Overrriden from TypeHandler."""
6145 f.write("%s GLES2Implementation::%s(%s) {\n" %
6146 (func.return_type, func.original_name,
6147 func.MakeTypedOriginalArgString("")))
6148 f.write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
6149 func.WriteDestinationInitalizationValidation(f)
6150 self.WriteClientGLCallLog(func, f)
6151 for arg in func.GetOriginalArgs():
6152 arg.WriteClientSideValidationCode(f, func)
6153 f.write(" GLuint client_id;\n")
6154 if func.return_type == "GLsync":
6155 f.write(
6156 " GetIdHandler(id_namespaces::kSyncs)->\n")
6157 else:
6158 f.write(
6159 " GetIdHandler(id_namespaces::kProgramsAndShaders)->\n")
6160 f.write(" MakeIds(this, 0, 1, &client_id);\n")
6161 f.write(" helper_->%s(%s);\n" %
6162 (func.name, func.MakeCmdArgString("")))
6163 f.write(' GPU_CLIENT_LOG("returned " << client_id);\n')
6164 f.write(" CheckGLError();\n")
6165 if func.return_type == "GLsync":
6166 f.write(" return reinterpret_cast<GLsync>(client_id);\n")
6167 else:
6168 f.write(" return client_id;\n")
6169 f.write("}\n")
6170 f.write("\n")
6173 class DeleteHandler(TypeHandler):
6174 """Handler for glDelete___ single resource type functions."""
6176 def WriteServiceImplementation(self, func, f):
6177 """Overrriden from TypeHandler."""
6178 if func.IsUnsafe():
6179 TypeHandler.WriteServiceImplementation(self, func, f)
6180 # HandleDeleteShader and HandleDeleteProgram are manually written.
6181 pass
6183 def WriteGLES2Implementation(self, func, f):
6184 """Overrriden from TypeHandler."""
6185 f.write("%s GLES2Implementation::%s(%s) {\n" %
6186 (func.return_type, func.original_name,
6187 func.MakeTypedOriginalArgString("")))
6188 f.write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
6189 func.WriteDestinationInitalizationValidation(f)
6190 self.WriteClientGLCallLog(func, f)
6191 for arg in func.GetOriginalArgs():
6192 arg.WriteClientSideValidationCode(f, func)
6193 f.write(
6194 " GPU_CLIENT_DCHECK(%s != 0);\n" % func.GetOriginalArgs()[-1].name)
6195 f.write(" %sHelper(%s);\n" %
6196 (func.original_name, func.GetOriginalArgs()[-1].name))
6197 f.write(" CheckGLError();\n")
6198 f.write("}\n")
6199 f.write("\n")
6201 def WriteHandlerImplementation (self, func, f):
6202 """Overrriden from TypeHandler."""
6203 assert len(func.GetOriginalArgs()) == 1
6204 arg = func.GetOriginalArgs()[0]
6205 if func.IsUnsafe():
6206 f.write(""" %(arg_type)s service_id = 0;
6207 if (group_->Get%(resource_type)sServiceId(%(arg_name)s, &service_id)) {
6208 glDelete%(resource_type)s(service_id);
6209 group_->Remove%(resource_type)sId(%(arg_name)s);
6210 } else {
6211 LOCAL_SET_GL_ERROR(
6212 GL_INVALID_VALUE, "gl%(func_name)s", "unknown %(arg_name)s");
6214 """ % { 'resource_type': func.GetInfo('resource_type'),
6215 'arg_name': arg.name,
6216 'arg_type': arg.type,
6217 'func_name': func.original_name })
6218 else:
6219 f.write(" %sHelper(%s);\n" % (func.original_name, arg.name))
6221 class DELnHandler(TypeHandler):
6222 """Handler for glDelete___ type functions."""
6224 def WriteGetDataSizeCode(self, func, f):
6225 """Overrriden from TypeHandler."""
6226 code = """ uint32_t data_size;
6227 if (!SafeMultiplyUint32(n, sizeof(GLuint), &data_size)) {
6228 return error::kOutOfBounds;
6231 f.write(code)
6233 def WriteGLES2ImplementationUnitTest(self, func, f):
6234 """Overrriden from TypeHandler."""
6235 code = """
6236 TEST_F(GLES2ImplementationTest, %(name)s) {
6237 GLuint ids[2] = { k%(types)sStartId, k%(types)sStartId + 1 };
6238 struct Cmds {
6239 cmds::%(name)sImmediate del;
6240 GLuint data[2];
6242 Cmds expected;
6243 expected.del.Init(arraysize(ids), &ids[0]);
6244 expected.data[0] = k%(types)sStartId;
6245 expected.data[1] = k%(types)sStartId + 1;
6246 gl_->%(name)s(arraysize(ids), &ids[0]);
6247 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
6250 f.write(code % {
6251 'name': func.name,
6252 'types': func.GetInfo('resource_types'),
6255 def WriteServiceUnitTest(self, func, f, *extras):
6256 """Overrriden from TypeHandler."""
6257 valid_test = """
6258 TEST_P(%(test_name)s, %(name)sValidArgs) {
6259 EXPECT_CALL(
6260 *gl_,
6261 %(gl_func_name)s(1, Pointee(kService%(upper_resource_name)sId)))
6262 .Times(1);
6263 GetSharedMemoryAs<GLuint*>()[0] = client_%(resource_name)s_id_;
6264 SpecializedSetup<cmds::%(name)s, 0>(true);
6265 cmds::%(name)s cmd;
6266 cmd.Init(%(args)s);
6267 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
6268 EXPECT_EQ(GL_NO_ERROR, GetGLError());
6269 EXPECT_TRUE(
6270 Get%(upper_resource_name)s(client_%(resource_name)s_id_) == NULL);
6273 self.WriteValidUnitTest(func, f, valid_test, {
6274 'resource_name': func.GetInfo('resource_type').lower(),
6275 'upper_resource_name': func.GetInfo('resource_type'),
6276 }, *extras)
6277 invalid_test = """
6278 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
6279 GetSharedMemoryAs<GLuint*>()[0] = kInvalidClientId;
6280 SpecializedSetup<cmds::%(name)s, 0>(false);
6281 cmds::%(name)s cmd;
6282 cmd.Init(%(args)s);
6283 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
6286 self.WriteValidUnitTest(func, f, invalid_test, *extras)
6288 def WriteImmediateServiceUnitTest(self, func, f, *extras):
6289 """Overrriden from TypeHandler."""
6290 valid_test = """
6291 TEST_P(%(test_name)s, %(name)sValidArgs) {
6292 EXPECT_CALL(
6293 *gl_,
6294 %(gl_func_name)s(1, Pointee(kService%(upper_resource_name)sId)))
6295 .Times(1);
6296 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
6297 SpecializedSetup<cmds::%(name)s, 0>(true);
6298 cmd.Init(1, &client_%(resource_name)s_id_);"""
6299 if func.IsUnsafe():
6300 valid_test += """
6301 decoder_->set_unsafe_es3_apis_enabled(true);"""
6302 valid_test += """
6303 EXPECT_EQ(error::kNoError,
6304 ExecuteImmediateCmd(cmd, sizeof(client_%(resource_name)s_id_)));
6305 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
6306 if func.IsUnsafe():
6307 valid_test += """
6308 EXPECT_FALSE(Get%(upper_resource_name)sServiceId(
6309 client_%(resource_name)s_id_, NULL));
6310 decoder_->set_unsafe_es3_apis_enabled(false);
6311 EXPECT_EQ(error::kUnknownCommand,
6312 ExecuteImmediateCmd(cmd, sizeof(client_%(resource_name)s_id_)));
6315 else:
6316 valid_test += """
6317 EXPECT_TRUE(
6318 Get%(upper_resource_name)s(client_%(resource_name)s_id_) == NULL);
6321 self.WriteValidUnitTest(func, f, valid_test, {
6322 'resource_name': func.GetInfo('resource_type').lower(),
6323 'upper_resource_name': func.GetInfo('resource_type'),
6324 }, *extras)
6325 invalid_test = """
6326 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
6327 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
6328 SpecializedSetup<cmds::%(name)s, 0>(false);
6329 GLuint temp = kInvalidClientId;
6330 cmd.Init(1, &temp);"""
6331 if func.IsUnsafe():
6332 invalid_test += """
6333 decoder_->set_unsafe_es3_apis_enabled(true);
6334 EXPECT_EQ(error::kNoError,
6335 ExecuteImmediateCmd(cmd, sizeof(temp)));
6336 decoder_->set_unsafe_es3_apis_enabled(false);
6337 EXPECT_EQ(error::kUnknownCommand,
6338 ExecuteImmediateCmd(cmd, sizeof(temp)));
6341 else:
6342 invalid_test += """
6343 EXPECT_EQ(error::kNoError,
6344 ExecuteImmediateCmd(cmd, sizeof(temp)));
6347 self.WriteValidUnitTest(func, f, invalid_test, *extras)
6349 def WriteHandlerImplementation (self, func, f):
6350 """Overrriden from TypeHandler."""
6351 f.write(" %sHelper(n, %s);\n" %
6352 (func.name, func.GetLastOriginalArg().name))
6354 def WriteImmediateHandlerImplementation (self, func, f):
6355 """Overrriden from TypeHandler."""
6356 if func.IsUnsafe():
6357 f.write(""" for (GLsizei ii = 0; ii < n; ++ii) {
6358 GLuint service_id = 0;
6359 if (group_->Get%(resource_type)sServiceId(
6360 %(last_arg_name)s[ii], &service_id)) {
6361 glDelete%(resource_type)ss(1, &service_id);
6362 group_->Remove%(resource_type)sId(%(last_arg_name)s[ii]);
6365 """ % { 'resource_type': func.GetInfo('resource_type'),
6366 'last_arg_name': func.GetLastOriginalArg().name })
6367 else:
6368 f.write(" %sHelper(n, %s);\n" %
6369 (func.original_name, func.GetLastOriginalArg().name))
6371 def WriteGLES2Implementation(self, func, f):
6372 """Overrriden from TypeHandler."""
6373 impl_decl = func.GetInfo('impl_decl')
6374 if impl_decl == None or impl_decl == True:
6375 args = {
6376 'return_type': func.return_type,
6377 'name': func.original_name,
6378 'typed_args': func.MakeTypedOriginalArgString(""),
6379 'args': func.MakeOriginalArgString(""),
6380 'resource_type': func.GetInfo('resource_type').lower(),
6381 'count_name': func.GetOriginalArgs()[0].name,
6383 f.write(
6384 "%(return_type)s GLES2Implementation::%(name)s(%(typed_args)s) {\n" %
6385 args)
6386 f.write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
6387 func.WriteDestinationInitalizationValidation(f)
6388 self.WriteClientGLCallLog(func, f)
6389 f.write(""" GPU_CLIENT_LOG_CODE_BLOCK({
6390 for (GLsizei i = 0; i < n; ++i) {
6391 GPU_CLIENT_LOG(" " << i << ": " << %s[i]);
6394 """ % func.GetOriginalArgs()[1].name)
6395 f.write(""" GPU_CLIENT_DCHECK_CODE_BLOCK({
6396 for (GLsizei i = 0; i < n; ++i) {
6397 DCHECK(%s[i] != 0);
6400 """ % func.GetOriginalArgs()[1].name)
6401 for arg in func.GetOriginalArgs():
6402 arg.WriteClientSideValidationCode(f, func)
6403 code = """ %(name)sHelper(%(args)s);
6404 CheckGLError();
6408 f.write(code % args)
6410 def WriteImmediateCmdComputeSize(self, func, f):
6411 """Overrriden from TypeHandler."""
6412 f.write(" static uint32_t ComputeDataSize(GLsizei n) {\n")
6413 f.write(
6414 " return static_cast<uint32_t>(sizeof(GLuint) * n); // NOLINT\n")
6415 f.write(" }\n")
6416 f.write("\n")
6417 f.write(" static uint32_t ComputeSize(GLsizei n) {\n")
6418 f.write(" return static_cast<uint32_t>(\n")
6419 f.write(" sizeof(ValueType) + ComputeDataSize(n)); // NOLINT\n")
6420 f.write(" }\n")
6421 f.write("\n")
6423 def WriteImmediateCmdSetHeader(self, func, f):
6424 """Overrriden from TypeHandler."""
6425 f.write(" void SetHeader(GLsizei n) {\n")
6426 f.write(" header.SetCmdByTotalSize<ValueType>(ComputeSize(n));\n")
6427 f.write(" }\n")
6428 f.write("\n")
6430 def WriteImmediateCmdInit(self, func, f):
6431 """Overrriden from TypeHandler."""
6432 last_arg = func.GetLastOriginalArg()
6433 f.write(" void Init(%s, %s _%s) {\n" %
6434 (func.MakeTypedCmdArgString("_"),
6435 last_arg.type, last_arg.name))
6436 f.write(" SetHeader(_n);\n")
6437 args = func.GetCmdArgs()
6438 for arg in args:
6439 f.write(" %s = _%s;\n" % (arg.name, arg.name))
6440 f.write(" memcpy(ImmediateDataAddress(this),\n")
6441 f.write(" _%s, ComputeDataSize(_n));\n" % last_arg.name)
6442 f.write(" }\n")
6443 f.write("\n")
6445 def WriteImmediateCmdSet(self, func, f):
6446 """Overrriden from TypeHandler."""
6447 last_arg = func.GetLastOriginalArg()
6448 copy_args = func.MakeCmdArgString("_", False)
6449 f.write(" void* Set(void* cmd%s, %s _%s) {\n" %
6450 (func.MakeTypedCmdArgString("_", True),
6451 last_arg.type, last_arg.name))
6452 f.write(" static_cast<ValueType*>(cmd)->Init(%s, _%s);\n" %
6453 (copy_args, last_arg.name))
6454 f.write(" const uint32_t size = ComputeSize(_n);\n")
6455 f.write(" return NextImmediateCmdAddressTotalSize<ValueType>("
6456 "cmd, size);\n")
6457 f.write(" }\n")
6458 f.write("\n")
6460 def WriteImmediateCmdHelper(self, func, f):
6461 """Overrriden from TypeHandler."""
6462 code = """ void %(name)s(%(typed_args)s) {
6463 const uint32_t size = gles2::cmds::%(name)s::ComputeSize(n);
6464 gles2::cmds::%(name)s* c =
6465 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
6466 if (c) {
6467 c->Init(%(args)s);
6472 f.write(code % {
6473 "name": func.name,
6474 "typed_args": func.MakeTypedOriginalArgString(""),
6475 "args": func.MakeOriginalArgString(""),
6478 def WriteImmediateFormatTest(self, func, f):
6479 """Overrriden from TypeHandler."""
6480 f.write("TEST_F(GLES2FormatTest, %s) {\n" % func.name)
6481 f.write(" static GLuint ids[] = { 12, 23, 34, };\n")
6482 f.write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
6483 (func.name, func.name))
6484 f.write(" void* next_cmd = cmd.Set(\n")
6485 f.write(" &cmd, static_cast<GLsizei>(arraysize(ids)), ids);\n")
6486 f.write(" EXPECT_EQ(static_cast<uint32_t>(cmds::%s::kCmdId),\n" %
6487 func.name)
6488 f.write(" cmd.header.command);\n")
6489 f.write(" EXPECT_EQ(sizeof(cmd) +\n")
6490 f.write(" RoundSizeToMultipleOfEntries(cmd.n * 4u),\n")
6491 f.write(" cmd.header.size * 4u);\n")
6492 f.write(" EXPECT_EQ(static_cast<GLsizei>(arraysize(ids)), cmd.n);\n");
6493 f.write(" CheckBytesWrittenMatchesExpectedSize(\n")
6494 f.write(" next_cmd, sizeof(cmd) +\n")
6495 f.write(" RoundSizeToMultipleOfEntries(arraysize(ids) * 4u));\n")
6496 f.write(" // TODO(gman): Check that ids were inserted;\n")
6497 f.write("}\n")
6498 f.write("\n")
6501 class GETnHandler(TypeHandler):
6502 """Handler for GETn for glGetBooleanv, glGetFloatv, ... type functions."""
6504 def NeedsDataTransferFunction(self, func):
6505 """Overriden from TypeHandler."""
6506 return False
6508 def WriteServiceImplementation(self, func, f):
6509 """Overrriden from TypeHandler."""
6510 self.WriteServiceHandlerFunctionHeader(func, f)
6511 last_arg = func.GetLastOriginalArg()
6512 # All except shm_id and shm_offset.
6513 all_but_last_args = func.GetCmdArgs()[:-2]
6514 for arg in all_but_last_args:
6515 arg.WriteGetCode(f)
6517 code = """ typedef cmds::%(func_name)s::Result Result;
6518 GLsizei num_values = 0;
6519 GetNumValuesReturnedForGLGet(pname, &num_values);
6520 Result* result = GetSharedMemoryAs<Result*>(
6521 c.%(last_arg_name)s_shm_id, c.%(last_arg_name)s_shm_offset,
6522 Result::ComputeSize(num_values));
6523 %(last_arg_type)s %(last_arg_name)s = result ? result->GetData() : NULL;
6525 f.write(code % {
6526 'last_arg_type': last_arg.type,
6527 'last_arg_name': last_arg.name,
6528 'func_name': func.name,
6530 func.WriteHandlerValidation(f)
6531 code = """ // Check that the client initialized the result.
6532 if (result->size != 0) {
6533 return error::kInvalidArguments;
6536 shadowed = func.GetInfo('shadowed')
6537 if not shadowed:
6538 f.write(' LOCAL_COPY_REAL_GL_ERRORS_TO_WRAPPER("%s");\n' % func.name)
6539 f.write(code)
6540 func.WriteHandlerImplementation(f)
6541 if shadowed:
6542 code = """ result->SetNumResults(num_values);
6543 return error::kNoError;
6546 else:
6547 code = """ GLenum error = LOCAL_PEEK_GL_ERROR("%(func_name)s");
6548 if (error == GL_NO_ERROR) {
6549 result->SetNumResults(num_values);
6551 return error::kNoError;
6555 f.write(code % {'func_name': func.name})
6557 def WriteGLES2Implementation(self, func, f):
6558 """Overrriden from TypeHandler."""
6559 impl_decl = func.GetInfo('impl_decl')
6560 if impl_decl == None or impl_decl == True:
6561 f.write("%s GLES2Implementation::%s(%s) {\n" %
6562 (func.return_type, func.original_name,
6563 func.MakeTypedOriginalArgString("")))
6564 f.write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
6565 func.WriteDestinationInitalizationValidation(f)
6566 self.WriteClientGLCallLog(func, f)
6567 for arg in func.GetOriginalArgs():
6568 arg.WriteClientSideValidationCode(f, func)
6569 all_but_last_args = func.GetOriginalArgs()[:-1]
6570 args = []
6571 has_length_arg = False
6572 for arg in all_but_last_args:
6573 if arg.type == 'GLsync':
6574 args.append('ToGLuint(%s)' % arg.name)
6575 elif arg.name.endswith('size') and arg.type == 'GLsizei':
6576 continue
6577 elif arg.name == 'length':
6578 has_length_arg = True
6579 continue
6580 else:
6581 args.append(arg.name)
6582 arg_string = ", ".join(args)
6583 all_arg_string = (
6584 ", ".join([
6585 "%s" % arg.name
6586 for arg in func.GetOriginalArgs() if not arg.IsConstant()]))
6587 self.WriteTraceEvent(func, f)
6588 code = """ if (%(func_name)sHelper(%(all_arg_string)s)) {
6589 return;
6591 typedef cmds::%(func_name)s::Result Result;
6592 Result* result = GetResultAs<Result*>();
6593 if (!result) {
6594 return;
6596 result->SetNumResults(0);
6597 helper_->%(func_name)s(%(arg_string)s,
6598 GetResultShmId(), GetResultShmOffset());
6599 WaitForCmd();
6600 result->CopyResult(%(last_arg_name)s);
6601 GPU_CLIENT_LOG_CODE_BLOCK({
6602 for (int32_t i = 0; i < result->GetNumResults(); ++i) {
6603 GPU_CLIENT_LOG(" " << i << ": " << result->GetData()[i]);
6605 });"""
6606 if has_length_arg:
6607 code += """
6608 if (length) {
6609 *length = result->GetNumResults();
6610 }"""
6611 code += """
6612 CheckGLError();
6615 f.write(code % {
6616 'func_name': func.name,
6617 'arg_string': arg_string,
6618 'all_arg_string': all_arg_string,
6619 'last_arg_name': func.GetLastOriginalArg().name,
6622 def WriteGLES2ImplementationUnitTest(self, func, f):
6623 """Writes the GLES2 Implemention unit test."""
6624 code = """
6625 TEST_F(GLES2ImplementationTest, %(name)s) {
6626 struct Cmds {
6627 cmds::%(name)s cmd;
6629 typedef cmds::%(name)s::Result::Type ResultType;
6630 ResultType result = 0;
6631 Cmds expected;
6632 ExpectedMemoryInfo result1 = GetExpectedResultMemory(
6633 sizeof(uint32_t) + sizeof(ResultType));
6634 expected.cmd.Init(%(cmd_args)s, result1.id, result1.offset);
6635 EXPECT_CALL(*command_buffer(), OnFlush())
6636 .WillOnce(SetMemory(result1.ptr, SizedResultHelper<ResultType>(1)))
6637 .RetiresOnSaturation();
6638 gl_->%(name)s(%(args)s, &result);
6639 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
6640 EXPECT_EQ(static_cast<ResultType>(1), result);
6643 first_cmd_arg = func.GetCmdArgs()[0].GetValidNonCachedClientSideCmdArg(func)
6644 if not first_cmd_arg:
6645 return
6647 first_gl_arg = func.GetOriginalArgs()[0].GetValidNonCachedClientSideArg(
6648 func)
6650 cmd_arg_strings = [first_cmd_arg]
6651 for arg in func.GetCmdArgs()[1:-2]:
6652 cmd_arg_strings.append(arg.GetValidClientSideCmdArg(func))
6653 gl_arg_strings = [first_gl_arg]
6654 for arg in func.GetOriginalArgs()[1:-1]:
6655 gl_arg_strings.append(arg.GetValidClientSideArg(func))
6657 f.write(code % {
6658 'name': func.name,
6659 'args': ", ".join(gl_arg_strings),
6660 'cmd_args': ", ".join(cmd_arg_strings),
6663 def WriteServiceUnitTest(self, func, f, *extras):
6664 """Overrriden from TypeHandler."""
6665 valid_test = """
6666 TEST_P(%(test_name)s, %(name)sValidArgs) {
6667 EXPECT_CALL(*gl_, GetError())
6668 .WillOnce(Return(GL_NO_ERROR))
6669 .WillOnce(Return(GL_NO_ERROR))
6670 .RetiresOnSaturation();
6671 SpecializedSetup<cmds::%(name)s, 0>(true);
6672 typedef cmds::%(name)s::Result Result;
6673 Result* result = static_cast<Result*>(shared_memory_address_);
6674 EXPECT_CALL(*gl_, %(gl_func_name)s(%(local_gl_args)s));
6675 result->size = 0;
6676 cmds::%(name)s cmd;
6677 cmd.Init(%(cmd_args)s);"""
6678 if func.IsUnsafe():
6679 valid_test += """
6680 decoder_->set_unsafe_es3_apis_enabled(true);"""
6681 valid_test += """
6682 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
6683 EXPECT_EQ(decoder_->GetGLES2Util()->GLGetNumValuesReturned(
6684 %(valid_pname)s),
6685 result->GetNumResults());
6686 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
6687 if func.IsUnsafe():
6688 valid_test += """
6689 decoder_->set_unsafe_es3_apis_enabled(false);
6690 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));"""
6691 valid_test += """
6694 gl_arg_strings = []
6695 cmd_arg_strings = []
6696 valid_pname = ''
6697 for arg in func.GetOriginalArgs()[:-1]:
6698 if arg.name == 'length':
6699 gl_arg_value = 'nullptr'
6700 elif arg.name.endswith('size'):
6701 gl_arg_value = ("decoder_->GetGLES2Util()->GLGetNumValuesReturned(%s)" %
6702 valid_pname)
6703 elif arg.type == 'GLsync':
6704 gl_arg_value = 'reinterpret_cast<GLsync>(kServiceSyncId)'
6705 else:
6706 gl_arg_value = arg.GetValidGLArg(func)
6707 gl_arg_strings.append(gl_arg_value)
6708 if arg.name == 'pname':
6709 valid_pname = gl_arg_value
6710 if arg.name.endswith('size') or arg.name == 'length':
6711 continue
6712 if arg.type == 'GLsync':
6713 arg_value = 'client_sync_id_'
6714 else:
6715 arg_value = arg.GetValidArg(func)
6716 cmd_arg_strings.append(arg_value)
6717 if func.GetInfo('gl_test_func') == 'glGetIntegerv':
6718 gl_arg_strings.append("_")
6719 else:
6720 gl_arg_strings.append("result->GetData()")
6721 cmd_arg_strings.append("shared_memory_id_")
6722 cmd_arg_strings.append("shared_memory_offset_")
6724 self.WriteValidUnitTest(func, f, valid_test, {
6725 'local_gl_args': ", ".join(gl_arg_strings),
6726 'cmd_args': ", ".join(cmd_arg_strings),
6727 'valid_pname': valid_pname,
6728 }, *extras)
6730 if not func.IsUnsafe():
6731 invalid_test = """
6732 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
6733 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
6734 SpecializedSetup<cmds::%(name)s, 0>(false);
6735 cmds::%(name)s::Result* result =
6736 static_cast<cmds::%(name)s::Result*>(shared_memory_address_);
6737 result->size = 0;
6738 cmds::%(name)s cmd;
6739 cmd.Init(%(args)s);
6740 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));
6741 EXPECT_EQ(0u, result->size);%(gl_error_test)s
6744 self.WriteInvalidUnitTest(func, f, invalid_test, *extras)
6746 class ArrayArgTypeHandler(TypeHandler):
6747 """Base class for type handlers that handle args that are arrays"""
6749 def GetArrayType(self, func):
6750 """Returns the type of the element in the element array being PUT to."""
6751 for arg in func.GetOriginalArgs():
6752 if arg.IsPointer():
6753 element_type = arg.GetPointedType()
6754 return element_type
6756 # Special case: array type handler is used for a function that is forwarded
6757 # to the actual array type implementation
6758 element_type = func.GetOriginalArgs()[-1].type
6759 assert all(arg.type == element_type \
6760 for arg in func.GetOriginalArgs()[-self.GetArrayCount(func):])
6761 return element_type
6763 def GetArrayCount(self, func):
6764 """Returns the count of the elements in the array being PUT to."""
6765 return func.GetInfo('count')
6767 class PUTHandler(ArrayArgTypeHandler):
6768 """Handler for glTexParameter_v, glVertexAttrib_v functions."""
6770 def WriteServiceUnitTest(self, func, f, *extras):
6771 """Writes the service unit test for a command."""
6772 expected_call = "EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));"
6773 if func.GetInfo("first_element_only"):
6774 gl_arg_strings = [
6775 arg.GetValidGLArg(func) for arg in func.GetOriginalArgs()
6777 gl_arg_strings[-1] = "*" + gl_arg_strings[-1]
6778 expected_call = ("EXPECT_CALL(*gl_, %%(gl_func_name)s(%s));" %
6779 ", ".join(gl_arg_strings))
6780 valid_test = """
6781 TEST_P(%(test_name)s, %(name)sValidArgs) {
6782 SpecializedSetup<cmds::%(name)s, 0>(true);
6783 cmds::%(name)s cmd;
6784 cmd.Init(%(args)s);
6785 GetSharedMemoryAs<%(data_type)s*>()[0] = %(data_value)s;
6786 %(expected_call)s
6787 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
6788 EXPECT_EQ(GL_NO_ERROR, GetGLError());
6791 extra = {
6792 'data_type': self.GetArrayType(func),
6793 'data_value': func.GetInfo('data_value') or '0',
6794 'expected_call': expected_call,
6796 self.WriteValidUnitTest(func, f, valid_test, extra, *extras)
6798 invalid_test = """
6799 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
6800 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
6801 SpecializedSetup<cmds::%(name)s, 0>(false);
6802 cmds::%(name)s cmd;
6803 cmd.Init(%(args)s);
6804 GetSharedMemoryAs<%(data_type)s*>()[0] = %(data_value)s;
6805 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
6808 self.WriteInvalidUnitTest(func, f, invalid_test, extra, *extras)
6810 def WriteImmediateServiceUnitTest(self, func, f, *extras):
6811 """Writes the service unit test for a command."""
6812 valid_test = """
6813 TEST_P(%(test_name)s, %(name)sValidArgs) {
6814 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
6815 SpecializedSetup<cmds::%(name)s, 0>(true);
6816 %(data_type)s temp[%(data_count)s] = { %(data_value)s, };
6817 cmd.Init(%(gl_args)s, &temp[0]);
6818 EXPECT_CALL(
6819 *gl_,
6820 %(gl_func_name)s(%(gl_args)s, %(data_ref)sreinterpret_cast<
6821 %(data_type)s*>(ImmediateDataAddress(&cmd))));"""
6822 if func.IsUnsafe():
6823 valid_test += """
6824 decoder_->set_unsafe_es3_apis_enabled(true);"""
6825 valid_test += """
6826 EXPECT_EQ(error::kNoError,
6827 ExecuteImmediateCmd(cmd, sizeof(temp)));
6828 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
6829 if func.IsUnsafe():
6830 valid_test += """
6831 decoder_->set_unsafe_es3_apis_enabled(false);
6832 EXPECT_EQ(error::kUnknownCommand,
6833 ExecuteImmediateCmd(cmd, sizeof(temp)));"""
6834 valid_test += """
6837 gl_arg_strings = [
6838 arg.GetValidGLArg(func) for arg in func.GetOriginalArgs()[0:-1]
6840 gl_any_strings = ["_"] * len(gl_arg_strings)
6842 extra = {
6843 'data_ref': ("*" if func.GetInfo('first_element_only') else ""),
6844 'data_type': self.GetArrayType(func),
6845 'data_count': self.GetArrayCount(func),
6846 'data_value': func.GetInfo('data_value') or '0',
6847 'gl_args': ", ".join(gl_arg_strings),
6848 'gl_any_args': ", ".join(gl_any_strings),
6850 self.WriteValidUnitTest(func, f, valid_test, extra, *extras)
6852 invalid_test = """
6853 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
6854 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();"""
6855 if func.IsUnsafe():
6856 invalid_test += """
6857 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_any_args)s, _)).Times(1);
6859 else:
6860 invalid_test += """
6861 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_any_args)s, _)).Times(0);
6863 invalid_test += """
6864 SpecializedSetup<cmds::%(name)s, 0>(false);
6865 %(data_type)s temp[%(data_count)s] = { %(data_value)s, };
6866 cmd.Init(%(all_but_last_args)s, &temp[0]);"""
6867 if func.IsUnsafe():
6868 invalid_test += """
6869 decoder_->set_unsafe_es3_apis_enabled(true);
6870 EXPECT_EQ(error::%(parse_result)s,
6871 ExecuteImmediateCmd(cmd, sizeof(temp)));
6872 decoder_->set_unsafe_es3_apis_enabled(false);
6875 else:
6876 invalid_test += """
6877 EXPECT_EQ(error::%(parse_result)s,
6878 ExecuteImmediateCmd(cmd, sizeof(temp)));
6879 %(gl_error_test)s
6882 self.WriteInvalidUnitTest(func, f, invalid_test, extra, *extras)
6884 def WriteGetDataSizeCode(self, func, f):
6885 """Overrriden from TypeHandler."""
6886 code = """ uint32_t data_size;
6887 if (!ComputeDataSize(1, sizeof(%s), %d, &data_size)) {
6888 return error::kOutOfBounds;
6891 f.write(code % (self.GetArrayType(func), self.GetArrayCount(func)))
6892 if func.IsImmediate():
6893 f.write(" if (data_size > immediate_data_size) {\n")
6894 f.write(" return error::kOutOfBounds;\n")
6895 f.write(" }\n")
6897 def __NeedsToCalcDataCount(self, func):
6898 use_count_func = func.GetInfo('use_count_func')
6899 return use_count_func != None and use_count_func != False
6901 def WriteGLES2Implementation(self, func, f):
6902 """Overrriden from TypeHandler."""
6903 impl_func = func.GetInfo('impl_func')
6904 if (impl_func != None and impl_func != True):
6905 return;
6906 f.write("%s GLES2Implementation::%s(%s) {\n" %
6907 (func.return_type, func.original_name,
6908 func.MakeTypedOriginalArgString("")))
6909 f.write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
6910 func.WriteDestinationInitalizationValidation(f)
6911 self.WriteClientGLCallLog(func, f)
6913 if self.__NeedsToCalcDataCount(func):
6914 f.write(" size_t count = GLES2Util::Calc%sDataCount(%s);\n" %
6915 (func.name, func.GetOriginalArgs()[0].name))
6916 f.write(" DCHECK_LE(count, %du);\n" % self.GetArrayCount(func))
6917 else:
6918 f.write(" size_t count = %d;" % self.GetArrayCount(func))
6919 f.write(" for (size_t ii = 0; ii < count; ++ii)\n")
6920 f.write(' GPU_CLIENT_LOG("value[" << ii << "]: " << %s[ii]);\n' %
6921 func.GetLastOriginalArg().name)
6922 for arg in func.GetOriginalArgs():
6923 arg.WriteClientSideValidationCode(f, func)
6924 f.write(" helper_->%sImmediate(%s);\n" %
6925 (func.name, func.MakeOriginalArgString("")))
6926 f.write(" CheckGLError();\n")
6927 f.write("}\n")
6928 f.write("\n")
6930 def WriteGLES2ImplementationUnitTest(self, func, f):
6931 """Writes the GLES2 Implemention unit test."""
6932 client_test = func.GetInfo('client_test')
6933 if (client_test != None and client_test != True):
6934 return;
6935 code = """
6936 TEST_F(GLES2ImplementationTest, %(name)s) {
6937 %(type)s data[%(count)d] = {0};
6938 struct Cmds {
6939 cmds::%(name)sImmediate cmd;
6940 %(type)s data[%(count)d];
6943 for (int jj = 0; jj < %(count)d; ++jj) {
6944 data[jj] = static_cast<%(type)s>(jj);
6946 Cmds expected;
6947 expected.cmd.Init(%(cmd_args)s, &data[0]);
6948 gl_->%(name)s(%(args)s, &data[0]);
6949 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
6952 cmd_arg_strings = [
6953 arg.GetValidClientSideCmdArg(func) for arg in func.GetCmdArgs()[0:-2]
6955 gl_arg_strings = [
6956 arg.GetValidClientSideArg(func) for arg in func.GetOriginalArgs()[0:-1]
6959 f.write(code % {
6960 'name': func.name,
6961 'type': self.GetArrayType(func),
6962 'count': self.GetArrayCount(func),
6963 'args': ", ".join(gl_arg_strings),
6964 'cmd_args': ", ".join(cmd_arg_strings),
6967 def WriteImmediateCmdComputeSize(self, func, f):
6968 """Overrriden from TypeHandler."""
6969 f.write(" static uint32_t ComputeDataSize() {\n")
6970 f.write(" return static_cast<uint32_t>(\n")
6971 f.write(" sizeof(%s) * %d);\n" %
6972 (self.GetArrayType(func), self.GetArrayCount(func)))
6973 f.write(" }\n")
6974 f.write("\n")
6975 if self.__NeedsToCalcDataCount(func):
6976 f.write(" static uint32_t ComputeEffectiveDataSize(%s %s) {\n" %
6977 (func.GetOriginalArgs()[0].type,
6978 func.GetOriginalArgs()[0].name))
6979 f.write(" return static_cast<uint32_t>(\n")
6980 f.write(" sizeof(%s) * GLES2Util::Calc%sDataCount(%s));\n" %
6981 (self.GetArrayType(func), func.original_name,
6982 func.GetOriginalArgs()[0].name))
6983 f.write(" }\n")
6984 f.write("\n")
6985 f.write(" static uint32_t ComputeSize() {\n")
6986 f.write(" return static_cast<uint32_t>(\n")
6987 f.write(
6988 " sizeof(ValueType) + ComputeDataSize());\n")
6989 f.write(" }\n")
6990 f.write("\n")
6992 def WriteImmediateCmdSetHeader(self, func, f):
6993 """Overrriden from TypeHandler."""
6994 f.write(" void SetHeader() {\n")
6995 f.write(
6996 " header.SetCmdByTotalSize<ValueType>(ComputeSize());\n")
6997 f.write(" }\n")
6998 f.write("\n")
7000 def WriteImmediateCmdInit(self, func, f):
7001 """Overrriden from TypeHandler."""
7002 last_arg = func.GetLastOriginalArg()
7003 f.write(" void Init(%s, %s _%s) {\n" %
7004 (func.MakeTypedCmdArgString("_"),
7005 last_arg.type, last_arg.name))
7006 f.write(" SetHeader();\n")
7007 args = func.GetCmdArgs()
7008 for arg in args:
7009 f.write(" %s = _%s;\n" % (arg.name, arg.name))
7010 f.write(" memcpy(ImmediateDataAddress(this),\n")
7011 if self.__NeedsToCalcDataCount(func):
7012 f.write(" _%s, ComputeEffectiveDataSize(%s));" %
7013 (last_arg.name, func.GetOriginalArgs()[0].name))
7014 f.write("""
7015 DCHECK_GE(ComputeDataSize(), ComputeEffectiveDataSize(%(arg)s));
7016 char* pointer = reinterpret_cast<char*>(ImmediateDataAddress(this)) +
7017 ComputeEffectiveDataSize(%(arg)s);
7018 memset(pointer, 0, ComputeDataSize() - ComputeEffectiveDataSize(%(arg)s));
7019 """ % { 'arg': func.GetOriginalArgs()[0].name, })
7020 else:
7021 f.write(" _%s, ComputeDataSize());\n" % last_arg.name)
7022 f.write(" }\n")
7023 f.write("\n")
7025 def WriteImmediateCmdSet(self, func, f):
7026 """Overrriden from TypeHandler."""
7027 last_arg = func.GetLastOriginalArg()
7028 copy_args = func.MakeCmdArgString("_", False)
7029 f.write(" void* Set(void* cmd%s, %s _%s) {\n" %
7030 (func.MakeTypedCmdArgString("_", True),
7031 last_arg.type, last_arg.name))
7032 f.write(" static_cast<ValueType*>(cmd)->Init(%s, _%s);\n" %
7033 (copy_args, last_arg.name))
7034 f.write(" const uint32_t size = ComputeSize();\n")
7035 f.write(" return NextImmediateCmdAddressTotalSize<ValueType>("
7036 "cmd, size);\n")
7037 f.write(" }\n")
7038 f.write("\n")
7040 def WriteImmediateCmdHelper(self, func, f):
7041 """Overrriden from TypeHandler."""
7042 code = """ void %(name)s(%(typed_args)s) {
7043 const uint32_t size = gles2::cmds::%(name)s::ComputeSize();
7044 gles2::cmds::%(name)s* c =
7045 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
7046 if (c) {
7047 c->Init(%(args)s);
7052 f.write(code % {
7053 "name": func.name,
7054 "typed_args": func.MakeTypedOriginalArgString(""),
7055 "args": func.MakeOriginalArgString(""),
7058 def WriteImmediateFormatTest(self, func, f):
7059 """Overrriden from TypeHandler."""
7060 f.write("TEST_F(GLES2FormatTest, %s) {\n" % func.name)
7061 f.write(" const int kSomeBaseValueToTestWith = 51;\n")
7062 f.write(" static %s data[] = {\n" % self.GetArrayType(func))
7063 for v in range(0, self.GetArrayCount(func)):
7064 f.write(" static_cast<%s>(kSomeBaseValueToTestWith + %d),\n" %
7065 (self.GetArrayType(func), v))
7066 f.write(" };\n")
7067 f.write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
7068 (func.name, func.name))
7069 f.write(" void* next_cmd = cmd.Set(\n")
7070 f.write(" &cmd")
7071 args = func.GetCmdArgs()
7072 for value, arg in enumerate(args):
7073 f.write(",\n static_cast<%s>(%d)" % (arg.type, value + 11))
7074 f.write(",\n data);\n")
7075 args = func.GetCmdArgs()
7076 f.write(" EXPECT_EQ(static_cast<uint32_t>(cmds::%s::kCmdId),\n"
7077 % func.name)
7078 f.write(" cmd.header.command);\n")
7079 f.write(" EXPECT_EQ(sizeof(cmd) +\n")
7080 f.write(" RoundSizeToMultipleOfEntries(sizeof(data)),\n")
7081 f.write(" cmd.header.size * 4u);\n")
7082 for value, arg in enumerate(args):
7083 f.write(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);\n" %
7084 (arg.type, value + 11, arg.name))
7085 f.write(" CheckBytesWrittenMatchesExpectedSize(\n")
7086 f.write(" next_cmd, sizeof(cmd) +\n")
7087 f.write(" RoundSizeToMultipleOfEntries(sizeof(data)));\n")
7088 f.write(" // TODO(gman): Check that data was inserted;\n")
7089 f.write("}\n")
7090 f.write("\n")
7093 class PUTnHandler(ArrayArgTypeHandler):
7094 """Handler for PUTn 'glUniform__v' type functions."""
7096 def WriteServiceUnitTest(self, func, f, *extras):
7097 """Overridden from TypeHandler."""
7098 ArrayArgTypeHandler.WriteServiceUnitTest(self, func, f, *extras)
7100 valid_test = """
7101 TEST_P(%(test_name)s, %(name)sValidArgsCountTooLarge) {
7102 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
7103 SpecializedSetup<cmds::%(name)s, 0>(true);
7104 cmds::%(name)s cmd;
7105 cmd.Init(%(args)s);
7106 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
7107 EXPECT_EQ(GL_NO_ERROR, GetGLError());
7110 gl_arg_strings = []
7111 arg_strings = []
7112 for count, arg in enumerate(func.GetOriginalArgs()):
7113 # hardcoded to match unit tests.
7114 if count == 0:
7115 # the location of the second element of the 2nd uniform.
7116 # defined in GLES2DecoderBase::SetupShaderForUniform
7117 gl_arg_strings.append("3")
7118 arg_strings.append("ProgramManager::MakeFakeLocation(1, 1)")
7119 elif count == 1:
7120 # the number of elements that gl will be called with.
7121 gl_arg_strings.append("3")
7122 # the number of elements requested in the command.
7123 arg_strings.append("5")
7124 else:
7125 gl_arg_strings.append(arg.GetValidGLArg(func))
7126 if not arg.IsConstant():
7127 arg_strings.append(arg.GetValidArg(func))
7128 extra = {
7129 'gl_args': ", ".join(gl_arg_strings),
7130 'args': ", ".join(arg_strings),
7132 self.WriteValidUnitTest(func, f, valid_test, extra, *extras)
7134 def WriteImmediateServiceUnitTest(self, func, f, *extras):
7135 """Overridden from TypeHandler."""
7136 valid_test = """
7137 TEST_P(%(test_name)s, %(name)sValidArgs) {
7138 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
7139 EXPECT_CALL(
7140 *gl_,
7141 %(gl_func_name)s(%(gl_args)s,
7142 reinterpret_cast<%(data_type)s*>(ImmediateDataAddress(&cmd))));
7143 SpecializedSetup<cmds::%(name)s, 0>(true);
7144 %(data_type)s temp[%(data_count)s * 2] = { 0, };
7145 cmd.Init(%(args)s, &temp[0]);"""
7146 if func.IsUnsafe():
7147 valid_test += """
7148 decoder_->set_unsafe_es3_apis_enabled(true);"""
7149 valid_test += """
7150 EXPECT_EQ(error::kNoError,
7151 ExecuteImmediateCmd(cmd, sizeof(temp)));
7152 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
7153 if func.IsUnsafe():
7154 valid_test += """
7155 decoder_->set_unsafe_es3_apis_enabled(false);
7156 EXPECT_EQ(error::kUnknownCommand,
7157 ExecuteImmediateCmd(cmd, sizeof(temp)));"""
7158 valid_test += """
7161 gl_arg_strings = []
7162 gl_any_strings = []
7163 arg_strings = []
7164 for arg in func.GetOriginalArgs()[0:-1]:
7165 gl_arg_strings.append(arg.GetValidGLArg(func))
7166 gl_any_strings.append("_")
7167 if not arg.IsConstant():
7168 arg_strings.append(arg.GetValidArg(func))
7169 extra = {
7170 'data_type': self.GetArrayType(func),
7171 'data_count': self.GetArrayCount(func),
7172 'args': ", ".join(arg_strings),
7173 'gl_args': ", ".join(gl_arg_strings),
7174 'gl_any_args': ", ".join(gl_any_strings),
7176 self.WriteValidUnitTest(func, f, valid_test, extra, *extras)
7178 invalid_test = """
7179 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
7180 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
7181 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_any_args)s, _)).Times(0);
7182 SpecializedSetup<cmds::%(name)s, 0>(false);
7183 %(data_type)s temp[%(data_count)s * 2] = { 0, };
7184 cmd.Init(%(all_but_last_args)s, &temp[0]);
7185 EXPECT_EQ(error::%(parse_result)s,
7186 ExecuteImmediateCmd(cmd, sizeof(temp)));%(gl_error_test)s
7189 self.WriteInvalidUnitTest(func, f, invalid_test, extra, *extras)
7191 def WriteGetDataSizeCode(self, func, f):
7192 """Overrriden from TypeHandler."""
7193 code = """ uint32_t data_size;
7194 if (!ComputeDataSize(count, sizeof(%s), %d, &data_size)) {
7195 return error::kOutOfBounds;
7198 f.write(code % (self.GetArrayType(func), self.GetArrayCount(func)))
7199 if func.IsImmediate():
7200 f.write(" if (data_size > immediate_data_size) {\n")
7201 f.write(" return error::kOutOfBounds;\n")
7202 f.write(" }\n")
7204 def WriteGLES2Implementation(self, func, f):
7205 """Overrriden from TypeHandler."""
7206 f.write("%s GLES2Implementation::%s(%s) {\n" %
7207 (func.return_type, func.original_name,
7208 func.MakeTypedOriginalArgString("")))
7209 f.write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
7210 func.WriteDestinationInitalizationValidation(f)
7211 self.WriteClientGLCallLog(func, f)
7212 last_pointer_name = func.GetLastOriginalPointerArg().name
7213 f.write(""" GPU_CLIENT_LOG_CODE_BLOCK({
7214 for (GLsizei i = 0; i < count; ++i) {
7215 """)
7216 values_str = ' << ", " << '.join(
7217 ["%s[%d + i * %d]" % (
7218 last_pointer_name, ndx, self.GetArrayCount(func)) for ndx in range(
7219 0, self.GetArrayCount(func))])
7220 f.write(' GPU_CLIENT_LOG(" " << i << ": " << %s);\n' % values_str)
7221 f.write(" }\n });\n")
7222 for arg in func.GetOriginalArgs():
7223 arg.WriteClientSideValidationCode(f, func)
7224 f.write(" helper_->%sImmediate(%s);\n" %
7225 (func.name, func.MakeInitString("")))
7226 f.write(" CheckGLError();\n")
7227 f.write("}\n")
7228 f.write("\n")
7230 def WriteGLES2ImplementationUnitTest(self, func, f):
7231 """Writes the GLES2 Implemention unit test."""
7232 code = """
7233 TEST_F(GLES2ImplementationTest, %(name)s) {
7234 %(type)s data[%(count_param)d][%(count)d] = {{0}};
7235 struct Cmds {
7236 cmds::%(name)sImmediate cmd;
7237 %(type)s data[%(count_param)d][%(count)d];
7240 Cmds expected;
7241 for (int ii = 0; ii < %(count_param)d; ++ii) {
7242 for (int jj = 0; jj < %(count)d; ++jj) {
7243 data[ii][jj] = static_cast<%(type)s>(ii * %(count)d + jj);
7246 expected.cmd.Init(%(cmd_args)s);
7247 gl_->%(name)s(%(args)s);
7248 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
7251 cmd_arg_strings = []
7252 for arg in func.GetCmdArgs():
7253 if arg.name.endswith("_shm_id"):
7254 cmd_arg_strings.append("&data[0][0]")
7255 elif arg.name.endswith("_shm_offset"):
7256 continue
7257 else:
7258 cmd_arg_strings.append(arg.GetValidClientSideCmdArg(func))
7259 gl_arg_strings = []
7260 count_param = 0
7261 for arg in func.GetOriginalArgs():
7262 if arg.IsPointer():
7263 valid_value = "&data[0][0]"
7264 else:
7265 valid_value = arg.GetValidClientSideArg(func)
7266 gl_arg_strings.append(valid_value)
7267 if arg.name == "count":
7268 count_param = int(valid_value)
7269 f.write(code % {
7270 'name': func.name,
7271 'type': self.GetArrayType(func),
7272 'count': self.GetArrayCount(func),
7273 'args': ", ".join(gl_arg_strings),
7274 'cmd_args': ", ".join(cmd_arg_strings),
7275 'count_param': count_param,
7278 # Test constants for invalid values, as they are not tested by the
7279 # service.
7280 constants = [
7281 arg for arg in func.GetOriginalArgs()[0:-1] if arg.IsConstant()
7283 if not constants:
7284 return
7286 code = """
7287 TEST_F(GLES2ImplementationTest, %(name)sInvalidConstantArg%(invalid_index)d) {
7288 %(type)s data[%(count_param)d][%(count)d] = {{0}};
7289 for (int ii = 0; ii < %(count_param)d; ++ii) {
7290 for (int jj = 0; jj < %(count)d; ++jj) {
7291 data[ii][jj] = static_cast<%(type)s>(ii * %(count)d + jj);
7294 gl_->%(name)s(%(args)s);
7295 EXPECT_TRUE(NoCommandsWritten());
7296 EXPECT_EQ(%(gl_error)s, CheckError());
7299 for invalid_arg in constants:
7300 gl_arg_strings = []
7301 invalid = invalid_arg.GetInvalidArg(func)
7302 for arg in func.GetOriginalArgs():
7303 if arg is invalid_arg:
7304 gl_arg_strings.append(invalid[0])
7305 elif arg.IsPointer():
7306 gl_arg_strings.append("&data[0][0]")
7307 else:
7308 valid_value = arg.GetValidClientSideArg(func)
7309 gl_arg_strings.append(valid_value)
7310 if arg.name == "count":
7311 count_param = int(valid_value)
7313 f.write(code % {
7314 'name': func.name,
7315 'invalid_index': func.GetOriginalArgs().index(invalid_arg),
7316 'type': self.GetArrayType(func),
7317 'count': self.GetArrayCount(func),
7318 'args': ", ".join(gl_arg_strings),
7319 'gl_error': invalid[2],
7320 'count_param': count_param,
7324 def WriteImmediateCmdComputeSize(self, func, f):
7325 """Overrriden from TypeHandler."""
7326 f.write(" static uint32_t ComputeDataSize(GLsizei count) {\n")
7327 f.write(" return static_cast<uint32_t>(\n")
7328 f.write(" sizeof(%s) * %d * count); // NOLINT\n" %
7329 (self.GetArrayType(func), self.GetArrayCount(func)))
7330 f.write(" }\n")
7331 f.write("\n")
7332 f.write(" static uint32_t ComputeSize(GLsizei count) {\n")
7333 f.write(" return static_cast<uint32_t>(\n")
7334 f.write(
7335 " sizeof(ValueType) + ComputeDataSize(count)); // NOLINT\n")
7336 f.write(" }\n")
7337 f.write("\n")
7339 def WriteImmediateCmdSetHeader(self, func, f):
7340 """Overrriden from TypeHandler."""
7341 f.write(" void SetHeader(GLsizei count) {\n")
7342 f.write(
7343 " header.SetCmdByTotalSize<ValueType>(ComputeSize(count));\n")
7344 f.write(" }\n")
7345 f.write("\n")
7347 def WriteImmediateCmdInit(self, func, f):
7348 """Overrriden from TypeHandler."""
7349 f.write(" void Init(%s) {\n" %
7350 func.MakeTypedInitString("_"))
7351 f.write(" SetHeader(_count);\n")
7352 args = func.GetCmdArgs()
7353 for arg in args:
7354 f.write(" %s = _%s;\n" % (arg.name, arg.name))
7355 f.write(" memcpy(ImmediateDataAddress(this),\n")
7356 pointer_arg = func.GetLastOriginalPointerArg()
7357 f.write(" _%s, ComputeDataSize(_count));\n" % pointer_arg.name)
7358 f.write(" }\n")
7359 f.write("\n")
7361 def WriteImmediateCmdSet(self, func, f):
7362 """Overrriden from TypeHandler."""
7363 f.write(" void* Set(void* cmd%s) {\n" %
7364 func.MakeTypedInitString("_", True))
7365 f.write(" static_cast<ValueType*>(cmd)->Init(%s);\n" %
7366 func.MakeInitString("_"))
7367 f.write(" const uint32_t size = ComputeSize(_count);\n")
7368 f.write(" return NextImmediateCmdAddressTotalSize<ValueType>("
7369 "cmd, size);\n")
7370 f.write(" }\n")
7371 f.write("\n")
7373 def WriteImmediateCmdHelper(self, func, f):
7374 """Overrriden from TypeHandler."""
7375 code = """ void %(name)s(%(typed_args)s) {
7376 const uint32_t size = gles2::cmds::%(name)s::ComputeSize(count);
7377 gles2::cmds::%(name)s* c =
7378 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
7379 if (c) {
7380 c->Init(%(args)s);
7385 f.write(code % {
7386 "name": func.name,
7387 "typed_args": func.MakeTypedInitString(""),
7388 "args": func.MakeInitString("")
7391 def WriteImmediateFormatTest(self, func, f):
7392 """Overrriden from TypeHandler."""
7393 args = func.GetOriginalArgs()
7394 count_param = 0
7395 for arg in args:
7396 if arg.name == "count":
7397 count_param = int(arg.GetValidClientSideCmdArg(func))
7398 f.write("TEST_F(GLES2FormatTest, %s) {\n" % func.name)
7399 f.write(" const int kSomeBaseValueToTestWith = 51;\n")
7400 f.write(" static %s data[] = {\n" % self.GetArrayType(func))
7401 for v in range(0, self.GetArrayCount(func) * count_param):
7402 f.write(" static_cast<%s>(kSomeBaseValueToTestWith + %d),\n" %
7403 (self.GetArrayType(func), v))
7404 f.write(" };\n")
7405 f.write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
7406 (func.name, func.name))
7407 f.write(" const GLsizei kNumElements = %d;\n" % count_param)
7408 f.write(" const size_t kExpectedCmdSize =\n")
7409 f.write(" sizeof(cmd) + kNumElements * sizeof(%s) * %d;\n" %
7410 (self.GetArrayType(func), self.GetArrayCount(func)))
7411 f.write(" void* next_cmd = cmd.Set(\n")
7412 f.write(" &cmd")
7413 for value, arg in enumerate(args):
7414 if arg.IsPointer():
7415 f.write(",\n data")
7416 elif arg.IsConstant():
7417 continue
7418 else:
7419 f.write(",\n static_cast<%s>(%d)" % (arg.type, value + 1))
7420 f.write(");\n")
7421 f.write(" EXPECT_EQ(static_cast<uint32_t>(cmds::%s::kCmdId),\n" %
7422 func.name)
7423 f.write(" cmd.header.command);\n")
7424 f.write(" EXPECT_EQ(kExpectedCmdSize, cmd.header.size * 4u);\n")
7425 for value, arg in enumerate(args):
7426 if arg.IsPointer() or arg.IsConstant():
7427 continue
7428 f.write(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);\n" %
7429 (arg.type, value + 1, arg.name))
7430 f.write(" CheckBytesWrittenMatchesExpectedSize(\n")
7431 f.write(" next_cmd, sizeof(cmd) +\n")
7432 f.write(" RoundSizeToMultipleOfEntries(sizeof(data)));\n")
7433 f.write(" // TODO(gman): Check that data was inserted;\n")
7434 f.write("}\n")
7435 f.write("\n")
7437 class PUTSTRHandler(ArrayArgTypeHandler):
7438 """Handler for functions that pass a string array."""
7440 def __GetDataArg(self, func):
7441 """Return the argument that points to the 2D char arrays"""
7442 for arg in func.GetOriginalArgs():
7443 if arg.IsPointer2D():
7444 return arg
7445 return None
7447 def __GetLengthArg(self, func):
7448 """Return the argument that holds length for each char array"""
7449 for arg in func.GetOriginalArgs():
7450 if arg.IsPointer() and not arg.IsPointer2D():
7451 return arg
7452 return None
7454 def WriteGLES2Implementation(self, func, f):
7455 """Overrriden from TypeHandler."""
7456 f.write("%s GLES2Implementation::%s(%s) {\n" %
7457 (func.return_type, func.original_name,
7458 func.MakeTypedOriginalArgString("")))
7459 f.write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
7460 func.WriteDestinationInitalizationValidation(f)
7461 self.WriteClientGLCallLog(func, f)
7462 data_arg = self.__GetDataArg(func)
7463 length_arg = self.__GetLengthArg(func)
7464 log_code_block = """ GPU_CLIENT_LOG_CODE_BLOCK({
7465 for (GLsizei ii = 0; ii < count; ++ii) {
7466 if (%(data)s[ii]) {"""
7467 if length_arg == None:
7468 log_code_block += """
7469 GPU_CLIENT_LOG(" " << ii << ": ---\\n" << %(data)s[ii] << "\\n---");"""
7470 else:
7471 log_code_block += """
7472 if (%(length)s && %(length)s[ii] >= 0) {
7473 const std::string my_str(%(data)s[ii], %(length)s[ii]);
7474 GPU_CLIENT_LOG(" " << ii << ": ---\\n" << my_str << "\\n---");
7475 } else {
7476 GPU_CLIENT_LOG(" " << ii << ": ---\\n" << %(data)s[ii] << "\\n---");
7477 }"""
7478 log_code_block += """
7479 } else {
7480 GPU_CLIENT_LOG(" " << ii << ": NULL");
7485 f.write(log_code_block % {
7486 'data': data_arg.name,
7487 'length': length_arg.name if not length_arg == None else ''
7489 for arg in func.GetOriginalArgs():
7490 arg.WriteClientSideValidationCode(f, func)
7492 bucket_args = []
7493 for arg in func.GetOriginalArgs():
7494 if arg.name == 'count' or arg == self.__GetLengthArg(func):
7495 continue
7496 if arg == self.__GetDataArg(func):
7497 bucket_args.append('kResultBucketId')
7498 else:
7499 bucket_args.append(arg.name)
7500 code_block = """
7501 if (!PackStringsToBucket(count, %(data)s, %(length)s, "gl%(func_name)s")) {
7502 return;
7504 helper_->%(func_name)sBucket(%(bucket_args)s);
7505 helper_->SetBucketSize(kResultBucketId, 0);
7506 CheckGLError();
7510 f.write(code_block % {
7511 'data': data_arg.name,
7512 'length': length_arg.name if not length_arg == None else 'NULL',
7513 'func_name': func.name,
7514 'bucket_args': ', '.join(bucket_args),
7517 def WriteGLES2ImplementationUnitTest(self, func, f):
7518 """Overrriden from TypeHandler."""
7519 code = """
7520 TEST_F(GLES2ImplementationTest, %(name)s) {
7521 const uint32 kBucketId = GLES2Implementation::kResultBucketId;
7522 const char* kString1 = "happy";
7523 const char* kString2 = "ending";
7524 const size_t kString1Size = ::strlen(kString1) + 1;
7525 const size_t kString2Size = ::strlen(kString2) + 1;
7526 const size_t kHeaderSize = sizeof(GLint) * 3;
7527 const size_t kSourceSize = kHeaderSize + kString1Size + kString2Size;
7528 const size_t kPaddedHeaderSize =
7529 transfer_buffer_->RoundToAlignment(kHeaderSize);
7530 const size_t kPaddedString1Size =
7531 transfer_buffer_->RoundToAlignment(kString1Size);
7532 const size_t kPaddedString2Size =
7533 transfer_buffer_->RoundToAlignment(kString2Size);
7534 struct Cmds {
7535 cmd::SetBucketSize set_bucket_size;
7536 cmd::SetBucketData set_bucket_header;
7537 cmd::SetToken set_token1;
7538 cmd::SetBucketData set_bucket_data1;
7539 cmd::SetToken set_token2;
7540 cmd::SetBucketData set_bucket_data2;
7541 cmd::SetToken set_token3;
7542 cmds::%(name)sBucket cmd_bucket;
7543 cmd::SetBucketSize clear_bucket_size;
7546 ExpectedMemoryInfo mem0 = GetExpectedMemory(kPaddedHeaderSize);
7547 ExpectedMemoryInfo mem1 = GetExpectedMemory(kPaddedString1Size);
7548 ExpectedMemoryInfo mem2 = GetExpectedMemory(kPaddedString2Size);
7550 Cmds expected;
7551 expected.set_bucket_size.Init(kBucketId, kSourceSize);
7552 expected.set_bucket_header.Init(
7553 kBucketId, 0, kHeaderSize, mem0.id, mem0.offset);
7554 expected.set_token1.Init(GetNextToken());
7555 expected.set_bucket_data1.Init(
7556 kBucketId, kHeaderSize, kString1Size, mem1.id, mem1.offset);
7557 expected.set_token2.Init(GetNextToken());
7558 expected.set_bucket_data2.Init(
7559 kBucketId, kHeaderSize + kString1Size, kString2Size, mem2.id,
7560 mem2.offset);
7561 expected.set_token3.Init(GetNextToken());
7562 expected.cmd_bucket.Init(%(bucket_args)s);
7563 expected.clear_bucket_size.Init(kBucketId, 0);
7564 const char* kStrings[] = { kString1, kString2 };
7565 gl_->%(name)s(%(gl_args)s);
7566 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
7569 gl_args = []
7570 bucket_args = []
7571 for arg in func.GetOriginalArgs():
7572 if arg == self.__GetDataArg(func):
7573 gl_args.append('kStrings')
7574 bucket_args.append('kBucketId')
7575 elif arg == self.__GetLengthArg(func):
7576 gl_args.append('NULL')
7577 elif arg.name == 'count':
7578 gl_args.append('2')
7579 else:
7580 gl_args.append(arg.GetValidClientSideArg(func))
7581 bucket_args.append(arg.GetValidClientSideArg(func))
7582 f.write(code % {
7583 'name': func.name,
7584 'gl_args': ", ".join(gl_args),
7585 'bucket_args': ", ".join(bucket_args),
7588 if self.__GetLengthArg(func) == None:
7589 return
7590 code = """
7591 TEST_F(GLES2ImplementationTest, %(name)sWithLength) {
7592 const uint32 kBucketId = GLES2Implementation::kResultBucketId;
7593 const char* kString = "foobar******";
7594 const size_t kStringSize = 6; // We only need "foobar".
7595 const size_t kHeaderSize = sizeof(GLint) * 2;
7596 const size_t kSourceSize = kHeaderSize + kStringSize + 1;
7597 const size_t kPaddedHeaderSize =
7598 transfer_buffer_->RoundToAlignment(kHeaderSize);
7599 const size_t kPaddedStringSize =
7600 transfer_buffer_->RoundToAlignment(kStringSize + 1);
7601 struct Cmds {
7602 cmd::SetBucketSize set_bucket_size;
7603 cmd::SetBucketData set_bucket_header;
7604 cmd::SetToken set_token1;
7605 cmd::SetBucketData set_bucket_data;
7606 cmd::SetToken set_token2;
7607 cmds::ShaderSourceBucket shader_source_bucket;
7608 cmd::SetBucketSize clear_bucket_size;
7611 ExpectedMemoryInfo mem0 = GetExpectedMemory(kPaddedHeaderSize);
7612 ExpectedMemoryInfo mem1 = GetExpectedMemory(kPaddedStringSize);
7614 Cmds expected;
7615 expected.set_bucket_size.Init(kBucketId, kSourceSize);
7616 expected.set_bucket_header.Init(
7617 kBucketId, 0, kHeaderSize, mem0.id, mem0.offset);
7618 expected.set_token1.Init(GetNextToken());
7619 expected.set_bucket_data.Init(
7620 kBucketId, kHeaderSize, kStringSize + 1, mem1.id, mem1.offset);
7621 expected.set_token2.Init(GetNextToken());
7622 expected.shader_source_bucket.Init(%(bucket_args)s);
7623 expected.clear_bucket_size.Init(kBucketId, 0);
7624 const char* kStrings[] = { kString };
7625 const GLint kLength[] = { kStringSize };
7626 gl_->%(name)s(%(gl_args)s);
7627 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
7630 gl_args = []
7631 for arg in func.GetOriginalArgs():
7632 if arg == self.__GetDataArg(func):
7633 gl_args.append('kStrings')
7634 elif arg == self.__GetLengthArg(func):
7635 gl_args.append('kLength')
7636 elif arg.name == 'count':
7637 gl_args.append('1')
7638 else:
7639 gl_args.append(arg.GetValidClientSideArg(func))
7640 f.write(code % {
7641 'name': func.name,
7642 'gl_args': ", ".join(gl_args),
7643 'bucket_args': ", ".join(bucket_args),
7646 def WriteBucketServiceUnitTest(self, func, f, *extras):
7647 """Overrriden from TypeHandler."""
7648 cmd_args = []
7649 cmd_args_with_invalid_id = []
7650 gl_args = []
7651 for index, arg in enumerate(func.GetOriginalArgs()):
7652 if arg == self.__GetLengthArg(func):
7653 gl_args.append('_')
7654 elif arg.name == 'count':
7655 gl_args.append('1')
7656 elif arg == self.__GetDataArg(func):
7657 cmd_args.append('kBucketId')
7658 cmd_args_with_invalid_id.append('kBucketId')
7659 gl_args.append('_')
7660 elif index == 0: # Resource ID arg
7661 cmd_args.append(arg.GetValidArg(func))
7662 cmd_args_with_invalid_id.append('kInvalidClientId')
7663 gl_args.append(arg.GetValidGLArg(func))
7664 else:
7665 cmd_args.append(arg.GetValidArg(func))
7666 cmd_args_with_invalid_id.append(arg.GetValidArg(func))
7667 gl_args.append(arg.GetValidGLArg(func))
7669 test = """
7670 TEST_P(%(test_name)s, %(name)sValidArgs) {
7671 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
7672 const uint32 kBucketId = 123;
7673 const char kSource0[] = "hello";
7674 const char* kSource[] = { kSource0 };
7675 const char kValidStrEnd = 0;
7676 SetBucketAsCStrings(kBucketId, 1, kSource, 1, kValidStrEnd);
7677 cmds::%(name)s cmd;
7678 cmd.Init(%(cmd_args)s);
7679 decoder_->set_unsafe_es3_apis_enabled(true);
7680 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));"""
7681 if func.IsUnsafe():
7682 test += """
7683 decoder_->set_unsafe_es3_apis_enabled(false);
7684 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));
7686 test += """
7689 self.WriteValidUnitTest(func, f, test, {
7690 'cmd_args': ", ".join(cmd_args),
7691 'gl_args': ", ".join(gl_args),
7692 }, *extras)
7694 test = """
7695 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
7696 const uint32 kBucketId = 123;
7697 const char kSource0[] = "hello";
7698 const char* kSource[] = { kSource0 };
7699 const char kValidStrEnd = 0;
7700 decoder_->set_unsafe_es3_apis_enabled(true);
7701 cmds::%(name)s cmd;
7702 // Test no bucket.
7703 cmd.Init(%(cmd_args)s);
7704 EXPECT_NE(error::kNoError, ExecuteCmd(cmd));
7705 // Test invalid client.
7706 SetBucketAsCStrings(kBucketId, 1, kSource, 1, kValidStrEnd);
7707 cmd.Init(%(cmd_args_with_invalid_id)s);
7708 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
7709 EXPECT_EQ(GL_INVALID_VALUE, GetGLError());
7712 self.WriteValidUnitTest(func, f, test, {
7713 'cmd_args': ", ".join(cmd_args),
7714 'cmd_args_with_invalid_id': ", ".join(cmd_args_with_invalid_id),
7715 }, *extras)
7717 test = """
7718 TEST_P(%(test_name)s, %(name)sInvalidHeader) {
7719 const uint32 kBucketId = 123;
7720 const char kSource0[] = "hello";
7721 const char* kSource[] = { kSource0 };
7722 const char kValidStrEnd = 0;
7723 const GLsizei kCount = static_cast<GLsizei>(arraysize(kSource));
7724 const GLsizei kTests[] = {
7725 kCount + 1,
7727 std::numeric_limits<GLsizei>::max(),
7730 decoder_->set_unsafe_es3_apis_enabled(true);
7731 for (size_t ii = 0; ii < arraysize(kTests); ++ii) {
7732 SetBucketAsCStrings(kBucketId, 1, kSource, kTests[ii], kValidStrEnd);
7733 cmds::%(name)s cmd;
7734 cmd.Init(%(cmd_args)s);
7735 EXPECT_EQ(error::kInvalidArguments, ExecuteCmd(cmd));
7739 self.WriteValidUnitTest(func, f, test, {
7740 'cmd_args': ", ".join(cmd_args),
7741 }, *extras)
7743 test = """
7744 TEST_P(%(test_name)s, %(name)sInvalidStringEnding) {
7745 const uint32 kBucketId = 123;
7746 const char kSource0[] = "hello";
7747 const char* kSource[] = { kSource0 };
7748 const char kInvalidStrEnd = '*';
7749 SetBucketAsCStrings(kBucketId, 1, kSource, 1, kInvalidStrEnd);
7750 cmds::%(name)s cmd;
7751 cmd.Init(%(cmd_args)s);
7752 decoder_->set_unsafe_es3_apis_enabled(true);
7753 EXPECT_EQ(error::kInvalidArguments, ExecuteCmd(cmd));
7756 self.WriteValidUnitTest(func, f, test, {
7757 'cmd_args': ", ".join(cmd_args),
7758 }, *extras)
7761 class PUTXnHandler(ArrayArgTypeHandler):
7762 """Handler for glUniform?f functions."""
7764 def WriteHandlerImplementation(self, func, f):
7765 """Overrriden from TypeHandler."""
7766 code = """ %(type)s temp[%(count)s] = { %(values)s};"""
7767 if func.IsUnsafe():
7768 code += """
7769 gl%(name)sv(%(location)s, 1, &temp[0]);
7771 else:
7772 code += """
7773 Do%(name)sv(%(location)s, 1, &temp[0]);
7775 values = ""
7776 args = func.GetOriginalArgs()
7777 count = int(self.GetArrayCount(func))
7778 num_args = len(args)
7779 for ii in range(count):
7780 values += "%s, " % args[len(args) - count + ii].name
7782 f.write(code % {
7783 'name': func.name,
7784 'count': self.GetArrayCount(func),
7785 'type': self.GetArrayType(func),
7786 'location': args[0].name,
7787 'args': func.MakeOriginalArgString(""),
7788 'values': values,
7791 def WriteServiceUnitTest(self, func, f, *extras):
7792 """Overrriden from TypeHandler."""
7793 valid_test = """
7794 TEST_P(%(test_name)s, %(name)sValidArgs) {
7795 EXPECT_CALL(*gl_, %(name)sv(%(local_args)s));
7796 SpecializedSetup<cmds::%(name)s, 0>(true);
7797 cmds::%(name)s cmd;
7798 cmd.Init(%(args)s);"""
7799 if func.IsUnsafe():
7800 valid_test += """
7801 decoder_->set_unsafe_es3_apis_enabled(true);"""
7802 valid_test += """
7803 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
7804 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
7805 if func.IsUnsafe():
7806 valid_test += """
7807 decoder_->set_unsafe_es3_apis_enabled(false);
7808 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));"""
7809 valid_test += """
7812 args = func.GetOriginalArgs()
7813 local_args = "%s, 1, _" % args[0].GetValidGLArg(func)
7814 self.WriteValidUnitTest(func, f, valid_test, {
7815 'name': func.name,
7816 'count': self.GetArrayCount(func),
7817 'local_args': local_args,
7818 }, *extras)
7820 invalid_test = """
7821 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
7822 EXPECT_CALL(*gl_, %(name)sv(_, _, _).Times(0);
7823 SpecializedSetup<cmds::%(name)s, 0>(false);
7824 cmds::%(name)s cmd;
7825 cmd.Init(%(args)s);
7826 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
7829 self.WriteInvalidUnitTest(func, f, invalid_test, {
7830 'name': func.GetInfo('name'),
7831 'count': self.GetArrayCount(func),
7835 class GLcharHandler(CustomHandler):
7836 """Handler for functions that pass a single string ."""
7838 def WriteImmediateCmdComputeSize(self, func, f):
7839 """Overrriden from TypeHandler."""
7840 f.write(" static uint32_t ComputeSize(uint32_t data_size) {\n")
7841 f.write(" return static_cast<uint32_t>(\n")
7842 f.write(" sizeof(ValueType) + data_size); // NOLINT\n")
7843 f.write(" }\n")
7845 def WriteImmediateCmdSetHeader(self, func, f):
7846 """Overrriden from TypeHandler."""
7847 code = """
7848 void SetHeader(uint32_t data_size) {
7849 header.SetCmdBySize<ValueType>(data_size);
7852 f.write(code)
7854 def WriteImmediateCmdInit(self, func, f):
7855 """Overrriden from TypeHandler."""
7856 last_arg = func.GetLastOriginalArg()
7857 args = func.GetCmdArgs()
7858 set_code = []
7859 for arg in args:
7860 set_code.append(" %s = _%s;" % (arg.name, arg.name))
7861 code = """
7862 void Init(%(typed_args)s, uint32_t _data_size) {
7863 SetHeader(_data_size);
7864 %(set_code)s
7865 memcpy(ImmediateDataAddress(this), _%(last_arg)s, _data_size);
7869 f.write(code % {
7870 "typed_args": func.MakeTypedArgString("_"),
7871 "set_code": "\n".join(set_code),
7872 "last_arg": last_arg.name
7875 def WriteImmediateCmdSet(self, func, f):
7876 """Overrriden from TypeHandler."""
7877 last_arg = func.GetLastOriginalArg()
7878 f.write(" void* Set(void* cmd%s, uint32_t _data_size) {\n" %
7879 func.MakeTypedCmdArgString("_", True))
7880 f.write(" static_cast<ValueType*>(cmd)->Init(%s, _data_size);\n" %
7881 func.MakeCmdArgString("_"))
7882 f.write(" return NextImmediateCmdAddress<ValueType>("
7883 "cmd, _data_size);\n")
7884 f.write(" }\n")
7885 f.write("\n")
7887 def WriteImmediateCmdHelper(self, func, f):
7888 """Overrriden from TypeHandler."""
7889 code = """ void %(name)s(%(typed_args)s) {
7890 const uint32_t data_size = strlen(name);
7891 gles2::cmds::%(name)s* c =
7892 GetImmediateCmdSpace<gles2::cmds::%(name)s>(data_size);
7893 if (c) {
7894 c->Init(%(args)s, data_size);
7899 f.write(code % {
7900 "name": func.name,
7901 "typed_args": func.MakeTypedOriginalArgString(""),
7902 "args": func.MakeOriginalArgString(""),
7906 def WriteImmediateFormatTest(self, func, f):
7907 """Overrriden from TypeHandler."""
7908 init_code = []
7909 check_code = []
7910 all_but_last_arg = func.GetCmdArgs()[:-1]
7911 for value, arg in enumerate(all_but_last_arg):
7912 init_code.append(" static_cast<%s>(%d)," % (arg.type, value + 11))
7913 for value, arg in enumerate(all_but_last_arg):
7914 check_code.append(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);" %
7915 (arg.type, value + 11, arg.name))
7916 code = """
7917 TEST_F(GLES2FormatTest, %(func_name)s) {
7918 cmds::%(func_name)s& cmd = *GetBufferAs<cmds::%(func_name)s>();
7919 static const char* const test_str = \"test string\";
7920 void* next_cmd = cmd.Set(
7921 &cmd,
7922 %(init_code)s
7923 test_str,
7924 strlen(test_str));
7925 EXPECT_EQ(static_cast<uint32_t>(cmds::%(func_name)s::kCmdId),
7926 cmd.header.command);
7927 EXPECT_EQ(sizeof(cmd) +
7928 RoundSizeToMultipleOfEntries(strlen(test_str)),
7929 cmd.header.size * 4u);
7930 EXPECT_EQ(static_cast<char*>(next_cmd),
7931 reinterpret_cast<char*>(&cmd) + sizeof(cmd) +
7932 RoundSizeToMultipleOfEntries(strlen(test_str)));
7933 %(check_code)s
7934 EXPECT_EQ(static_cast<uint32_t>(strlen(test_str)), cmd.data_size);
7935 EXPECT_EQ(0, memcmp(test_str, ImmediateDataAddress(&cmd), strlen(test_str)));
7936 CheckBytesWritten(
7937 next_cmd,
7938 sizeof(cmd) + RoundSizeToMultipleOfEntries(strlen(test_str)),
7939 sizeof(cmd) + strlen(test_str));
7943 f.write(code % {
7944 'func_name': func.name,
7945 'init_code': "\n".join(init_code),
7946 'check_code': "\n".join(check_code),
7950 class GLcharNHandler(CustomHandler):
7951 """Handler for functions that pass a single string with an optional len."""
7953 def InitFunction(self, func):
7954 """Overrriden from TypeHandler."""
7955 func.cmd_args = []
7956 func.AddCmdArg(Argument('bucket_id', 'GLuint'))
7958 def NeedsDataTransferFunction(self, func):
7959 """Overriden from TypeHandler."""
7960 return False
7962 def WriteServiceImplementation(self, func, f):
7963 """Overrriden from TypeHandler."""
7964 self.WriteServiceHandlerFunctionHeader(func, f)
7965 f.write("""
7966 GLuint bucket_id = static_cast<GLuint>(c.%(bucket_id)s);
7967 Bucket* bucket = GetBucket(bucket_id);
7968 if (!bucket || bucket->size() == 0) {
7969 return error::kInvalidArguments;
7971 std::string str;
7972 if (!bucket->GetAsString(&str)) {
7973 return error::kInvalidArguments;
7975 %(gl_func_name)s(0, str.c_str());
7976 return error::kNoError;
7979 """ % {
7980 'name': func.name,
7981 'gl_func_name': func.GetGLFunctionName(),
7982 'bucket_id': func.cmd_args[0].name,
7986 class IsHandler(TypeHandler):
7987 """Handler for glIs____ type and glGetError functions."""
7989 def InitFunction(self, func):
7990 """Overrriden from TypeHandler."""
7991 func.AddCmdArg(Argument("result_shm_id", 'uint32_t'))
7992 func.AddCmdArg(Argument("result_shm_offset", 'uint32_t'))
7993 if func.GetInfo('result') == None:
7994 func.AddInfo('result', ['uint32_t'])
7996 def WriteServiceUnitTest(self, func, f, *extras):
7997 """Overrriden from TypeHandler."""
7998 valid_test = """
7999 TEST_P(%(test_name)s, %(name)sValidArgs) {
8000 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
8001 SpecializedSetup<cmds::%(name)s, 0>(true);
8002 cmds::%(name)s cmd;
8003 cmd.Init(%(args)s%(comma)sshared_memory_id_, shared_memory_offset_);"""
8004 if func.IsUnsafe():
8005 valid_test += """
8006 decoder_->set_unsafe_es3_apis_enabled(true);"""
8007 valid_test += """
8008 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
8009 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
8010 if func.IsUnsafe():
8011 valid_test += """
8012 decoder_->set_unsafe_es3_apis_enabled(false);
8013 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));"""
8014 valid_test += """
8017 comma = ""
8018 if len(func.GetOriginalArgs()):
8019 comma =", "
8020 self.WriteValidUnitTest(func, f, valid_test, {
8021 'comma': comma,
8022 }, *extras)
8024 invalid_test = """
8025 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
8026 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
8027 SpecializedSetup<cmds::%(name)s, 0>(false);
8028 cmds::%(name)s cmd;
8029 cmd.Init(%(args)s%(comma)sshared_memory_id_, shared_memory_offset_);
8030 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
8033 self.WriteInvalidUnitTest(func, f, invalid_test, {
8034 'comma': comma,
8035 }, *extras)
8037 invalid_test = """
8038 TEST_P(%(test_name)s, %(name)sInvalidArgsBadSharedMemoryId) {
8039 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
8040 SpecializedSetup<cmds::%(name)s, 0>(false);"""
8041 if func.IsUnsafe():
8042 invalid_test += """
8043 decoder_->set_unsafe_es3_apis_enabled(true);"""
8044 invalid_test += """
8045 cmds::%(name)s cmd;
8046 cmd.Init(%(args)s%(comma)skInvalidSharedMemoryId, shared_memory_offset_);
8047 EXPECT_EQ(error::kOutOfBounds, ExecuteCmd(cmd));
8048 cmd.Init(%(args)s%(comma)sshared_memory_id_, kInvalidSharedMemoryOffset);
8049 EXPECT_EQ(error::kOutOfBounds, ExecuteCmd(cmd));"""
8050 if func.IsUnsafe():
8051 invalid_test += """
8052 decoder_->set_unsafe_es3_apis_enabled(true);"""
8053 invalid_test += """
8056 self.WriteValidUnitTest(func, f, invalid_test, {
8057 'comma': comma,
8058 }, *extras)
8060 def WriteServiceImplementation(self, func, f):
8061 """Overrriden from TypeHandler."""
8062 self.WriteServiceHandlerFunctionHeader(func, f)
8063 self.WriteHandlerExtensionCheck(func, f)
8064 args = func.GetOriginalArgs()
8065 for arg in args:
8066 arg.WriteGetCode(f)
8068 code = """ typedef cmds::%(func_name)s::Result Result;
8069 Result* result_dst = GetSharedMemoryAs<Result*>(
8070 c.result_shm_id, c.result_shm_offset, sizeof(*result_dst));
8071 if (!result_dst) {
8072 return error::kOutOfBounds;
8075 f.write(code % {'func_name': func.name})
8076 func.WriteHandlerValidation(f)
8077 if func.IsUnsafe():
8078 assert func.GetInfo('id_mapping')
8079 assert len(func.GetInfo('id_mapping')) == 1
8080 assert len(args) == 1
8081 id_type = func.GetInfo('id_mapping')[0]
8082 f.write(" %s service_%s = 0;\n" % (args[0].type, id_type.lower()))
8083 f.write(" *result_dst = group_->Get%sServiceId(%s, &service_%s);\n" %
8084 (id_type, id_type.lower(), id_type.lower()))
8085 else:
8086 f.write(" *result_dst = %s(%s);\n" %
8087 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
8088 f.write(" return error::kNoError;\n")
8089 f.write("}\n")
8090 f.write("\n")
8092 def WriteGLES2Implementation(self, func, f):
8093 """Overrriden from TypeHandler."""
8094 impl_func = func.GetInfo('impl_func')
8095 if impl_func == None or impl_func == True:
8096 error_value = func.GetInfo("error_value") or "GL_FALSE"
8097 f.write("%s GLES2Implementation::%s(%s) {\n" %
8098 (func.return_type, func.original_name,
8099 func.MakeTypedOriginalArgString("")))
8100 f.write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
8101 self.WriteTraceEvent(func, f)
8102 func.WriteDestinationInitalizationValidation(f)
8103 self.WriteClientGLCallLog(func, f)
8104 f.write(" typedef cmds::%s::Result Result;\n" % func.name)
8105 f.write(" Result* result = GetResultAs<Result*>();\n")
8106 f.write(" if (!result) {\n")
8107 f.write(" return %s;\n" % error_value)
8108 f.write(" }\n")
8109 f.write(" *result = 0;\n")
8110 assert len(func.GetOriginalArgs()) == 1
8111 id_arg = func.GetOriginalArgs()[0]
8112 if id_arg.type == 'GLsync':
8113 arg_string = "ToGLuint(%s)" % func.MakeOriginalArgString("")
8114 else:
8115 arg_string = func.MakeOriginalArgString("")
8116 f.write(
8117 " helper_->%s(%s, GetResultShmId(), GetResultShmOffset());\n" %
8118 (func.name, arg_string))
8119 f.write(" WaitForCmd();\n")
8120 f.write(" %s result_value = *result" % func.return_type)
8121 if func.return_type == "GLboolean":
8122 f.write(" != 0")
8123 f.write(';\n GPU_CLIENT_LOG("returned " << result_value);\n')
8124 f.write(" CheckGLError();\n")
8125 f.write(" return result_value;\n")
8126 f.write("}\n")
8127 f.write("\n")
8129 def WriteGLES2ImplementationUnitTest(self, func, f):
8130 """Overrriden from TypeHandler."""
8131 client_test = func.GetInfo('client_test')
8132 if client_test == None or client_test == True:
8133 code = """
8134 TEST_F(GLES2ImplementationTest, %(name)s) {
8135 struct Cmds {
8136 cmds::%(name)s cmd;
8139 Cmds expected;
8140 ExpectedMemoryInfo result1 =
8141 GetExpectedResultMemory(sizeof(cmds::%(name)s::Result));
8142 expected.cmd.Init(%(cmd_id_value)s, result1.id, result1.offset);
8144 EXPECT_CALL(*command_buffer(), OnFlush())
8145 .WillOnce(SetMemory(result1.ptr, uint32_t(GL_TRUE)))
8146 .RetiresOnSaturation();
8148 GLboolean result = gl_->%(name)s(%(gl_id_value)s);
8149 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
8150 EXPECT_TRUE(result);
8153 args = func.GetOriginalArgs()
8154 assert len(args) == 1
8155 f.write(code % {
8156 'name': func.name,
8157 'cmd_id_value': args[0].GetValidClientSideCmdArg(func),
8158 'gl_id_value': args[0].GetValidClientSideArg(func) })
8161 class STRnHandler(TypeHandler):
8162 """Handler for GetProgramInfoLog, GetShaderInfoLog, GetShaderSource, and
8163 GetTranslatedShaderSourceANGLE."""
8165 def InitFunction(self, func):
8166 """Overrriden from TypeHandler."""
8167 # remove all but the first cmd args.
8168 cmd_args = func.GetCmdArgs()
8169 func.ClearCmdArgs()
8170 func.AddCmdArg(cmd_args[0])
8171 # add on a bucket id.
8172 func.AddCmdArg(Argument('bucket_id', 'uint32_t'))
8174 def WriteGLES2Implementation(self, func, f):
8175 """Overrriden from TypeHandler."""
8176 code_1 = """%(return_type)s GLES2Implementation::%(func_name)s(%(args)s) {
8177 GPU_CLIENT_SINGLE_THREAD_CHECK();
8179 code_2 = """ GPU_CLIENT_LOG("[" << GetLogPrefix()
8180 << "] gl%(func_name)s" << "("
8181 << %(arg0)s << ", "
8182 << %(arg1)s << ", "
8183 << static_cast<void*>(%(arg2)s) << ", "
8184 << static_cast<void*>(%(arg3)s) << ")");
8185 helper_->SetBucketSize(kResultBucketId, 0);
8186 helper_->%(func_name)s(%(id_name)s, kResultBucketId);
8187 std::string str;
8188 GLsizei max_size = 0;
8189 if (GetBucketAsString(kResultBucketId, &str)) {
8190 if (bufsize > 0) {
8191 max_size =
8192 std::min(static_cast<size_t>(%(bufsize_name)s) - 1, str.size());
8193 memcpy(%(dest_name)s, str.c_str(), max_size);
8194 %(dest_name)s[max_size] = '\\0';
8195 GPU_CLIENT_LOG("------\\n" << %(dest_name)s << "\\n------");
8198 if (%(length_name)s != NULL) {
8199 *%(length_name)s = max_size;
8201 CheckGLError();
8204 args = func.GetOriginalArgs()
8205 str_args = {
8206 'return_type': func.return_type,
8207 'func_name': func.original_name,
8208 'args': func.MakeTypedOriginalArgString(""),
8209 'id_name': args[0].name,
8210 'bufsize_name': args[1].name,
8211 'length_name': args[2].name,
8212 'dest_name': args[3].name,
8213 'arg0': args[0].name,
8214 'arg1': args[1].name,
8215 'arg2': args[2].name,
8216 'arg3': args[3].name,
8218 f.write(code_1 % str_args)
8219 func.WriteDestinationInitalizationValidation(f)
8220 f.write(code_2 % str_args)
8222 def WriteServiceUnitTest(self, func, f, *extras):
8223 """Overrriden from TypeHandler."""
8224 valid_test = """
8225 TEST_P(%(test_name)s, %(name)sValidArgs) {
8226 const char* kInfo = "hello";
8227 const uint32_t kBucketId = 123;
8228 SpecializedSetup<cmds::%(name)s, 0>(true);
8229 %(expect_len_code)s
8230 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s))
8231 .WillOnce(DoAll(SetArgumentPointee<2>(strlen(kInfo)),
8232 SetArrayArgument<3>(kInfo, kInfo + strlen(kInfo) + 1)));
8233 cmds::%(name)s cmd;
8234 cmd.Init(%(args)s);
8235 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
8236 CommonDecoder::Bucket* bucket = decoder_->GetBucket(kBucketId);
8237 ASSERT_TRUE(bucket != NULL);
8238 EXPECT_EQ(strlen(kInfo) + 1, bucket->size());
8239 EXPECT_EQ(0, memcmp(bucket->GetData(0, bucket->size()), kInfo,
8240 bucket->size()));
8241 EXPECT_EQ(GL_NO_ERROR, GetGLError());
8244 args = func.GetOriginalArgs()
8245 id_name = args[0].GetValidGLArg(func)
8246 get_len_func = func.GetInfo('get_len_func')
8247 get_len_enum = func.GetInfo('get_len_enum')
8248 sub = {
8249 'id_name': id_name,
8250 'get_len_func': get_len_func,
8251 'get_len_enum': get_len_enum,
8252 'gl_args': '%s, strlen(kInfo) + 1, _, _' %
8253 args[0].GetValidGLArg(func),
8254 'args': '%s, kBucketId' % args[0].GetValidArg(func),
8255 'expect_len_code': '',
8257 if get_len_func and get_len_func[0:2] == 'gl':
8258 sub['expect_len_code'] = (
8259 " EXPECT_CALL(*gl_, %s(%s, %s, _))\n"
8260 " .WillOnce(SetArgumentPointee<2>(strlen(kInfo) + 1));") % (
8261 get_len_func[2:], id_name, get_len_enum)
8262 self.WriteValidUnitTest(func, f, valid_test, sub, *extras)
8264 invalid_test = """
8265 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
8266 const uint32_t kBucketId = 123;
8267 EXPECT_CALL(*gl_, %(gl_func_name)s(_, _, _, _))
8268 .Times(0);
8269 cmds::%(name)s cmd;
8270 cmd.Init(kInvalidClientId, kBucketId);
8271 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
8272 EXPECT_EQ(GL_INVALID_VALUE, GetGLError());
8275 self.WriteValidUnitTest(func, f, invalid_test, *extras)
8277 def WriteServiceImplementation(self, func, f):
8278 """Overrriden from TypeHandler."""
8279 pass
8281 class NamedType(object):
8282 """A class that represents a type of an argument in a client function.
8284 A type of an argument that is to be passed through in the command buffer
8285 command. Currently used only for the arguments that are specificly named in
8286 the 'cmd_buffer_functions.txt' f, mostly enums.
8289 def __init__(self, info):
8290 assert not 'is_complete' in info or info['is_complete'] == True
8291 self.info = info
8292 self.valid = info['valid']
8293 if 'invalid' in info:
8294 self.invalid = info['invalid']
8295 else:
8296 self.invalid = []
8297 if 'valid_es3' in info:
8298 self.valid_es3 = info['valid_es3']
8299 else:
8300 self.valid_es3 = []
8301 if 'deprecated_es3' in info:
8302 self.deprecated_es3 = info['deprecated_es3']
8303 else:
8304 self.deprecated_es3 = []
8306 def GetType(self):
8307 return self.info['type']
8309 def GetInvalidValues(self):
8310 return self.invalid
8312 def GetValidValues(self):
8313 return self.valid
8315 def GetValidValuesES3(self):
8316 return self.valid_es3
8318 def GetDeprecatedValuesES3(self):
8319 return self.deprecated_es3
8321 def IsConstant(self):
8322 if not 'is_complete' in self.info:
8323 return False
8325 return len(self.GetValidValues()) == 1
8327 def GetConstantValue(self):
8328 return self.GetValidValues()[0]
8330 class Argument(object):
8331 """A class that represents a function argument."""
8333 cmd_type_map_ = {
8334 'GLenum': 'uint32_t',
8335 'GLint': 'int32_t',
8336 'GLintptr': 'int32_t',
8337 'GLsizei': 'int32_t',
8338 'GLsizeiptr': 'int32_t',
8339 'GLfloat': 'float',
8340 'GLclampf': 'float',
8342 need_validation_ = ['GLsizei*', 'GLboolean*', 'GLenum*', 'GLint*']
8344 def __init__(self, name, type):
8345 self.name = name
8346 self.optional = type.endswith("Optional*")
8347 if self.optional:
8348 type = type[:-9] + "*"
8349 self.type = type
8351 if type in self.cmd_type_map_:
8352 self.cmd_type = self.cmd_type_map_[type]
8353 else:
8354 self.cmd_type = 'uint32_t'
8356 def IsPointer(self):
8357 """Returns true if argument is a pointer."""
8358 return False
8360 def IsPointer2D(self):
8361 """Returns true if argument is a 2D pointer."""
8362 return False
8364 def IsConstant(self):
8365 """Returns true if the argument has only one valid value."""
8366 return False
8368 def AddCmdArgs(self, args):
8369 """Adds command arguments for this argument to the given list."""
8370 if not self.IsConstant():
8371 return args.append(self)
8373 def AddInitArgs(self, args):
8374 """Adds init arguments for this argument to the given list."""
8375 if not self.IsConstant():
8376 return args.append(self)
8378 def GetValidArg(self, func):
8379 """Gets a valid value for this argument."""
8380 valid_arg = func.GetValidArg(self)
8381 if valid_arg != None:
8382 return valid_arg
8384 index = func.GetOriginalArgs().index(self)
8385 return str(index + 1)
8387 def GetValidClientSideArg(self, func):
8388 """Gets a valid value for this argument."""
8389 valid_arg = func.GetValidArg(self)
8390 if valid_arg != None:
8391 return valid_arg
8393 if self.IsPointer():
8394 return 'nullptr'
8395 index = func.GetOriginalArgs().index(self)
8396 if self.type == 'GLsync':
8397 return ("reinterpret_cast<GLsync>(%d)" % (index + 1))
8398 return str(index + 1)
8400 def GetValidClientSideCmdArg(self, func):
8401 """Gets a valid value for this argument."""
8402 valid_arg = func.GetValidArg(self)
8403 if valid_arg != None:
8404 return valid_arg
8405 try:
8406 index = func.GetOriginalArgs().index(self)
8407 return str(index + 1)
8408 except ValueError:
8409 pass
8410 index = func.GetCmdArgs().index(self)
8411 return str(index + 1)
8413 def GetValidGLArg(self, func):
8414 """Gets a valid GL value for this argument."""
8415 value = self.GetValidArg(func)
8416 if self.type == 'GLsync':
8417 return ("reinterpret_cast<GLsync>(%s)" % value)
8418 return value
8420 def GetValidNonCachedClientSideArg(self, func):
8421 """Returns a valid value for this argument in a GL call.
8422 Using the value will produce a command buffer service invocation.
8423 Returns None if there is no such value."""
8424 value = '123'
8425 if self.type == 'GLsync':
8426 return ("reinterpret_cast<GLsync>(%s)" % value)
8427 return value
8429 def GetValidNonCachedClientSideCmdArg(self, func):
8430 """Returns a valid value for this argument in a command buffer command.
8431 Calling the GL function with the value returned by
8432 GetValidNonCachedClientSideArg will result in a command buffer command
8433 that contains the value returned by this function. """
8434 return '123'
8436 def GetNumInvalidValues(self, func):
8437 """returns the number of invalid values to be tested."""
8438 return 0
8440 def GetInvalidArg(self, index):
8441 """returns an invalid value and expected parse result by index."""
8442 return ("---ERROR0---", "---ERROR2---", None)
8444 def GetLogArg(self):
8445 """Get argument appropriate for LOG macro."""
8446 if self.type == 'GLboolean':
8447 return 'GLES2Util::GetStringBool(%s)' % self.name
8448 if self.type == 'GLenum':
8449 return 'GLES2Util::GetStringEnum(%s)' % self.name
8450 return self.name
8452 def WriteGetCode(self, f):
8453 """Writes the code to get an argument from a command structure."""
8454 if self.type == 'GLsync':
8455 my_type = 'GLuint'
8456 else:
8457 my_type = self.type
8458 f.write(" %s %s = static_cast<%s>(c.%s);\n" %
8459 (my_type, self.name, my_type, self.name))
8461 def WriteValidationCode(self, f, func):
8462 """Writes the validation code for an argument."""
8463 pass
8465 def WriteClientSideValidationCode(self, f, func):
8466 """Writes the validation code for an argument."""
8467 pass
8469 def WriteDestinationInitalizationValidation(self, f, func):
8470 """Writes the client side destintion initialization validation."""
8471 pass
8473 def WriteDestinationInitalizationValidatationIfNeeded(self, f, func):
8474 """Writes the client side destintion initialization validation if needed."""
8475 parts = self.type.split(" ")
8476 if len(parts) > 1:
8477 return
8478 if parts[0] in self.need_validation_:
8479 f.write(
8480 " GPU_CLIENT_VALIDATE_DESTINATION_%sINITALIZATION(%s, %s);\n" %
8481 ("OPTIONAL_" if self.optional else "", self.type[:-1], self.name))
8483 def GetImmediateVersion(self):
8484 """Gets the immediate version of this argument."""
8485 return self
8487 def GetBucketVersion(self):
8488 """Gets the bucket version of this argument."""
8489 return self
8492 class BoolArgument(Argument):
8493 """class for GLboolean"""
8495 def __init__(self, name, type):
8496 Argument.__init__(self, name, 'GLboolean')
8498 def GetValidArg(self, func):
8499 """Gets a valid value for this argument."""
8500 return 'true'
8502 def GetValidClientSideArg(self, func):
8503 """Gets a valid value for this argument."""
8504 return 'true'
8506 def GetValidClientSideCmdArg(self, func):
8507 """Gets a valid value for this argument."""
8508 return 'true'
8510 def GetValidGLArg(self, func):
8511 """Gets a valid GL value for this argument."""
8512 return 'true'
8515 class UniformLocationArgument(Argument):
8516 """class for uniform locations."""
8518 def __init__(self, name):
8519 Argument.__init__(self, name, "GLint")
8521 def WriteGetCode(self, f):
8522 """Writes the code to get an argument from a command structure."""
8523 code = """ %s %s = static_cast<%s>(c.%s);
8525 f.write(code % (self.type, self.name, self.type, self.name))
8527 class DataSizeArgument(Argument):
8528 """class for data_size which Bucket commands do not need."""
8530 def __init__(self, name):
8531 Argument.__init__(self, name, "uint32_t")
8533 def GetBucketVersion(self):
8534 return None
8537 class SizeArgument(Argument):
8538 """class for GLsizei and GLsizeiptr."""
8540 def GetNumInvalidValues(self, func):
8541 """overridden from Argument."""
8542 if func.IsImmediate():
8543 return 0
8544 return 1
8546 def GetInvalidArg(self, index):
8547 """overridden from Argument."""
8548 return ("-1", "kNoError", "GL_INVALID_VALUE")
8550 def WriteValidationCode(self, f, func):
8551 """overridden from Argument."""
8552 if func.IsUnsafe():
8553 return
8554 code = """ if (%(var_name)s < 0) {
8555 LOCAL_SET_GL_ERROR(GL_INVALID_VALUE, "gl%(func_name)s", "%(var_name)s < 0");
8556 return error::kNoError;
8559 f.write(code % {
8560 "var_name": self.name,
8561 "func_name": func.original_name,
8564 def WriteClientSideValidationCode(self, f, func):
8565 """overridden from Argument."""
8566 code = """ if (%(var_name)s < 0) {
8567 SetGLError(GL_INVALID_VALUE, "gl%(func_name)s", "%(var_name)s < 0");
8568 return;
8571 f.write(code % {
8572 "var_name": self.name,
8573 "func_name": func.original_name,
8577 class SizeNotNegativeArgument(SizeArgument):
8578 """class for GLsizeiNotNegative. It's NEVER allowed to be negative"""
8580 def __init__(self, name, type, gl_type):
8581 SizeArgument.__init__(self, name, gl_type)
8583 def GetInvalidArg(self, index):
8584 """overridden from SizeArgument."""
8585 return ("-1", "kOutOfBounds", "GL_NO_ERROR")
8587 def WriteValidationCode(self, f, func):
8588 """overridden from SizeArgument."""
8589 pass
8592 class EnumBaseArgument(Argument):
8593 """Base class for EnumArgument, IntArgument, BitfieldArgument, and
8594 ValidatedBoolArgument."""
8596 def __init__(self, name, gl_type, type, gl_error):
8597 Argument.__init__(self, name, gl_type)
8599 self.gl_error = gl_error
8600 name = type[len(gl_type):]
8601 self.type_name = name
8602 self.named_type = NamedType(_NAMED_TYPE_INFO[name])
8604 def IsConstant(self):
8605 return self.named_type.IsConstant()
8607 def GetConstantValue(self):
8608 return self.named_type.GetConstantValue()
8610 def WriteValidationCode(self, f, func):
8611 if func.IsUnsafe():
8612 return
8613 if self.named_type.IsConstant():
8614 return
8615 f.write(" if (!validators_->%s.IsValid(%s)) {\n" %
8616 (ToUnderscore(self.type_name), self.name))
8617 if self.gl_error == "GL_INVALID_ENUM":
8618 f.write(
8619 " LOCAL_SET_GL_ERROR_INVALID_ENUM(\"gl%s\", %s, \"%s\");\n" %
8620 (func.original_name, self.name, self.name))
8621 else:
8622 f.write(
8623 " LOCAL_SET_GL_ERROR(%s, \"gl%s\", \"%s %s\");\n" %
8624 (self.gl_error, func.original_name, self.name, self.gl_error))
8625 f.write(" return error::kNoError;\n")
8626 f.write(" }\n")
8628 def WriteClientSideValidationCode(self, f, func):
8629 if not self.named_type.IsConstant():
8630 return
8631 f.write(" if (%s != %s) {" % (self.name,
8632 self.GetConstantValue()))
8633 f.write(
8634 " SetGLError(%s, \"gl%s\", \"%s %s\");\n" %
8635 (self.gl_error, func.original_name, self.name, self.gl_error))
8636 if func.return_type == "void":
8637 f.write(" return;\n")
8638 else:
8639 f.write(" return %s;\n" % func.GetErrorReturnString())
8640 f.write(" }\n")
8642 def GetValidArg(self, func):
8643 valid_arg = func.GetValidArg(self)
8644 if valid_arg != None:
8645 return valid_arg
8646 valid = self.named_type.GetValidValues()
8647 if valid:
8648 return valid[0]
8650 index = func.GetOriginalArgs().index(self)
8651 return str(index + 1)
8653 def GetValidClientSideArg(self, func):
8654 """Gets a valid value for this argument."""
8655 return self.GetValidArg(func)
8657 def GetValidClientSideCmdArg(self, func):
8658 """Gets a valid value for this argument."""
8659 valid_arg = func.GetValidArg(self)
8660 if valid_arg != None:
8661 return valid_arg
8663 valid = self.named_type.GetValidValues()
8664 if valid:
8665 return valid[0]
8667 try:
8668 index = func.GetOriginalArgs().index(self)
8669 return str(index + 1)
8670 except ValueError:
8671 pass
8672 index = func.GetCmdArgs().index(self)
8673 return str(index + 1)
8675 def GetValidGLArg(self, func):
8676 """Gets a valid value for this argument."""
8677 return self.GetValidArg(func)
8679 def GetNumInvalidValues(self, func):
8680 """returns the number of invalid values to be tested."""
8681 return len(self.named_type.GetInvalidValues())
8683 def GetInvalidArg(self, index):
8684 """returns an invalid value by index."""
8685 invalid = self.named_type.GetInvalidValues()
8686 if invalid:
8687 num_invalid = len(invalid)
8688 if index >= num_invalid:
8689 index = num_invalid - 1
8690 return (invalid[index], "kNoError", self.gl_error)
8691 return ("---ERROR1---", "kNoError", self.gl_error)
8694 class EnumArgument(EnumBaseArgument):
8695 """A class that represents a GLenum argument"""
8697 def __init__(self, name, type):
8698 EnumBaseArgument.__init__(self, name, "GLenum", type, "GL_INVALID_ENUM")
8700 def GetLogArg(self):
8701 """Overridden from Argument."""
8702 return ("GLES2Util::GetString%s(%s)" %
8703 (self.type_name, self.name))
8706 class IntArgument(EnumBaseArgument):
8707 """A class for a GLint argument that can only accept specific values.
8709 For example glTexImage2D takes a GLint for its internalformat
8710 argument instead of a GLenum.
8713 def __init__(self, name, type):
8714 EnumBaseArgument.__init__(self, name, "GLint", type, "GL_INVALID_VALUE")
8717 class ValidatedBoolArgument(EnumBaseArgument):
8718 """A class for a GLboolean argument that can only accept specific values.
8720 For example glUniformMatrix takes a GLboolean for it's transpose but it
8721 must be false.
8724 def __init__(self, name, type):
8725 EnumBaseArgument.__init__(self, name, "GLboolean", type, "GL_INVALID_VALUE")
8727 def GetLogArg(self):
8728 """Overridden from Argument."""
8729 return 'GLES2Util::GetStringBool(%s)' % self.name
8732 class BitFieldArgument(EnumBaseArgument):
8733 """A class for a GLbitfield argument that can only accept specific values.
8735 For example glFenceSync takes a GLbitfield for its flags argument bit it
8736 must be 0.
8739 def __init__(self, name, type):
8740 EnumBaseArgument.__init__(self, name, "GLbitfield", type,
8741 "GL_INVALID_VALUE")
8744 class ImmediatePointerArgument(Argument):
8745 """A class that represents an immediate argument to a function.
8747 An immediate argument is one where the data follows the command.
8750 def IsPointer(self):
8751 return True
8753 def GetPointedType(self):
8754 match = re.match('(const\s+)?(?P<element_type>[\w]+)\s*\*', self.type)
8755 assert match
8756 return match.groupdict()['element_type']
8758 def AddCmdArgs(self, args):
8759 """Overridden from Argument."""
8760 pass
8762 def WriteGetCode(self, f):
8763 """Overridden from Argument."""
8764 f.write(
8765 " %s %s = GetImmediateDataAs<%s>(\n" %
8766 (self.type, self.name, self.type))
8767 f.write(" c, data_size, immediate_data_size);\n")
8769 def WriteValidationCode(self, f, func):
8770 """Overridden from Argument."""
8771 if self.optional:
8772 return
8773 f.write(" if (%s == NULL) {\n" % self.name)
8774 f.write(" return error::kOutOfBounds;\n")
8775 f.write(" }\n")
8777 def GetImmediateVersion(self):
8778 """Overridden from Argument."""
8779 return None
8781 def WriteDestinationInitalizationValidation(self, f, func):
8782 """Overridden from Argument."""
8783 self.WriteDestinationInitalizationValidatationIfNeeded(f, func)
8785 def GetLogArg(self):
8786 """Overridden from Argument."""
8787 return "static_cast<const void*>(%s)" % self.name
8790 class PointerArgument(Argument):
8791 """A class that represents a pointer argument to a function."""
8793 def IsPointer(self):
8794 """Overridden from Argument."""
8795 return True
8797 def IsPointer2D(self):
8798 """Overridden from Argument."""
8799 return self.type.count('*') == 2
8801 def GetPointedType(self):
8802 match = re.match('(const\s+)?(?P<element_type>[\w]+)\s*\*', self.type)
8803 assert match
8804 return match.groupdict()['element_type']
8806 def GetValidArg(self, func):
8807 """Overridden from Argument."""
8808 return "shared_memory_id_, shared_memory_offset_"
8810 def GetValidGLArg(self, func):
8811 """Overridden from Argument."""
8812 return "reinterpret_cast<%s>(shared_memory_address_)" % self.type
8814 def GetNumInvalidValues(self, func):
8815 """Overridden from Argument."""
8816 return 2
8818 def GetInvalidArg(self, index):
8819 """Overridden from Argument."""
8820 if index == 0:
8821 return ("kInvalidSharedMemoryId, 0", "kOutOfBounds", None)
8822 else:
8823 return ("shared_memory_id_, kInvalidSharedMemoryOffset",
8824 "kOutOfBounds", None)
8826 def GetLogArg(self):
8827 """Overridden from Argument."""
8828 return "static_cast<const void*>(%s)" % self.name
8830 def AddCmdArgs(self, args):
8831 """Overridden from Argument."""
8832 args.append(Argument("%s_shm_id" % self.name, 'uint32_t'))
8833 args.append(Argument("%s_shm_offset" % self.name, 'uint32_t'))
8835 def WriteGetCode(self, f):
8836 """Overridden from Argument."""
8837 f.write(
8838 " %s %s = GetSharedMemoryAs<%s>(\n" %
8839 (self.type, self.name, self.type))
8840 f.write(
8841 " c.%s_shm_id, c.%s_shm_offset, data_size);\n" %
8842 (self.name, self.name))
8844 def WriteValidationCode(self, f, func):
8845 """Overridden from Argument."""
8846 if self.optional:
8847 return
8848 f.write(" if (%s == NULL) {\n" % self.name)
8849 f.write(" return error::kOutOfBounds;\n")
8850 f.write(" }\n")
8852 def GetImmediateVersion(self):
8853 """Overridden from Argument."""
8854 return ImmediatePointerArgument(self.name, self.type)
8856 def GetBucketVersion(self):
8857 """Overridden from Argument."""
8858 if self.type.find('char') >= 0:
8859 if self.IsPointer2D():
8860 return InputStringArrayBucketArgument(self.name, self.type)
8861 return InputStringBucketArgument(self.name, self.type)
8862 return BucketPointerArgument(self.name, self.type)
8864 def WriteDestinationInitalizationValidation(self, f, func):
8865 """Overridden from Argument."""
8866 self.WriteDestinationInitalizationValidatationIfNeeded(f, func)
8869 class BucketPointerArgument(PointerArgument):
8870 """A class that represents an bucket argument to a function."""
8872 def AddCmdArgs(self, args):
8873 """Overridden from Argument."""
8874 pass
8876 def WriteGetCode(self, f):
8877 """Overridden from Argument."""
8878 f.write(
8879 " %s %s = bucket->GetData(0, data_size);\n" %
8880 (self.type, self.name))
8882 def WriteValidationCode(self, f, func):
8883 """Overridden from Argument."""
8884 pass
8886 def GetImmediateVersion(self):
8887 """Overridden from Argument."""
8888 return None
8890 def WriteDestinationInitalizationValidation(self, f, func):
8891 """Overridden from Argument."""
8892 self.WriteDestinationInitalizationValidatationIfNeeded(f, func)
8894 def GetLogArg(self):
8895 """Overridden from Argument."""
8896 return "static_cast<const void*>(%s)" % self.name
8899 class InputStringBucketArgument(Argument):
8900 """A string input argument where the string is passed in a bucket."""
8902 def __init__(self, name, type):
8903 Argument.__init__(self, name + "_bucket_id", "uint32_t")
8905 def IsPointer(self):
8906 """Overridden from Argument."""
8907 return True
8909 def IsPointer2D(self):
8910 """Overridden from Argument."""
8911 return False
8914 class InputStringArrayBucketArgument(Argument):
8915 """A string array input argument where the strings are passed in a bucket."""
8917 def __init__(self, name, type):
8918 Argument.__init__(self, name + "_bucket_id", "uint32_t")
8919 self._original_name = name
8921 def WriteGetCode(self, f):
8922 """Overridden from Argument."""
8923 code = """
8924 Bucket* bucket = GetBucket(c.%(name)s);
8925 if (!bucket) {
8926 return error::kInvalidArguments;
8928 GLsizei count = 0;
8929 std::vector<char*> strs;
8930 std::vector<GLint> len;
8931 if (!bucket->GetAsStrings(&count, &strs, &len)) {
8932 return error::kInvalidArguments;
8934 const char** %(original_name)s =
8935 strs.size() > 0 ? const_cast<const char**>(&strs[0]) : NULL;
8936 const GLint* length =
8937 len.size() > 0 ? const_cast<const GLint*>(&len[0]) : NULL;
8938 (void)length;
8940 f.write(code % {
8941 'name': self.name,
8942 'original_name': self._original_name,
8945 def GetValidArg(self, func):
8946 return "kNameBucketId"
8948 def GetValidGLArg(self, func):
8949 return "_"
8951 def IsPointer(self):
8952 """Overridden from Argument."""
8953 return True
8955 def IsPointer2D(self):
8956 """Overridden from Argument."""
8957 return True
8960 class ResourceIdArgument(Argument):
8961 """A class that represents a resource id argument to a function."""
8963 def __init__(self, name, type):
8964 match = re.match("(GLid\w+)", type)
8965 self.resource_type = match.group(1)[4:]
8966 if self.resource_type == "Sync":
8967 type = type.replace(match.group(1), "GLsync")
8968 else:
8969 type = type.replace(match.group(1), "GLuint")
8970 Argument.__init__(self, name, type)
8972 def WriteGetCode(self, f):
8973 """Overridden from Argument."""
8974 if self.type == "GLsync":
8975 my_type = "GLuint"
8976 else:
8977 my_type = self.type
8978 f.write(" %s %s = c.%s;\n" % (my_type, self.name, self.name))
8980 def GetValidArg(self, func):
8981 return "client_%s_id_" % self.resource_type.lower()
8983 def GetValidGLArg(self, func):
8984 if self.resource_type == "Sync":
8985 return "reinterpret_cast<GLsync>(kService%sId)" % self.resource_type
8986 return "kService%sId" % self.resource_type
8989 class ResourceIdBindArgument(Argument):
8990 """Represents a resource id argument to a bind function."""
8992 def __init__(self, name, type):
8993 match = re.match("(GLidBind\w+)", type)
8994 self.resource_type = match.group(1)[8:]
8995 type = type.replace(match.group(1), "GLuint")
8996 Argument.__init__(self, name, type)
8998 def WriteGetCode(self, f):
8999 """Overridden from Argument."""
9000 code = """ %(type)s %(name)s = c.%(name)s;
9002 f.write(code % {'type': self.type, 'name': self.name})
9004 def GetValidArg(self, func):
9005 return "client_%s_id_" % self.resource_type.lower()
9007 def GetValidGLArg(self, func):
9008 return "kService%sId" % self.resource_type
9011 class ResourceIdZeroArgument(Argument):
9012 """Represents a resource id argument to a function that can be zero."""
9014 def __init__(self, name, type):
9015 match = re.match("(GLidZero\w+)", type)
9016 self.resource_type = match.group(1)[8:]
9017 type = type.replace(match.group(1), "GLuint")
9018 Argument.__init__(self, name, type)
9020 def WriteGetCode(self, f):
9021 """Overridden from Argument."""
9022 f.write(" %s %s = c.%s;\n" % (self.type, self.name, self.name))
9024 def GetValidArg(self, func):
9025 return "client_%s_id_" % self.resource_type.lower()
9027 def GetValidGLArg(self, func):
9028 return "kService%sId" % self.resource_type
9030 def GetNumInvalidValues(self, func):
9031 """returns the number of invalid values to be tested."""
9032 return 1
9034 def GetInvalidArg(self, index):
9035 """returns an invalid value by index."""
9036 return ("kInvalidClientId", "kNoError", "GL_INVALID_VALUE")
9039 class Function(object):
9040 """A class that represents a function."""
9042 type_handlers = {
9043 '': TypeHandler(),
9044 'Bind': BindHandler(),
9045 'Create': CreateHandler(),
9046 'Custom': CustomHandler(),
9047 'Data': DataHandler(),
9048 'Delete': DeleteHandler(),
9049 'DELn': DELnHandler(),
9050 'GENn': GENnHandler(),
9051 'GETn': GETnHandler(),
9052 'GLchar': GLcharHandler(),
9053 'GLcharN': GLcharNHandler(),
9054 'HandWritten': HandWrittenHandler(),
9055 'Is': IsHandler(),
9056 'Manual': ManualHandler(),
9057 'PUT': PUTHandler(),
9058 'PUTn': PUTnHandler(),
9059 'PUTSTR': PUTSTRHandler(),
9060 'PUTXn': PUTXnHandler(),
9061 'StateSet': StateSetHandler(),
9062 'StateSetRGBAlpha': StateSetRGBAlphaHandler(),
9063 'StateSetFrontBack': StateSetFrontBackHandler(),
9064 'StateSetFrontBackSeparate': StateSetFrontBackSeparateHandler(),
9065 'StateSetNamedParameter': StateSetNamedParameter(),
9066 'STRn': STRnHandler(),
9069 def __init__(self, name, info):
9070 self.name = name
9071 self.original_name = info['original_name']
9073 self.original_args = self.ParseArgs(info['original_args'])
9075 if 'cmd_args' in info:
9076 self.args_for_cmds = self.ParseArgs(info['cmd_args'])
9077 else:
9078 self.args_for_cmds = self.original_args[:]
9080 self.return_type = info['return_type']
9081 if self.return_type != 'void':
9082 self.return_arg = CreateArg(info['return_type'] + " result")
9083 else:
9084 self.return_arg = None
9086 self.num_pointer_args = sum(
9087 [1 for arg in self.args_for_cmds if arg.IsPointer()])
9088 if self.num_pointer_args > 0:
9089 for arg in reversed(self.original_args):
9090 if arg.IsPointer():
9091 self.last_original_pointer_arg = arg
9092 break
9093 else:
9094 self.last_original_pointer_arg = None
9095 self.info = info
9096 self.type_handler = self.type_handlers[info['type']]
9097 self.can_auto_generate = (self.num_pointer_args == 0 and
9098 info['return_type'] == "void")
9099 self.InitFunction()
9101 def ParseArgs(self, arg_string):
9102 """Parses a function arg string."""
9103 args = []
9104 parts = arg_string.split(',')
9105 for arg_string in parts:
9106 arg = CreateArg(arg_string)
9107 if arg:
9108 args.append(arg)
9109 return args
9111 def IsType(self, type_name):
9112 """Returns true if function is a certain type."""
9113 return self.info['type'] == type_name
9115 def InitFunction(self):
9116 """Creates command args and calls the init function for the type handler.
9118 Creates argument lists for command buffer commands, eg. self.cmd_args and
9119 self.init_args.
9120 Calls the type function initialization.
9121 Override to create different kind of command buffer command argument lists.
9123 self.cmd_args = []
9124 for arg in self.args_for_cmds:
9125 arg.AddCmdArgs(self.cmd_args)
9127 self.init_args = []
9128 for arg in self.args_for_cmds:
9129 arg.AddInitArgs(self.init_args)
9131 if self.return_arg:
9132 self.init_args.append(self.return_arg)
9134 self.type_handler.InitFunction(self)
9136 def IsImmediate(self):
9137 """Returns whether the function is immediate data function or not."""
9138 return False
9140 def IsUnsafe(self):
9141 """Returns whether the function has service side validation or not."""
9142 return self.GetInfo('unsafe', False)
9144 def GetInfo(self, name, default = None):
9145 """Returns a value from the function info for this function."""
9146 if name in self.info:
9147 return self.info[name]
9148 return default
9150 def GetValidArg(self, arg):
9151 """Gets a valid argument value for the parameter arg from the function info
9152 if one exists."""
9153 try:
9154 index = self.GetOriginalArgs().index(arg)
9155 except ValueError:
9156 return None
9158 valid_args = self.GetInfo('valid_args')
9159 if valid_args and str(index) in valid_args:
9160 return valid_args[str(index)]
9161 return None
9163 def AddInfo(self, name, value):
9164 """Adds an info."""
9165 self.info[name] = value
9167 def IsExtension(self):
9168 return self.GetInfo('extension') or self.GetInfo('extension_flag')
9170 def IsCoreGLFunction(self):
9171 return (not self.IsExtension() and
9172 not self.GetInfo('pepper_interface') and
9173 not self.IsUnsafe())
9175 def InPepperInterface(self, interface):
9176 ext = self.GetInfo('pepper_interface')
9177 if not interface.GetName():
9178 return self.IsCoreGLFunction()
9179 return ext == interface.GetName()
9181 def InAnyPepperExtension(self):
9182 return self.IsCoreGLFunction() or self.GetInfo('pepper_interface')
9184 def GetErrorReturnString(self):
9185 if self.GetInfo("error_return"):
9186 return self.GetInfo("error_return")
9187 elif self.return_type == "GLboolean":
9188 return "GL_FALSE"
9189 elif "*" in self.return_type:
9190 return "NULL"
9191 return "0"
9193 def GetGLFunctionName(self):
9194 """Gets the function to call to execute GL for this command."""
9195 if self.GetInfo('decoder_func'):
9196 return self.GetInfo('decoder_func')
9197 return "gl%s" % self.original_name
9199 def GetGLTestFunctionName(self):
9200 gl_func_name = self.GetInfo('gl_test_func')
9201 if gl_func_name == None:
9202 gl_func_name = self.GetGLFunctionName()
9203 if gl_func_name.startswith("gl"):
9204 gl_func_name = gl_func_name[2:]
9205 else:
9206 gl_func_name = self.original_name
9207 return gl_func_name
9209 def GetDataTransferMethods(self):
9210 return self.GetInfo('data_transfer_methods',
9211 ['immediate' if self.num_pointer_args == 1 else 'shm'])
9213 def AddCmdArg(self, arg):
9214 """Adds a cmd argument to this function."""
9215 self.cmd_args.append(arg)
9217 def GetCmdArgs(self):
9218 """Gets the command args for this function."""
9219 return self.cmd_args
9221 def ClearCmdArgs(self):
9222 """Clears the command args for this function."""
9223 self.cmd_args = []
9225 def GetCmdConstants(self):
9226 """Gets the constants for this function."""
9227 return [arg for arg in self.args_for_cmds if arg.IsConstant()]
9229 def GetInitArgs(self):
9230 """Gets the init args for this function."""
9231 return self.init_args
9233 def GetOriginalArgs(self):
9234 """Gets the original arguments to this function."""
9235 return self.original_args
9237 def GetLastOriginalArg(self):
9238 """Gets the last original argument to this function."""
9239 return self.original_args[len(self.original_args) - 1]
9241 def GetLastOriginalPointerArg(self):
9242 return self.last_original_pointer_arg
9244 def GetResourceIdArg(self):
9245 for arg in self.original_args:
9246 if hasattr(arg, 'resource_type'):
9247 return arg
9248 return None
9250 def _MaybePrependComma(self, arg_string, add_comma):
9251 """Adds a comma if arg_string is not empty and add_comma is true."""
9252 comma = ""
9253 if add_comma and len(arg_string):
9254 comma = ", "
9255 return "%s%s" % (comma, arg_string)
9257 def MakeTypedOriginalArgString(self, prefix, add_comma = False):
9258 """Gets a list of arguments as they are in GL."""
9259 args = self.GetOriginalArgs()
9260 arg_string = ", ".join(
9261 ["%s %s%s" % (arg.type, prefix, arg.name) for arg in args])
9262 return self._MaybePrependComma(arg_string, add_comma)
9264 def MakeOriginalArgString(self, prefix, add_comma = False, separator = ", "):
9265 """Gets the list of arguments as they are in GL."""
9266 args = self.GetOriginalArgs()
9267 arg_string = separator.join(
9268 ["%s%s" % (prefix, arg.name) for arg in args])
9269 return self._MaybePrependComma(arg_string, add_comma)
9271 def MakeHelperArgString(self, prefix, add_comma = False, separator = ", "):
9272 """Gets a list of GL arguments after removing unneeded arguments."""
9273 args = self.GetOriginalArgs()
9274 arg_string = separator.join(
9275 ["%s%s" % (prefix, arg.name)
9276 for arg in args if not arg.IsConstant()])
9277 return self._MaybePrependComma(arg_string, add_comma)
9279 def MakeTypedPepperArgString(self, prefix):
9280 """Gets a list of arguments as they need to be for Pepper."""
9281 if self.GetInfo("pepper_args"):
9282 return self.GetInfo("pepper_args")
9283 else:
9284 return self.MakeTypedOriginalArgString(prefix, False)
9286 def MapCTypeToPepperIdlType(self, ctype, is_for_return_type=False):
9287 """Converts a C type name to the corresponding Pepper IDL type."""
9288 idltype = {
9289 'char*': '[out] str_t',
9290 'const GLchar* const*': '[out] cstr_t',
9291 'const char*': 'cstr_t',
9292 'const void*': 'mem_t',
9293 'void*': '[out] mem_t',
9294 'void**': '[out] mem_ptr_t',
9295 }.get(ctype, ctype)
9296 # We use "GLxxx_ptr_t" for "GLxxx*".
9297 matched = re.match(r'(const )?(GL\w+)\*$', ctype)
9298 if matched:
9299 idltype = matched.group(2) + '_ptr_t'
9300 if not matched.group(1):
9301 idltype = '[out] ' + idltype
9302 # If an in/out specifier is not specified yet, prepend [in].
9303 if idltype[0] != '[':
9304 idltype = '[in] ' + idltype
9305 # Strip the in/out specifier for a return type.
9306 if is_for_return_type:
9307 idltype = re.sub(r'\[\w+\] ', '', idltype)
9308 return idltype
9310 def MakeTypedPepperIdlArgStrings(self):
9311 """Gets a list of arguments as they need to be for Pepper IDL."""
9312 args = self.GetOriginalArgs()
9313 return ["%s %s" % (self.MapCTypeToPepperIdlType(arg.type), arg.name)
9314 for arg in args]
9316 def GetPepperName(self):
9317 if self.GetInfo("pepper_name"):
9318 return self.GetInfo("pepper_name")
9319 return self.name
9321 def MakeTypedCmdArgString(self, prefix, add_comma = False):
9322 """Gets a typed list of arguments as they need to be for command buffers."""
9323 args = self.GetCmdArgs()
9324 arg_string = ", ".join(
9325 ["%s %s%s" % (arg.type, prefix, arg.name) for arg in args])
9326 return self._MaybePrependComma(arg_string, add_comma)
9328 def MakeCmdArgString(self, prefix, add_comma = False):
9329 """Gets the list of arguments as they need to be for command buffers."""
9330 args = self.GetCmdArgs()
9331 arg_string = ", ".join(
9332 ["%s%s" % (prefix, arg.name) for arg in args])
9333 return self._MaybePrependComma(arg_string, add_comma)
9335 def MakeTypedInitString(self, prefix, add_comma = False):
9336 """Gets a typed list of arguments as they need to be for cmd Init/Set."""
9337 args = self.GetInitArgs()
9338 arg_string = ", ".join(
9339 ["%s %s%s" % (arg.type, prefix, arg.name) for arg in args])
9340 return self._MaybePrependComma(arg_string, add_comma)
9342 def MakeInitString(self, prefix, add_comma = False):
9343 """Gets the list of arguments as they need to be for cmd Init/Set."""
9344 args = self.GetInitArgs()
9345 arg_string = ", ".join(
9346 ["%s%s" % (prefix, arg.name) for arg in args])
9347 return self._MaybePrependComma(arg_string, add_comma)
9349 def MakeLogArgString(self):
9350 """Makes a string of the arguments for the LOG macros"""
9351 args = self.GetOriginalArgs()
9352 return ' << ", " << '.join([arg.GetLogArg() for arg in args])
9354 def WriteHandlerValidation(self, f):
9355 """Writes validation code for the function."""
9356 for arg in self.GetOriginalArgs():
9357 arg.WriteValidationCode(f, self)
9358 self.WriteValidationCode(f)
9360 def WriteHandlerImplementation(self, f):
9361 """Writes the handler implementation for this command."""
9362 self.type_handler.WriteHandlerImplementation(self, f)
9364 def WriteValidationCode(self, f):
9365 """Writes the validation code for a command."""
9366 pass
9368 def WriteCmdFlag(self, f):
9369 """Writes the cmd cmd_flags constant."""
9370 flags = []
9371 # By default trace only at the highest level 3.
9372 trace_level = int(self.GetInfo('trace_level', default = 3))
9373 if trace_level not in xrange(0, 4):
9374 raise KeyError("Unhandled trace_level: %d" % trace_level)
9376 flags.append('CMD_FLAG_SET_TRACE_LEVEL(%d)' % trace_level)
9378 if len(flags) > 0:
9379 cmd_flags = ' | '.join(flags)
9380 else:
9381 cmd_flags = 0
9383 f.write(" static const uint8 cmd_flags = %s;\n" % cmd_flags)
9386 def WriteCmdArgFlag(self, f):
9387 """Writes the cmd kArgFlags constant."""
9388 f.write(" static const cmd::ArgFlags kArgFlags = cmd::kFixed;\n")
9390 def WriteCmdComputeSize(self, f):
9391 """Writes the ComputeSize function for the command."""
9392 f.write(" static uint32_t ComputeSize() {\n")
9393 f.write(
9394 " return static_cast<uint32_t>(sizeof(ValueType)); // NOLINT\n")
9395 f.write(" }\n")
9396 f.write("\n")
9398 def WriteCmdSetHeader(self, f):
9399 """Writes the cmd's SetHeader function."""
9400 f.write(" void SetHeader() {\n")
9401 f.write(" header.SetCmd<ValueType>();\n")
9402 f.write(" }\n")
9403 f.write("\n")
9405 def WriteCmdInit(self, f):
9406 """Writes the cmd's Init function."""
9407 f.write(" void Init(%s) {\n" % self.MakeTypedCmdArgString("_"))
9408 f.write(" SetHeader();\n")
9409 args = self.GetCmdArgs()
9410 for arg in args:
9411 f.write(" %s = _%s;\n" % (arg.name, arg.name))
9412 f.write(" }\n")
9413 f.write("\n")
9415 def WriteCmdSet(self, f):
9416 """Writes the cmd's Set function."""
9417 copy_args = self.MakeCmdArgString("_", False)
9418 f.write(" void* Set(void* cmd%s) {\n" %
9419 self.MakeTypedCmdArgString("_", True))
9420 f.write(" static_cast<ValueType*>(cmd)->Init(%s);\n" % copy_args)
9421 f.write(" return NextCmdAddress<ValueType>(cmd);\n")
9422 f.write(" }\n")
9423 f.write("\n")
9425 def WriteStruct(self, f):
9426 self.type_handler.WriteStruct(self, f)
9428 def WriteDocs(self, f):
9429 self.type_handler.WriteDocs(self, f)
9431 def WriteCmdHelper(self, f):
9432 """Writes the cmd's helper."""
9433 self.type_handler.WriteCmdHelper(self, f)
9435 def WriteServiceImplementation(self, f):
9436 """Writes the service implementation for a command."""
9437 self.type_handler.WriteServiceImplementation(self, f)
9439 def WriteServiceUnitTest(self, f, *extras):
9440 """Writes the service implementation for a command."""
9441 self.type_handler.WriteServiceUnitTest(self, f, *extras)
9443 def WriteGLES2CLibImplementation(self, f):
9444 """Writes the GLES2 C Lib Implemention."""
9445 self.type_handler.WriteGLES2CLibImplementation(self, f)
9447 def WriteGLES2InterfaceHeader(self, f):
9448 """Writes the GLES2 Interface declaration."""
9449 self.type_handler.WriteGLES2InterfaceHeader(self, f)
9451 def WriteMojoGLES2ImplHeader(self, f):
9452 """Writes the Mojo GLES2 implementation header declaration."""
9453 self.type_handler.WriteMojoGLES2ImplHeader(self, f)
9455 def WriteMojoGLES2Impl(self, f):
9456 """Writes the Mojo GLES2 implementation declaration."""
9457 self.type_handler.WriteMojoGLES2Impl(self, f)
9459 def WriteGLES2InterfaceStub(self, f):
9460 """Writes the GLES2 Interface Stub declaration."""
9461 self.type_handler.WriteGLES2InterfaceStub(self, f)
9463 def WriteGLES2InterfaceStubImpl(self, f):
9464 """Writes the GLES2 Interface Stub declaration."""
9465 self.type_handler.WriteGLES2InterfaceStubImpl(self, f)
9467 def WriteGLES2ImplementationHeader(self, f):
9468 """Writes the GLES2 Implemention declaration."""
9469 self.type_handler.WriteGLES2ImplementationHeader(self, f)
9471 def WriteGLES2Implementation(self, f):
9472 """Writes the GLES2 Implemention definition."""
9473 self.type_handler.WriteGLES2Implementation(self, f)
9475 def WriteGLES2TraceImplementationHeader(self, f):
9476 """Writes the GLES2 Trace Implemention declaration."""
9477 self.type_handler.WriteGLES2TraceImplementationHeader(self, f)
9479 def WriteGLES2TraceImplementation(self, f):
9480 """Writes the GLES2 Trace Implemention definition."""
9481 self.type_handler.WriteGLES2TraceImplementation(self, f)
9483 def WriteGLES2Header(self, f):
9484 """Writes the GLES2 Implemention unit test."""
9485 self.type_handler.WriteGLES2Header(self, f)
9487 def WriteGLES2ImplementationUnitTest(self, f):
9488 """Writes the GLES2 Implemention unit test."""
9489 self.type_handler.WriteGLES2ImplementationUnitTest(self, f)
9491 def WriteDestinationInitalizationValidation(self, f):
9492 """Writes the client side destintion initialization validation."""
9493 self.type_handler.WriteDestinationInitalizationValidation(self, f)
9495 def WriteFormatTest(self, f):
9496 """Writes the cmd's format test."""
9497 self.type_handler.WriteFormatTest(self, f)
9500 class PepperInterface(object):
9501 """A class that represents a function."""
9503 def __init__(self, info):
9504 self.name = info["name"]
9505 self.dev = info["dev"]
9507 def GetName(self):
9508 return self.name
9510 def GetInterfaceName(self):
9511 upperint = ""
9512 dev = ""
9513 if self.name:
9514 upperint = "_" + self.name.upper()
9515 if self.dev:
9516 dev = "_DEV"
9517 return "PPB_OPENGLES2%s%s_INTERFACE" % (upperint, dev)
9519 def GetStructName(self):
9520 dev = ""
9521 if self.dev:
9522 dev = "_Dev"
9523 return "PPB_OpenGLES2%s%s" % (self.name, dev)
9526 class ImmediateFunction(Function):
9527 """A class that represnets an immediate function command."""
9529 def __init__(self, func):
9530 Function.__init__(
9531 self,
9532 "%sImmediate" % func.name,
9533 func.info)
9535 def InitFunction(self):
9536 # Override args in original_args and args_for_cmds with immediate versions
9537 # of the args.
9539 new_original_args = []
9540 for arg in self.original_args:
9541 new_arg = arg.GetImmediateVersion()
9542 if new_arg:
9543 new_original_args.append(new_arg)
9544 self.original_args = new_original_args
9546 new_args_for_cmds = []
9547 for arg in self.args_for_cmds:
9548 new_arg = arg.GetImmediateVersion()
9549 if new_arg:
9550 new_args_for_cmds.append(new_arg)
9552 self.args_for_cmds = new_args_for_cmds
9554 Function.InitFunction(self)
9556 def IsImmediate(self):
9557 return True
9559 def WriteServiceImplementation(self, f):
9560 """Overridden from Function"""
9561 self.type_handler.WriteImmediateServiceImplementation(self, f)
9563 def WriteHandlerImplementation(self, f):
9564 """Overridden from Function"""
9565 self.type_handler.WriteImmediateHandlerImplementation(self, f)
9567 def WriteServiceUnitTest(self, f, *extras):
9568 """Writes the service implementation for a command."""
9569 self.type_handler.WriteImmediateServiceUnitTest(self, f, *extras)
9571 def WriteValidationCode(self, f):
9572 """Overridden from Function"""
9573 self.type_handler.WriteImmediateValidationCode(self, f)
9575 def WriteCmdArgFlag(self, f):
9576 """Overridden from Function"""
9577 f.write(" static const cmd::ArgFlags kArgFlags = cmd::kAtLeastN;\n")
9579 def WriteCmdComputeSize(self, f):
9580 """Overridden from Function"""
9581 self.type_handler.WriteImmediateCmdComputeSize(self, f)
9583 def WriteCmdSetHeader(self, f):
9584 """Overridden from Function"""
9585 self.type_handler.WriteImmediateCmdSetHeader(self, f)
9587 def WriteCmdInit(self, f):
9588 """Overridden from Function"""
9589 self.type_handler.WriteImmediateCmdInit(self, f)
9591 def WriteCmdSet(self, f):
9592 """Overridden from Function"""
9593 self.type_handler.WriteImmediateCmdSet(self, f)
9595 def WriteCmdHelper(self, f):
9596 """Overridden from Function"""
9597 self.type_handler.WriteImmediateCmdHelper(self, f)
9599 def WriteFormatTest(self, f):
9600 """Overridden from Function"""
9601 self.type_handler.WriteImmediateFormatTest(self, f)
9604 class BucketFunction(Function):
9605 """A class that represnets a bucket version of a function command."""
9607 def __init__(self, func):
9608 Function.__init__(
9609 self,
9610 "%sBucket" % func.name,
9611 func.info)
9613 def InitFunction(self):
9614 # Override args in original_args and args_for_cmds with bucket versions
9615 # of the args.
9617 new_original_args = []
9618 for arg in self.original_args:
9619 new_arg = arg.GetBucketVersion()
9620 if new_arg:
9621 new_original_args.append(new_arg)
9622 self.original_args = new_original_args
9624 new_args_for_cmds = []
9625 for arg in self.args_for_cmds:
9626 new_arg = arg.GetBucketVersion()
9627 if new_arg:
9628 new_args_for_cmds.append(new_arg)
9630 self.args_for_cmds = new_args_for_cmds
9632 Function.InitFunction(self)
9634 def WriteServiceImplementation(self, f):
9635 """Overridden from Function"""
9636 self.type_handler.WriteBucketServiceImplementation(self, f)
9638 def WriteHandlerImplementation(self, f):
9639 """Overridden from Function"""
9640 self.type_handler.WriteBucketHandlerImplementation(self, f)
9642 def WriteServiceUnitTest(self, f, *extras):
9643 """Overridden from Function"""
9644 self.type_handler.WriteBucketServiceUnitTest(self, f, *extras)
9646 def MakeOriginalArgString(self, prefix, add_comma = False, separator = ", "):
9647 """Overridden from Function"""
9648 args = self.GetOriginalArgs()
9649 arg_string = separator.join(
9650 ["%s%s" % (prefix, arg.name[0:-10] if arg.name.endswith("_bucket_id")
9651 else arg.name) for arg in args])
9652 return super(BucketFunction, self)._MaybePrependComma(arg_string, add_comma)
9655 def CreateArg(arg_string):
9656 """Creates an Argument."""
9657 arg_parts = arg_string.split()
9658 if len(arg_parts) == 1 and arg_parts[0] == 'void':
9659 return None
9660 # Is this a pointer argument?
9661 elif arg_string.find('*') >= 0:
9662 return PointerArgument(
9663 arg_parts[-1],
9664 " ".join(arg_parts[0:-1]))
9665 # Is this a resource argument? Must come after pointer check.
9666 elif arg_parts[0].startswith('GLidBind'):
9667 return ResourceIdBindArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
9668 elif arg_parts[0].startswith('GLidZero'):
9669 return ResourceIdZeroArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
9670 elif arg_parts[0].startswith('GLid'):
9671 return ResourceIdArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
9672 elif arg_parts[0].startswith('GLenum') and len(arg_parts[0]) > 6:
9673 return EnumArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
9674 elif arg_parts[0].startswith('GLbitfield') and len(arg_parts[0]) > 10:
9675 return BitFieldArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
9676 elif arg_parts[0].startswith('GLboolean') and len(arg_parts[0]) > 9:
9677 return ValidatedBoolArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
9678 elif arg_parts[0].startswith('GLboolean'):
9679 return BoolArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
9680 elif arg_parts[0].startswith('GLintUniformLocation'):
9681 return UniformLocationArgument(arg_parts[-1])
9682 elif (arg_parts[0].startswith('GLint') and len(arg_parts[0]) > 5 and
9683 not arg_parts[0].startswith('GLintptr')):
9684 return IntArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
9685 elif (arg_parts[0].startswith('GLsizeiNotNegative') or
9686 arg_parts[0].startswith('GLintptrNotNegative')):
9687 return SizeNotNegativeArgument(arg_parts[-1],
9688 " ".join(arg_parts[0:-1]),
9689 arg_parts[0][0:-11])
9690 elif arg_parts[0].startswith('GLsize'):
9691 return SizeArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
9692 else:
9693 return Argument(arg_parts[-1], " ".join(arg_parts[0:-1]))
9696 class GLGenerator(object):
9697 """A class to generate GL command buffers."""
9699 _function_re = re.compile(r'GL_APICALL(.*?)GL_APIENTRY (.*?) \((.*?)\);')
9701 def __init__(self, verbose):
9702 self.original_functions = []
9703 self.functions = []
9704 self.verbose = verbose
9705 self.errors = 0
9706 self.pepper_interfaces = []
9707 self.interface_info = {}
9708 self.generated_cpp_filenames = []
9710 for interface in _PEPPER_INTERFACES:
9711 interface = PepperInterface(interface)
9712 self.pepper_interfaces.append(interface)
9713 self.interface_info[interface.GetName()] = interface
9715 def AddFunction(self, func):
9716 """Adds a function."""
9717 self.functions.append(func)
9719 def GetFunctionInfo(self, name):
9720 """Gets a type info for the given function name."""
9721 if name in _FUNCTION_INFO:
9722 func_info = _FUNCTION_INFO[name].copy()
9723 else:
9724 func_info = {}
9726 if not 'type' in func_info:
9727 func_info['type'] = ''
9729 return func_info
9731 def Log(self, msg):
9732 """Prints something if verbose is true."""
9733 if self.verbose:
9734 print msg
9736 def Error(self, msg):
9737 """Prints an error."""
9738 print "Error: %s" % msg
9739 self.errors += 1
9741 def ParseGLH(self, filename):
9742 """Parses the cmd_buffer_functions.txt file and extracts the functions"""
9743 with open(filename, "r") as f:
9744 functions = f.read()
9745 for line in functions.splitlines():
9746 match = self._function_re.match(line)
9747 if match:
9748 func_name = match.group(2)[2:]
9749 func_info = self.GetFunctionInfo(func_name)
9750 if func_info['type'] == 'Noop':
9751 continue
9753 parsed_func_info = {
9754 'original_name': func_name,
9755 'original_args': match.group(3),
9756 'return_type': match.group(1).strip(),
9759 for k in parsed_func_info.keys():
9760 if not k in func_info:
9761 func_info[k] = parsed_func_info[k]
9763 f = Function(func_name, func_info)
9764 self.original_functions.append(f)
9766 #for arg in f.GetOriginalArgs():
9767 # if not isinstance(arg, EnumArgument) and arg.type == 'GLenum':
9768 # self.Log("%s uses bare GLenum %s." % (func_name, arg.name))
9770 gen_cmd = f.GetInfo('gen_cmd')
9771 if gen_cmd == True or gen_cmd == None:
9772 if f.type_handler.NeedsDataTransferFunction(f):
9773 methods = f.GetDataTransferMethods()
9774 if 'immediate' in methods:
9775 self.AddFunction(ImmediateFunction(f))
9776 if 'bucket' in methods:
9777 self.AddFunction(BucketFunction(f))
9778 if 'shm' in methods:
9779 self.AddFunction(f)
9780 else:
9781 self.AddFunction(f)
9783 self.Log("Auto Generated Functions : %d" %
9784 len([f for f in self.functions if f.can_auto_generate or
9785 (not f.IsType('') and not f.IsType('Custom') and
9786 not f.IsType('Todo'))]))
9788 funcs = [f for f in self.functions if not f.can_auto_generate and
9789 (f.IsType('') or f.IsType('Custom') or f.IsType('Todo'))]
9790 self.Log("Non Auto Generated Functions: %d" % len(funcs))
9792 for f in funcs:
9793 self.Log(" %-10s %-20s gl%s" % (f.info['type'], f.return_type, f.name))
9795 def WriteCommandIds(self, filename):
9796 """Writes the command buffer format"""
9797 with CHeaderWriter(filename) as f:
9798 f.write("#define GLES2_COMMAND_LIST(OP) \\\n")
9799 id = 256
9800 for func in self.functions:
9801 f.write(" %-60s /* %d */ \\\n" %
9802 ("OP(%s)" % func.name, id))
9803 id += 1
9804 f.write("\n")
9806 f.write("enum CommandId {\n")
9807 f.write(" kStartPoint = cmd::kLastCommonId, "
9808 "// All GLES2 commands start after this.\n")
9809 f.write("#define GLES2_CMD_OP(name) k ## name,\n")
9810 f.write(" GLES2_COMMAND_LIST(GLES2_CMD_OP)\n")
9811 f.write("#undef GLES2_CMD_OP\n")
9812 f.write(" kNumCommands\n")
9813 f.write("};\n")
9814 f.write("\n")
9815 self.generated_cpp_filenames.append(filename)
9817 def WriteFormat(self, filename):
9818 """Writes the command buffer format"""
9819 with CHeaderWriter(filename) as f:
9820 # Forward declaration of a few enums used in constant argument
9821 # to avoid including GL header files.
9822 enum_defines = {
9823 'GL_SYNC_GPU_COMMANDS_COMPLETE': '0x9117',
9824 'GL_SYNC_FLUSH_COMMANDS_BIT': '0x00000001',
9826 f.write('\n')
9827 for enum in enum_defines:
9828 f.write("#define %s %s\n" % (enum, enum_defines[enum]))
9829 f.write('\n')
9830 for func in self.functions:
9831 if True:
9832 #gen_cmd = func.GetInfo('gen_cmd')
9833 #if gen_cmd == True or gen_cmd == None:
9834 func.WriteStruct(f)
9835 f.write("\n")
9836 self.generated_cpp_filenames.append(filename)
9838 def WriteDocs(self, filename):
9839 """Writes the command buffer doc version of the commands"""
9840 with CHeaderWriter(filename) as f:
9841 for func in self.functions:
9842 if True:
9843 #gen_cmd = func.GetInfo('gen_cmd')
9844 #if gen_cmd == True or gen_cmd == None:
9845 func.WriteDocs(f)
9846 f.write("\n")
9847 self.generated_cpp_filenames.append(filename)
9849 def WriteFormatTest(self, filename):
9850 """Writes the command buffer format test."""
9851 comment = ("// This file contains unit tests for gles2 commmands\n"
9852 "// It is included by gles2_cmd_format_test.cc\n\n")
9853 with CHeaderWriter(filename, comment) as f:
9854 for func in self.functions:
9855 if True:
9856 #gen_cmd = func.GetInfo('gen_cmd')
9857 #if gen_cmd == True or gen_cmd == None:
9858 func.WriteFormatTest(f)
9859 self.generated_cpp_filenames.append(filename)
9861 def WriteCmdHelperHeader(self, filename):
9862 """Writes the gles2 command helper."""
9863 with CHeaderWriter(filename) as f:
9864 for func in self.functions:
9865 if True:
9866 #gen_cmd = func.GetInfo('gen_cmd')
9867 #if gen_cmd == True or gen_cmd == None:
9868 func.WriteCmdHelper(f)
9869 self.generated_cpp_filenames.append(filename)
9871 def WriteServiceContextStateHeader(self, filename):
9872 """Writes the service context state header."""
9873 comment = "// It is included by context_state.h\n"
9874 with CHeaderWriter(filename, comment) as f:
9875 f.write("struct EnableFlags {\n")
9876 f.write(" EnableFlags();\n")
9877 for capability in _CAPABILITY_FLAGS:
9878 f.write(" bool %s;\n" % capability['name'])
9879 f.write(" bool cached_%s;\n" % capability['name'])
9880 f.write("};\n\n")
9882 for state_name in sorted(_STATES.keys()):
9883 state = _STATES[state_name]
9884 for item in state['states']:
9885 if isinstance(item['default'], list):
9886 f.write("%s %s[%d];\n" % (item['type'], item['name'],
9887 len(item['default'])))
9888 else:
9889 f.write("%s %s;\n" % (item['type'], item['name']))
9891 if item.get('cached', False):
9892 if isinstance(item['default'], list):
9893 f.write("%s cached_%s[%d];\n" % (item['type'], item['name'],
9894 len(item['default'])))
9895 else:
9896 f.write("%s cached_%s;\n" % (item['type'], item['name']))
9898 f.write("\n")
9899 f.write("""
9900 inline void SetDeviceCapabilityState(GLenum cap, bool enable) {
9901 switch (cap) {
9902 """)
9903 for capability in _CAPABILITY_FLAGS:
9904 f.write("""\
9905 case GL_%s:
9906 """ % capability['name'].upper())
9907 f.write("""\
9908 if (enable_flags.cached_%(name)s == enable &&
9909 !ignore_cached_state)
9910 return;
9911 enable_flags.cached_%(name)s = enable;
9912 break;
9913 """ % capability)
9915 f.write("""\
9916 default:
9917 NOTREACHED();
9918 return;
9920 if (enable)
9921 glEnable(cap);
9922 else
9923 glDisable(cap);
9925 """)
9926 self.generated_cpp_filenames.append(filename)
9928 def WriteClientContextStateHeader(self, filename):
9929 """Writes the client context state header."""
9930 comment = "// It is included by client_context_state.h\n"
9931 with CHeaderWriter(filename, comment) as f:
9932 f.write("struct EnableFlags {\n")
9933 f.write(" EnableFlags();\n")
9934 for capability in _CAPABILITY_FLAGS:
9935 f.write(" bool %s;\n" % capability['name'])
9936 f.write("};\n\n")
9937 self.generated_cpp_filenames.append(filename)
9939 def WriteContextStateGetters(self, f, class_name):
9940 """Writes the state getters."""
9941 for gl_type in ["GLint", "GLfloat"]:
9942 f.write("""
9943 bool %s::GetStateAs%s(
9944 GLenum pname, %s* params, GLsizei* num_written) const {
9945 switch (pname) {
9946 """ % (class_name, gl_type, gl_type))
9947 for state_name in sorted(_STATES.keys()):
9948 state = _STATES[state_name]
9949 if 'enum' in state:
9950 f.write(" case %s:\n" % state['enum'])
9951 f.write(" *num_written = %d;\n" % len(state['states']))
9952 f.write(" if (params) {\n")
9953 for ndx,item in enumerate(state['states']):
9954 f.write(" params[%d] = static_cast<%s>(%s);\n" %
9955 (ndx, gl_type, item['name']))
9956 f.write(" }\n")
9957 f.write(" return true;\n")
9958 else:
9959 for item in state['states']:
9960 f.write(" case %s:\n" % item['enum'])
9961 if isinstance(item['default'], list):
9962 item_len = len(item['default'])
9963 f.write(" *num_written = %d;\n" % item_len)
9964 f.write(" if (params) {\n")
9965 if item['type'] == gl_type:
9966 f.write(" memcpy(params, %s, sizeof(%s) * %d);\n" %
9967 (item['name'], item['type'], item_len))
9968 else:
9969 f.write(" for (size_t i = 0; i < %s; ++i) {\n" %
9970 item_len)
9971 f.write(" params[i] = %s;\n" %
9972 (GetGLGetTypeConversion(gl_type, item['type'],
9973 "%s[i]" % item['name'])))
9974 f.write(" }\n");
9975 else:
9976 f.write(" *num_written = 1;\n")
9977 f.write(" if (params) {\n")
9978 f.write(" params[0] = %s;\n" %
9979 (GetGLGetTypeConversion(gl_type, item['type'],
9980 item['name'])))
9981 f.write(" }\n")
9982 f.write(" return true;\n")
9983 for capability in _CAPABILITY_FLAGS:
9984 f.write(" case GL_%s:\n" % capability['name'].upper())
9985 f.write(" *num_written = 1;\n")
9986 f.write(" if (params) {\n")
9987 f.write(
9988 " params[0] = static_cast<%s>(enable_flags.%s);\n" %
9989 (gl_type, capability['name']))
9990 f.write(" }\n")
9991 f.write(" return true;\n")
9992 f.write(""" default:
9993 return false;
9996 """)
9998 def WriteServiceContextStateImpl(self, filename):
9999 """Writes the context state service implementation."""
10000 comment = "// It is included by context_state.cc\n"
10001 with CHeaderWriter(filename, comment) as f:
10002 code = []
10003 for capability in _CAPABILITY_FLAGS:
10004 code.append("%s(%s)" %
10005 (capability['name'],
10006 ('false', 'true')['default' in capability]))
10007 code.append("cached_%s(%s)" %
10008 (capability['name'],
10009 ('false', 'true')['default' in capability]))
10010 f.write("ContextState::EnableFlags::EnableFlags()\n : %s {\n}\n" %
10011 ",\n ".join(code))
10012 f.write("\n")
10014 f.write("void ContextState::Initialize() {\n")
10015 for state_name in sorted(_STATES.keys()):
10016 state = _STATES[state_name]
10017 for item in state['states']:
10018 if isinstance(item['default'], list):
10019 for ndx, value in enumerate(item['default']):
10020 f.write(" %s[%d] = %s;\n" % (item['name'], ndx, value))
10021 else:
10022 f.write(" %s = %s;\n" % (item['name'], item['default']))
10023 if item.get('cached', False):
10024 if isinstance(item['default'], list):
10025 for ndx, value in enumerate(item['default']):
10026 f.write(" cached_%s[%d] = %s;\n" % (item['name'], ndx, value))
10027 else:
10028 f.write(" cached_%s = %s;\n" % (item['name'], item['default']))
10029 f.write("}\n")
10031 f.write("""
10032 void ContextState::InitCapabilities(const ContextState* prev_state) const {
10033 """)
10034 def WriteCapabilities(test_prev, es3_caps):
10035 for capability in _CAPABILITY_FLAGS:
10036 capability_name = capability['name']
10037 capability_es3 = 'es3' in capability and capability['es3'] == True
10038 if capability_es3 and not es3_caps or not capability_es3 and es3_caps:
10039 continue
10040 if test_prev:
10041 f.write(""" if (prev_state->enable_flags.cached_%s !=
10042 enable_flags.cached_%s) {\n""" %
10043 (capability_name, capability_name))
10044 f.write(" EnableDisable(GL_%s, enable_flags.cached_%s);\n" %
10045 (capability_name.upper(), capability_name))
10046 if test_prev:
10047 f.write(" }")
10049 f.write(" if (prev_state) {")
10050 WriteCapabilities(True, False)
10051 f.write(" if (feature_info_->IsES3Capable()) {\n")
10052 WriteCapabilities(True, True)
10053 f.write(" }\n")
10054 f.write(" } else {")
10055 WriteCapabilities(False, False)
10056 f.write(" if (feature_info_->IsES3Capable()) {\n")
10057 WriteCapabilities(False, True)
10058 f.write(" }\n")
10059 f.write(" }")
10060 f.write("""}
10062 void ContextState::InitState(const ContextState *prev_state) const {
10063 """)
10065 def WriteStates(test_prev):
10066 # We need to sort the keys so the expectations match
10067 for state_name in sorted(_STATES.keys()):
10068 state = _STATES[state_name]
10069 if state['type'] == 'FrontBack':
10070 num_states = len(state['states'])
10071 for ndx, group in enumerate(Grouper(num_states / 2,
10072 state['states'])):
10073 if test_prev:
10074 f.write(" if (")
10075 args = []
10076 for place, item in enumerate(group):
10077 item_name = CachedStateName(item)
10078 args.append('%s' % item_name)
10079 if test_prev:
10080 if place > 0:
10081 f.write(' ||\n')
10082 f.write("(%s != prev_state->%s)" % (item_name, item_name))
10083 if test_prev:
10084 f.write(")\n")
10085 f.write(
10086 " gl%s(%s, %s);\n" %
10087 (state['func'], ('GL_FRONT', 'GL_BACK')[ndx],
10088 ", ".join(args)))
10089 elif state['type'] == 'NamedParameter':
10090 for item in state['states']:
10091 item_name = CachedStateName(item)
10093 if 'extension_flag' in item:
10094 f.write(" if (feature_info_->feature_flags().%s) {\n " %
10095 item['extension_flag'])
10096 if test_prev:
10097 if isinstance(item['default'], list):
10098 f.write(" if (memcmp(prev_state->%s, %s, "
10099 "sizeof(%s) * %d)) {\n" %
10100 (item_name, item_name, item['type'],
10101 len(item['default'])))
10102 else:
10103 f.write(" if (prev_state->%s != %s) {\n " %
10104 (item_name, item_name))
10105 if 'gl_version_flag' in item:
10106 item_name = item['gl_version_flag']
10107 inverted = ''
10108 if item_name[0] == '!':
10109 inverted = '!'
10110 item_name = item_name[1:]
10111 f.write(" if (%sfeature_info_->gl_version_info().%s) {\n" %
10112 (inverted, item_name))
10113 f.write(" gl%s(%s, %s);\n" %
10114 (state['func'],
10115 (item['enum_set']
10116 if 'enum_set' in item else item['enum']),
10117 item['name']))
10118 if 'gl_version_flag' in item:
10119 f.write(" }\n")
10120 if test_prev:
10121 if 'extension_flag' in item:
10122 f.write(" ")
10123 f.write(" }")
10124 if 'extension_flag' in item:
10125 f.write(" }")
10126 else:
10127 if 'extension_flag' in state:
10128 f.write(" if (feature_info_->feature_flags().%s)\n " %
10129 state['extension_flag'])
10130 if test_prev:
10131 f.write(" if (")
10132 args = []
10133 for place, item in enumerate(state['states']):
10134 item_name = CachedStateName(item)
10135 args.append('%s' % item_name)
10136 if test_prev:
10137 if place > 0:
10138 f.write(' ||\n')
10139 f.write("(%s != prev_state->%s)" %
10140 (item_name, item_name))
10141 if test_prev:
10142 f.write(" )\n")
10143 f.write(" gl%s(%s);\n" % (state['func'], ", ".join(args)))
10145 f.write(" if (prev_state) {")
10146 WriteStates(True)
10147 f.write(" } else {")
10148 WriteStates(False)
10149 f.write(" }")
10150 f.write("}\n")
10152 f.write("""bool ContextState::GetEnabled(GLenum cap) const {
10153 switch (cap) {
10154 """)
10155 for capability in _CAPABILITY_FLAGS:
10156 f.write(" case GL_%s:\n" % capability['name'].upper())
10157 f.write(" return enable_flags.%s;\n" % capability['name'])
10158 f.write(""" default:
10159 NOTREACHED();
10160 return false;
10163 """)
10164 self.WriteContextStateGetters(f, "ContextState")
10165 self.generated_cpp_filenames.append(filename)
10167 def WriteClientContextStateImpl(self, filename):
10168 """Writes the context state client side implementation."""
10169 comment = "// It is included by client_context_state.cc\n"
10170 with CHeaderWriter(filename, comment) as f:
10171 code = []
10172 for capability in _CAPABILITY_FLAGS:
10173 code.append("%s(%s)" %
10174 (capability['name'],
10175 ('false', 'true')['default' in capability]))
10176 f.write(
10177 "ClientContextState::EnableFlags::EnableFlags()\n : %s {\n}\n" %
10178 ",\n ".join(code))
10179 f.write("\n")
10181 f.write("""
10182 bool ClientContextState::SetCapabilityState(
10183 GLenum cap, bool enabled, bool* changed) {
10184 *changed = false;
10185 switch (cap) {
10186 """)
10187 for capability in _CAPABILITY_FLAGS:
10188 f.write(" case GL_%s:\n" % capability['name'].upper())
10189 f.write(""" if (enable_flags.%(name)s != enabled) {
10190 *changed = true;
10191 enable_flags.%(name)s = enabled;
10193 return true;
10194 """ % capability)
10195 f.write(""" default:
10196 return false;
10199 """)
10200 f.write("""bool ClientContextState::GetEnabled(
10201 GLenum cap, bool* enabled) const {
10202 switch (cap) {
10203 """)
10204 for capability in _CAPABILITY_FLAGS:
10205 f.write(" case GL_%s:\n" % capability['name'].upper())
10206 f.write(" *enabled = enable_flags.%s;\n" % capability['name'])
10207 f.write(" return true;\n")
10208 f.write(""" default:
10209 return false;
10212 """)
10213 self.generated_cpp_filenames.append(filename)
10215 def WriteServiceImplementation(self, filename):
10216 """Writes the service decorder implementation."""
10217 comment = "// It is included by gles2_cmd_decoder.cc\n"
10218 with CHeaderWriter(filename, comment) as f:
10219 for func in self.functions:
10220 if True:
10221 #gen_cmd = func.GetInfo('gen_cmd')
10222 #if gen_cmd == True or gen_cmd == None:
10223 func.WriteServiceImplementation(f)
10225 f.write("""
10226 bool GLES2DecoderImpl::SetCapabilityState(GLenum cap, bool enabled) {
10227 switch (cap) {
10228 """)
10229 for capability in _CAPABILITY_FLAGS:
10230 f.write(" case GL_%s:\n" % capability['name'].upper())
10231 if 'state_flag' in capability:
10233 f.write("""\
10234 state_.enable_flags.%(name)s = enabled;
10235 if (state_.enable_flags.cached_%(name)s != enabled
10236 || state_.ignore_cached_state) {
10237 %(state_flag)s = true;
10239 return false;
10240 """ % capability)
10241 else:
10242 f.write("""\
10243 state_.enable_flags.%(name)s = enabled;
10244 if (state_.enable_flags.cached_%(name)s != enabled
10245 || state_.ignore_cached_state) {
10246 state_.enable_flags.cached_%(name)s = enabled;
10247 return true;
10249 return false;
10250 """ % capability)
10251 f.write(""" default:
10252 NOTREACHED();
10253 return false;
10256 """)
10257 self.generated_cpp_filenames.append(filename)
10259 def WriteServiceUnitTests(self, filename_pattern):
10260 """Writes the service decorder unit tests."""
10261 num_tests = len(self.functions)
10262 FUNCTIONS_PER_FILE = 98 # hard code this so it doesn't change.
10263 count = 0
10264 for test_num in range(0, num_tests, FUNCTIONS_PER_FILE):
10265 count += 1
10266 filename = filename_pattern % count
10267 comment = "// It is included by gles2_cmd_decoder_unittest_%d.cc\n" \
10268 % count
10269 with CHeaderWriter(filename, comment) as f:
10270 test_name = 'GLES2DecoderTest%d' % count
10271 end = test_num + FUNCTIONS_PER_FILE
10272 if end > num_tests:
10273 end = num_tests
10274 for idx in range(test_num, end):
10275 func = self.functions[idx]
10277 # Do any filtering of the functions here, so that the functions
10278 # will not move between the numbered files if filtering properties
10279 # are changed.
10280 if func.GetInfo('extension_flag'):
10281 continue
10283 if True:
10284 #gen_cmd = func.GetInfo('gen_cmd')
10285 #if gen_cmd == True or gen_cmd == None:
10286 if func.GetInfo('unit_test') == False:
10287 f.write("// TODO(gman): %s\n" % func.name)
10288 else:
10289 func.WriteServiceUnitTest(f, {
10290 'test_name': test_name
10292 self.generated_cpp_filenames.append(filename)
10294 comment = "// It is included by gles2_cmd_decoder_unittest_base.cc\n"
10295 filename = filename_pattern % 0
10296 with CHeaderWriter(filename, comment) as f:
10297 f.write(
10298 """void GLES2DecoderTestBase::SetupInitCapabilitiesExpectations(
10299 bool es3_capable) {""")
10300 for capability in _CAPABILITY_FLAGS:
10301 capability_es3 = 'es3' in capability and capability['es3'] == True
10302 if not capability_es3:
10303 f.write(" ExpectEnableDisable(GL_%s, %s);\n" %
10304 (capability['name'].upper(),
10305 ('false', 'true')['default' in capability]))
10307 f.write(" if (es3_capable) {")
10308 for capability in _CAPABILITY_FLAGS:
10309 capability_es3 = 'es3' in capability and capability['es3'] == True
10310 if capability_es3:
10311 f.write(" ExpectEnableDisable(GL_%s, %s);\n" %
10312 (capability['name'].upper(),
10313 ('false', 'true')['default' in capability]))
10314 f.write(""" }
10317 void GLES2DecoderTestBase::SetupInitStateExpectations() {
10318 """)
10319 # We need to sort the keys so the expectations match
10320 for state_name in sorted(_STATES.keys()):
10321 state = _STATES[state_name]
10322 if state['type'] == 'FrontBack':
10323 num_states = len(state['states'])
10324 for ndx, group in enumerate(Grouper(num_states / 2, state['states'])):
10325 args = []
10326 for item in group:
10327 if 'expected' in item:
10328 args.append(item['expected'])
10329 else:
10330 args.append(item['default'])
10331 f.write(
10332 " EXPECT_CALL(*gl_, %s(%s, %s))\n" %
10333 (state['func'], ('GL_FRONT', 'GL_BACK')[ndx], ", ".join(args)))
10334 f.write(" .Times(1)\n")
10335 f.write(" .RetiresOnSaturation();\n")
10336 elif state['type'] == 'NamedParameter':
10337 for item in state['states']:
10338 if 'extension_flag' in item:
10339 f.write(" if (group_->feature_info()->feature_flags().%s) {\n" %
10340 item['extension_flag'])
10341 f.write(" ")
10342 expect_value = item['default']
10343 if isinstance(expect_value, list):
10344 # TODO: Currently we do not check array values.
10345 expect_value = "_"
10347 f.write(
10348 " EXPECT_CALL(*gl_, %s(%s, %s))\n" %
10349 (state['func'],
10350 (item['enum_set']
10351 if 'enum_set' in item else item['enum']),
10352 expect_value))
10353 f.write(" .Times(1)\n")
10354 f.write(" .RetiresOnSaturation();\n")
10355 if 'extension_flag' in item:
10356 f.write(" }\n")
10357 else:
10358 if 'extension_flag' in state:
10359 f.write(" if (group_->feature_info()->feature_flags().%s) {\n" %
10360 state['extension_flag'])
10361 f.write(" ")
10362 args = []
10363 for item in state['states']:
10364 if 'expected' in item:
10365 args.append(item['expected'])
10366 else:
10367 args.append(item['default'])
10368 # TODO: Currently we do not check array values.
10369 args = ["_" if isinstance(arg, list) else arg for arg in args]
10370 f.write(" EXPECT_CALL(*gl_, %s(%s))\n" %
10371 (state['func'], ", ".join(args)))
10372 f.write(" .Times(1)\n")
10373 f.write(" .RetiresOnSaturation();\n")
10374 if 'extension_flag' in state:
10375 f.write(" }\n")
10376 f.write("}\n")
10377 self.generated_cpp_filenames.append(filename)
10379 def WriteServiceUnitTestsForExtensions(self, filename):
10380 """Writes the service decorder unit tests for functions with extension_flag.
10382 The functions are special in that they need a specific unit test
10383 baseclass to turn on the extension.
10385 functions = [f for f in self.functions if f.GetInfo('extension_flag')]
10386 comment = "// It is included by gles2_cmd_decoder_unittest_extensions.cc\n"
10387 with CHeaderWriter(filename, comment) as f:
10388 for func in functions:
10389 if True:
10390 if func.GetInfo('unit_test') == False:
10391 f.write("// TODO(gman): %s\n" % func.name)
10392 else:
10393 extension = ToCamelCase(
10394 ToGLExtensionString(func.GetInfo('extension_flag')))
10395 func.WriteServiceUnitTest(f, {
10396 'test_name': 'GLES2DecoderTestWith%s' % extension
10398 self.generated_cpp_filenames.append(filename)
10400 def WriteGLES2Header(self, filename):
10401 """Writes the GLES2 header."""
10402 comment = "// This file contains Chromium-specific GLES2 declarations.\n\n"
10403 with CHeaderWriter(filename, comment) as f:
10404 for func in self.original_functions:
10405 func.WriteGLES2Header(f)
10406 f.write("\n")
10407 self.generated_cpp_filenames.append(filename)
10409 def WriteGLES2CLibImplementation(self, filename):
10410 """Writes the GLES2 c lib implementation."""
10411 comment = "// These functions emulate GLES2 over command buffers.\n"
10412 with CHeaderWriter(filename, comment) as f:
10413 for func in self.original_functions:
10414 func.WriteGLES2CLibImplementation(f)
10415 f.write("""
10416 namespace gles2 {
10418 extern const NameToFunc g_gles2_function_table[] = {
10419 """)
10420 for func in self.original_functions:
10421 f.write(
10422 ' { "gl%s", reinterpret_cast<GLES2FunctionPointer>(gl%s), },\n' %
10423 (func.name, func.name))
10424 f.write(""" { NULL, NULL, },
10427 } // namespace gles2
10428 """)
10429 self.generated_cpp_filenames.append(filename)
10431 def WriteGLES2InterfaceHeader(self, filename):
10432 """Writes the GLES2 interface header."""
10433 comment = ("// This file is included by gles2_interface.h to declare the\n"
10434 "// GL api functions.\n")
10435 with CHeaderWriter(filename, comment) as f:
10436 for func in self.original_functions:
10437 func.WriteGLES2InterfaceHeader(f)
10438 self.generated_cpp_filenames.append(filename)
10440 def WriteMojoGLES2ImplHeader(self, filename):
10441 """Writes the Mojo GLES2 implementation header."""
10442 comment = ("// This file is included by gles2_interface.h to declare the\n"
10443 "// GL api functions.\n")
10444 code = """
10445 #include "gpu/command_buffer/client/gles2_interface.h"
10446 #include "third_party/mojo/src/mojo/public/c/gles2/gles2.h"
10448 namespace mojo {
10450 class MojoGLES2Impl : public gpu::gles2::GLES2Interface {
10451 public:
10452 explicit MojoGLES2Impl(MojoGLES2Context context) {
10453 context_ = context;
10455 ~MojoGLES2Impl() override {}
10457 with CHeaderWriter(filename, comment) as f:
10458 f.write(code);
10459 for func in self.original_functions:
10460 func.WriteMojoGLES2ImplHeader(f)
10461 code = """
10462 private:
10463 MojoGLES2Context context_;
10466 } // namespace mojo
10468 f.write(code);
10469 self.generated_cpp_filenames.append(filename)
10471 def WriteMojoGLES2Impl(self, filename):
10472 """Writes the Mojo GLES2 implementation."""
10473 code = """
10474 #include "mojo/gpu/mojo_gles2_impl_autogen.h"
10476 #include "base/logging.h"
10477 #include "third_party/mojo/src/mojo/public/c/gles2/chromium_copy_texture.h"
10478 #include "third_party/mojo/src/mojo/public/c/gles2/chromium_image.h"
10479 #include "third_party/mojo/src/mojo/public/c/gles2/chromium_miscellaneous.h"
10480 #include "third_party/mojo/src/mojo/public/c/gles2/chromium_pixel_transfer_buffer_object.h"
10481 #include "third_party/mojo/src/mojo/public/c/gles2/chromium_sub_image.h"
10482 #include "third_party/mojo/src/mojo/public/c/gles2/chromium_sync_point.h"
10483 #include "third_party/mojo/src/mojo/public/c/gles2/chromium_texture_mailbox.h"
10484 #include "third_party/mojo/src/mojo/public/c/gles2/gles2.h"
10485 #include "third_party/mojo/src/mojo/public/c/gles2/occlusion_query_ext.h"
10487 namespace mojo {
10490 with CWriter(filename) as f:
10491 f.write(code);
10492 for func in self.original_functions:
10493 func.WriteMojoGLES2Impl(f)
10494 code = """
10496 } // namespace mojo
10498 f.write(code);
10499 self.generated_cpp_filenames.append(filename)
10501 def WriteGLES2InterfaceStub(self, filename):
10502 """Writes the GLES2 interface stub header."""
10503 comment = "// This file is included by gles2_interface_stub.h.\n"
10504 with CHeaderWriter(filename, comment) as f:
10505 for func in self.original_functions:
10506 func.WriteGLES2InterfaceStub(f)
10507 self.generated_cpp_filenames.append(filename)
10509 def WriteGLES2InterfaceStubImpl(self, filename):
10510 """Writes the GLES2 interface header."""
10511 comment = "// This file is included by gles2_interface_stub.cc.\n"
10512 with CHeaderWriter(filename, comment) as f:
10513 for func in self.original_functions:
10514 func.WriteGLES2InterfaceStubImpl(f)
10515 self.generated_cpp_filenames.append(filename)
10517 def WriteGLES2ImplementationHeader(self, filename):
10518 """Writes the GLES2 Implementation header."""
10519 comment = \
10520 ("// This file is included by gles2_implementation.h to declare the\n"
10521 "// GL api functions.\n")
10522 with CHeaderWriter(filename, comment) as f:
10523 for func in self.original_functions:
10524 func.WriteGLES2ImplementationHeader(f)
10525 self.generated_cpp_filenames.append(filename)
10527 def WriteGLES2Implementation(self, filename):
10528 """Writes the GLES2 Implementation."""
10529 comment = \
10530 ("// This file is included by gles2_implementation.cc to define the\n"
10531 "// GL api functions.\n")
10532 with CHeaderWriter(filename, comment) as f:
10533 for func in self.original_functions:
10534 func.WriteGLES2Implementation(f)
10535 self.generated_cpp_filenames.append(filename)
10537 def WriteGLES2TraceImplementationHeader(self, filename):
10538 """Writes the GLES2 Trace Implementation header."""
10539 comment = "// This file is included by gles2_trace_implementation.h\n"
10540 with CHeaderWriter(filename, comment) as f:
10541 for func in self.original_functions:
10542 func.WriteGLES2TraceImplementationHeader(f)
10543 self.generated_cpp_filenames.append(filename)
10545 def WriteGLES2TraceImplementation(self, filename):
10546 """Writes the GLES2 Trace Implementation."""
10547 comment = "// This file is included by gles2_trace_implementation.cc\n"
10548 with CHeaderWriter(filename, comment) as f:
10549 for func in self.original_functions:
10550 func.WriteGLES2TraceImplementation(f)
10551 self.generated_cpp_filenames.append(filename)
10553 def WriteGLES2ImplementationUnitTests(self, filename):
10554 """Writes the GLES2 helper header."""
10555 comment = \
10556 ("// This file is included by gles2_implementation.h to declare the\n"
10557 "// GL api functions.\n")
10558 with CHeaderWriter(filename, comment) as f:
10559 for func in self.original_functions:
10560 func.WriteGLES2ImplementationUnitTest(f)
10561 self.generated_cpp_filenames.append(filename)
10563 def WriteServiceUtilsHeader(self, filename):
10564 """Writes the gles2 auto generated utility header."""
10565 with CHeaderWriter(filename) as f:
10566 for name in sorted(_NAMED_TYPE_INFO.keys()):
10567 named_type = NamedType(_NAMED_TYPE_INFO[name])
10568 if named_type.IsConstant():
10569 continue
10570 f.write("ValueValidator<%s> %s;\n" %
10571 (named_type.GetType(), ToUnderscore(name)))
10572 f.write("\n")
10573 self.generated_cpp_filenames.append(filename)
10575 def WriteServiceUtilsImplementation(self, filename):
10576 """Writes the gles2 auto generated utility implementation."""
10577 with CHeaderWriter(filename) as f:
10578 names = sorted(_NAMED_TYPE_INFO.keys())
10579 for name in names:
10580 named_type = NamedType(_NAMED_TYPE_INFO[name])
10581 if named_type.IsConstant():
10582 continue
10583 if named_type.GetValidValues():
10584 f.write("static const %s valid_%s_table[] = {\n" %
10585 (named_type.GetType(), ToUnderscore(name)))
10586 for value in named_type.GetValidValues():
10587 f.write(" %s,\n" % value)
10588 f.write("};\n")
10589 f.write("\n")
10590 if named_type.GetValidValuesES3():
10591 f.write("static const %s valid_%s_table_es3[] = {\n" %
10592 (named_type.GetType(), ToUnderscore(name)))
10593 for value in named_type.GetValidValuesES3():
10594 f.write(" %s,\n" % value)
10595 f.write("};\n")
10596 f.write("\n")
10597 if named_type.GetDeprecatedValuesES3():
10598 f.write("static const %s deprecated_%s_table_es3[] = {\n" %
10599 (named_type.GetType(), ToUnderscore(name)))
10600 for value in named_type.GetDeprecatedValuesES3():
10601 f.write(" %s,\n" % value)
10602 f.write("};\n")
10603 f.write("\n")
10604 f.write("Validators::Validators()")
10605 pre = ' : '
10606 for count, name in enumerate(names):
10607 named_type = NamedType(_NAMED_TYPE_INFO[name])
10608 if named_type.IsConstant():
10609 continue
10610 if named_type.GetValidValues():
10611 code = """%(pre)s%(name)s(
10612 valid_%(name)s_table, arraysize(valid_%(name)s_table))"""
10613 else:
10614 code = "%(pre)s%(name)s()"
10615 f.write(code % {
10616 'name': ToUnderscore(name),
10617 'pre': pre,
10619 pre = ',\n '
10620 f.write(" {\n");
10621 f.write("}\n\n");
10623 f.write("void Validators::UpdateValuesES3() {\n")
10624 for name in names:
10625 named_type = NamedType(_NAMED_TYPE_INFO[name])
10626 if named_type.GetDeprecatedValuesES3():
10627 code = """ %(name)s.RemoveValues(
10628 deprecated_%(name)s_table_es3, arraysize(deprecated_%(name)s_table_es3));
10630 f.write(code % {
10631 'name': ToUnderscore(name),
10633 if named_type.GetValidValuesES3():
10634 code = """ %(name)s.AddValues(
10635 valid_%(name)s_table_es3, arraysize(valid_%(name)s_table_es3));
10637 f.write(code % {
10638 'name': ToUnderscore(name),
10640 f.write("}\n\n");
10641 self.generated_cpp_filenames.append(filename)
10643 def WriteCommonUtilsHeader(self, filename):
10644 """Writes the gles2 common utility header."""
10645 with CHeaderWriter(filename) as f:
10646 type_infos = sorted(_NAMED_TYPE_INFO.keys())
10647 for type_info in type_infos:
10648 if _NAMED_TYPE_INFO[type_info]['type'] == 'GLenum':
10649 f.write("static std::string GetString%s(uint32_t value);\n" %
10650 type_info)
10651 f.write("\n")
10652 self.generated_cpp_filenames.append(filename)
10654 def WriteCommonUtilsImpl(self, filename):
10655 """Writes the gles2 common utility header."""
10656 enum_re = re.compile(r'\#define\s+(GL_[a-zA-Z0-9_]+)\s+([0-9A-Fa-fx]+)')
10657 dict = {}
10658 for fname in ['third_party/khronos/GLES2/gl2.h',
10659 'third_party/khronos/GLES2/gl2ext.h',
10660 'third_party/khronos/GLES3/gl3.h',
10661 'gpu/GLES2/gl2chromium.h',
10662 'gpu/GLES2/gl2extchromium.h']:
10663 lines = open(fname).readlines()
10664 for line in lines:
10665 m = enum_re.match(line)
10666 if m:
10667 name = m.group(1)
10668 value = m.group(2)
10669 if len(value) <= 10:
10670 if not value in dict:
10671 dict[value] = name
10672 # check our own _CHROMIUM macro conflicts with khronos GL headers.
10673 elif dict[value] != name and (name.endswith('_CHROMIUM') or
10674 dict[value].endswith('_CHROMIUM')):
10675 self.Error("code collision: %s and %s have the same code %s" %
10676 (dict[value], name, value))
10678 with CHeaderWriter(filename) as f:
10679 f.write("static const GLES2Util::EnumToString "
10680 "enum_to_string_table[] = {\n")
10681 for value in dict:
10682 f.write(' { %s, "%s", },\n' % (value, dict[value]))
10683 f.write("""};
10685 const GLES2Util::EnumToString* const GLES2Util::enum_to_string_table_ =
10686 enum_to_string_table;
10687 const size_t GLES2Util::enum_to_string_table_len_ =
10688 sizeof(enum_to_string_table) / sizeof(enum_to_string_table[0]);
10690 """)
10692 enums = sorted(_NAMED_TYPE_INFO.keys())
10693 for enum in enums:
10694 if _NAMED_TYPE_INFO[enum]['type'] == 'GLenum':
10695 f.write("std::string GLES2Util::GetString%s(uint32_t value) {\n" %
10696 enum)
10697 valid_list = _NAMED_TYPE_INFO[enum]['valid']
10698 if 'valid_es3' in _NAMED_TYPE_INFO[enum]:
10699 valid_list = valid_list + _NAMED_TYPE_INFO[enum]['valid_es3']
10700 assert len(valid_list) == len(set(valid_list))
10701 if len(valid_list) > 0:
10702 f.write(" static const EnumToString string_table[] = {\n")
10703 for value in valid_list:
10704 f.write(' { %s, "%s" },\n' % (value, value))
10705 f.write(""" };
10706 return GLES2Util::GetQualifiedEnumString(
10707 string_table, arraysize(string_table), value);
10710 """)
10711 else:
10712 f.write(""" return GLES2Util::GetQualifiedEnumString(
10713 NULL, 0, value);
10716 """)
10717 self.generated_cpp_filenames.append(filename)
10719 def WritePepperGLES2Interface(self, filename, dev):
10720 """Writes the Pepper OpenGLES interface definition."""
10721 with CWriter(filename) as f:
10722 f.write("label Chrome {\n")
10723 f.write(" M39 = 1.0\n")
10724 f.write("};\n\n")
10726 if not dev:
10727 # Declare GL types.
10728 f.write("[version=1.0]\n")
10729 f.write("describe {\n")
10730 for gltype in ['GLbitfield', 'GLboolean', 'GLbyte', 'GLclampf',
10731 'GLclampx', 'GLenum', 'GLfixed', 'GLfloat', 'GLint',
10732 'GLintptr', 'GLshort', 'GLsizei', 'GLsizeiptr',
10733 'GLubyte', 'GLuint', 'GLushort']:
10734 f.write(" %s;\n" % gltype)
10735 f.write(" %s_ptr_t;\n" % gltype)
10736 f.write("};\n\n")
10738 # C level typedefs.
10739 f.write("#inline c\n")
10740 f.write("#include \"ppapi/c/pp_resource.h\"\n")
10741 if dev:
10742 f.write("#include \"ppapi/c/ppb_opengles2.h\"\n\n")
10743 else:
10744 f.write("\n#ifndef __gl2_h_\n")
10745 for (k, v) in _GL_TYPES.iteritems():
10746 f.write("typedef %s %s;\n" % (v, k))
10747 f.write("#ifdef _WIN64\n")
10748 for (k, v) in _GL_TYPES_64.iteritems():
10749 f.write("typedef %s %s;\n" % (v, k))
10750 f.write("#else\n")
10751 for (k, v) in _GL_TYPES_32.iteritems():
10752 f.write("typedef %s %s;\n" % (v, k))
10753 f.write("#endif // _WIN64\n")
10754 f.write("#endif // __gl2_h_\n\n")
10755 f.write("#endinl\n")
10757 for interface in self.pepper_interfaces:
10758 if interface.dev != dev:
10759 continue
10760 # Historically, we provide OpenGLES2 interfaces with struct
10761 # namespace. Not to break code which uses the interface as
10762 # "struct OpenGLES2", we put it in struct namespace.
10763 f.write('\n[macro="%s", force_struct_namespace]\n' %
10764 interface.GetInterfaceName())
10765 f.write("interface %s {\n" % interface.GetStructName())
10766 for func in self.original_functions:
10767 if not func.InPepperInterface(interface):
10768 continue
10770 ret_type = func.MapCTypeToPepperIdlType(func.return_type,
10771 is_for_return_type=True)
10772 func_prefix = " %s %s(" % (ret_type, func.GetPepperName())
10773 f.write(func_prefix)
10774 f.write("[in] PP_Resource context")
10775 for arg in func.MakeTypedPepperIdlArgStrings():
10776 f.write(",\n" + " " * len(func_prefix) + arg)
10777 f.write(");\n")
10778 f.write("};\n\n")
10780 def WritePepperGLES2Implementation(self, filename):
10781 """Writes the Pepper OpenGLES interface implementation."""
10782 with CWriter(filename) as f:
10783 f.write("#include \"ppapi/shared_impl/ppb_opengles2_shared.h\"\n\n")
10784 f.write("#include \"base/logging.h\"\n")
10785 f.write("#include \"gpu/command_buffer/client/gles2_implementation.h\"\n")
10786 f.write("#include \"ppapi/shared_impl/ppb_graphics_3d_shared.h\"\n")
10787 f.write("#include \"ppapi/thunk/enter.h\"\n\n")
10789 f.write("namespace ppapi {\n\n")
10790 f.write("namespace {\n\n")
10792 f.write("typedef thunk::EnterResource<thunk::PPB_Graphics3D_API>"
10793 " Enter3D;\n\n")
10795 f.write("gpu::gles2::GLES2Implementation* ToGles2Impl(Enter3D*"
10796 " enter) {\n")
10797 f.write(" DCHECK(enter);\n")
10798 f.write(" DCHECK(enter->succeeded());\n")
10799 f.write(" return static_cast<PPB_Graphics3D_Shared*>(enter->object())->"
10800 "gles2_impl();\n");
10801 f.write("}\n\n");
10803 for func in self.original_functions:
10804 if not func.InAnyPepperExtension():
10805 continue
10807 original_arg = func.MakeTypedPepperArgString("")
10808 context_arg = "PP_Resource context_id"
10809 if len(original_arg):
10810 arg = context_arg + ", " + original_arg
10811 else:
10812 arg = context_arg
10813 f.write("%s %s(%s) {\n" %
10814 (func.return_type, func.GetPepperName(), arg))
10815 f.write(" Enter3D enter(context_id, true);\n")
10816 f.write(" if (enter.succeeded()) {\n")
10818 return_str = "" if func.return_type == "void" else "return "
10819 f.write(" %sToGles2Impl(&enter)->%s(%s);\n" %
10820 (return_str, func.original_name,
10821 func.MakeOriginalArgString("")))
10822 f.write(" }")
10823 if func.return_type == "void":
10824 f.write("\n")
10825 else:
10826 f.write(" else {\n")
10827 f.write(" return %s;\n" % func.GetErrorReturnString())
10828 f.write(" }\n")
10829 f.write("}\n\n")
10831 f.write("} // namespace\n")
10833 for interface in self.pepper_interfaces:
10834 f.write("const %s* PPB_OpenGLES2_Shared::Get%sInterface() {\n" %
10835 (interface.GetStructName(), interface.GetName()))
10836 f.write(" static const struct %s "
10837 "ppb_opengles2 = {\n" % interface.GetStructName())
10838 f.write(" &")
10839 f.write(",\n &".join(
10840 f.GetPepperName() for f in self.original_functions
10841 if f.InPepperInterface(interface)))
10842 f.write("\n")
10844 f.write(" };\n")
10845 f.write(" return &ppb_opengles2;\n")
10846 f.write("}\n")
10848 f.write("} // namespace ppapi\n")
10849 self.generated_cpp_filenames.append(filename)
10851 def WriteGLES2ToPPAPIBridge(self, filename):
10852 """Connects GLES2 helper library to PPB_OpenGLES2 interface"""
10853 with CWriter(filename) as f:
10854 f.write("#ifndef GL_GLEXT_PROTOTYPES\n")
10855 f.write("#define GL_GLEXT_PROTOTYPES\n")
10856 f.write("#endif\n")
10857 f.write("#include <GLES2/gl2.h>\n")
10858 f.write("#include <GLES2/gl2ext.h>\n")
10859 f.write("#include \"ppapi/lib/gl/gles2/gl2ext_ppapi.h\"\n\n")
10861 for func in self.original_functions:
10862 if not func.InAnyPepperExtension():
10863 continue
10865 interface = self.interface_info[func.GetInfo('pepper_interface') or '']
10867 f.write("%s GL_APIENTRY gl%s(%s) {\n" %
10868 (func.return_type, func.GetPepperName(),
10869 func.MakeTypedPepperArgString("")))
10870 return_str = "" if func.return_type == "void" else "return "
10871 interface_str = "glGet%sInterfacePPAPI()" % interface.GetName()
10872 original_arg = func.MakeOriginalArgString("")
10873 context_arg = "glGetCurrentContextPPAPI()"
10874 if len(original_arg):
10875 arg = context_arg + ", " + original_arg
10876 else:
10877 arg = context_arg
10878 if interface.GetName():
10879 f.write(" const struct %s* ext = %s;\n" %
10880 (interface.GetStructName(), interface_str))
10881 f.write(" if (ext)\n")
10882 f.write(" %sext->%s(%s);\n" %
10883 (return_str, func.GetPepperName(), arg))
10884 if return_str:
10885 f.write(" %s0;\n" % return_str)
10886 else:
10887 f.write(" %s%s->%s(%s);\n" %
10888 (return_str, interface_str, func.GetPepperName(), arg))
10889 f.write("}\n\n")
10890 self.generated_cpp_filenames.append(filename)
10892 def WriteMojoGLCallVisitor(self, filename):
10893 """Provides the GL implementation for mojo"""
10894 with CWriter(filename) as f:
10895 for func in self.original_functions:
10896 if not func.IsCoreGLFunction():
10897 continue
10898 f.write("VISIT_GL_CALL(%s, %s, (%s), (%s))\n" %
10899 (func.name, func.return_type,
10900 func.MakeTypedOriginalArgString(""),
10901 func.MakeOriginalArgString("")))
10902 self.generated_cpp_filenames.append(filename)
10904 def WriteMojoGLCallVisitorForExtension(self, filename, extension):
10905 """Provides the GL implementation for mojo for a particular extension"""
10906 with CWriter(filename) as f:
10907 for func in self.original_functions:
10908 if func.GetInfo("extension") != extension:
10909 continue
10910 f.write("VISIT_GL_CALL(%s, %s, (%s), (%s))\n" %
10911 (func.name, func.return_type,
10912 func.MakeTypedOriginalArgString(""),
10913 func.MakeOriginalArgString("")))
10914 self.generated_cpp_filenames.append(filename)
10916 def Format(generated_files):
10917 formatter = "clang-format"
10918 if platform.system() == "Windows":
10919 formatter += ".bat"
10920 for filename in generated_files:
10921 call([formatter, "-i", "-style=chromium", filename])
10923 def main(argv):
10924 """This is the main function."""
10925 parser = OptionParser()
10926 parser.add_option(
10927 "--output-dir",
10928 help="base directory for resulting files, under chrome/src. default is "
10929 "empty. Use this if you want the result stored under gen.")
10930 parser.add_option(
10931 "-v", "--verbose", action="store_true",
10932 help="prints more output.")
10934 (options, args) = parser.parse_args(args=argv)
10936 # Add in states and capabilites to GLState
10937 gl_state_valid = _NAMED_TYPE_INFO['GLState']['valid']
10938 for state_name in sorted(_STATES.keys()):
10939 state = _STATES[state_name]
10940 if 'extension_flag' in state:
10941 continue
10942 if 'enum' in state:
10943 if not state['enum'] in gl_state_valid:
10944 gl_state_valid.append(state['enum'])
10945 else:
10946 for item in state['states']:
10947 if 'extension_flag' in item:
10948 continue
10949 if not item['enum'] in gl_state_valid:
10950 gl_state_valid.append(item['enum'])
10951 for capability in _CAPABILITY_FLAGS:
10952 valid_value = "GL_%s" % capability['name'].upper()
10953 if not valid_value in gl_state_valid:
10954 gl_state_valid.append(valid_value)
10956 # This script lives under gpu/command_buffer, cd to base directory.
10957 os.chdir(os.path.dirname(__file__) + "/../..")
10958 base_dir = os.getcwd()
10959 gen = GLGenerator(options.verbose)
10960 gen.ParseGLH("gpu/command_buffer/cmd_buffer_functions.txt")
10962 # Support generating files under gen/
10963 if options.output_dir != None:
10964 os.chdir(options.output_dir)
10966 gen.WritePepperGLES2Interface("ppapi/api/ppb_opengles2.idl", False)
10967 gen.WritePepperGLES2Interface("ppapi/api/dev/ppb_opengles2ext_dev.idl", True)
10968 gen.WriteGLES2ToPPAPIBridge("ppapi/lib/gl/gles2/gles2.c")
10969 gen.WritePepperGLES2Implementation(
10970 "ppapi/shared_impl/ppb_opengles2_shared.cc")
10971 os.chdir(base_dir)
10972 gen.WriteCommandIds("gpu/command_buffer/common/gles2_cmd_ids_autogen.h")
10973 gen.WriteFormat("gpu/command_buffer/common/gles2_cmd_format_autogen.h")
10974 gen.WriteFormatTest(
10975 "gpu/command_buffer/common/gles2_cmd_format_test_autogen.h")
10976 gen.WriteGLES2InterfaceHeader(
10977 "gpu/command_buffer/client/gles2_interface_autogen.h")
10978 gen.WriteMojoGLES2ImplHeader(
10979 "mojo/gpu/mojo_gles2_impl_autogen.h")
10980 gen.WriteMojoGLES2Impl(
10981 "mojo/gpu/mojo_gles2_impl_autogen.cc")
10982 gen.WriteGLES2InterfaceStub(
10983 "gpu/command_buffer/client/gles2_interface_stub_autogen.h")
10984 gen.WriteGLES2InterfaceStubImpl(
10985 "gpu/command_buffer/client/gles2_interface_stub_impl_autogen.h")
10986 gen.WriteGLES2ImplementationHeader(
10987 "gpu/command_buffer/client/gles2_implementation_autogen.h")
10988 gen.WriteGLES2Implementation(
10989 "gpu/command_buffer/client/gles2_implementation_impl_autogen.h")
10990 gen.WriteGLES2ImplementationUnitTests(
10991 "gpu/command_buffer/client/gles2_implementation_unittest_autogen.h")
10992 gen.WriteGLES2TraceImplementationHeader(
10993 "gpu/command_buffer/client/gles2_trace_implementation_autogen.h")
10994 gen.WriteGLES2TraceImplementation(
10995 "gpu/command_buffer/client/gles2_trace_implementation_impl_autogen.h")
10996 gen.WriteGLES2CLibImplementation(
10997 "gpu/command_buffer/client/gles2_c_lib_autogen.h")
10998 gen.WriteCmdHelperHeader(
10999 "gpu/command_buffer/client/gles2_cmd_helper_autogen.h")
11000 gen.WriteServiceImplementation(
11001 "gpu/command_buffer/service/gles2_cmd_decoder_autogen.h")
11002 gen.WriteServiceContextStateHeader(
11003 "gpu/command_buffer/service/context_state_autogen.h")
11004 gen.WriteServiceContextStateImpl(
11005 "gpu/command_buffer/service/context_state_impl_autogen.h")
11006 gen.WriteClientContextStateHeader(
11007 "gpu/command_buffer/client/client_context_state_autogen.h")
11008 gen.WriteClientContextStateImpl(
11009 "gpu/command_buffer/client/client_context_state_impl_autogen.h")
11010 gen.WriteServiceUnitTests(
11011 "gpu/command_buffer/service/gles2_cmd_decoder_unittest_%d_autogen.h")
11012 gen.WriteServiceUnitTestsForExtensions(
11013 "gpu/command_buffer/service/"
11014 "gles2_cmd_decoder_unittest_extensions_autogen.h")
11015 gen.WriteServiceUtilsHeader(
11016 "gpu/command_buffer/service/gles2_cmd_validation_autogen.h")
11017 gen.WriteServiceUtilsImplementation(
11018 "gpu/command_buffer/service/"
11019 "gles2_cmd_validation_implementation_autogen.h")
11020 gen.WriteCommonUtilsHeader(
11021 "gpu/command_buffer/common/gles2_cmd_utils_autogen.h")
11022 gen.WriteCommonUtilsImpl(
11023 "gpu/command_buffer/common/gles2_cmd_utils_implementation_autogen.h")
11024 gen.WriteGLES2Header("gpu/GLES2/gl2chromium_autogen.h")
11025 mojo_gles2_prefix = ("third_party/mojo/src/mojo/public/c/gles2/"
11026 "gles2_call_visitor")
11027 gen.WriteMojoGLCallVisitor(mojo_gles2_prefix + "_autogen.h")
11028 gen.WriteMojoGLCallVisitorForExtension(
11029 mojo_gles2_prefix + "_chromium_texture_mailbox_autogen.h",
11030 "CHROMIUM_texture_mailbox")
11031 gen.WriteMojoGLCallVisitorForExtension(
11032 mojo_gles2_prefix + "_chromium_sync_point_autogen.h",
11033 "CHROMIUM_sync_point")
11034 gen.WriteMojoGLCallVisitorForExtension(
11035 mojo_gles2_prefix + "_chromium_sub_image_autogen.h",
11036 "CHROMIUM_sub_image")
11037 gen.WriteMojoGLCallVisitorForExtension(
11038 mojo_gles2_prefix + "_chromium_miscellaneous_autogen.h",
11039 "CHROMIUM_miscellaneous")
11040 gen.WriteMojoGLCallVisitorForExtension(
11041 mojo_gles2_prefix + "_occlusion_query_ext_autogen.h",
11042 "occlusion_query_EXT")
11043 gen.WriteMojoGLCallVisitorForExtension(
11044 mojo_gles2_prefix + "_chromium_image_autogen.h",
11045 "CHROMIUM_image")
11046 gen.WriteMojoGLCallVisitorForExtension(
11047 mojo_gles2_prefix + "_chromium_copy_texture_autogen.h",
11048 "CHROMIUM_copy_texture")
11049 gen.WriteMojoGLCallVisitorForExtension(
11050 mojo_gles2_prefix + "_chromium_pixel_transfer_buffer_object_autogen.h",
11051 "CHROMIUM_pixel_transfer_buffer_object")
11053 Format(gen.generated_cpp_filenames)
11055 if gen.errors > 0:
11056 print "%d errors" % gen.errors
11057 return 1
11058 return 0
11061 if __name__ == '__main__':
11062 sys.exit(main(sys.argv[1:]))