Fix waterfall bots to not use fastbuild and add presubmit validation.
[chromium-blink-merge.git] / gpu / command_buffer / build_gles2_cmd_buffer.py
blobbb61e1820deb11c59e99d2f389e3e301a1f7e85a
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_MAJOR_VERSION',
816 'GL_MAX_3D_TEXTURE_SIZE',
817 'GL_MAX_ARRAY_TEXTURE_LAYERS',
818 'GL_MAX_COLOR_ATTACHMENTS',
819 'GL_MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS',
820 'GL_MAX_COMBINED_UNIFORM_BLOCKS',
821 'GL_MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS',
822 'GL_MAX_DRAW_BUFFERS',
823 'GL_MAX_ELEMENT_INDEX',
824 'GL_MAX_ELEMENTS_INDICES',
825 'GL_MAX_ELEMENTS_VERTICES',
826 'GL_MAX_FRAGMENT_INPUT_COMPONENTS',
827 'GL_MAX_FRAGMENT_UNIFORM_BLOCKS',
828 'GL_MAX_FRAGMENT_UNIFORM_COMPONENTS',
829 'GL_MAX_PROGRAM_TEXEL_OFFSET',
830 'GL_MAX_SAMPLES',
831 'GL_MAX_SERVER_WAIT_TIMEOUT',
832 'GL_MAX_TEXTURE_LOD_BIAS',
833 'GL_MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS',
834 'GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS',
835 'GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS',
836 'GL_MAX_UNIFORM_BLOCK_SIZE',
837 'GL_MAX_UNIFORM_BUFFER_BINDINGS',
838 'GL_MAX_VARYING_COMPONENTS',
839 'GL_MAX_VERTEX_OUTPUT_COMPONENTS',
840 'GL_MAX_VERTEX_UNIFORM_BLOCKS',
841 'GL_MAX_VERTEX_UNIFORM_COMPONENTS',
842 'GL_MIN_PROGRAM_TEXEL_OFFSET',
843 'GL_MINOR_VERSION',
844 'GL_NUM_EXTENSIONS',
845 'GL_NUM_PROGRAM_BINARY_FORMATS',
846 'GL_PACK_ROW_LENGTH',
847 'GL_PACK_SKIP_PIXELS',
848 'GL_PACK_SKIP_ROWS',
849 'GL_PIXEL_PACK_BUFFER_BINDING',
850 'GL_PIXEL_UNPACK_BUFFER_BINDING',
851 'GL_PROGRAM_BINARY_FORMATS',
852 'GL_READ_BUFFER',
853 'GL_READ_FRAMEBUFFER_BINDING',
854 'GL_SAMPLER_BINDING',
855 'GL_TEXTURE_BINDING_2D_ARRAY',
856 'GL_TEXTURE_BINDING_3D',
857 'GL_TRANSFORM_FEEDBACK_BINDING',
858 'GL_TRANSFORM_FEEDBACK_ACTIVE',
859 'GL_TRANSFORM_FEEDBACK_BUFFER_BINDING',
860 'GL_TRANSFORM_FEEDBACK_PAUSED',
861 'GL_TRANSFORM_FEEDBACK_BUFFER_SIZE',
862 'GL_TRANSFORM_FEEDBACK_BUFFER_START',
863 'GL_UNIFORM_BUFFER_BINDING',
864 'GL_UNIFORM_BUFFER_OFFSET_ALIGNMENT',
865 'GL_UNIFORM_BUFFER_SIZE',
866 'GL_UNIFORM_BUFFER_START',
867 'GL_UNPACK_IMAGE_HEIGHT',
868 'GL_UNPACK_ROW_LENGTH',
869 'GL_UNPACK_SKIP_IMAGES',
870 'GL_UNPACK_SKIP_PIXELS',
871 'GL_UNPACK_SKIP_ROWS',
872 # GL_VERTEX_ARRAY_BINDING is the same as GL_VERTEX_ARRAY_BINDING_OES
873 # 'GL_VERTEX_ARRAY_BINDING',
875 'invalid': [
876 'GL_FOG_HINT',
879 'IndexedGLState': {
880 'type': 'GLenum',
881 'valid': [
882 'GL_TRANSFORM_FEEDBACK_BUFFER_BINDING',
883 'GL_TRANSFORM_FEEDBACK_BUFFER_SIZE',
884 'GL_TRANSFORM_FEEDBACK_BUFFER_START',
885 'GL_UNIFORM_BUFFER_BINDING',
886 'GL_UNIFORM_BUFFER_SIZE',
887 'GL_UNIFORM_BUFFER_START',
889 'invalid': [
890 'GL_FOG_HINT',
893 'GetTexParamTarget': {
894 'type': 'GLenum',
895 'valid': [
896 'GL_TEXTURE_2D',
897 'GL_TEXTURE_CUBE_MAP',
899 'valid_es3': [
900 'GL_TEXTURE_2D_ARRAY',
901 'GL_TEXTURE_3D',
903 'invalid': [
904 'GL_PROXY_TEXTURE_CUBE_MAP',
907 'ReadBuffer': {
908 'type': 'GLenum',
909 'valid': [
910 'GL_NONE',
911 'GL_BACK',
912 'GL_COLOR_ATTACHMENT0',
913 'GL_COLOR_ATTACHMENT1',
914 'GL_COLOR_ATTACHMENT2',
915 'GL_COLOR_ATTACHMENT3',
916 'GL_COLOR_ATTACHMENT4',
917 'GL_COLOR_ATTACHMENT5',
918 'GL_COLOR_ATTACHMENT6',
919 'GL_COLOR_ATTACHMENT7',
920 'GL_COLOR_ATTACHMENT8',
921 'GL_COLOR_ATTACHMENT9',
922 'GL_COLOR_ATTACHMENT10',
923 'GL_COLOR_ATTACHMENT11',
924 'GL_COLOR_ATTACHMENT12',
925 'GL_COLOR_ATTACHMENT13',
926 'GL_COLOR_ATTACHMENT14',
927 'GL_COLOR_ATTACHMENT15',
929 'invalid': [
930 'GL_RENDERBUFFER',
933 'TextureTarget': {
934 'type': 'GLenum',
935 'valid': [
936 'GL_TEXTURE_2D',
937 'GL_TEXTURE_CUBE_MAP_POSITIVE_X',
938 'GL_TEXTURE_CUBE_MAP_NEGATIVE_X',
939 'GL_TEXTURE_CUBE_MAP_POSITIVE_Y',
940 'GL_TEXTURE_CUBE_MAP_NEGATIVE_Y',
941 'GL_TEXTURE_CUBE_MAP_POSITIVE_Z',
942 'GL_TEXTURE_CUBE_MAP_NEGATIVE_Z',
944 'invalid': [
945 'GL_PROXY_TEXTURE_CUBE_MAP',
948 'Texture3DTarget': {
949 'type': 'GLenum',
950 'valid': [
951 'GL_TEXTURE_3D',
952 'GL_TEXTURE_2D_ARRAY',
954 'invalid': [
955 'GL_TEXTURE_2D',
958 'TextureBindTarget': {
959 'type': 'GLenum',
960 'valid': [
961 'GL_TEXTURE_2D',
962 'GL_TEXTURE_CUBE_MAP',
964 'valid_es3': [
965 'GL_TEXTURE_3D',
966 'GL_TEXTURE_2D_ARRAY',
968 'invalid': [
969 'GL_TEXTURE_1D',
970 'GL_TEXTURE_3D',
973 'TransformFeedbackBindTarget': {
974 'type': 'GLenum',
975 'valid': [
976 'GL_TRANSFORM_FEEDBACK',
978 'invalid': [
979 'GL_TEXTURE_2D',
982 'TransformFeedbackPrimitiveMode': {
983 'type': 'GLenum',
984 'valid': [
985 'GL_POINTS',
986 'GL_LINES',
987 'GL_TRIANGLES',
989 'invalid': [
990 'GL_LINE_LOOP',
993 'ShaderType': {
994 'type': 'GLenum',
995 'valid': [
996 'GL_VERTEX_SHADER',
997 'GL_FRAGMENT_SHADER',
999 'invalid': [
1000 'GL_GEOMETRY_SHADER',
1003 'FaceType': {
1004 'type': 'GLenum',
1005 'valid': [
1006 'GL_FRONT',
1007 'GL_BACK',
1008 'GL_FRONT_AND_BACK',
1011 'FaceMode': {
1012 'type': 'GLenum',
1013 'valid': [
1014 'GL_CW',
1015 'GL_CCW',
1018 'CmpFunction': {
1019 'type': 'GLenum',
1020 'valid': [
1021 'GL_NEVER',
1022 'GL_LESS',
1023 'GL_EQUAL',
1024 'GL_LEQUAL',
1025 'GL_GREATER',
1026 'GL_NOTEQUAL',
1027 'GL_GEQUAL',
1028 'GL_ALWAYS',
1031 'Equation': {
1032 'type': 'GLenum',
1033 'valid': [
1034 'GL_FUNC_ADD',
1035 'GL_FUNC_SUBTRACT',
1036 'GL_FUNC_REVERSE_SUBTRACT',
1038 'valid_es3': [
1039 'GL_MIN',
1040 'GL_MAX',
1042 'invalid': [
1043 'GL_NONE',
1046 'SrcBlendFactor': {
1047 'type': 'GLenum',
1048 'valid': [
1049 'GL_ZERO',
1050 'GL_ONE',
1051 'GL_SRC_COLOR',
1052 'GL_ONE_MINUS_SRC_COLOR',
1053 'GL_DST_COLOR',
1054 'GL_ONE_MINUS_DST_COLOR',
1055 'GL_SRC_ALPHA',
1056 'GL_ONE_MINUS_SRC_ALPHA',
1057 'GL_DST_ALPHA',
1058 'GL_ONE_MINUS_DST_ALPHA',
1059 'GL_CONSTANT_COLOR',
1060 'GL_ONE_MINUS_CONSTANT_COLOR',
1061 'GL_CONSTANT_ALPHA',
1062 'GL_ONE_MINUS_CONSTANT_ALPHA',
1063 'GL_SRC_ALPHA_SATURATE',
1066 'DstBlendFactor': {
1067 'type': 'GLenum',
1068 'valid': [
1069 'GL_ZERO',
1070 'GL_ONE',
1071 'GL_SRC_COLOR',
1072 'GL_ONE_MINUS_SRC_COLOR',
1073 'GL_DST_COLOR',
1074 'GL_ONE_MINUS_DST_COLOR',
1075 'GL_SRC_ALPHA',
1076 'GL_ONE_MINUS_SRC_ALPHA',
1077 'GL_DST_ALPHA',
1078 'GL_ONE_MINUS_DST_ALPHA',
1079 'GL_CONSTANT_COLOR',
1080 'GL_ONE_MINUS_CONSTANT_COLOR',
1081 'GL_CONSTANT_ALPHA',
1082 'GL_ONE_MINUS_CONSTANT_ALPHA',
1085 'Capability': {
1086 'type': 'GLenum',
1087 'valid': ["GL_%s" % cap['name'].upper() for cap in _CAPABILITY_FLAGS
1088 if 'es3' not in cap or cap['es3'] != True],
1089 'valid_es3': ["GL_%s" % cap['name'].upper() for cap in _CAPABILITY_FLAGS
1090 if 'es3' in cap and cap['es3'] == True],
1091 'invalid': [
1092 'GL_CLIP_PLANE0',
1093 'GL_POINT_SPRITE',
1096 'DrawMode': {
1097 'type': 'GLenum',
1098 'valid': [
1099 'GL_POINTS',
1100 'GL_LINE_STRIP',
1101 'GL_LINE_LOOP',
1102 'GL_LINES',
1103 'GL_TRIANGLE_STRIP',
1104 'GL_TRIANGLE_FAN',
1105 'GL_TRIANGLES',
1107 'invalid': [
1108 'GL_QUADS',
1109 'GL_POLYGON',
1112 'IndexType': {
1113 'type': 'GLenum',
1114 'valid': [
1115 'GL_UNSIGNED_BYTE',
1116 'GL_UNSIGNED_SHORT',
1118 'valid_es3': [
1119 'GL_UNSIGNED_INT',
1121 'invalid': [
1122 'GL_INT',
1125 'GetMaxIndexType': {
1126 'type': 'GLenum',
1127 'valid': [
1128 'GL_UNSIGNED_BYTE',
1129 'GL_UNSIGNED_SHORT',
1130 'GL_UNSIGNED_INT',
1132 'invalid': [
1133 'GL_INT',
1136 'Attachment': {
1137 'type': 'GLenum',
1138 'valid': [
1139 'GL_COLOR_ATTACHMENT0',
1140 'GL_DEPTH_ATTACHMENT',
1141 'GL_STENCIL_ATTACHMENT',
1143 'valid_es3': [
1144 'GL_DEPTH_STENCIL_ATTACHMENT',
1147 'BackbufferAttachment': {
1148 'type': 'GLenum',
1149 'valid': [
1150 'GL_COLOR_EXT',
1151 'GL_DEPTH_EXT',
1152 'GL_STENCIL_EXT',
1155 'BufferParameter': {
1156 'type': 'GLenum',
1157 'valid': [
1158 'GL_BUFFER_SIZE',
1159 'GL_BUFFER_USAGE',
1161 'valid_es3': [
1162 'GL_BUFFER_ACCESS_FLAGS',
1163 'GL_BUFFER_MAPPED',
1165 'invalid': [
1166 'GL_PIXEL_PACK_BUFFER',
1169 'BufferParameter64': {
1170 'type': 'GLenum',
1171 'valid': [
1172 'GL_BUFFER_SIZE',
1173 'GL_BUFFER_MAP_LENGTH',
1174 'GL_BUFFER_MAP_OFFSET',
1176 'invalid': [
1177 'GL_PIXEL_PACK_BUFFER',
1180 'BufferMode': {
1181 'type': 'GLenum',
1182 'valid': [
1183 'GL_INTERLEAVED_ATTRIBS',
1184 'GL_SEPARATE_ATTRIBS',
1186 'invalid': [
1187 'GL_PIXEL_PACK_BUFFER',
1190 'FrameBufferParameter': {
1191 'type': 'GLenum',
1192 'valid': [
1193 'GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE',
1194 'GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME',
1195 'GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL',
1196 'GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE',
1198 'valid_es3': [
1199 'GL_FRAMEBUFFER_ATTACHMENT_RED_SIZE',
1200 'GL_FRAMEBUFFER_ATTACHMENT_GREEN_SIZE',
1201 'GL_FRAMEBUFFER_ATTACHMENT_BLUE_SIZE',
1202 'GL_FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE',
1203 'GL_FRAMEBUFFER_ATTACHMENT_DEPTH_SIZE',
1204 'GL_FRAMEBUFFER_ATTACHMENT_STENCIL_SIZE',
1205 'GL_FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE',
1206 'GL_FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING',
1207 'GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER',
1210 'MatrixMode': {
1211 'type': 'GLenum',
1212 'valid': [
1213 'GL_PATH_PROJECTION_CHROMIUM',
1214 'GL_PATH_MODELVIEW_CHROMIUM',
1217 'ProgramParameter': {
1218 'type': 'GLenum',
1219 'valid': [
1220 'GL_DELETE_STATUS',
1221 'GL_LINK_STATUS',
1222 'GL_VALIDATE_STATUS',
1223 'GL_INFO_LOG_LENGTH',
1224 'GL_ATTACHED_SHADERS',
1225 'GL_ACTIVE_ATTRIBUTES',
1226 'GL_ACTIVE_ATTRIBUTE_MAX_LENGTH',
1227 'GL_ACTIVE_UNIFORMS',
1228 'GL_ACTIVE_UNIFORM_MAX_LENGTH',
1230 'valid_es3': [
1231 'GL_ACTIVE_UNIFORM_BLOCKS',
1232 'GL_ACTIVE_UNIFORM_BLOCK_MAX_NAME_LENGTH',
1233 'GL_TRANSFORM_FEEDBACK_BUFFER_MODE',
1234 'GL_TRANSFORM_FEEDBACK_VARYINGS',
1235 'GL_TRANSFORM_FEEDBACK_VARYING_MAX_LENGTH',
1237 'invalid': [
1238 'GL_PROGRAM_BINARY_RETRIEVABLE_HINT', # not supported in Chromium.
1241 'QueryObjectParameter': {
1242 'type': 'GLenum',
1243 'valid': [
1244 'GL_QUERY_RESULT_EXT',
1245 'GL_QUERY_RESULT_AVAILABLE_EXT',
1248 'QueryParameter': {
1249 'type': 'GLenum',
1250 'valid': [
1251 'GL_CURRENT_QUERY_EXT',
1254 'QueryTarget': {
1255 'type': 'GLenum',
1256 'valid': [
1257 'GL_ANY_SAMPLES_PASSED_EXT',
1258 'GL_ANY_SAMPLES_PASSED_CONSERVATIVE_EXT',
1259 'GL_COMMANDS_ISSUED_CHROMIUM',
1260 'GL_LATENCY_QUERY_CHROMIUM',
1261 'GL_ASYNC_PIXEL_UNPACK_COMPLETED_CHROMIUM',
1262 'GL_ASYNC_PIXEL_PACK_COMPLETED_CHROMIUM',
1263 'GL_COMMANDS_COMPLETED_CHROMIUM',
1266 'RenderBufferParameter': {
1267 'type': 'GLenum',
1268 'valid': [
1269 'GL_RENDERBUFFER_RED_SIZE',
1270 'GL_RENDERBUFFER_GREEN_SIZE',
1271 'GL_RENDERBUFFER_BLUE_SIZE',
1272 'GL_RENDERBUFFER_ALPHA_SIZE',
1273 'GL_RENDERBUFFER_DEPTH_SIZE',
1274 'GL_RENDERBUFFER_STENCIL_SIZE',
1275 'GL_RENDERBUFFER_WIDTH',
1276 'GL_RENDERBUFFER_HEIGHT',
1277 'GL_RENDERBUFFER_INTERNAL_FORMAT',
1279 'valid_es3': [
1280 'GL_RENDERBUFFER_SAMPLES',
1283 'InternalFormatParameter': {
1284 'type': 'GLenum',
1285 'valid': [
1286 'GL_NUM_SAMPLE_COUNTS',
1287 'GL_SAMPLES',
1290 'SamplerParameter': {
1291 'type': 'GLenum',
1292 'valid': [
1293 'GL_TEXTURE_MAG_FILTER',
1294 'GL_TEXTURE_MIN_FILTER',
1295 'GL_TEXTURE_MIN_LOD',
1296 'GL_TEXTURE_MAX_LOD',
1297 'GL_TEXTURE_WRAP_S',
1298 'GL_TEXTURE_WRAP_T',
1299 'GL_TEXTURE_WRAP_R',
1300 'GL_TEXTURE_COMPARE_MODE',
1301 'GL_TEXTURE_COMPARE_FUNC',
1303 'invalid': [
1304 'GL_GENERATE_MIPMAP',
1307 'ShaderParameter': {
1308 'type': 'GLenum',
1309 'valid': [
1310 'GL_SHADER_TYPE',
1311 'GL_DELETE_STATUS',
1312 'GL_COMPILE_STATUS',
1313 'GL_INFO_LOG_LENGTH',
1314 'GL_SHADER_SOURCE_LENGTH',
1315 'GL_TRANSLATED_SHADER_SOURCE_LENGTH_ANGLE',
1318 'ShaderPrecision': {
1319 'type': 'GLenum',
1320 'valid': [
1321 'GL_LOW_FLOAT',
1322 'GL_MEDIUM_FLOAT',
1323 'GL_HIGH_FLOAT',
1324 'GL_LOW_INT',
1325 'GL_MEDIUM_INT',
1326 'GL_HIGH_INT',
1329 'StringType': {
1330 'type': 'GLenum',
1331 'valid': [
1332 'GL_VENDOR',
1333 'GL_RENDERER',
1334 'GL_VERSION',
1335 'GL_SHADING_LANGUAGE_VERSION',
1336 'GL_EXTENSIONS',
1339 'TextureParameter': {
1340 'type': 'GLenum',
1341 'valid': [
1342 'GL_TEXTURE_MAG_FILTER',
1343 'GL_TEXTURE_MIN_FILTER',
1344 'GL_TEXTURE_POOL_CHROMIUM',
1345 'GL_TEXTURE_WRAP_S',
1346 'GL_TEXTURE_WRAP_T',
1348 'valid_es3': [
1349 'GL_TEXTURE_BASE_LEVEL',
1350 'GL_TEXTURE_COMPARE_FUNC',
1351 'GL_TEXTURE_COMPARE_MODE',
1352 'GL_TEXTURE_IMMUTABLE_FORMAT',
1353 'GL_TEXTURE_IMMUTABLE_LEVELS',
1354 'GL_TEXTURE_MAX_LEVEL',
1355 'GL_TEXTURE_MAX_LOD',
1356 'GL_TEXTURE_MIN_LOD',
1357 'GL_TEXTURE_WRAP_R',
1359 'invalid': [
1360 'GL_GENERATE_MIPMAP',
1363 'TexturePool': {
1364 'type': 'GLenum',
1365 'valid': [
1366 'GL_TEXTURE_POOL_MANAGED_CHROMIUM',
1367 'GL_TEXTURE_POOL_UNMANAGED_CHROMIUM',
1370 'TextureWrapMode': {
1371 'type': 'GLenum',
1372 'valid': [
1373 'GL_CLAMP_TO_EDGE',
1374 'GL_MIRRORED_REPEAT',
1375 'GL_REPEAT',
1378 'TextureMinFilterMode': {
1379 'type': 'GLenum',
1380 'valid': [
1381 'GL_NEAREST',
1382 'GL_LINEAR',
1383 'GL_NEAREST_MIPMAP_NEAREST',
1384 'GL_LINEAR_MIPMAP_NEAREST',
1385 'GL_NEAREST_MIPMAP_LINEAR',
1386 'GL_LINEAR_MIPMAP_LINEAR',
1389 'TextureMagFilterMode': {
1390 'type': 'GLenum',
1391 'valid': [
1392 'GL_NEAREST',
1393 'GL_LINEAR',
1396 'TextureCompareFunc': {
1397 'type': 'GLenum',
1398 'valid': [
1399 'GL_LEQUAL',
1400 'GL_GEQUAL',
1401 'GL_LESS',
1402 'GL_GREATER',
1403 'GL_EQUAL',
1404 'GL_NOTEQUAL',
1405 'GL_ALWAYS',
1406 'GL_NEVER',
1409 'TextureCompareMode': {
1410 'type': 'GLenum',
1411 'valid': [
1412 'GL_NONE',
1413 'GL_COMPARE_REF_TO_TEXTURE',
1416 'TextureUsage': {
1417 'type': 'GLenum',
1418 'valid': [
1419 'GL_NONE',
1420 'GL_FRAMEBUFFER_ATTACHMENT_ANGLE',
1423 'VertexAttribute': {
1424 'type': 'GLenum',
1425 'valid': [
1426 # some enum that the decoder actually passes through to GL needs
1427 # to be the first listed here since it's used in unit tests.
1428 'GL_VERTEX_ATTRIB_ARRAY_NORMALIZED',
1429 'GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING',
1430 'GL_VERTEX_ATTRIB_ARRAY_ENABLED',
1431 'GL_VERTEX_ATTRIB_ARRAY_SIZE',
1432 'GL_VERTEX_ATTRIB_ARRAY_STRIDE',
1433 'GL_VERTEX_ATTRIB_ARRAY_TYPE',
1434 'GL_CURRENT_VERTEX_ATTRIB',
1436 'valid_es3': [
1437 'GL_VERTEX_ATTRIB_ARRAY_INTEGER',
1438 'GL_VERTEX_ATTRIB_ARRAY_DIVISOR',
1441 'VertexPointer': {
1442 'type': 'GLenum',
1443 'valid': [
1444 'GL_VERTEX_ATTRIB_ARRAY_POINTER',
1447 'HintTarget': {
1448 'type': 'GLenum',
1449 'valid': [
1450 'GL_GENERATE_MIPMAP_HINT',
1452 'valid_es3': [
1453 'GL_FRAGMENT_SHADER_DERIVATIVE_HINT',
1455 'invalid': [
1456 'GL_PERSPECTIVE_CORRECTION_HINT',
1459 'HintMode': {
1460 'type': 'GLenum',
1461 'valid': [
1462 'GL_FASTEST',
1463 'GL_NICEST',
1464 'GL_DONT_CARE',
1467 'PixelStore': {
1468 'type': 'GLenum',
1469 'valid': [
1470 'GL_PACK_ALIGNMENT',
1471 'GL_UNPACK_ALIGNMENT',
1473 'valid_es3': [
1474 'GL_PACK_ROW_LENGTH',
1475 'GL_PACK_SKIP_PIXELS',
1476 'GL_PACK_SKIP_ROWS',
1477 'GL_UNPACK_ROW_LENGTH',
1478 'GL_UNPACK_IMAGE_HEIGHT',
1479 'GL_UNPACK_SKIP_PIXELS',
1480 'GL_UNPACK_SKIP_ROWS',
1481 'GL_UNPACK_SKIP_IMAGES',
1483 'invalid': [
1484 'GL_PACK_SWAP_BYTES',
1485 'GL_UNPACK_SWAP_BYTES',
1488 'PixelStoreAlignment': {
1489 'type': 'GLint',
1490 'valid': [
1491 '1',
1492 '2',
1493 '4',
1494 '8',
1496 'invalid': [
1497 '3',
1498 '9',
1501 'ReadPixelFormat': {
1502 'type': 'GLenum',
1503 'valid': [
1504 'GL_ALPHA',
1505 'GL_RGB',
1506 'GL_RGBA',
1508 'valid_es3': [
1509 'GL_RGBA_INTEGER',
1511 'deprecated_es3': [
1512 'GL_ALPHA',
1513 'GL_RGB',
1516 'PixelType': {
1517 'type': 'GLenum',
1518 'valid': [
1519 'GL_UNSIGNED_BYTE',
1520 'GL_UNSIGNED_SHORT_5_6_5',
1521 'GL_UNSIGNED_SHORT_4_4_4_4',
1522 'GL_UNSIGNED_SHORT_5_5_5_1',
1524 'valid_es3': [
1525 'GL_BYTE',
1526 'GL_UNSIGNED_SHORT',
1527 'GL_SHORT',
1528 'GL_UNSIGNED_INT',
1529 'GL_INT',
1530 'GL_HALF_FLOAT',
1531 'GL_FLOAT',
1532 'GL_UNSIGNED_INT_2_10_10_10_REV',
1533 'GL_UNSIGNED_INT_10F_11F_11F_REV',
1534 'GL_UNSIGNED_INT_5_9_9_9_REV',
1535 'GL_UNSIGNED_INT_24_8',
1536 'GL_FLOAT_32_UNSIGNED_INT_24_8_REV',
1538 'invalid': [
1539 'GL_UNSIGNED_BYTE_3_3_2',
1542 'PathCoordType': {
1543 'type': 'GLenum',
1544 'valid': [
1545 'GL_BYTE',
1546 'GL_UNSIGNED_BYTE',
1547 'GL_SHORT',
1548 'GL_UNSIGNED_SHORT',
1549 'GL_FLOAT',
1552 'PathCoverMode': {
1553 'type': 'GLenum',
1554 'valid': [
1555 'GL_CONVEX_HULL_CHROMIUM',
1556 'GL_BOUNDING_BOX_CHROMIUM',
1559 'PathFillMode': {
1560 'type': 'GLenum',
1561 'valid': [
1562 'GL_INVERT',
1563 'GL_COUNT_UP_CHROMIUM',
1564 'GL_COUNT_DOWN_CHROMIUM',
1567 'PathParameter': {
1568 'type': 'GLenum',
1569 'valid': [
1570 'GL_PATH_STROKE_WIDTH_CHROMIUM',
1571 'GL_PATH_END_CAPS_CHROMIUM',
1572 'GL_PATH_JOIN_STYLE_CHROMIUM',
1573 'GL_PATH_MITER_LIMIT_CHROMIUM',
1574 'GL_PATH_STROKE_BOUND_CHROMIUM',
1577 'PathParameterCapValues': {
1578 'type': 'GLint',
1579 'valid': [
1580 'GL_FLAT',
1581 'GL_SQUARE_CHROMIUM',
1582 'GL_ROUND_CHROMIUM',
1585 'PathParameterJoinValues': {
1586 'type': 'GLint',
1587 'valid': [
1588 'GL_MITER_REVERT_CHROMIUM',
1589 'GL_BEVEL_CHROMIUM',
1590 'GL_ROUND_CHROMIUM',
1593 'ReadPixelType': {
1594 'type': 'GLenum',
1595 'valid': [
1596 'GL_UNSIGNED_BYTE',
1597 'GL_UNSIGNED_SHORT_5_6_5',
1598 'GL_UNSIGNED_SHORT_4_4_4_4',
1599 'GL_UNSIGNED_SHORT_5_5_5_1',
1601 'invalid': [
1602 'GL_SHORT',
1604 'valid_es3': [
1605 'GL_UNSIGNED_INT',
1606 'GL_INT',
1607 'GL_FLOAT',
1608 'GL_UNSIGNED_INT_2_10_10_10_REV',
1610 'deprecated_es3': [
1611 'GL_UNSIGNED_SHORT_5_6_5',
1612 'GL_UNSIGNED_SHORT_4_4_4_4',
1613 'GL_UNSIGNED_SHORT_5_5_5_1',
1616 'RenderBufferFormat': {
1617 'type': 'GLenum',
1618 'valid': [
1619 'GL_RGBA4',
1620 'GL_RGB565',
1621 'GL_RGB5_A1',
1622 'GL_DEPTH_COMPONENT16',
1623 'GL_STENCIL_INDEX8',
1625 'valid_es3': [
1626 'GL_R8',
1627 'GL_R8UI',
1628 'GL_R8I',
1629 'GL_R16UI',
1630 'GL_R16I',
1631 'GL_R32UI',
1632 'GL_R32I',
1633 'GL_RG8',
1634 'GL_RG8UI',
1635 'GL_RG8I',
1636 'GL_RG16UI',
1637 'GL_RG16I',
1638 'GL_RG32UI',
1639 'GL_RG32I',
1640 'GL_RGB8',
1641 'GL_RGBA8',
1642 'GL_SRGB8_ALPHA8',
1643 'GL_RGB10_A2',
1644 'GL_RGBA8UI',
1645 'GL_RGBA8I',
1646 'GL_RGB10_A2UI',
1647 'GL_RGBA16UI',
1648 'GL_RGBA16I',
1649 'GL_RGBA32UI',
1650 'GL_RGBA32I',
1651 'GL_DEPTH_COMPONENT24',
1652 'GL_DEPTH_COMPONENT32F',
1653 'GL_DEPTH24_STENCIL8',
1654 'GL_DEPTH32F_STENCIL8',
1657 'ShaderBinaryFormat': {
1658 'type': 'GLenum',
1659 'valid': [
1662 'StencilOp': {
1663 'type': 'GLenum',
1664 'valid': [
1665 'GL_KEEP',
1666 'GL_ZERO',
1667 'GL_REPLACE',
1668 'GL_INCR',
1669 'GL_INCR_WRAP',
1670 'GL_DECR',
1671 'GL_DECR_WRAP',
1672 'GL_INVERT',
1675 'TextureFormat': {
1676 'type': 'GLenum',
1677 'valid': [
1678 'GL_ALPHA',
1679 'GL_LUMINANCE',
1680 'GL_LUMINANCE_ALPHA',
1681 'GL_RGB',
1682 'GL_RGBA',
1684 'valid_es3': [
1685 'GL_RED',
1686 'GL_RED_INTEGER',
1687 'GL_RG',
1688 'GL_RG_INTEGER',
1689 'GL_RGB_INTEGER',
1690 'GL_RGBA_INTEGER',
1691 'GL_DEPTH_COMPONENT',
1692 'GL_DEPTH_STENCIL',
1694 'invalid': [
1695 'GL_BGRA',
1696 'GL_BGR',
1699 'TextureInternalFormat': {
1700 'type': 'GLenum',
1701 'valid': [
1702 'GL_ALPHA',
1703 'GL_LUMINANCE',
1704 'GL_LUMINANCE_ALPHA',
1705 'GL_RGB',
1706 'GL_RGBA',
1708 'valid_es3': [
1709 'GL_R8',
1710 'GL_R8_SNORM',
1711 'GL_R16F',
1712 'GL_R32F',
1713 'GL_R8UI',
1714 'GL_R8I',
1715 'GL_R16UI',
1716 'GL_R16I',
1717 'GL_R32UI',
1718 'GL_R32I',
1719 'GL_RG8',
1720 'GL_RG8_SNORM',
1721 'GL_RG16F',
1722 'GL_RG32F',
1723 'GL_RG8UI',
1724 'GL_RG8I',
1725 'GL_RG16UI',
1726 'GL_RG16I',
1727 'GL_RG32UI',
1728 'GL_RG32I',
1729 'GL_RGB8',
1730 'GL_SRGB8',
1731 'GL_RGB565',
1732 'GL_RGB8_SNORM',
1733 'GL_R11F_G11F_B10F',
1734 'GL_RGB9_E5',
1735 'GL_RGB16F',
1736 'GL_RGB32F',
1737 'GL_RGB8UI',
1738 'GL_RGB8I',
1739 'GL_RGB16UI',
1740 'GL_RGB16I',
1741 'GL_RGB32UI',
1742 'GL_RGB32I',
1743 'GL_RGBA8',
1744 'GL_SRGB8_ALPHA8',
1745 'GL_RGBA8_SNORM',
1746 'GL_RGB5_A1',
1747 'GL_RGBA4',
1748 'GL_RGB10_A2',
1749 'GL_RGBA16F',
1750 'GL_RGBA32F',
1751 'GL_RGBA8UI',
1752 'GL_RGBA8I',
1753 'GL_RGB10_A2UI',
1754 'GL_RGBA16UI',
1755 'GL_RGBA16I',
1756 'GL_RGBA32UI',
1757 'GL_RGBA32I',
1758 # The DEPTH/STENCIL formats are not supported in CopyTexImage2D.
1759 # We will reject them dynamically in GPU command buffer.
1760 'GL_DEPTH_COMPONENT16',
1761 'GL_DEPTH_COMPONENT24',
1762 'GL_DEPTH_COMPONENT32F',
1763 'GL_DEPTH24_STENCIL8',
1764 'GL_DEPTH32F_STENCIL8',
1766 'invalid': [
1767 'GL_BGRA',
1768 'GL_BGR',
1771 'TextureInternalFormatStorage': {
1772 'type': 'GLenum',
1773 'valid': [
1774 'GL_RGB565',
1775 'GL_RGBA4',
1776 'GL_RGB5_A1',
1777 'GL_ALPHA8_EXT',
1778 'GL_LUMINANCE8_EXT',
1779 'GL_LUMINANCE8_ALPHA8_EXT',
1780 'GL_RGB8_OES',
1781 'GL_RGBA8_OES',
1783 'valid_es3': [
1784 'GL_R8',
1785 'GL_R8_SNORM',
1786 'GL_R16F',
1787 'GL_R32F',
1788 'GL_R8UI',
1789 'GL_R8I',
1790 'GL_R16UI',
1791 'GL_R16I',
1792 'GL_R32UI',
1793 'GL_R32I',
1794 'GL_RG8',
1795 'GL_RG8_SNORM',
1796 'GL_RG16F',
1797 'GL_RG32F',
1798 'GL_RG8UI',
1799 'GL_RG8I',
1800 'GL_RG16UI',
1801 'GL_RG16I',
1802 'GL_RG32UI',
1803 'GL_RG32I',
1804 'GL_RGB8',
1805 'GL_SRGB8',
1806 'GL_RGB8_SNORM',
1807 'GL_R11F_G11F_B10F',
1808 'GL_RGB9_E5',
1809 'GL_RGB16F',
1810 'GL_RGB32F',
1811 'GL_RGB8UI',
1812 'GL_RGB8I',
1813 'GL_RGB16UI',
1814 'GL_RGB16I',
1815 'GL_RGB32UI',
1816 'GL_RGB32I',
1817 'GL_RGBA8',
1818 'GL_SRGB8_ALPHA8',
1819 'GL_RGBA8_SNORM',
1820 'GL_RGB10_A2',
1821 'GL_RGBA16F',
1822 'GL_RGBA32F',
1823 'GL_RGBA8UI',
1824 'GL_RGBA8I',
1825 'GL_RGB10_A2UI',
1826 'GL_RGBA16UI',
1827 'GL_RGBA16I',
1828 'GL_RGBA32UI',
1829 'GL_RGBA32I',
1830 'GL_DEPTH_COMPONENT16',
1831 'GL_DEPTH_COMPONENT24',
1832 'GL_DEPTH_COMPONENT32F',
1833 'GL_DEPTH24_STENCIL8',
1834 'GL_DEPTH32F_STENCIL8',
1835 'GL_COMPRESSED_R11_EAC',
1836 'GL_COMPRESSED_SIGNED_R11_EAC',
1837 'GL_COMPRESSED_RG11_EAC',
1838 'GL_COMPRESSED_SIGNED_RG11_EAC',
1839 'GL_COMPRESSED_RGB8_ETC2',
1840 'GL_COMPRESSED_SRGB8_ETC2',
1841 'GL_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2',
1842 'GL_COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2',
1843 'GL_COMPRESSED_RGBA8_ETC2_EAC',
1844 'GL_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC',
1846 'deprecated_es3': [
1847 'GL_ALPHA8_EXT',
1848 'GL_LUMINANCE8_EXT',
1849 'GL_LUMINANCE8_ALPHA8_EXT',
1850 'GL_ALPHA16F_EXT',
1851 'GL_LUMINANCE16F_EXT',
1852 'GL_LUMINANCE_ALPHA16F_EXT',
1853 'GL_ALPHA32F_EXT',
1854 'GL_LUMINANCE32F_EXT',
1855 'GL_LUMINANCE_ALPHA32F_EXT',
1858 'ImageInternalFormat': {
1859 'type': 'GLenum',
1860 'valid': [
1861 'GL_RGB',
1862 'GL_RGB_YUV_420_CHROMIUM',
1863 'GL_RGBA',
1866 'ImageUsage': {
1867 'type': 'GLenum',
1868 'valid': [
1869 'GL_MAP_CHROMIUM',
1870 'GL_SCANOUT_CHROMIUM'
1873 'ValueBufferTarget': {
1874 'type': 'GLenum',
1875 'valid': [
1876 'GL_SUBSCRIBED_VALUES_BUFFER_CHROMIUM',
1879 'SubscriptionTarget': {
1880 'type': 'GLenum',
1881 'valid': [
1882 'GL_MOUSE_POSITION_CHROMIUM',
1885 'UniformParameter': {
1886 'type': 'GLenum',
1887 'valid': [
1888 'GL_UNIFORM_SIZE',
1889 'GL_UNIFORM_TYPE',
1890 'GL_UNIFORM_NAME_LENGTH',
1891 'GL_UNIFORM_BLOCK_INDEX',
1892 'GL_UNIFORM_OFFSET',
1893 'GL_UNIFORM_ARRAY_STRIDE',
1894 'GL_UNIFORM_MATRIX_STRIDE',
1895 'GL_UNIFORM_IS_ROW_MAJOR',
1897 'invalid': [
1898 'GL_UNIFORM_BLOCK_NAME_LENGTH',
1901 'UniformBlockParameter': {
1902 'type': 'GLenum',
1903 'valid': [
1904 'GL_UNIFORM_BLOCK_BINDING',
1905 'GL_UNIFORM_BLOCK_DATA_SIZE',
1906 'GL_UNIFORM_BLOCK_NAME_LENGTH',
1907 'GL_UNIFORM_BLOCK_ACTIVE_UNIFORMS',
1908 'GL_UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES',
1909 'GL_UNIFORM_BLOCK_REFERENCED_BY_VERTEX_SHADER',
1910 'GL_UNIFORM_BLOCK_REFERENCED_BY_FRAGMENT_SHADER',
1912 'invalid': [
1913 'GL_NEAREST',
1916 'VertexAttribType': {
1917 'type': 'GLenum',
1918 'valid': [
1919 'GL_BYTE',
1920 'GL_UNSIGNED_BYTE',
1921 'GL_SHORT',
1922 'GL_UNSIGNED_SHORT',
1923 # 'GL_FIXED', // This is not available on Desktop GL.
1924 'GL_FLOAT',
1926 'valid_es3': [
1927 'GL_INT',
1928 'GL_UNSIGNED_INT',
1929 'GL_HALF_FLOAT',
1930 'GL_INT_2_10_10_10_REV',
1931 'GL_UNSIGNED_INT_2_10_10_10_REV',
1933 'invalid': [
1934 'GL_DOUBLE',
1937 'VertexAttribIType': {
1938 'type': 'GLenum',
1939 'valid': [
1940 'GL_BYTE',
1941 'GL_UNSIGNED_BYTE',
1942 'GL_SHORT',
1943 'GL_UNSIGNED_SHORT',
1944 'GL_INT',
1945 'GL_UNSIGNED_INT',
1947 'invalid': [
1948 'GL_FLOAT',
1949 'GL_DOUBLE',
1952 'TextureBorder': {
1953 'type': 'GLint',
1954 'is_complete': True,
1955 'valid': [
1956 '0',
1958 'invalid': [
1959 '1',
1962 'VertexAttribSize': {
1963 'type': 'GLint',
1964 'valid': [
1965 '1',
1966 '2',
1967 '3',
1968 '4',
1970 'invalid': [
1971 '0',
1972 '5',
1975 'ZeroOnly': {
1976 'type': 'GLint',
1977 'is_complete': True,
1978 'valid': [
1979 '0',
1981 'invalid': [
1982 '1',
1985 'FalseOnly': {
1986 'type': 'GLboolean',
1987 'is_complete': True,
1988 'valid': [
1989 'false',
1991 'invalid': [
1992 'true',
1995 'ResetStatus': {
1996 'type': 'GLenum',
1997 'valid': [
1998 'GL_GUILTY_CONTEXT_RESET_ARB',
1999 'GL_INNOCENT_CONTEXT_RESET_ARB',
2000 'GL_UNKNOWN_CONTEXT_RESET_ARB',
2003 'SyncCondition': {
2004 'type': 'GLenum',
2005 'is_complete': True,
2006 'valid': [
2007 'GL_SYNC_GPU_COMMANDS_COMPLETE',
2009 'invalid': [
2010 '0',
2013 'SyncFlags': {
2014 'type': 'GLbitfield',
2015 'is_complete': True,
2016 'valid': [
2017 '0',
2019 'invalid': [
2020 '1',
2023 'SyncFlushFlags': {
2024 'type': 'GLbitfield',
2025 'valid': [
2026 'GL_SYNC_FLUSH_COMMANDS_BIT',
2027 '0',
2029 'invalid': [
2030 '0xFFFFFFFF',
2033 'SyncParameter': {
2034 'type': 'GLenum',
2035 'valid': [
2036 'GL_SYNC_STATUS', # This needs to be the 1st; all others are cached.
2037 'GL_OBJECT_TYPE',
2038 'GL_SYNC_CONDITION',
2039 'GL_SYNC_FLAGS',
2041 'invalid': [
2042 'GL_SYNC_FENCE',
2047 # This table specifies the different pepper interfaces that are supported for
2048 # GL commands. 'dev' is true if it's a dev interface.
2049 _PEPPER_INTERFACES = [
2050 {'name': '', 'dev': False},
2051 {'name': 'InstancedArrays', 'dev': False},
2052 {'name': 'FramebufferBlit', 'dev': False},
2053 {'name': 'FramebufferMultisample', 'dev': False},
2054 {'name': 'ChromiumEnableFeature', 'dev': False},
2055 {'name': 'ChromiumMapSub', 'dev': False},
2056 {'name': 'Query', 'dev': False},
2057 {'name': 'VertexArrayObject', 'dev': False},
2058 {'name': 'DrawBuffers', 'dev': True},
2061 # A function info object specifies the type and other special data for the
2062 # command that will be generated. A base function info object is generated by
2063 # parsing the "cmd_buffer_functions.txt", one for each function in the
2064 # file. These function info objects can be augmented and their values can be
2065 # overridden by adding an object to the table below.
2067 # Must match function names specified in "cmd_buffer_functions.txt".
2069 # cmd_comment: A comment added to the cmd format.
2070 # type: defines which handler will be used to generate code.
2071 # decoder_func: defines which function to call in the decoder to execute the
2072 # corresponding GL command. If not specified the GL command will
2073 # be called directly.
2074 # gl_test_func: GL function that is expected to be called when testing.
2075 # cmd_args: The arguments to use for the command. This overrides generating
2076 # them based on the GL function arguments.
2077 # gen_cmd: Whether or not this function geneates a command. Default = True.
2078 # data_transfer_methods: Array of methods that are used for transfering the
2079 # pointer data. Possible values: 'immediate', 'shm', 'bucket'.
2080 # The default is 'immediate' if the command has one pointer
2081 # argument, otherwise 'shm'. One command is generated for each
2082 # transfer method. Affects only commands which are not of type
2083 # 'HandWritten', 'GETn' or 'GLcharN'.
2084 # Note: the command arguments that affect this are the final args,
2085 # taking cmd_args override into consideration.
2086 # impl_func: Whether or not to generate the GLES2Implementation part of this
2087 # command.
2088 # impl_decl: Whether or not to generate the GLES2Implementation declaration
2089 # for this command.
2090 # needs_size: If True a data_size field is added to the command.
2091 # count: The number of units per element. For PUTn or PUT types.
2092 # use_count_func: If True the actual data count needs to be computed; the count
2093 # argument specifies the maximum count.
2094 # unit_test: If False no service side unit test will be generated.
2095 # client_test: If False no client side unit test will be generated.
2096 # expectation: If False the unit test will have no expected calls.
2097 # gen_func: Name of function that generates GL resource for corresponding
2098 # bind function.
2099 # states: array of states that get set by this function corresponding to
2100 # the given arguments
2101 # state_flag: name of flag that is set to true when function is called.
2102 # no_gl: no GL function is called.
2103 # valid_args: A dictionary of argument indices to args to use in unit tests
2104 # when they can not be automatically determined.
2105 # pepper_interface: The pepper interface that is used for this extension
2106 # pepper_name: The name of the function as exposed to pepper.
2107 # pepper_args: A string representing the argument list (what would appear in
2108 # C/C++ between the parentheses for the function declaration)
2109 # that the Pepper API expects for this function. Use this only if
2110 # the stable Pepper API differs from the GLES2 argument list.
2111 # invalid_test: False if no invalid test needed.
2112 # shadowed: True = the value is shadowed so no glGetXXX call will be made.
2113 # first_element_only: For PUT types, True if only the first element of an
2114 # array is used and we end up calling the single value
2115 # corresponding function. eg. TexParameteriv -> TexParameteri
2116 # extension: Function is an extension to GL and should not be exposed to
2117 # pepper unless pepper_interface is defined.
2118 # extension_flag: Function is an extension and should be enabled only when
2119 # the corresponding feature info flag is enabled. Implies
2120 # 'extension': True.
2121 # not_shared: For GENn types, True if objects can't be shared between contexts
2122 # unsafe: True = no validation is implemented on the service side and the
2123 # command is only available with --enable-unsafe-es3-apis.
2124 # id_mapping: A list of resource type names whose client side IDs need to be
2125 # mapped to service side IDs. This is only used for unsafe APIs.
2127 _FUNCTION_INFO = {
2128 'ActiveTexture': {
2129 'decoder_func': 'DoActiveTexture',
2130 'unit_test': False,
2131 'impl_func': False,
2132 'client_test': False,
2134 'AttachShader': {'decoder_func': 'DoAttachShader'},
2135 'BindAttribLocation': {
2136 'type': 'GLchar',
2137 'data_transfer_methods': ['bucket'],
2138 'needs_size': True,
2140 'BindBuffer': {
2141 'type': 'Bind',
2142 'decoder_func': 'DoBindBuffer',
2143 'gen_func': 'GenBuffersARB',
2145 'BindBufferBase': {
2146 'type': 'Bind',
2147 'id_mapping': [ 'Buffer' ],
2148 'gen_func': 'GenBuffersARB',
2149 'unsafe': True,
2151 'BindBufferRange': {
2152 'type': 'Bind',
2153 'id_mapping': [ 'Buffer' ],
2154 'gen_func': 'GenBuffersARB',
2155 'valid_args': {
2156 '3': '4',
2157 '4': '4'
2159 'unsafe': True,
2161 'BindFramebuffer': {
2162 'type': 'Bind',
2163 'decoder_func': 'DoBindFramebuffer',
2164 'gl_test_func': 'glBindFramebufferEXT',
2165 'gen_func': 'GenFramebuffersEXT',
2166 'trace_level': 1,
2168 'BindRenderbuffer': {
2169 'type': 'Bind',
2170 'decoder_func': 'DoBindRenderbuffer',
2171 'gl_test_func': 'glBindRenderbufferEXT',
2172 'gen_func': 'GenRenderbuffersEXT',
2174 'BindSampler': {
2175 'type': 'Bind',
2176 'id_mapping': [ 'Sampler' ],
2177 'unsafe': True,
2179 'BindTexture': {
2180 'type': 'Bind',
2181 'decoder_func': 'DoBindTexture',
2182 'gen_func': 'GenTextures',
2183 # TODO(gman): remove this once client side caching works.
2184 'client_test': False,
2185 'trace_level': 2,
2187 'BindTransformFeedback': {
2188 'type': 'Bind',
2189 'id_mapping': [ 'TransformFeedback' ],
2190 'unsafe': True,
2192 'BlitFramebufferCHROMIUM': {
2193 'decoder_func': 'DoBlitFramebufferCHROMIUM',
2194 'unit_test': False,
2195 'extension_flag': 'chromium_framebuffer_multisample',
2196 'pepper_interface': 'FramebufferBlit',
2197 'pepper_name': 'BlitFramebufferEXT',
2198 'defer_reads': True,
2199 'defer_draws': True,
2200 'trace_level': 1,
2202 'BufferData': {
2203 'type': 'Manual',
2204 'data_transfer_methods': ['shm'],
2205 'client_test': False,
2206 'trace_level': 2,
2208 'BufferSubData': {
2209 'type': 'Data',
2210 'client_test': False,
2211 'decoder_func': 'DoBufferSubData',
2212 'data_transfer_methods': ['shm'],
2213 'trace_level': 2,
2215 'CheckFramebufferStatus': {
2216 'type': 'Is',
2217 'decoder_func': 'DoCheckFramebufferStatus',
2218 'gl_test_func': 'glCheckFramebufferStatusEXT',
2219 'error_value': 'GL_FRAMEBUFFER_UNSUPPORTED',
2220 'result': ['GLenum'],
2222 'Clear': {
2223 'decoder_func': 'DoClear',
2224 'defer_draws': True,
2225 'trace_level': 2,
2227 'ClearBufferiv': {
2228 'type': 'PUT',
2229 'use_count_func': True,
2230 'count': 4,
2231 'unsafe': True,
2232 'trace_level': 2,
2234 'ClearBufferuiv': {
2235 'type': 'PUT',
2236 'count': 4,
2237 'unsafe': True,
2238 'trace_level': 2,
2240 'ClearBufferfv': {
2241 'type': 'PUT',
2242 'use_count_func': True,
2243 'count': 4,
2244 'unsafe': True,
2245 'trace_level': 2,
2247 'ClearBufferfi': {
2248 'unsafe': True,
2249 'trace_level': 2,
2251 'ClearColor': {
2252 'type': 'StateSet',
2253 'state': 'ClearColor',
2255 'ClearDepthf': {
2256 'type': 'StateSet',
2257 'state': 'ClearDepthf',
2258 'decoder_func': 'glClearDepth',
2259 'gl_test_func': 'glClearDepth',
2260 'valid_args': {
2261 '0': '0.5f'
2264 'ClientWaitSync': {
2265 'type': 'Custom',
2266 'data_transfer_methods': ['shm'],
2267 'cmd_args': 'GLuint sync, GLbitfieldSyncFlushFlags flags, '
2268 'GLuint timeout_0, GLuint timeout_1, GLenum* result',
2269 'unsafe': True,
2270 'result': ['GLenum'],
2271 'trace_level': 2,
2273 'ColorMask': {
2274 'type': 'StateSet',
2275 'state': 'ColorMask',
2276 'no_gl': True,
2277 'expectation': False,
2279 'ConsumeTextureCHROMIUM': {
2280 'decoder_func': 'DoConsumeTextureCHROMIUM',
2281 'impl_func': False,
2282 'type': 'PUT',
2283 'count': 64, # GL_MAILBOX_SIZE_CHROMIUM
2284 'unit_test': False,
2285 'client_test': False,
2286 'extension': "CHROMIUM_texture_mailbox",
2287 'chromium': True,
2288 'trace_level': 2,
2290 'CopyBufferSubData': {
2291 'unsafe': True,
2293 'CreateAndConsumeTextureCHROMIUM': {
2294 'decoder_func': 'DoCreateAndConsumeTextureCHROMIUM',
2295 'impl_func': False,
2296 'type': 'HandWritten',
2297 'data_transfer_methods': ['immediate'],
2298 'unit_test': False,
2299 'client_test': False,
2300 'extension': "CHROMIUM_texture_mailbox",
2301 'chromium': True,
2302 'trace_level': 2,
2304 'GenValuebuffersCHROMIUM': {
2305 'type': 'GENn',
2306 'gl_test_func': 'glGenValuebuffersCHROMIUM',
2307 'resource_type': 'Valuebuffer',
2308 'resource_types': 'Valuebuffers',
2309 'unit_test': False,
2310 'extension': True,
2311 'chromium': True,
2313 'DeleteValuebuffersCHROMIUM': {
2314 'type': 'DELn',
2315 'gl_test_func': 'glDeleteValuebuffersCHROMIUM',
2316 'resource_type': 'Valuebuffer',
2317 'resource_types': 'Valuebuffers',
2318 'unit_test': False,
2319 'extension': True,
2320 'chromium': True,
2322 'IsValuebufferCHROMIUM': {
2323 'type': 'Is',
2324 'decoder_func': 'DoIsValuebufferCHROMIUM',
2325 'expectation': False,
2326 'extension': True,
2327 'chromium': True,
2329 'BindValuebufferCHROMIUM': {
2330 'type': 'Bind',
2331 'decoder_func': 'DoBindValueBufferCHROMIUM',
2332 'gen_func': 'GenValueBuffersCHROMIUM',
2333 'unit_test': False,
2334 'extension': True,
2335 'chromium': True,
2337 'SubscribeValueCHROMIUM': {
2338 'decoder_func': 'DoSubscribeValueCHROMIUM',
2339 'unit_test': False,
2340 'extension': True,
2341 'chromium': True,
2343 'PopulateSubscribedValuesCHROMIUM': {
2344 'decoder_func': 'DoPopulateSubscribedValuesCHROMIUM',
2345 'unit_test': False,
2346 'extension': True,
2347 'chromium': True,
2349 'UniformValuebufferCHROMIUM': {
2350 'decoder_func': 'DoUniformValueBufferCHROMIUM',
2351 'unit_test': False,
2352 'extension': True,
2353 'chromium': True,
2355 'ClearStencil': {
2356 'type': 'StateSet',
2357 'state': 'ClearStencil',
2359 'EnableFeatureCHROMIUM': {
2360 'type': 'Custom',
2361 'data_transfer_methods': ['shm'],
2362 'decoder_func': 'DoEnableFeatureCHROMIUM',
2363 'expectation': False,
2364 'cmd_args': 'GLuint bucket_id, GLint* result',
2365 'result': ['GLint'],
2366 'extension': True,
2367 'chromium': True,
2368 'pepper_interface': 'ChromiumEnableFeature',
2370 'CompileShader': {'decoder_func': 'DoCompileShader', 'unit_test': False},
2371 'CompressedTexImage2D': {
2372 'type': 'Manual',
2373 'data_transfer_methods': ['bucket', 'shm'],
2374 'trace_level': 1,
2376 'CompressedTexSubImage2D': {
2377 'type': 'Data',
2378 'data_transfer_methods': ['bucket', 'shm'],
2379 'decoder_func': 'DoCompressedTexSubImage2D',
2380 'trace_level': 1,
2382 'CopyTexImage2D': {
2383 'decoder_func': 'DoCopyTexImage2D',
2384 'unit_test': False,
2385 'defer_reads': True,
2386 'trace_level': 1,
2388 'CopyTexSubImage2D': {
2389 'decoder_func': 'DoCopyTexSubImage2D',
2390 'defer_reads': True,
2391 'trace_level': 1,
2393 'CompressedTexImage3D': {
2394 'type': 'Manual',
2395 'data_transfer_methods': ['bucket', 'shm'],
2396 'unsafe': True,
2397 'trace_level': 1,
2399 'CompressedTexSubImage3D': {
2400 'type': 'Data',
2401 'data_transfer_methods': ['bucket', 'shm'],
2402 'decoder_func': 'DoCompressedTexSubImage3D',
2403 'unsafe': True,
2404 'trace_level': 1,
2406 'CopyTexSubImage3D': {
2407 'defer_reads': True,
2408 'unsafe': True,
2409 'trace_level': 1,
2411 'CreateImageCHROMIUM': {
2412 'type': 'Manual',
2413 'cmd_args':
2414 'ClientBuffer buffer, GLsizei width, GLsizei height, '
2415 'GLenum internalformat',
2416 'result': ['GLuint'],
2417 'client_test': False,
2418 'gen_cmd': False,
2419 'expectation': False,
2420 'extension': "CHROMIUM_image",
2421 'chromium': True,
2422 'trace_level': 1,
2424 'DestroyImageCHROMIUM': {
2425 'type': 'Manual',
2426 'client_test': False,
2427 'gen_cmd': False,
2428 'extension': "CHROMIUM_image",
2429 'chromium': True,
2430 'trace_level': 1,
2432 'CreateGpuMemoryBufferImageCHROMIUM': {
2433 'type': 'Manual',
2434 'cmd_args':
2435 'GLsizei width, GLsizei height, GLenum internalformat, GLenum usage',
2436 'result': ['GLuint'],
2437 'client_test': False,
2438 'gen_cmd': False,
2439 'expectation': False,
2440 'extension': "CHROMIUM_image",
2441 'chromium': True,
2442 'trace_level': 1,
2444 'CreateProgram': {
2445 'type': 'Create',
2446 'client_test': False,
2448 'CreateShader': {
2449 'type': 'Create',
2450 'client_test': False,
2452 'BlendColor': {
2453 'type': 'StateSet',
2454 'state': 'BlendColor',
2456 'BlendEquation': {
2457 'type': 'StateSetRGBAlpha',
2458 'state': 'BlendEquation',
2459 'valid_args': {
2460 '0': 'GL_FUNC_SUBTRACT'
2463 'BlendEquationSeparate': {
2464 'type': 'StateSet',
2465 'state': 'BlendEquation',
2466 'valid_args': {
2467 '0': 'GL_FUNC_SUBTRACT'
2470 'BlendFunc': {
2471 'type': 'StateSetRGBAlpha',
2472 'state': 'BlendFunc',
2474 'BlendFuncSeparate': {
2475 'type': 'StateSet',
2476 'state': 'BlendFunc',
2478 'BlendBarrierKHR': {
2479 'gl_test_func': 'glBlendBarrierKHR',
2480 'extension': True,
2481 'extension_flag': 'blend_equation_advanced',
2482 'client_test': False,
2484 'SampleCoverage': {'decoder_func': 'DoSampleCoverage'},
2485 'StencilFunc': {
2486 'type': 'StateSetFrontBack',
2487 'state': 'StencilFunc',
2489 'StencilFuncSeparate': {
2490 'type': 'StateSetFrontBackSeparate',
2491 'state': 'StencilFunc',
2493 'StencilOp': {
2494 'type': 'StateSetFrontBack',
2495 'state': 'StencilOp',
2496 'valid_args': {
2497 '1': 'GL_INCR'
2500 'StencilOpSeparate': {
2501 'type': 'StateSetFrontBackSeparate',
2502 'state': 'StencilOp',
2503 'valid_args': {
2504 '1': 'GL_INCR'
2507 'Hint': {
2508 'type': 'StateSetNamedParameter',
2509 'state': 'Hint',
2511 'CullFace': {'type': 'StateSet', 'state': 'CullFace'},
2512 'FrontFace': {'type': 'StateSet', 'state': 'FrontFace'},
2513 'DepthFunc': {'type': 'StateSet', 'state': 'DepthFunc'},
2514 'LineWidth': {
2515 'type': 'StateSet',
2516 'state': 'LineWidth',
2517 'valid_args': {
2518 '0': '0.5f'
2521 'PolygonOffset': {
2522 'type': 'StateSet',
2523 'state': 'PolygonOffset',
2525 'DeleteBuffers': {
2526 'type': 'DELn',
2527 'gl_test_func': 'glDeleteBuffersARB',
2528 'resource_type': 'Buffer',
2529 'resource_types': 'Buffers',
2531 'DeleteFramebuffers': {
2532 'type': 'DELn',
2533 'gl_test_func': 'glDeleteFramebuffersEXT',
2534 'resource_type': 'Framebuffer',
2535 'resource_types': 'Framebuffers',
2536 'trace_level': 2,
2538 'DeleteProgram': { 'type': 'Delete' },
2539 'DeleteRenderbuffers': {
2540 'type': 'DELn',
2541 'gl_test_func': 'glDeleteRenderbuffersEXT',
2542 'resource_type': 'Renderbuffer',
2543 'resource_types': 'Renderbuffers',
2544 'trace_level': 2,
2546 'DeleteSamplers': {
2547 'type': 'DELn',
2548 'resource_type': 'Sampler',
2549 'resource_types': 'Samplers',
2550 'unsafe': True,
2552 'DeleteShader': { 'type': 'Delete' },
2553 'DeleteSync': {
2554 'type': 'Delete',
2555 'cmd_args': 'GLuint sync',
2556 'resource_type': 'Sync',
2557 'unsafe': True,
2559 'DeleteTextures': {
2560 'type': 'DELn',
2561 'resource_type': 'Texture',
2562 'resource_types': 'Textures',
2564 'DeleteTransformFeedbacks': {
2565 'type': 'DELn',
2566 'resource_type': 'TransformFeedback',
2567 'resource_types': 'TransformFeedbacks',
2568 'unsafe': True,
2570 'DepthRangef': {
2571 'decoder_func': 'DoDepthRangef',
2572 'gl_test_func': 'glDepthRange',
2574 'DepthMask': {
2575 'type': 'StateSet',
2576 'state': 'DepthMask',
2577 'no_gl': True,
2578 'expectation': False,
2580 'DetachShader': {'decoder_func': 'DoDetachShader'},
2581 'Disable': {
2582 'decoder_func': 'DoDisable',
2583 'impl_func': False,
2584 'client_test': False,
2586 'DisableVertexAttribArray': {
2587 'decoder_func': 'DoDisableVertexAttribArray',
2588 'impl_decl': False,
2590 'DrawArrays': {
2591 'type': 'Manual',
2592 'cmd_args': 'GLenumDrawMode mode, GLint first, GLsizei count',
2593 'defer_draws': True,
2594 'trace_level': 2,
2596 'DrawElements': {
2597 'type': 'Manual',
2598 'cmd_args': 'GLenumDrawMode mode, GLsizei count, '
2599 'GLenumIndexType type, GLuint index_offset',
2600 'client_test': False,
2601 'defer_draws': True,
2602 'trace_level': 2,
2604 'DrawRangeElements': {
2605 'type': 'Manual',
2606 'gen_cmd': 'False',
2607 'unsafe': True,
2609 'Enable': {
2610 'decoder_func': 'DoEnable',
2611 'impl_func': False,
2612 'client_test': False,
2614 'EnableVertexAttribArray': {
2615 'decoder_func': 'DoEnableVertexAttribArray',
2616 'impl_decl': False,
2618 'FenceSync': {
2619 'type': 'Create',
2620 'client_test': False,
2621 'unsafe': True,
2622 'trace_level': 1,
2624 'Finish': {
2625 'impl_func': False,
2626 'client_test': False,
2627 'decoder_func': 'DoFinish',
2628 'defer_reads': True,
2629 'trace_level': 1,
2631 'Flush': {
2632 'impl_func': False,
2633 'decoder_func': 'DoFlush',
2634 'trace_level': 1,
2636 'FramebufferRenderbuffer': {
2637 'decoder_func': 'DoFramebufferRenderbuffer',
2638 'gl_test_func': 'glFramebufferRenderbufferEXT',
2639 'trace_level': 1,
2641 'FramebufferTexture2D': {
2642 'decoder_func': 'DoFramebufferTexture2D',
2643 'gl_test_func': 'glFramebufferTexture2DEXT',
2644 'trace_level': 1,
2646 'FramebufferTexture2DMultisampleEXT': {
2647 'decoder_func': 'DoFramebufferTexture2DMultisample',
2648 'gl_test_func': 'glFramebufferTexture2DMultisampleEXT',
2649 'expectation': False,
2650 'unit_test': False,
2651 'extension_flag': 'multisampled_render_to_texture',
2652 'trace_level': 1,
2654 'FramebufferTextureLayer': {
2655 'decoder_func': 'DoFramebufferTextureLayer',
2656 'unsafe': True,
2657 'trace_level': 1,
2659 'GenerateMipmap': {
2660 'decoder_func': 'DoGenerateMipmap',
2661 'gl_test_func': 'glGenerateMipmapEXT',
2662 'trace_level': 1,
2664 'GenBuffers': {
2665 'type': 'GENn',
2666 'gl_test_func': 'glGenBuffersARB',
2667 'resource_type': 'Buffer',
2668 'resource_types': 'Buffers',
2670 'GenMailboxCHROMIUM': {
2671 'type': 'HandWritten',
2672 'impl_func': False,
2673 'extension': "CHROMIUM_texture_mailbox",
2674 'chromium': True,
2676 'GenFramebuffers': {
2677 'type': 'GENn',
2678 'gl_test_func': 'glGenFramebuffersEXT',
2679 'resource_type': 'Framebuffer',
2680 'resource_types': 'Framebuffers',
2682 'GenRenderbuffers': {
2683 'type': 'GENn', 'gl_test_func': 'glGenRenderbuffersEXT',
2684 'resource_type': 'Renderbuffer',
2685 'resource_types': 'Renderbuffers',
2687 'GenSamplers': {
2688 'type': 'GENn',
2689 'gl_test_func': 'glGenSamplers',
2690 'resource_type': 'Sampler',
2691 'resource_types': 'Samplers',
2692 'unsafe': True,
2694 'GenTextures': {
2695 'type': 'GENn',
2696 'gl_test_func': 'glGenTextures',
2697 'resource_type': 'Texture',
2698 'resource_types': 'Textures',
2700 'GenTransformFeedbacks': {
2701 'type': 'GENn',
2702 'gl_test_func': 'glGenTransformFeedbacks',
2703 'resource_type': 'TransformFeedback',
2704 'resource_types': 'TransformFeedbacks',
2705 'unsafe': True,
2707 'GetActiveAttrib': {
2708 'type': 'Custom',
2709 'data_transfer_methods': ['shm'],
2710 'cmd_args':
2711 'GLidProgram program, GLuint index, uint32_t name_bucket_id, '
2712 'void* result',
2713 'result': [
2714 'int32_t success',
2715 'int32_t size',
2716 'uint32_t type',
2719 'GetActiveUniform': {
2720 'type': 'Custom',
2721 'data_transfer_methods': ['shm'],
2722 'cmd_args':
2723 'GLidProgram program, GLuint index, uint32_t name_bucket_id, '
2724 'void* result',
2725 'result': [
2726 'int32_t success',
2727 'int32_t size',
2728 'uint32_t type',
2731 'GetActiveUniformBlockiv': {
2732 'type': 'Custom',
2733 'data_transfer_methods': ['shm'],
2734 'result': ['SizedResult<GLint>'],
2735 'unsafe': True,
2737 'GetActiveUniformBlockName': {
2738 'type': 'Custom',
2739 'data_transfer_methods': ['shm'],
2740 'cmd_args':
2741 'GLidProgram program, GLuint index, uint32_t name_bucket_id, '
2742 'void* result',
2743 'result': ['int32_t'],
2744 'unsafe': True,
2746 'GetActiveUniformsiv': {
2747 'type': 'Custom',
2748 'data_transfer_methods': ['shm'],
2749 'cmd_args':
2750 'GLidProgram program, uint32_t indices_bucket_id, GLenum pname, '
2751 'GLint* params',
2752 'result': ['SizedResult<GLint>'],
2753 'unsafe': True,
2755 'GetAttachedShaders': {
2756 'type': 'Custom',
2757 'data_transfer_methods': ['shm'],
2758 'cmd_args': 'GLidProgram program, void* result, uint32_t result_size',
2759 'result': ['SizedResult<GLuint>'],
2761 'GetAttribLocation': {
2762 'type': 'Custom',
2763 'data_transfer_methods': ['shm'],
2764 'cmd_args':
2765 'GLidProgram program, uint32_t name_bucket_id, GLint* location',
2766 'result': ['GLint'],
2767 'error_return': -1,
2769 'GetFragDataLocation': {
2770 'type': 'Custom',
2771 'data_transfer_methods': ['shm'],
2772 'cmd_args':
2773 'GLidProgram program, uint32_t name_bucket_id, GLint* location',
2774 'result': ['GLint'],
2775 'error_return': -1,
2776 'unsafe': True,
2778 'GetBooleanv': {
2779 'type': 'GETn',
2780 'result': ['SizedResult<GLboolean>'],
2781 'decoder_func': 'DoGetBooleanv',
2782 'gl_test_func': 'glGetBooleanv',
2784 'GetBufferParameteri64v': {
2785 'type': 'GETn',
2786 'result': ['SizedResult<GLint64>'],
2787 'decoder_func': 'DoGetBufferParameteri64v',
2788 'expectation': False,
2789 'shadowed': True,
2790 'unsafe': True,
2792 'GetBufferParameteriv': {
2793 'type': 'GETn',
2794 'result': ['SizedResult<GLint>'],
2795 'decoder_func': 'DoGetBufferParameteriv',
2796 'expectation': False,
2797 'shadowed': True,
2799 'GetError': {
2800 'type': 'Is',
2801 'decoder_func': 'GetErrorState()->GetGLError',
2802 'impl_func': False,
2803 'result': ['GLenum'],
2804 'client_test': False,
2806 'GetFloatv': {
2807 'type': 'GETn',
2808 'result': ['SizedResult<GLfloat>'],
2809 'decoder_func': 'DoGetFloatv',
2810 'gl_test_func': 'glGetFloatv',
2812 'GetFramebufferAttachmentParameteriv': {
2813 'type': 'GETn',
2814 'decoder_func': 'DoGetFramebufferAttachmentParameteriv',
2815 'gl_test_func': 'glGetFramebufferAttachmentParameterivEXT',
2816 'result': ['SizedResult<GLint>'],
2818 'GetGraphicsResetStatusKHR': {
2819 'extension': True,
2820 'client_test': False,
2821 'gen_cmd': False,
2822 'trace_level': 1,
2824 'GetInteger64v': {
2825 'type': 'GETn',
2826 'result': ['SizedResult<GLint64>'],
2827 'client_test': False,
2828 'decoder_func': 'DoGetInteger64v',
2829 'unsafe': True
2831 'GetIntegerv': {
2832 'type': 'GETn',
2833 'result': ['SizedResult<GLint>'],
2834 'decoder_func': 'DoGetIntegerv',
2835 'client_test': False,
2837 'GetInteger64i_v': {
2838 'type': 'GETn',
2839 'result': ['SizedResult<GLint64>'],
2840 'client_test': False,
2841 'unsafe': True
2843 'GetIntegeri_v': {
2844 'type': 'GETn',
2845 'result': ['SizedResult<GLint>'],
2846 'client_test': False,
2847 'unsafe': True
2849 'GetInternalformativ': {
2850 'type': 'Custom',
2851 'data_transfer_methods': ['shm'],
2852 'result': ['SizedResult<GLint>'],
2853 'cmd_args':
2854 'GLenumRenderBufferTarget target, GLenumRenderBufferFormat format, '
2855 'GLenumInternalFormatParameter pname, GLint* params',
2856 'unsafe': True,
2858 'GetMaxValueInBufferCHROMIUM': {
2859 'type': 'Is',
2860 'decoder_func': 'DoGetMaxValueInBufferCHROMIUM',
2861 'result': ['GLuint'],
2862 'unit_test': False,
2863 'client_test': False,
2864 'extension': True,
2865 'chromium': True,
2866 'impl_func': False,
2868 'GetProgramiv': {
2869 'type': 'GETn',
2870 'decoder_func': 'DoGetProgramiv',
2871 'result': ['SizedResult<GLint>'],
2872 'expectation': False,
2874 'GetProgramInfoCHROMIUM': {
2875 'type': 'Custom',
2876 'expectation': False,
2877 'impl_func': False,
2878 'extension': True,
2879 'chromium': True,
2880 'client_test': False,
2881 'cmd_args': 'GLidProgram program, uint32_t bucket_id',
2882 'result': [
2883 'uint32_t link_status',
2884 'uint32_t num_attribs',
2885 'uint32_t num_uniforms',
2888 'GetProgramInfoLog': {
2889 'type': 'STRn',
2890 'expectation': False,
2892 'GetRenderbufferParameteriv': {
2893 'type': 'GETn',
2894 'decoder_func': 'DoGetRenderbufferParameteriv',
2895 'gl_test_func': 'glGetRenderbufferParameterivEXT',
2896 'result': ['SizedResult<GLint>'],
2898 'GetSamplerParameterfv': {
2899 'type': 'GETn',
2900 'result': ['SizedResult<GLfloat>'],
2901 'id_mapping': [ 'Sampler' ],
2902 'unsafe': True,
2904 'GetSamplerParameteriv': {
2905 'type': 'GETn',
2906 'result': ['SizedResult<GLint>'],
2907 'id_mapping': [ 'Sampler' ],
2908 'unsafe': True,
2910 'GetShaderiv': {
2911 'type': 'GETn',
2912 'decoder_func': 'DoGetShaderiv',
2913 'result': ['SizedResult<GLint>'],
2915 'GetShaderInfoLog': {
2916 'type': 'STRn',
2917 'get_len_func': 'glGetShaderiv',
2918 'get_len_enum': 'GL_INFO_LOG_LENGTH',
2919 'unit_test': False,
2921 'GetShaderPrecisionFormat': {
2922 'type': 'Custom',
2923 'data_transfer_methods': ['shm'],
2924 'cmd_args':
2925 'GLenumShaderType shadertype, GLenumShaderPrecision precisiontype, '
2926 'void* result',
2927 'result': [
2928 'int32_t success',
2929 'int32_t min_range',
2930 'int32_t max_range',
2931 'int32_t precision',
2934 'GetShaderSource': {
2935 'type': 'STRn',
2936 'get_len_func': 'DoGetShaderiv',
2937 'get_len_enum': 'GL_SHADER_SOURCE_LENGTH',
2938 'unit_test': False,
2939 'client_test': False,
2941 'GetString': {
2942 'type': 'Custom',
2943 'client_test': False,
2944 'cmd_args': 'GLenumStringType name, uint32_t bucket_id',
2946 'GetSynciv': {
2947 'type': 'GETn',
2948 'cmd_args': 'GLuint sync, GLenumSyncParameter pname, void* values',
2949 'result': ['SizedResult<GLint>'],
2950 'id_mapping': ['Sync'],
2951 'unsafe': True,
2953 'GetTexParameterfv': {
2954 'type': 'GETn',
2955 'decoder_func': 'DoGetTexParameterfv',
2956 'result': ['SizedResult<GLfloat>']
2958 'GetTexParameteriv': {
2959 'type': 'GETn',
2960 'decoder_func': 'DoGetTexParameteriv',
2961 'result': ['SizedResult<GLint>']
2963 'GetTranslatedShaderSourceANGLE': {
2964 'type': 'STRn',
2965 'get_len_func': 'DoGetShaderiv',
2966 'get_len_enum': 'GL_TRANSLATED_SHADER_SOURCE_LENGTH_ANGLE',
2967 'unit_test': False,
2968 'extension': True,
2970 'GetUniformBlockIndex': {
2971 'type': 'Custom',
2972 'data_transfer_methods': ['shm'],
2973 'cmd_args':
2974 'GLidProgram program, uint32_t name_bucket_id, GLuint* index',
2975 'result': ['GLuint'],
2976 'error_return': 'GL_INVALID_INDEX',
2977 'unsafe': True,
2979 'GetUniformBlocksCHROMIUM': {
2980 'type': 'Custom',
2981 'expectation': False,
2982 'impl_func': False,
2983 'extension': True,
2984 'chromium': True,
2985 'client_test': False,
2986 'cmd_args': 'GLidProgram program, uint32_t bucket_id',
2987 'result': ['uint32_t'],
2988 'unsafe': True,
2990 'GetUniformsES3CHROMIUM': {
2991 'type': 'Custom',
2992 'expectation': False,
2993 'impl_func': False,
2994 'extension': True,
2995 'chromium': True,
2996 'client_test': False,
2997 'cmd_args': 'GLidProgram program, uint32_t bucket_id',
2998 'result': ['uint32_t'],
2999 'unsafe': True,
3001 'GetTransformFeedbackVarying': {
3002 'type': 'Custom',
3003 'data_transfer_methods': ['shm'],
3004 'cmd_args':
3005 'GLidProgram program, GLuint index, uint32_t name_bucket_id, '
3006 'void* result',
3007 'result': [
3008 'int32_t success',
3009 'int32_t size',
3010 'uint32_t type',
3012 'unsafe': True,
3014 'GetTransformFeedbackVaryingsCHROMIUM': {
3015 'type': 'Custom',
3016 'expectation': False,
3017 'impl_func': False,
3018 'extension': True,
3019 'chromium': True,
3020 'client_test': False,
3021 'cmd_args': 'GLidProgram program, uint32_t bucket_id',
3022 'result': ['uint32_t'],
3023 'unsafe': True,
3025 'GetUniformfv': {
3026 'type': 'Custom',
3027 'data_transfer_methods': ['shm'],
3028 'result': ['SizedResult<GLfloat>'],
3030 'GetUniformiv': {
3031 'type': 'Custom',
3032 'data_transfer_methods': ['shm'],
3033 'result': ['SizedResult<GLint>'],
3035 'GetUniformuiv': {
3036 'type': 'Custom',
3037 'data_transfer_methods': ['shm'],
3038 'result': ['SizedResult<GLuint>'],
3039 'unsafe': True,
3041 'GetUniformIndices': {
3042 'type': 'Custom',
3043 'data_transfer_methods': ['shm'],
3044 'result': ['SizedResult<GLuint>'],
3045 'cmd_args': 'GLidProgram program, uint32_t names_bucket_id, '
3046 'GLuint* indices',
3047 'unsafe': True,
3049 'GetUniformLocation': {
3050 'type': 'Custom',
3051 'data_transfer_methods': ['shm'],
3052 'cmd_args':
3053 'GLidProgram program, uint32_t name_bucket_id, GLint* location',
3054 'result': ['GLint'],
3055 'error_return': -1, # http://www.opengl.org/sdk/docs/man/xhtml/glGetUniformLocation.xml
3057 'GetVertexAttribfv': {
3058 'type': 'GETn',
3059 'result': ['SizedResult<GLfloat>'],
3060 'impl_decl': False,
3061 'decoder_func': 'DoGetVertexAttribfv',
3062 'expectation': False,
3063 'client_test': False,
3065 'GetVertexAttribiv': {
3066 'type': 'GETn',
3067 'result': ['SizedResult<GLint>'],
3068 'impl_decl': False,
3069 'decoder_func': 'DoGetVertexAttribiv',
3070 'expectation': False,
3071 'client_test': False,
3073 'GetVertexAttribIiv': {
3074 'type': 'GETn',
3075 'result': ['SizedResult<GLint>'],
3076 'impl_decl': False,
3077 'decoder_func': 'DoGetVertexAttribIiv',
3078 'expectation': False,
3079 'client_test': False,
3080 'unsafe': True,
3082 'GetVertexAttribIuiv': {
3083 'type': 'GETn',
3084 'result': ['SizedResult<GLuint>'],
3085 'impl_decl': False,
3086 'decoder_func': 'DoGetVertexAttribIuiv',
3087 'expectation': False,
3088 'client_test': False,
3089 'unsafe': True,
3091 'GetVertexAttribPointerv': {
3092 'type': 'Custom',
3093 'data_transfer_methods': ['shm'],
3094 'result': ['SizedResult<GLuint>'],
3095 'client_test': False,
3097 'InvalidateFramebuffer': {
3098 'type': 'PUTn',
3099 'count': 1,
3100 'client_test': False,
3101 'unit_test': False,
3102 'unsafe': True,
3104 'InvalidateSubFramebuffer': {
3105 'type': 'PUTn',
3106 'count': 1,
3107 'client_test': False,
3108 'unit_test': False,
3109 'unsafe': True,
3111 'IsBuffer': {
3112 'type': 'Is',
3113 'decoder_func': 'DoIsBuffer',
3114 'expectation': False,
3116 'IsEnabled': {
3117 'type': 'Is',
3118 'decoder_func': 'DoIsEnabled',
3119 'client_test': False,
3120 'impl_func': False,
3121 'expectation': False,
3123 'IsFramebuffer': {
3124 'type': 'Is',
3125 'decoder_func': 'DoIsFramebuffer',
3126 'expectation': False,
3128 'IsProgram': {
3129 'type': 'Is',
3130 'decoder_func': 'DoIsProgram',
3131 'expectation': False,
3133 'IsRenderbuffer': {
3134 'type': 'Is',
3135 'decoder_func': 'DoIsRenderbuffer',
3136 'expectation': False,
3138 'IsShader': {
3139 'type': 'Is',
3140 'decoder_func': 'DoIsShader',
3141 'expectation': False,
3143 'IsSampler': {
3144 'type': 'Is',
3145 'id_mapping': [ 'Sampler' ],
3146 'expectation': False,
3147 'unsafe': True,
3149 'IsSync': {
3150 'type': 'Is',
3151 'id_mapping': [ 'Sync' ],
3152 'cmd_args': 'GLuint sync',
3153 'expectation': False,
3154 'unsafe': True,
3156 'IsTexture': {
3157 'type': 'Is',
3158 'decoder_func': 'DoIsTexture',
3159 'expectation': False,
3161 'IsTransformFeedback': {
3162 'type': 'Is',
3163 'id_mapping': [ 'TransformFeedback' ],
3164 'expectation': False,
3165 'unsafe': True,
3167 'LinkProgram': {
3168 'decoder_func': 'DoLinkProgram',
3169 'impl_func': False,
3170 'trace_level': 1,
3172 'MapBufferCHROMIUM': {
3173 'gen_cmd': False,
3174 'extension': "CHROMIUM_pixel_transfer_buffer_object",
3175 'chromium': True,
3176 'client_test': False,
3177 'trace_level': 1,
3179 'MapBufferSubDataCHROMIUM': {
3180 'gen_cmd': False,
3181 'extension': True,
3182 'chromium': True,
3183 'client_test': False,
3184 'pepper_interface': 'ChromiumMapSub',
3185 'trace_level': 1,
3187 'MapTexSubImage2DCHROMIUM': {
3188 'gen_cmd': False,
3189 'extension': "CHROMIUM_sub_image",
3190 'chromium': True,
3191 'client_test': False,
3192 'pepper_interface': 'ChromiumMapSub',
3193 'trace_level': 1,
3195 'MapBufferRange': {
3196 'type': 'Custom',
3197 'data_transfer_methods': ['shm'],
3198 'cmd_args': 'GLenumBufferTarget target, GLintptrNotNegative offset, '
3199 'GLsizeiptr size, GLbitfieldMapBufferAccess access, '
3200 'uint32_t data_shm_id, uint32_t data_shm_offset, '
3201 'uint32_t result_shm_id, uint32_t result_shm_offset',
3202 'unsafe': True,
3203 'result': ['uint32_t'],
3204 'trace_level': 1,
3206 'PauseTransformFeedback': {
3207 'unsafe': True,
3209 'PixelStorei': {'type': 'Manual'},
3210 'PostSubBufferCHROMIUM': {
3211 'type': 'Custom',
3212 'impl_func': False,
3213 'unit_test': False,
3214 'client_test': False,
3215 'extension': True,
3216 'chromium': True,
3218 'ProduceTextureCHROMIUM': {
3219 'decoder_func': 'DoProduceTextureCHROMIUM',
3220 'impl_func': False,
3221 'type': 'PUT',
3222 'count': 64, # GL_MAILBOX_SIZE_CHROMIUM
3223 'unit_test': False,
3224 'client_test': False,
3225 'extension': "CHROMIUM_texture_mailbox",
3226 'chromium': True,
3227 'trace_level': 1,
3229 'ProduceTextureDirectCHROMIUM': {
3230 'decoder_func': 'DoProduceTextureDirectCHROMIUM',
3231 'impl_func': False,
3232 'type': 'PUT',
3233 'count': 64, # GL_MAILBOX_SIZE_CHROMIUM
3234 'unit_test': False,
3235 'client_test': False,
3236 'extension': "CHROMIUM_texture_mailbox",
3237 'chromium': True,
3238 'trace_level': 1,
3240 'RenderbufferStorage': {
3241 'decoder_func': 'DoRenderbufferStorage',
3242 'gl_test_func': 'glRenderbufferStorageEXT',
3243 'expectation': False,
3244 'trace_level': 1,
3246 'RenderbufferStorageMultisampleCHROMIUM': {
3247 'cmd_comment':
3248 '// GL_CHROMIUM_framebuffer_multisample\n',
3249 'decoder_func': 'DoRenderbufferStorageMultisampleCHROMIUM',
3250 'gl_test_func': 'glRenderbufferStorageMultisampleCHROMIUM',
3251 'expectation': False,
3252 'unit_test': False,
3253 'extension_flag': 'chromium_framebuffer_multisample',
3254 'pepper_interface': 'FramebufferMultisample',
3255 'pepper_name': 'RenderbufferStorageMultisampleEXT',
3256 'trace_level': 1,
3258 'RenderbufferStorageMultisampleEXT': {
3259 'cmd_comment':
3260 '// GL_EXT_multisampled_render_to_texture\n',
3261 'decoder_func': 'DoRenderbufferStorageMultisampleEXT',
3262 'gl_test_func': 'glRenderbufferStorageMultisampleEXT',
3263 'expectation': False,
3264 'unit_test': False,
3265 'extension_flag': 'multisampled_render_to_texture',
3266 'trace_level': 1,
3268 'ReadBuffer': {
3269 'unsafe': True,
3270 'decoder_func': 'DoReadBuffer',
3271 'trace_level': 1,
3273 'ReadPixels': {
3274 'cmd_comment':
3275 '// ReadPixels has the result separated from the pixel buffer so that\n'
3276 '// it is easier to specify the result going to some specific place\n'
3277 '// that exactly fits the rectangle of pixels.\n',
3278 'type': 'Custom',
3279 'data_transfer_methods': ['shm'],
3280 'impl_func': False,
3281 'client_test': False,
3282 'cmd_args':
3283 'GLint x, GLint y, GLsizei width, GLsizei height, '
3284 'GLenumReadPixelFormat format, GLenumReadPixelType type, '
3285 'uint32_t pixels_shm_id, uint32_t pixels_shm_offset, '
3286 'uint32_t result_shm_id, uint32_t result_shm_offset, '
3287 'GLboolean async',
3288 'result': ['uint32_t'],
3289 'defer_reads': True,
3290 'trace_level': 1,
3292 'ReleaseShaderCompiler': {
3293 'decoder_func': 'DoReleaseShaderCompiler',
3294 'unit_test': False,
3296 'ResumeTransformFeedback': {
3297 'unsafe': True,
3299 'SamplerParameterf': {
3300 'valid_args': {
3301 '2': 'GL_NEAREST'
3303 'id_mapping': [ 'Sampler' ],
3304 'unsafe': True,
3306 'SamplerParameterfv': {
3307 'type': 'PUT',
3308 'data_value': 'GL_NEAREST',
3309 'count': 1,
3310 'gl_test_func': 'glSamplerParameterf',
3311 'decoder_func': 'DoSamplerParameterfv',
3312 'first_element_only': True,
3313 'id_mapping': [ 'Sampler' ],
3314 'unsafe': True,
3316 'SamplerParameteri': {
3317 'valid_args': {
3318 '2': 'GL_NEAREST'
3320 'id_mapping': [ 'Sampler' ],
3321 'unsafe': True,
3323 'SamplerParameteriv': {
3324 'type': 'PUT',
3325 'data_value': 'GL_NEAREST',
3326 'count': 1,
3327 'gl_test_func': 'glSamplerParameteri',
3328 'decoder_func': 'DoSamplerParameteriv',
3329 'first_element_only': True,
3330 'unsafe': True,
3332 'ShaderBinary': {
3333 'type': 'Custom',
3334 'client_test': False,
3336 'ShaderSource': {
3337 'type': 'PUTSTR',
3338 'decoder_func': 'DoShaderSource',
3339 'expectation': False,
3340 'data_transfer_methods': ['bucket'],
3341 'cmd_args':
3342 'GLuint shader, const char** str',
3343 'pepper_args':
3344 'GLuint shader, GLsizei count, const char** str, const GLint* length',
3346 'StencilMask': {
3347 'type': 'StateSetFrontBack',
3348 'state': 'StencilMask',
3349 'no_gl': True,
3350 'expectation': False,
3352 'StencilMaskSeparate': {
3353 'type': 'StateSetFrontBackSeparate',
3354 'state': 'StencilMask',
3355 'no_gl': True,
3356 'expectation': False,
3358 'SwapBuffers': {
3359 'impl_func': False,
3360 'decoder_func': 'DoSwapBuffers',
3361 'unit_test': False,
3362 'client_test': False,
3363 'extension': True,
3364 'trace_level': 1,
3366 'SwapInterval': {
3367 'impl_func': False,
3368 'decoder_func': 'DoSwapInterval',
3369 'unit_test': False,
3370 'client_test': False,
3371 'extension': True,
3372 'trace_level': 1,
3374 'TexImage2D': {
3375 'type': 'Manual',
3376 'data_transfer_methods': ['shm'],
3377 'client_test': False,
3378 'trace_level': 2,
3380 'TexImage3D': {
3381 'type': 'Manual',
3382 'data_transfer_methods': ['shm'],
3383 'client_test': False,
3384 'unsafe': True,
3385 'trace_level': 2,
3387 'TexParameterf': {
3388 'decoder_func': 'DoTexParameterf',
3389 'valid_args': {
3390 '2': 'GL_NEAREST'
3393 'TexParameteri': {
3394 'decoder_func': 'DoTexParameteri',
3395 'valid_args': {
3396 '2': 'GL_NEAREST'
3399 'TexParameterfv': {
3400 'type': 'PUT',
3401 'data_value': 'GL_NEAREST',
3402 'count': 1,
3403 'decoder_func': 'DoTexParameterfv',
3404 'gl_test_func': 'glTexParameterf',
3405 'first_element_only': True,
3407 'TexParameteriv': {
3408 'type': 'PUT',
3409 'data_value': 'GL_NEAREST',
3410 'count': 1,
3411 'decoder_func': 'DoTexParameteriv',
3412 'gl_test_func': 'glTexParameteri',
3413 'first_element_only': True,
3415 'TexStorage3D': {
3416 'unsafe': True,
3417 'trace_level': 2,
3419 'TexSubImage2D': {
3420 'type': 'Manual',
3421 'data_transfer_methods': ['shm'],
3422 'client_test': False,
3423 'trace_level': 2,
3424 'cmd_args': 'GLenumTextureTarget target, GLint level, '
3425 'GLint xoffset, GLint yoffset, '
3426 'GLsizei width, GLsizei height, '
3427 'GLenumTextureFormat format, GLenumPixelType type, '
3428 'const void* pixels, GLboolean internal'
3430 'TexSubImage3D': {
3431 'type': 'Manual',
3432 'data_transfer_methods': ['shm'],
3433 'client_test': False,
3434 'trace_level': 2,
3435 'cmd_args': 'GLenumTextureTarget target, GLint level, '
3436 'GLint xoffset, GLint yoffset, GLint zoffset, '
3437 'GLsizei width, GLsizei height, GLsizei depth, '
3438 'GLenumTextureFormat format, GLenumPixelType type, '
3439 'const void* pixels, GLboolean internal',
3440 'unsafe': True,
3442 'TransformFeedbackVaryings': {
3443 'type': 'PUTSTR',
3444 'data_transfer_methods': ['bucket'],
3445 'decoder_func': 'DoTransformFeedbackVaryings',
3446 'cmd_args':
3447 'GLuint program, const char** varyings, GLenum buffermode',
3448 'unsafe': True,
3450 'Uniform1f': {'type': 'PUTXn', 'count': 1},
3451 'Uniform1fv': {
3452 'type': 'PUTn',
3453 'count': 1,
3454 'decoder_func': 'DoUniform1fv',
3456 'Uniform1i': {'decoder_func': 'DoUniform1i', 'unit_test': False},
3457 'Uniform1iv': {
3458 'type': 'PUTn',
3459 'count': 1,
3460 'decoder_func': 'DoUniform1iv',
3461 'unit_test': False,
3463 'Uniform1ui': {
3464 'type': 'PUTXn',
3465 'count': 1,
3466 'unsafe': True,
3468 'Uniform1uiv': {
3469 'type': 'PUTn',
3470 'count': 1,
3471 'unsafe': True,
3473 'Uniform2i': {'type': 'PUTXn', 'count': 2},
3474 'Uniform2f': {'type': 'PUTXn', 'count': 2},
3475 'Uniform2fv': {
3476 'type': 'PUTn',
3477 'count': 2,
3478 'decoder_func': 'DoUniform2fv',
3480 'Uniform2iv': {
3481 'type': 'PUTn',
3482 'count': 2,
3483 'decoder_func': 'DoUniform2iv',
3485 'Uniform2ui': {
3486 'type': 'PUTXn',
3487 'count': 2,
3488 'unsafe': True,
3490 'Uniform2uiv': {
3491 'type': 'PUTn',
3492 'count': 2,
3493 'unsafe': True,
3495 'Uniform3i': {'type': 'PUTXn', 'count': 3},
3496 'Uniform3f': {'type': 'PUTXn', 'count': 3},
3497 'Uniform3fv': {
3498 'type': 'PUTn',
3499 'count': 3,
3500 'decoder_func': 'DoUniform3fv',
3502 'Uniform3iv': {
3503 'type': 'PUTn',
3504 'count': 3,
3505 'decoder_func': 'DoUniform3iv',
3507 'Uniform3ui': {
3508 'type': 'PUTXn',
3509 'count': 3,
3510 'unsafe': True,
3512 'Uniform3uiv': {
3513 'type': 'PUTn',
3514 'count': 3,
3515 'unsafe': True,
3517 'Uniform4i': {'type': 'PUTXn', 'count': 4},
3518 'Uniform4f': {'type': 'PUTXn', 'count': 4},
3519 'Uniform4fv': {
3520 'type': 'PUTn',
3521 'count': 4,
3522 'decoder_func': 'DoUniform4fv',
3524 'Uniform4iv': {
3525 'type': 'PUTn',
3526 'count': 4,
3527 'decoder_func': 'DoUniform4iv',
3529 'Uniform4ui': {
3530 'type': 'PUTXn',
3531 'count': 4,
3532 'unsafe': True,
3534 'Uniform4uiv': {
3535 'type': 'PUTn',
3536 'count': 4,
3537 'unsafe': True,
3539 'UniformMatrix2fv': {
3540 'type': 'PUTn',
3541 'count': 4,
3542 'decoder_func': 'DoUniformMatrix2fv',
3544 'UniformMatrix2x3fv': {
3545 'type': 'PUTn',
3546 'count': 6,
3547 'unsafe': True,
3549 'UniformMatrix2x4fv': {
3550 'type': 'PUTn',
3551 'count': 8,
3552 'unsafe': True,
3554 'UniformMatrix3fv': {
3555 'type': 'PUTn',
3556 'count': 9,
3557 'decoder_func': 'DoUniformMatrix3fv',
3559 'UniformMatrix3x2fv': {
3560 'type': 'PUTn',
3561 'count': 6,
3562 'unsafe': True,
3564 'UniformMatrix3x4fv': {
3565 'type': 'PUTn',
3566 'count': 12,
3567 'unsafe': True,
3569 'UniformMatrix4fv': {
3570 'type': 'PUTn',
3571 'count': 16,
3572 'decoder_func': 'DoUniformMatrix4fv',
3574 'UniformMatrix4x2fv': {
3575 'type': 'PUTn',
3576 'count': 8,
3577 'unsafe': True,
3579 'UniformMatrix4x3fv': {
3580 'type': 'PUTn',
3581 'count': 12,
3582 'unsafe': True,
3584 'UniformBlockBinding': {
3585 'type': 'Custom',
3586 'impl_func': False,
3587 'unsafe': True,
3589 'UnmapBufferCHROMIUM': {
3590 'gen_cmd': False,
3591 'extension': "CHROMIUM_pixel_transfer_buffer_object",
3592 'chromium': True,
3593 'client_test': False,
3594 'trace_level': 1,
3596 'UnmapBufferSubDataCHROMIUM': {
3597 'gen_cmd': False,
3598 'extension': True,
3599 'chromium': True,
3600 'client_test': False,
3601 'pepper_interface': 'ChromiumMapSub',
3602 'trace_level': 1,
3604 'UnmapBuffer': {
3605 'type': 'Custom',
3606 'unsafe': True,
3607 'trace_level': 1,
3609 'UnmapTexSubImage2DCHROMIUM': {
3610 'gen_cmd': False,
3611 'extension': "CHROMIUM_sub_image",
3612 'chromium': True,
3613 'client_test': False,
3614 'pepper_interface': 'ChromiumMapSub',
3615 'trace_level': 1,
3617 'UseProgram': {
3618 'type': 'Bind',
3619 'decoder_func': 'DoUseProgram',
3621 'ValidateProgram': {'decoder_func': 'DoValidateProgram'},
3622 'VertexAttrib1f': {'decoder_func': 'DoVertexAttrib1f'},
3623 'VertexAttrib1fv': {
3624 'type': 'PUT',
3625 'count': 1,
3626 'decoder_func': 'DoVertexAttrib1fv',
3628 'VertexAttrib2f': {'decoder_func': 'DoVertexAttrib2f'},
3629 'VertexAttrib2fv': {
3630 'type': 'PUT',
3631 'count': 2,
3632 'decoder_func': 'DoVertexAttrib2fv',
3634 'VertexAttrib3f': {'decoder_func': 'DoVertexAttrib3f'},
3635 'VertexAttrib3fv': {
3636 'type': 'PUT',
3637 'count': 3,
3638 'decoder_func': 'DoVertexAttrib3fv',
3640 'VertexAttrib4f': {'decoder_func': 'DoVertexAttrib4f'},
3641 'VertexAttrib4fv': {
3642 'type': 'PUT',
3643 'count': 4,
3644 'decoder_func': 'DoVertexAttrib4fv',
3646 'VertexAttribI4i': {
3647 'unsafe': True,
3648 'decoder_func': 'DoVertexAttribI4i',
3650 'VertexAttribI4iv': {
3651 'type': 'PUT',
3652 'count': 4,
3653 'unsafe': True,
3654 'decoder_func': 'DoVertexAttribI4iv',
3656 'VertexAttribI4ui': {
3657 'unsafe': True,
3658 'decoder_func': 'DoVertexAttribI4ui',
3660 'VertexAttribI4uiv': {
3661 'type': 'PUT',
3662 'count': 4,
3663 'unsafe': True,
3664 'decoder_func': 'DoVertexAttribI4uiv',
3666 'VertexAttribIPointer': {
3667 'type': 'Manual',
3668 'cmd_args': 'GLuint indx, GLintVertexAttribSize size, '
3669 'GLenumVertexAttribIType type, GLsizei stride, '
3670 'GLuint offset',
3671 'client_test': False,
3672 'unsafe': True,
3674 'VertexAttribPointer': {
3675 'type': 'Manual',
3676 'cmd_args': 'GLuint indx, GLintVertexAttribSize size, '
3677 'GLenumVertexAttribType type, GLboolean normalized, '
3678 'GLsizei stride, GLuint offset',
3679 'client_test': False,
3681 'WaitSync': {
3682 'type': 'Custom',
3683 'cmd_args': 'GLuint sync, GLbitfieldSyncFlushFlags flags, '
3684 'GLuint timeout_0, GLuint timeout_1',
3685 'impl_func': False,
3686 'client_test': False,
3687 'unsafe': True,
3688 'trace_level': 1,
3690 'Scissor': {
3691 'type': 'StateSet',
3692 'state': 'Scissor',
3694 'Viewport': {
3695 'decoder_func': 'DoViewport',
3697 'ResizeCHROMIUM': {
3698 'type': 'Custom',
3699 'impl_func': False,
3700 'unit_test': False,
3701 'extension': True,
3702 'chromium': True,
3703 'trace_level': 1,
3705 'GetRequestableExtensionsCHROMIUM': {
3706 'type': 'Custom',
3707 'impl_func': False,
3708 'cmd_args': 'uint32_t bucket_id',
3709 'extension': True,
3710 'chromium': True,
3712 'RequestExtensionCHROMIUM': {
3713 'type': 'Custom',
3714 'impl_func': False,
3715 'client_test': False,
3716 'cmd_args': 'uint32_t bucket_id',
3717 'extension': True,
3718 'chromium': True,
3720 'RateLimitOffscreenContextCHROMIUM': {
3721 'gen_cmd': False,
3722 'extension': True,
3723 'chromium': True,
3724 'client_test': False,
3726 'CreateStreamTextureCHROMIUM': {
3727 'type': 'HandWritten',
3728 'impl_func': False,
3729 'gen_cmd': False,
3730 'extension': True,
3731 'chromium': True,
3732 'trace_level': 1,
3734 'TexImageIOSurface2DCHROMIUM': {
3735 'decoder_func': 'DoTexImageIOSurface2DCHROMIUM',
3736 'unit_test': False,
3737 'extension': True,
3738 'chromium': True,
3739 'trace_level': 1,
3741 'CopyTextureCHROMIUM': {
3742 'decoder_func': 'DoCopyTextureCHROMIUM',
3743 'unit_test': False,
3744 'extension': "CHROMIUM_copy_texture",
3745 'chromium': True,
3746 'trace_level': 2,
3748 'CopySubTextureCHROMIUM': {
3749 'decoder_func': 'DoCopySubTextureCHROMIUM',
3750 'unit_test': False,
3751 'extension': "CHROMIUM_copy_texture",
3752 'chromium': True,
3753 'trace_level': 2,
3755 'CompressedCopyTextureCHROMIUM': {
3756 'decoder_func': 'DoCompressedCopyTextureCHROMIUM',
3757 'unit_test': False,
3758 'extension': True,
3759 'chromium': True,
3761 'TexStorage2DEXT': {
3762 'unit_test': False,
3763 'extension': True,
3764 'decoder_func': 'DoTexStorage2DEXT',
3765 'trace_level': 2,
3767 'DrawArraysInstancedANGLE': {
3768 'type': 'Manual',
3769 'cmd_args': 'GLenumDrawMode mode, GLint first, GLsizei count, '
3770 'GLsizei primcount',
3771 'extension': True,
3772 'unit_test': False,
3773 'pepper_interface': 'InstancedArrays',
3774 'defer_draws': True,
3775 'trace_level': 2,
3777 'DrawBuffersEXT': {
3778 'type': 'PUTn',
3779 'decoder_func': 'DoDrawBuffersEXT',
3780 'count': 1,
3781 'client_test': False,
3782 'unit_test': False,
3783 # could use 'extension_flag': 'ext_draw_buffers' but currently expected to
3784 # work without.
3785 'extension': True,
3786 'pepper_interface': 'DrawBuffers',
3787 'trace_level': 2,
3789 'DrawElementsInstancedANGLE': {
3790 'type': 'Manual',
3791 'cmd_args': 'GLenumDrawMode mode, GLsizei count, '
3792 'GLenumIndexType type, GLuint index_offset, GLsizei primcount',
3793 'extension': True,
3794 'unit_test': False,
3795 'client_test': False,
3796 'pepper_interface': 'InstancedArrays',
3797 'defer_draws': True,
3798 'trace_level': 2,
3800 'VertexAttribDivisorANGLE': {
3801 'type': 'Manual',
3802 'cmd_args': 'GLuint index, GLuint divisor',
3803 'extension': True,
3804 'unit_test': False,
3805 'pepper_interface': 'InstancedArrays',
3807 'GenQueriesEXT': {
3808 'type': 'GENn',
3809 'gl_test_func': 'glGenQueriesARB',
3810 'resource_type': 'Query',
3811 'resource_types': 'Queries',
3812 'unit_test': False,
3813 'pepper_interface': 'Query',
3814 'not_shared': 'True',
3815 'extension': "occlusion_query_EXT",
3817 'DeleteQueriesEXT': {
3818 'type': 'DELn',
3819 'gl_test_func': 'glDeleteQueriesARB',
3820 'resource_type': 'Query',
3821 'resource_types': 'Queries',
3822 'unit_test': False,
3823 'pepper_interface': 'Query',
3824 'extension': "occlusion_query_EXT",
3826 'IsQueryEXT': {
3827 'gen_cmd': False,
3828 'client_test': False,
3829 'pepper_interface': 'Query',
3830 'extension': "occlusion_query_EXT",
3832 'BeginQueryEXT': {
3833 'type': 'Manual',
3834 'cmd_args': 'GLenumQueryTarget target, GLidQuery id, void* sync_data',
3835 'data_transfer_methods': ['shm'],
3836 'gl_test_func': 'glBeginQuery',
3837 'pepper_interface': 'Query',
3838 'extension': "occlusion_query_EXT",
3840 'BeginTransformFeedback': {
3841 'unsafe': True,
3843 'EndQueryEXT': {
3844 'type': 'Manual',
3845 'cmd_args': 'GLenumQueryTarget target, GLuint submit_count',
3846 'gl_test_func': 'glEndnQuery',
3847 'client_test': False,
3848 'pepper_interface': 'Query',
3849 'extension': "occlusion_query_EXT",
3851 'EndTransformFeedback': {
3852 'unsafe': True,
3854 'FlushDriverCachesCHROMIUM': {
3855 'decoder_func': 'DoFlushDriverCachesCHROMIUM',
3856 'unit_test': False,
3857 'extension': True,
3858 'chromium': True,
3859 'trace_level': 1,
3861 'GetQueryivEXT': {
3862 'gen_cmd': False,
3863 'client_test': False,
3864 'gl_test_func': 'glGetQueryiv',
3865 'pepper_interface': 'Query',
3866 'extension': "occlusion_query_EXT",
3868 'QueryCounterEXT' : {
3869 'type': 'Manual',
3870 'cmd_args': 'GLidQuery id, GLenumQueryTarget target, '
3871 'void* sync_data, GLuint submit_count',
3872 'data_transfer_methods': ['shm'],
3873 'gl_test_func': 'glQueryCounter',
3874 'extension': "disjoint_timer_query_EXT",
3876 'GetQueryObjectuivEXT': {
3877 'gen_cmd': False,
3878 'client_test': False,
3879 'gl_test_func': 'glGetQueryObjectuiv',
3880 'pepper_interface': 'Query',
3881 'extension': "occlusion_query_EXT",
3883 'GetQueryObjectui64vEXT': {
3884 'gen_cmd': False,
3885 'client_test': False,
3886 'gl_test_func': 'glGetQueryObjectui64v',
3887 'extension': "disjoint_timer_query_EXT",
3889 'BindUniformLocationCHROMIUM': {
3890 'type': 'GLchar',
3891 'extension': True,
3892 'data_transfer_methods': ['bucket'],
3893 'needs_size': True,
3894 'gl_test_func': 'DoBindUniformLocationCHROMIUM',
3896 'InsertEventMarkerEXT': {
3897 'type': 'GLcharN',
3898 'decoder_func': 'DoInsertEventMarkerEXT',
3899 'expectation': False,
3900 'extension': True,
3902 'PushGroupMarkerEXT': {
3903 'type': 'GLcharN',
3904 'decoder_func': 'DoPushGroupMarkerEXT',
3905 'expectation': False,
3906 'extension': True,
3908 'PopGroupMarkerEXT': {
3909 'decoder_func': 'DoPopGroupMarkerEXT',
3910 'expectation': False,
3911 'extension': True,
3912 'impl_func': False,
3915 'GenVertexArraysOES': {
3916 'type': 'GENn',
3917 'extension': True,
3918 'gl_test_func': 'glGenVertexArraysOES',
3919 'resource_type': 'VertexArray',
3920 'resource_types': 'VertexArrays',
3921 'unit_test': False,
3922 'pepper_interface': 'VertexArrayObject',
3924 'BindVertexArrayOES': {
3925 'type': 'Bind',
3926 'extension': True,
3927 'gl_test_func': 'glBindVertexArrayOES',
3928 'decoder_func': 'DoBindVertexArrayOES',
3929 'gen_func': 'GenVertexArraysOES',
3930 'unit_test': False,
3931 'client_test': False,
3932 'pepper_interface': 'VertexArrayObject',
3934 'DeleteVertexArraysOES': {
3935 'type': 'DELn',
3936 'extension': True,
3937 'gl_test_func': 'glDeleteVertexArraysOES',
3938 'resource_type': 'VertexArray',
3939 'resource_types': 'VertexArrays',
3940 'unit_test': False,
3941 'pepper_interface': 'VertexArrayObject',
3943 'IsVertexArrayOES': {
3944 'type': 'Is',
3945 'extension': True,
3946 'gl_test_func': 'glIsVertexArrayOES',
3947 'decoder_func': 'DoIsVertexArrayOES',
3948 'expectation': False,
3949 'unit_test': False,
3950 'pepper_interface': 'VertexArrayObject',
3952 'BindTexImage2DCHROMIUM': {
3953 'decoder_func': 'DoBindTexImage2DCHROMIUM',
3954 'unit_test': False,
3955 'extension': "CHROMIUM_image",
3956 'chromium': True,
3958 'ReleaseTexImage2DCHROMIUM': {
3959 'decoder_func': 'DoReleaseTexImage2DCHROMIUM',
3960 'unit_test': False,
3961 'extension': "CHROMIUM_image",
3962 'chromium': True,
3964 'ShallowFinishCHROMIUM': {
3965 'impl_func': False,
3966 'gen_cmd': False,
3967 'extension': True,
3968 'chromium': True,
3969 'client_test': False,
3971 'ShallowFlushCHROMIUM': {
3972 'impl_func': False,
3973 'gen_cmd': False,
3974 'extension': "CHROMIUM_miscellaneous",
3975 'chromium': True,
3976 'client_test': False,
3978 'OrderingBarrierCHROMIUM': {
3979 'impl_func': False,
3980 'gen_cmd': False,
3981 'extension': True,
3982 'chromium': True,
3983 'client_test': False,
3985 'TraceBeginCHROMIUM': {
3986 'type': 'Custom',
3987 'impl_func': False,
3988 'client_test': False,
3989 'cmd_args': 'GLuint category_bucket_id, GLuint name_bucket_id',
3990 'extension': True,
3991 'chromium': True,
3993 'TraceEndCHROMIUM': {
3994 'impl_func': False,
3995 'client_test': False,
3996 'decoder_func': 'DoTraceEndCHROMIUM',
3997 'unit_test': False,
3998 'extension': True,
3999 'chromium': True,
4001 'AsyncTexImage2DCHROMIUM': {
4002 'type': 'Manual',
4003 'data_transfer_methods': ['shm'],
4004 'client_test': False,
4005 'cmd_args': 'GLenumTextureTarget target, GLint level, '
4006 'GLintTextureInternalFormat internalformat, '
4007 'GLsizei width, GLsizei height, '
4008 'GLintTextureBorder border, '
4009 'GLenumTextureFormat format, GLenumPixelType type, '
4010 'const void* pixels, '
4011 'uint32_t async_upload_token, '
4012 'void* sync_data',
4013 'extension': True,
4014 'chromium': True,
4015 'trace_level': 2,
4017 'AsyncTexSubImage2DCHROMIUM': {
4018 'type': 'Manual',
4019 'data_transfer_methods': ['shm'],
4020 'client_test': False,
4021 'cmd_args': 'GLenumTextureTarget target, GLint level, '
4022 'GLint xoffset, GLint yoffset, '
4023 'GLsizei width, GLsizei height, '
4024 'GLenumTextureFormat format, GLenumPixelType type, '
4025 'const void* data, '
4026 'uint32_t async_upload_token, '
4027 'void* sync_data',
4028 'extension': True,
4029 'chromium': True,
4030 'trace_level': 2,
4032 'WaitAsyncTexImage2DCHROMIUM': {
4033 'type': 'Manual',
4034 'client_test': False,
4035 'extension': True,
4036 'chromium': True,
4037 'trace_level': 1,
4039 'WaitAllAsyncTexImage2DCHROMIUM': {
4040 'type': 'Manual',
4041 'client_test': False,
4042 'extension': True,
4043 'chromium': True,
4044 'trace_level': 1,
4046 'DiscardFramebufferEXT': {
4047 'type': 'PUTn',
4048 'count': 1,
4049 'decoder_func': 'DoDiscardFramebufferEXT',
4050 'unit_test': False,
4051 'client_test': False,
4052 'extension_flag': 'ext_discard_framebuffer',
4053 'trace_level': 2,
4055 'LoseContextCHROMIUM': {
4056 'decoder_func': 'DoLoseContextCHROMIUM',
4057 'unit_test': False,
4058 'extension': True,
4059 'chromium': True,
4060 'trace_level': 1,
4062 'InsertSyncPointCHROMIUM': {
4063 'type': 'HandWritten',
4064 'impl_func': False,
4065 'extension': "CHROMIUM_sync_point",
4066 'chromium': True,
4067 'trace_level': 1,
4069 'WaitSyncPointCHROMIUM': {
4070 'type': 'Custom',
4071 'impl_func': True,
4072 'extension': "CHROMIUM_sync_point",
4073 'chromium': True,
4074 'trace_level': 1,
4076 'DiscardBackbufferCHROMIUM': {
4077 'type': 'Custom',
4078 'impl_func': True,
4079 'extension': True,
4080 'chromium': True,
4081 'trace_level': 2,
4083 'ScheduleOverlayPlaneCHROMIUM': {
4084 'type': 'Custom',
4085 'impl_func': True,
4086 'unit_test': False,
4087 'client_test': False,
4088 'extension': True,
4089 'chromium': True,
4091 'MatrixLoadfCHROMIUM': {
4092 'type': 'PUT',
4093 'count': 16,
4094 'data_type': 'GLfloat',
4095 'decoder_func': 'DoMatrixLoadfCHROMIUM',
4096 'gl_test_func': 'glMatrixLoadfEXT',
4097 'chromium': True,
4098 'extension': True,
4099 'extension_flag': 'chromium_path_rendering',
4101 'MatrixLoadIdentityCHROMIUM': {
4102 'decoder_func': 'DoMatrixLoadIdentityCHROMIUM',
4103 'gl_test_func': 'glMatrixLoadIdentityEXT',
4104 'chromium': True,
4105 'extension': True,
4106 'extension_flag': 'chromium_path_rendering',
4108 'GenPathsCHROMIUM': {
4109 'type': 'Custom',
4110 'cmd_args': 'GLuint first_client_id, GLsizei range',
4111 'chromium': True,
4112 'extension': True,
4113 'extension_flag': 'chromium_path_rendering',
4115 'DeletePathsCHROMIUM': {
4116 'type': 'Custom',
4117 'cmd_args': 'GLuint first_client_id, GLsizei range',
4118 'impl_func': False,
4119 'unit_test': False,
4120 'chromium': True,
4121 'extension': True,
4122 'extension_flag': 'chromium_path_rendering',
4124 'IsPathCHROMIUM': {
4125 'type': 'Is',
4126 'decoder_func': 'DoIsPathCHROMIUM',
4127 'gl_test_func': 'glIsPathNV',
4128 'chromium': True,
4129 'extension': True,
4130 'extension_flag': 'chromium_path_rendering',
4132 'PathCommandsCHROMIUM': {
4133 'type': 'Manual',
4134 'immediate': False,
4135 'chromium': True,
4136 'extension': True,
4137 'extension_flag': 'chromium_path_rendering',
4139 'PathParameterfCHROMIUM': {
4140 'type': 'Custom',
4141 'chromium': True,
4142 'extension': True,
4143 'extension_flag': 'chromium_path_rendering',
4145 'PathParameteriCHROMIUM': {
4146 'type': 'Custom',
4147 'chromium': True,
4148 'extension': True,
4149 'extension_flag': 'chromium_path_rendering',
4151 'PathStencilFuncCHROMIUM': {
4152 'type': 'StateSet',
4153 'state': 'PathStencilFuncCHROMIUM',
4154 'decoder_func': 'glPathStencilFuncNV',
4155 'chromium': True,
4156 'extension': True,
4157 'extension_flag': 'chromium_path_rendering',
4159 'StencilFillPathCHROMIUM': {
4160 'type': 'Custom',
4161 'chromium': True,
4162 'extension': True,
4163 'extension_flag': 'chromium_path_rendering',
4165 'StencilStrokePathCHROMIUM': {
4166 'type': 'Custom',
4167 'chromium': True,
4168 'extension': True,
4169 'extension_flag': 'chromium_path_rendering',
4171 'CoverFillPathCHROMIUM': {
4172 'type': 'Custom',
4173 'chromium': True,
4174 'extension': True,
4175 'extension_flag': 'chromium_path_rendering',
4177 'CoverStrokePathCHROMIUM': {
4178 'type': 'Custom',
4179 'chromium': True,
4180 'extension': True,
4181 'extension_flag': 'chromium_path_rendering',
4183 'StencilThenCoverFillPathCHROMIUM': {
4184 'type': 'Custom',
4185 'chromium': True,
4186 'extension': True,
4187 'extension_flag': 'chromium_path_rendering',
4189 'StencilThenCoverStrokePathCHROMIUM': {
4190 'type': 'Custom',
4191 'chromium': True,
4192 'extension': True,
4193 'extension_flag': 'chromium_path_rendering',
4199 def Grouper(n, iterable, fillvalue=None):
4200 """Collect data into fixed-length chunks or blocks"""
4201 args = [iter(iterable)] * n
4202 return itertools.izip_longest(fillvalue=fillvalue, *args)
4205 def SplitWords(input_string):
4206 """Split by '_' if found, otherwise split at uppercase/numeric chars.
4208 Will split "some_TEXT" into ["some", "TEXT"], "CamelCase" into ["Camel",
4209 "Case"], and "Vector3" into ["Vector", "3"].
4211 if input_string.find('_') > -1:
4212 # 'some_TEXT_' -> 'some TEXT'
4213 return input_string.replace('_', ' ').strip().split()
4214 else:
4215 if re.search('[A-Z]', input_string) and re.search('[a-z]', input_string):
4216 # mixed case.
4217 # look for capitalization to cut input_strings
4218 # 'SomeText' -> 'Some Text'
4219 input_string = re.sub('([A-Z])', r' \1', input_string).strip()
4220 # 'Vector3' -> 'Vector 3'
4221 input_string = re.sub('([^0-9])([0-9])', r'\1 \2', input_string)
4222 return input_string.split()
4224 def ToUnderscore(input_string):
4225 """converts CamelCase to camel_case."""
4226 words = SplitWords(input_string)
4227 return '_'.join([word.lower() for word in words])
4229 def CachedStateName(item):
4230 if item.get('cached', False):
4231 return 'cached_' + item['name']
4232 return item['name']
4234 def ToGLExtensionString(extension_flag):
4235 """Returns GL-type extension string of a extension flag."""
4236 if extension_flag == "oes_compressed_etc1_rgb8_texture":
4237 return "OES_compressed_ETC1_RGB8_texture" # Fixup inconsitency with rgb8,
4238 # unfortunate.
4239 uppercase_words = [ 'img', 'ext', 'arb', 'chromium', 'oes', 'amd', 'bgra8888',
4240 'egl', 'atc', 'etc1', 'angle']
4241 parts = extension_flag.split('_')
4242 return "_".join(
4243 [part.upper() if part in uppercase_words else part for part in parts])
4245 def ToCamelCase(input_string):
4246 """converts ABC_underscore_case to ABCUnderscoreCase."""
4247 return ''.join(w[0].upper() + w[1:] for w in input_string.split('_'))
4249 def GetGLGetTypeConversion(result_type, value_type, value):
4250 """Makes a gl compatible type conversion string for accessing state variables.
4252 Useful when accessing state variables through glGetXXX calls.
4253 glGet documetation (for example, the manual pages):
4254 [...] If glGetIntegerv is called, [...] most floating-point values are
4255 rounded to the nearest integer value. [...]
4257 Args:
4258 result_type: the gl type to be obtained
4259 value_type: the GL type of the state variable
4260 value: the name of the state variable
4262 Returns:
4263 String that converts the state variable to desired GL type according to GL
4264 rules.
4267 if result_type == 'GLint':
4268 if value_type == 'GLfloat':
4269 return 'static_cast<GLint>(round(%s))' % value
4270 return 'static_cast<%s>(%s)' % (result_type, value)
4273 class CWriter(object):
4274 """Context manager that creates a C source file.
4276 To be used with the `with` statement. Returns a normal `file` type, open only
4277 for writing - any existing files with that name will be overwritten. It will
4278 automatically write the contents of `_LICENSE` and `_DO_NOT_EDIT_WARNING`
4279 at the beginning.
4281 Example:
4282 with CWriter("file.cpp") as myfile:
4283 myfile.write("hello")
4284 # type(myfile) == file
4286 def __init__(self, filename):
4287 self.filename = filename
4288 self._file = open(filename, 'w')
4289 self._ENTER_MSG = _LICENSE + _DO_NOT_EDIT_WARNING
4290 self._EXIT_MSG = ""
4292 def __enter__(self):
4293 self._file.write(self._ENTER_MSG)
4294 return self._file
4296 def __exit__(self, exc_type, exc_value, traceback):
4297 self._file.write(self._EXIT_MSG)
4298 self._file.close()
4301 class CHeaderWriter(CWriter):
4302 """Context manager that creates a C header file.
4304 Works the same way as CWriter, except it will also add the #ifdef guard
4305 around it. If `file_comment` is set, it will write that before the #ifdef
4306 guard.
4308 def __init__(self, filename, file_comment=None):
4309 super(CHeaderWriter, self).__init__(filename)
4310 guard = self._get_guard()
4311 if file_comment is None:
4312 file_comment = ""
4313 self._ENTER_MSG = self._ENTER_MSG + file_comment \
4314 + "#ifndef %s\n#define %s\n\n" % (guard, guard)
4315 self._EXIT_MSG = self._EXIT_MSG + "#endif // %s\n" % guard
4317 def _get_guard(self):
4318 non_alnum_re = re.compile(r'[^a-zA-Z0-9]')
4319 base = os.path.abspath(self.filename)
4320 while os.path.basename(base) != 'src':
4321 new_base = os.path.dirname(base)
4322 assert new_base != base # Prevent infinite loop.
4323 base = new_base
4324 hpath = os.path.relpath(self.filename, base)
4325 return non_alnum_re.sub('_', hpath).upper() + '_'
4328 class TypeHandler(object):
4329 """This class emits code for a particular type of function."""
4331 _remove_expected_call_re = re.compile(r' EXPECT_CALL.*?;\n', re.S)
4333 def InitFunction(self, func):
4334 """Add or adjust anything type specific for this function."""
4335 if func.GetInfo('needs_size') and not func.name.endswith('Bucket'):
4336 func.AddCmdArg(DataSizeArgument('data_size'))
4338 def NeedsDataTransferFunction(self, func):
4339 """Overriden from TypeHandler."""
4340 return func.num_pointer_args >= 1
4342 def WriteStruct(self, func, f):
4343 """Writes a structure that matches the arguments to a function."""
4344 comment = func.GetInfo('cmd_comment')
4345 if not comment == None:
4346 f.write(comment)
4347 f.write("struct %s {\n" % func.name)
4348 f.write(" typedef %s ValueType;\n" % func.name)
4349 f.write(" static const CommandId kCmdId = k%s;\n" % func.name)
4350 func.WriteCmdArgFlag(f)
4351 func.WriteCmdFlag(f)
4352 f.write("\n")
4353 result = func.GetInfo('result')
4354 if not result == None:
4355 if len(result) == 1:
4356 f.write(" typedef %s Result;\n\n" % result[0])
4357 else:
4358 f.write(" struct Result {\n")
4359 for line in result:
4360 f.write(" %s;\n" % line)
4361 f.write(" };\n\n")
4363 func.WriteCmdComputeSize(f)
4364 func.WriteCmdSetHeader(f)
4365 func.WriteCmdInit(f)
4366 func.WriteCmdSet(f)
4368 f.write(" gpu::CommandHeader header;\n")
4369 args = func.GetCmdArgs()
4370 for arg in args:
4371 f.write(" %s %s;\n" % (arg.cmd_type, arg.name))
4373 consts = func.GetCmdConstants()
4374 for const in consts:
4375 f.write(" static const %s %s = %s;\n" %
4376 (const.cmd_type, const.name, const.GetConstantValue()))
4378 f.write("};\n")
4379 f.write("\n")
4381 size = len(args) * _SIZE_OF_UINT32 + _SIZE_OF_COMMAND_HEADER
4382 f.write("static_assert(sizeof(%s) == %d,\n" % (func.name, size))
4383 f.write(" \"size of %s should be %d\");\n" %
4384 (func.name, size))
4385 f.write("static_assert(offsetof(%s, header) == 0,\n" % func.name)
4386 f.write(" \"offset of %s header should be 0\");\n" %
4387 func.name)
4388 offset = _SIZE_OF_COMMAND_HEADER
4389 for arg in args:
4390 f.write("static_assert(offsetof(%s, %s) == %d,\n" %
4391 (func.name, arg.name, offset))
4392 f.write(" \"offset of %s %s should be %d\");\n" %
4393 (func.name, arg.name, offset))
4394 offset += _SIZE_OF_UINT32
4395 if not result == None and len(result) > 1:
4396 offset = 0;
4397 for line in result:
4398 parts = line.split()
4399 name = parts[-1]
4400 check = """
4401 static_assert(offsetof(%(cmd_name)s::Result, %(field_name)s) == %(offset)d,
4402 "offset of %(cmd_name)s Result %(field_name)s should be "
4403 "%(offset)d");
4405 f.write((check.strip() + "\n") % {
4406 'cmd_name': func.name,
4407 'field_name': name,
4408 'offset': offset,
4410 offset += _SIZE_OF_UINT32
4411 f.write("\n")
4413 def WriteHandlerImplementation(self, func, f):
4414 """Writes the handler implementation for this command."""
4415 if func.IsUnsafe() and func.GetInfo('id_mapping'):
4416 code_no_gen = """ if (!group_->Get%(type)sServiceId(
4417 %(var)s, &%(service_var)s)) {
4418 LOCAL_SET_GL_ERROR(GL_INVALID_OPERATION, "%(func)s", "invalid %(var)s id");
4419 return error::kNoError;
4422 code_gen = """ if (!group_->Get%(type)sServiceId(
4423 %(var)s, &%(service_var)s)) {
4424 if (!group_->bind_generates_resource()) {
4425 LOCAL_SET_GL_ERROR(
4426 GL_INVALID_OPERATION, "%(func)s", "invalid %(var)s id");
4427 return error::kNoError;
4429 GLuint client_id = %(var)s;
4430 gl%(gen_func)s(1, &%(service_var)s);
4431 Create%(type)s(client_id, %(service_var)s);
4434 gen_func = func.GetInfo('gen_func')
4435 for id_type in func.GetInfo('id_mapping'):
4436 service_var = id_type.lower()
4437 if id_type == 'Sync':
4438 service_var = "service_%s" % service_var
4439 f.write(" GLsync %s = 0;\n" % service_var)
4440 if gen_func and id_type in gen_func:
4441 f.write(code_gen % { 'type': id_type,
4442 'var': id_type.lower(),
4443 'service_var': service_var,
4444 'func': func.GetGLFunctionName(),
4445 'gen_func': gen_func })
4446 else:
4447 f.write(code_no_gen % { 'type': id_type,
4448 'var': id_type.lower(),
4449 'service_var': service_var,
4450 'func': func.GetGLFunctionName() })
4451 args = []
4452 for arg in func.GetOriginalArgs():
4453 if arg.type == "GLsync":
4454 args.append("service_%s" % arg.name)
4455 elif arg.name.endswith("size") and arg.type == "GLsizei":
4456 args.append("num_%s" % func.GetLastOriginalArg().name)
4457 elif arg.name == "length":
4458 args.append("nullptr")
4459 else:
4460 args.append(arg.name)
4461 f.write(" %s(%s);\n" %
4462 (func.GetGLFunctionName(), ", ".join(args)))
4464 def WriteCmdSizeTest(self, func, f):
4465 """Writes the size test for a command."""
4466 f.write(" EXPECT_EQ(sizeof(cmd), cmd.header.size * 4u);\n")
4468 def WriteFormatTest(self, func, f):
4469 """Writes a format test for a command."""
4470 f.write("TEST_F(GLES2FormatTest, %s) {\n" % func.name)
4471 f.write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
4472 (func.name, func.name))
4473 f.write(" void* next_cmd = cmd.Set(\n")
4474 f.write(" &cmd")
4475 args = func.GetCmdArgs()
4476 for value, arg in enumerate(args):
4477 f.write(",\n static_cast<%s>(%d)" % (arg.type, value + 11))
4478 f.write(");\n")
4479 f.write(" EXPECT_EQ(static_cast<uint32_t>(cmds::%s::kCmdId),\n" %
4480 func.name)
4481 f.write(" cmd.header.command);\n")
4482 func.type_handler.WriteCmdSizeTest(func, f)
4483 for value, arg in enumerate(args):
4484 f.write(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);\n" %
4485 (arg.type, value + 11, arg.name))
4486 f.write(" CheckBytesWrittenMatchesExpectedSize(\n")
4487 f.write(" next_cmd, sizeof(cmd));\n")
4488 f.write("}\n")
4489 f.write("\n")
4491 def WriteImmediateFormatTest(self, func, f):
4492 """Writes a format test for an immediate version of a command."""
4493 pass
4495 def WriteGetDataSizeCode(self, func, f):
4496 """Writes the code to set data_size used in validation"""
4497 pass
4499 def __WriteIdMapping(self, func, f):
4500 """Writes client side / service side ID mapping."""
4501 if not func.IsUnsafe() or not func.GetInfo('id_mapping'):
4502 return
4503 for id_type in func.GetInfo('id_mapping'):
4504 f.write(" group_->Get%sServiceId(%s, &%s);\n" %
4505 (id_type, id_type.lower(), id_type.lower()))
4507 def WriteImmediateHandlerImplementation (self, func, f):
4508 """Writes the handler impl for the immediate version of a command."""
4509 self.__WriteIdMapping(func, f)
4510 f.write(" %s(%s);\n" %
4511 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
4513 def WriteBucketHandlerImplementation (self, func, f):
4514 """Writes the handler impl for the bucket version of a command."""
4515 self.__WriteIdMapping(func, f)
4516 f.write(" %s(%s);\n" %
4517 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
4519 def WriteServiceHandlerFunctionHeader(self, func, f):
4520 """Writes function header for service implementation handlers."""
4521 f.write("""error::Error GLES2DecoderImpl::Handle%(name)s(
4522 uint32_t immediate_data_size, const void* cmd_data) {
4523 """ % {'name': func.name})
4524 if func.IsUnsafe():
4525 f.write("""if (!unsafe_es3_apis_enabled())
4526 return error::kUnknownCommand;
4527 """)
4528 f.write("""const gles2::cmds::%(name)s& c =
4529 *static_cast<const gles2::cmds::%(name)s*>(cmd_data);
4530 (void)c;
4531 """ % {'name': func.name})
4533 def WriteServiceImplementation(self, func, f):
4534 """Writes the service implementation for a command."""
4535 self.WriteServiceHandlerFunctionHeader(func, f)
4536 self.WriteHandlerExtensionCheck(func, f)
4537 self.WriteHandlerDeferReadWrite(func, f);
4538 if len(func.GetOriginalArgs()) > 0:
4539 last_arg = func.GetLastOriginalArg()
4540 all_but_last_arg = func.GetOriginalArgs()[:-1]
4541 for arg in all_but_last_arg:
4542 arg.WriteGetCode(f)
4543 self.WriteGetDataSizeCode(func, f)
4544 last_arg.WriteGetCode(f)
4545 func.WriteHandlerValidation(f)
4546 func.WriteHandlerImplementation(f)
4547 f.write(" return error::kNoError;\n")
4548 f.write("}\n")
4549 f.write("\n")
4551 def WriteImmediateServiceImplementation(self, func, f):
4552 """Writes the service implementation for an immediate version of command."""
4553 self.WriteServiceHandlerFunctionHeader(func, f)
4554 self.WriteHandlerExtensionCheck(func, f)
4555 self.WriteHandlerDeferReadWrite(func, f);
4556 for arg in func.GetOriginalArgs():
4557 if arg.IsPointer():
4558 self.WriteGetDataSizeCode(func, f)
4559 arg.WriteGetCode(f)
4560 func.WriteHandlerValidation(f)
4561 func.WriteHandlerImplementation(f)
4562 f.write(" return error::kNoError;\n")
4563 f.write("}\n")
4564 f.write("\n")
4566 def WriteBucketServiceImplementation(self, func, f):
4567 """Writes the service implementation for a bucket version of command."""
4568 self.WriteServiceHandlerFunctionHeader(func, f)
4569 self.WriteHandlerExtensionCheck(func, f)
4570 self.WriteHandlerDeferReadWrite(func, f);
4571 for arg in func.GetCmdArgs():
4572 arg.WriteGetCode(f)
4573 func.WriteHandlerValidation(f)
4574 func.WriteHandlerImplementation(f)
4575 f.write(" return error::kNoError;\n")
4576 f.write("}\n")
4577 f.write("\n")
4579 def WriteHandlerExtensionCheck(self, func, f):
4580 if func.GetInfo('extension_flag'):
4581 f.write(" if (!features().%s) {\n" % func.GetInfo('extension_flag'))
4582 f.write(" LOCAL_SET_GL_ERROR(GL_INVALID_OPERATION, \"gl%s\","
4583 " \"function not available\");\n" % func.original_name)
4584 f.write(" return error::kNoError;")
4585 f.write(" }\n\n")
4587 def WriteHandlerDeferReadWrite(self, func, f):
4588 """Writes the code to handle deferring reads or writes."""
4589 defer_draws = func.GetInfo('defer_draws')
4590 defer_reads = func.GetInfo('defer_reads')
4591 if defer_draws or defer_reads:
4592 f.write(" error::Error error;\n")
4593 if defer_draws:
4594 f.write(" error = WillAccessBoundFramebufferForDraw();\n")
4595 f.write(" if (error != error::kNoError)\n")
4596 f.write(" return error;\n")
4597 if defer_reads:
4598 f.write(" error = WillAccessBoundFramebufferForRead();\n")
4599 f.write(" if (error != error::kNoError)\n")
4600 f.write(" return error;\n")
4602 def WriteValidUnitTest(self, func, f, test, *extras):
4603 """Writes a valid unit test for the service implementation."""
4604 if func.GetInfo('expectation') == False:
4605 test = self._remove_expected_call_re.sub('', test)
4606 name = func.name
4607 arg_strings = [
4608 arg.GetValidArg(func) \
4609 for arg in func.GetOriginalArgs() if not arg.IsConstant()
4611 gl_arg_strings = [
4612 arg.GetValidGLArg(func) \
4613 for arg in func.GetOriginalArgs()
4615 gl_func_name = func.GetGLTestFunctionName()
4616 vars = {
4617 'name':name,
4618 'gl_func_name': gl_func_name,
4619 'args': ", ".join(arg_strings),
4620 'gl_args': ", ".join(gl_arg_strings),
4622 for extra in extras:
4623 vars.update(extra)
4624 old_test = ""
4625 while (old_test != test):
4626 old_test = test
4627 test = test % vars
4628 f.write(test % vars)
4630 def WriteInvalidUnitTest(self, func, f, test, *extras):
4631 """Writes an invalid unit test for the service implementation."""
4632 if func.IsUnsafe():
4633 return
4634 for invalid_arg_index, invalid_arg in enumerate(func.GetOriginalArgs()):
4635 # Service implementation does not test constants, as they are not part of
4636 # the call in the service side.
4637 if invalid_arg.IsConstant():
4638 continue
4640 num_invalid_values = invalid_arg.GetNumInvalidValues(func)
4641 for value_index in range(0, num_invalid_values):
4642 arg_strings = []
4643 parse_result = "kNoError"
4644 gl_error = None
4645 for arg in func.GetOriginalArgs():
4646 if arg.IsConstant():
4647 continue
4648 if invalid_arg is arg:
4649 (arg_string, parse_result, gl_error) = arg.GetInvalidArg(
4650 value_index)
4651 else:
4652 arg_string = arg.GetValidArg(func)
4653 arg_strings.append(arg_string)
4654 gl_arg_strings = []
4655 for arg in func.GetOriginalArgs():
4656 gl_arg_strings.append("_")
4657 gl_func_name = func.GetGLTestFunctionName()
4658 gl_error_test = ''
4659 if not gl_error == None:
4660 gl_error_test = '\n EXPECT_EQ(%s, GetGLError());' % gl_error
4662 vars = {
4663 'name': func.name,
4664 'arg_index': invalid_arg_index,
4665 'value_index': value_index,
4666 'gl_func_name': gl_func_name,
4667 'args': ", ".join(arg_strings),
4668 'all_but_last_args': ", ".join(arg_strings[:-1]),
4669 'gl_args': ", ".join(gl_arg_strings),
4670 'parse_result': parse_result,
4671 'gl_error_test': gl_error_test,
4673 for extra in extras:
4674 vars.update(extra)
4675 f.write(test % vars)
4677 def WriteServiceUnitTest(self, func, f, *extras):
4678 """Writes the service unit test for a command."""
4680 if func.name == 'Enable':
4681 valid_test = """
4682 TEST_P(%(test_name)s, %(name)sValidArgs) {
4683 SetupExpectationsForEnableDisable(%(gl_args)s, true);
4684 SpecializedSetup<cmds::%(name)s, 0>(true);
4685 cmds::%(name)s cmd;
4686 cmd.Init(%(args)s);"""
4687 elif func.name == 'Disable':
4688 valid_test = """
4689 TEST_P(%(test_name)s, %(name)sValidArgs) {
4690 SetupExpectationsForEnableDisable(%(gl_args)s, false);
4691 SpecializedSetup<cmds::%(name)s, 0>(true);
4692 cmds::%(name)s cmd;
4693 cmd.Init(%(args)s);"""
4694 else:
4695 valid_test = """
4696 TEST_P(%(test_name)s, %(name)sValidArgs) {
4697 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
4698 SpecializedSetup<cmds::%(name)s, 0>(true);
4699 cmds::%(name)s cmd;
4700 cmd.Init(%(args)s);"""
4701 if func.IsUnsafe():
4702 valid_test += """
4703 decoder_->set_unsafe_es3_apis_enabled(true);
4704 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4705 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4706 decoder_->set_unsafe_es3_apis_enabled(false);
4707 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));
4710 else:
4711 valid_test += """
4712 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4713 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4716 self.WriteValidUnitTest(func, f, valid_test, *extras)
4718 if not func.IsUnsafe():
4719 invalid_test = """
4720 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
4721 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
4722 SpecializedSetup<cmds::%(name)s, 0>(false);
4723 cmds::%(name)s cmd;
4724 cmd.Init(%(args)s);
4725 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
4728 self.WriteInvalidUnitTest(func, f, invalid_test, *extras)
4730 def WriteImmediateServiceUnitTest(self, func, f, *extras):
4731 """Writes the service unit test for an immediate command."""
4732 f.write("// TODO(gman): %s\n" % func.name)
4734 def WriteImmediateValidationCode(self, func, f):
4735 """Writes the validation code for an immediate version of a command."""
4736 pass
4738 def WriteBucketServiceUnitTest(self, func, f, *extras):
4739 """Writes the service unit test for a bucket command."""
4740 f.write("// TODO(gman): %s\n" % func.name)
4742 def WriteGLES2ImplementationDeclaration(self, func, f):
4743 """Writes the GLES2 Implemention declaration."""
4744 impl_decl = func.GetInfo('impl_decl')
4745 if impl_decl == None or impl_decl == True:
4746 f.write("%s %s(%s) override;\n" %
4747 (func.return_type, func.original_name,
4748 func.MakeTypedOriginalArgString("")))
4749 f.write("\n")
4751 def WriteGLES2CLibImplementation(self, func, f):
4752 f.write("%s GL_APIENTRY GLES2%s(%s) {\n" %
4753 (func.return_type, func.name,
4754 func.MakeTypedOriginalArgString("")))
4755 result_string = "return "
4756 if func.return_type == "void":
4757 result_string = ""
4758 f.write(" %sgles2::GetGLContext()->%s(%s);\n" %
4759 (result_string, func.original_name,
4760 func.MakeOriginalArgString("")))
4761 f.write("}\n")
4763 def WriteGLES2Header(self, func, f):
4764 """Writes a re-write macro for GLES"""
4765 f.write("#define gl%s GLES2_GET_FUN(%s)\n" %(func.name, func.name))
4767 def WriteClientGLCallLog(self, func, f):
4768 """Writes a logging macro for the client side code."""
4769 comma = ""
4770 if len(func.GetOriginalArgs()):
4771 comma = " << "
4772 f.write(
4773 ' GPU_CLIENT_LOG("[" << GetLogPrefix() << "] gl%s("%s%s << ")");\n' %
4774 (func.original_name, comma, func.MakeLogArgString()))
4776 def WriteClientGLReturnLog(self, func, f):
4777 """Writes the return value logging code."""
4778 if func.return_type != "void":
4779 f.write(' GPU_CLIENT_LOG("return:" << result)\n')
4781 def WriteGLES2ImplementationHeader(self, func, f):
4782 """Writes the GLES2 Implemention."""
4783 self.WriteGLES2ImplementationDeclaration(func, f)
4785 def WriteGLES2TraceImplementationHeader(self, func, f):
4786 """Writes the GLES2 Trace Implemention header."""
4787 f.write("%s %s(%s) override;\n" %
4788 (func.return_type, func.original_name,
4789 func.MakeTypedOriginalArgString("")))
4791 def WriteGLES2TraceImplementation(self, func, f):
4792 """Writes the GLES2 Trace Implemention."""
4793 f.write("%s GLES2TraceImplementation::%s(%s) {\n" %
4794 (func.return_type, func.original_name,
4795 func.MakeTypedOriginalArgString("")))
4796 result_string = "return "
4797 if func.return_type == "void":
4798 result_string = ""
4799 f.write(' TRACE_EVENT_BINARY_EFFICIENT0("gpu", "GLES2Trace::%s");\n' %
4800 func.name)
4801 f.write(" %sgl_->%s(%s);\n" %
4802 (result_string, func.name, func.MakeOriginalArgString("")))
4803 f.write("}\n")
4804 f.write("\n")
4806 def WriteGLES2Implementation(self, func, f):
4807 """Writes the GLES2 Implemention."""
4808 impl_func = func.GetInfo('impl_func')
4809 impl_decl = func.GetInfo('impl_decl')
4810 gen_cmd = func.GetInfo('gen_cmd')
4811 if (func.can_auto_generate and
4812 (impl_func == None or impl_func == True) and
4813 (impl_decl == None or impl_decl == True) and
4814 (gen_cmd == None or gen_cmd == True)):
4815 f.write("%s GLES2Implementation::%s(%s) {\n" %
4816 (func.return_type, func.original_name,
4817 func.MakeTypedOriginalArgString("")))
4818 f.write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
4819 self.WriteClientGLCallLog(func, f)
4820 func.WriteDestinationInitalizationValidation(f)
4821 for arg in func.GetOriginalArgs():
4822 arg.WriteClientSideValidationCode(f, func)
4823 f.write(" helper_->%s(%s);\n" %
4824 (func.name, func.MakeHelperArgString("")))
4825 f.write(" CheckGLError();\n")
4826 self.WriteClientGLReturnLog(func, f)
4827 f.write("}\n")
4828 f.write("\n")
4830 def WriteGLES2InterfaceHeader(self, func, f):
4831 """Writes the GLES2 Interface."""
4832 f.write("virtual %s %s(%s) = 0;\n" %
4833 (func.return_type, func.original_name,
4834 func.MakeTypedOriginalArgString("")))
4836 def WriteMojoGLES2ImplHeader(self, func, f):
4837 """Writes the Mojo GLES2 implementation header."""
4838 f.write("%s %s(%s) override;\n" %
4839 (func.return_type, func.original_name,
4840 func.MakeTypedOriginalArgString("")))
4842 def WriteMojoGLES2Impl(self, func, f):
4843 """Writes the Mojo GLES2 implementation."""
4844 f.write("%s MojoGLES2Impl::%s(%s) {\n" %
4845 (func.return_type, func.original_name,
4846 func.MakeTypedOriginalArgString("")))
4847 extensions = ["CHROMIUM_sync_point", "CHROMIUM_texture_mailbox",
4848 "CHROMIUM_sub_image", "CHROMIUM_miscellaneous",
4849 "occlusion_query_EXT", "CHROMIUM_image",
4850 "CHROMIUM_copy_texture",
4851 "CHROMIUM_pixel_transfer_buffer_object"]
4852 if func.IsCoreGLFunction() or func.GetInfo("extension") in extensions:
4853 f.write("MojoGLES2MakeCurrent(context_);");
4854 func_return = "gl" + func.original_name + "(" + \
4855 func.MakeOriginalArgString("") + ");"
4856 if func.return_type == "void":
4857 f.write(func_return);
4858 else:
4859 f.write("return " + func_return);
4860 else:
4861 f.write("NOTREACHED() << \"Unimplemented %s.\";\n" %
4862 func.original_name);
4863 if func.return_type != "void":
4864 f.write("return 0;")
4865 f.write("}")
4867 def WriteGLES2InterfaceStub(self, func, f):
4868 """Writes the GLES2 Interface stub declaration."""
4869 f.write("%s %s(%s) override;\n" %
4870 (func.return_type, func.original_name,
4871 func.MakeTypedOriginalArgString("")))
4873 def WriteGLES2InterfaceStubImpl(self, func, f):
4874 """Writes the GLES2 Interface stub declaration."""
4875 args = func.GetOriginalArgs()
4876 arg_string = ", ".join(
4877 ["%s /* %s */" % (arg.type, arg.name) for arg in args])
4878 f.write("%s GLES2InterfaceStub::%s(%s) {\n" %
4879 (func.return_type, func.original_name, arg_string))
4880 if func.return_type != "void":
4881 f.write(" return 0;\n")
4882 f.write("}\n")
4884 def WriteGLES2ImplementationUnitTest(self, func, f):
4885 """Writes the GLES2 Implemention unit test."""
4886 client_test = func.GetInfo('client_test')
4887 if (func.can_auto_generate and
4888 (client_test == None or client_test == True)):
4889 code = """
4890 TEST_F(GLES2ImplementationTest, %(name)s) {
4891 struct Cmds {
4892 cmds::%(name)s cmd;
4894 Cmds expected;
4895 expected.cmd.Init(%(cmd_args)s);
4897 gl_->%(name)s(%(args)s);
4898 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
4901 cmd_arg_strings = [
4902 arg.GetValidClientSideCmdArg(func) for arg in func.GetCmdArgs()
4905 gl_arg_strings = [
4906 arg.GetValidClientSideArg(func) for arg in func.GetOriginalArgs()
4909 f.write(code % {
4910 'name': func.name,
4911 'args': ", ".join(gl_arg_strings),
4912 'cmd_args': ", ".join(cmd_arg_strings),
4915 # Test constants for invalid values, as they are not tested by the
4916 # service.
4917 constants = [arg for arg in func.GetOriginalArgs() if arg.IsConstant()]
4918 if constants:
4919 code = """
4920 TEST_F(GLES2ImplementationTest, %(name)sInvalidConstantArg%(invalid_index)d) {
4921 gl_->%(name)s(%(args)s);
4922 EXPECT_TRUE(NoCommandsWritten());
4923 EXPECT_EQ(%(gl_error)s, CheckError());
4926 for invalid_arg in constants:
4927 gl_arg_strings = []
4928 invalid = invalid_arg.GetInvalidArg(func)
4929 for arg in func.GetOriginalArgs():
4930 if arg is invalid_arg:
4931 gl_arg_strings.append(invalid[0])
4932 else:
4933 gl_arg_strings.append(arg.GetValidClientSideArg(func))
4935 f.write(code % {
4936 'name': func.name,
4937 'invalid_index': func.GetOriginalArgs().index(invalid_arg),
4938 'args': ", ".join(gl_arg_strings),
4939 'gl_error': invalid[2],
4941 else:
4942 if client_test != False:
4943 f.write("// TODO(zmo): Implement unit test for %s\n" % func.name)
4945 def WriteDestinationInitalizationValidation(self, func, f):
4946 """Writes the client side destintion initialization validation."""
4947 for arg in func.GetOriginalArgs():
4948 arg.WriteDestinationInitalizationValidation(f, func)
4950 def WriteTraceEvent(self, func, f):
4951 f.write(' TRACE_EVENT0("gpu", "GLES2Implementation::%s");\n' %
4952 func.original_name)
4954 def WriteImmediateCmdComputeSize(self, func, f):
4955 """Writes the size computation code for the immediate version of a cmd."""
4956 f.write(" static uint32_t ComputeSize(uint32_t size_in_bytes) {\n")
4957 f.write(" return static_cast<uint32_t>(\n")
4958 f.write(" sizeof(ValueType) + // NOLINT\n")
4959 f.write(" RoundSizeToMultipleOfEntries(size_in_bytes));\n")
4960 f.write(" }\n")
4961 f.write("\n")
4963 def WriteImmediateCmdSetHeader(self, func, f):
4964 """Writes the SetHeader function for the immediate version of a cmd."""
4965 f.write(" void SetHeader(uint32_t size_in_bytes) {\n")
4966 f.write(" header.SetCmdByTotalSize<ValueType>(size_in_bytes);\n")
4967 f.write(" }\n")
4968 f.write("\n")
4970 def WriteImmediateCmdInit(self, func, f):
4971 """Writes the Init function for the immediate version of a command."""
4972 raise NotImplementedError(func.name)
4974 def WriteImmediateCmdSet(self, func, f):
4975 """Writes the Set function for the immediate version of a command."""
4976 raise NotImplementedError(func.name)
4978 def WriteCmdHelper(self, func, f):
4979 """Writes the cmd helper definition for a cmd."""
4980 code = """ void %(name)s(%(typed_args)s) {
4981 gles2::cmds::%(name)s* c = GetCmdSpace<gles2::cmds::%(name)s>();
4982 if (c) {
4983 c->Init(%(args)s);
4988 f.write(code % {
4989 "name": func.name,
4990 "typed_args": func.MakeTypedCmdArgString(""),
4991 "args": func.MakeCmdArgString(""),
4994 def WriteImmediateCmdHelper(self, func, f):
4995 """Writes the cmd helper definition for the immediate version of a cmd."""
4996 code = """ void %(name)s(%(typed_args)s) {
4997 const uint32_t s = 0; // TODO(gman): compute correct size
4998 gles2::cmds::%(name)s* c =
4999 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(s);
5000 if (c) {
5001 c->Init(%(args)s);
5006 f.write(code % {
5007 "name": func.name,
5008 "typed_args": func.MakeTypedCmdArgString(""),
5009 "args": func.MakeCmdArgString(""),
5013 class StateSetHandler(TypeHandler):
5014 """Handler for commands that simply set state."""
5016 def WriteHandlerImplementation(self, func, f):
5017 """Overrriden from TypeHandler."""
5018 state_name = func.GetInfo('state')
5019 state = _STATES[state_name]
5020 states = state['states']
5021 args = func.GetOriginalArgs()
5022 for ndx,item in enumerate(states):
5023 code = []
5024 if 'range_checks' in item:
5025 for range_check in item['range_checks']:
5026 code.append("%s %s" % (args[ndx].name, range_check['check']))
5027 if 'nan_check' in item:
5028 # Drivers might generate an INVALID_VALUE error when a value is set
5029 # to NaN. This is allowed behavior under GLES 3.0 section 2.1.1 or
5030 # OpenGL 4.5 section 2.3.4.1 - providing NaN allows undefined results.
5031 # Make this behavior consistent within Chromium, and avoid leaking GL
5032 # errors by generating the error in the command buffer instead of
5033 # letting the GL driver generate it.
5034 code.append("std::isnan(%s)" % args[ndx].name)
5035 if len(code):
5036 f.write(" if (%s) {\n" % " ||\n ".join(code))
5037 f.write(
5038 ' LOCAL_SET_GL_ERROR(GL_INVALID_VALUE,'
5039 ' "%s", "%s out of range");\n' %
5040 (func.name, args[ndx].name))
5041 f.write(" return error::kNoError;\n")
5042 f.write(" }\n")
5043 code = []
5044 for ndx,item in enumerate(states):
5045 code.append("state_.%s != %s" % (item['name'], args[ndx].name))
5046 f.write(" if (%s) {\n" % " ||\n ".join(code))
5047 for ndx,item in enumerate(states):
5048 f.write(" state_.%s = %s;\n" % (item['name'], args[ndx].name))
5049 if 'state_flag' in state:
5050 f.write(" %s = true;\n" % state['state_flag'])
5051 if not func.GetInfo("no_gl"):
5052 for ndx,item in enumerate(states):
5053 if item.get('cached', False):
5054 f.write(" state_.%s = %s;\n" %
5055 (CachedStateName(item), args[ndx].name))
5056 f.write(" %s(%s);\n" %
5057 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
5058 f.write(" }\n")
5060 def WriteServiceUnitTest(self, func, f, *extras):
5061 """Overrriden from TypeHandler."""
5062 TypeHandler.WriteServiceUnitTest(self, func, f, *extras)
5063 state_name = func.GetInfo('state')
5064 state = _STATES[state_name]
5065 states = state['states']
5066 for ndx,item in enumerate(states):
5067 if 'range_checks' in item:
5068 for check_ndx, range_check in enumerate(item['range_checks']):
5069 valid_test = """
5070 TEST_P(%(test_name)s, %(name)sInvalidValue%(ndx)d_%(check_ndx)d) {
5071 SpecializedSetup<cmds::%(name)s, 0>(false);
5072 cmds::%(name)s cmd;
5073 cmd.Init(%(args)s);
5074 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5075 EXPECT_EQ(GL_INVALID_VALUE, GetGLError());
5078 name = func.name
5079 arg_strings = [
5080 arg.GetValidArg(func) \
5081 for arg in func.GetOriginalArgs() if not arg.IsConstant()
5084 arg_strings[ndx] = range_check['test_value']
5085 vars = {
5086 'name': name,
5087 'ndx': ndx,
5088 'check_ndx': check_ndx,
5089 'args': ", ".join(arg_strings),
5091 for extra in extras:
5092 vars.update(extra)
5093 f.write(valid_test % vars)
5094 if 'nan_check' in item:
5095 valid_test = """
5096 TEST_P(%(test_name)s, %(name)sNaNValue%(ndx)d) {
5097 SpecializedSetup<cmds::%(name)s, 0>(false);
5098 cmds::%(name)s cmd;
5099 cmd.Init(%(args)s);
5100 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5101 EXPECT_EQ(GL_INVALID_VALUE, GetGLError());
5104 name = func.name
5105 arg_strings = [
5106 arg.GetValidArg(func) \
5107 for arg in func.GetOriginalArgs() if not arg.IsConstant()
5110 arg_strings[ndx] = 'nanf("")'
5111 vars = {
5112 'name': name,
5113 'ndx': ndx,
5114 'args': ", ".join(arg_strings),
5116 for extra in extras:
5117 vars.update(extra)
5118 f.write(valid_test % vars)
5121 class StateSetRGBAlphaHandler(TypeHandler):
5122 """Handler for commands that simply set state that have rgb/alpha."""
5124 def WriteHandlerImplementation(self, func, f):
5125 """Overrriden from TypeHandler."""
5126 state_name = func.GetInfo('state')
5127 state = _STATES[state_name]
5128 states = state['states']
5129 args = func.GetOriginalArgs()
5130 num_args = len(args)
5131 code = []
5132 for ndx,item in enumerate(states):
5133 code.append("state_.%s != %s" % (item['name'], args[ndx % num_args].name))
5134 f.write(" if (%s) {\n" % " ||\n ".join(code))
5135 for ndx, item in enumerate(states):
5136 f.write(" state_.%s = %s;\n" %
5137 (item['name'], args[ndx % num_args].name))
5138 if 'state_flag' in state:
5139 f.write(" %s = true;\n" % state['state_flag'])
5140 if not func.GetInfo("no_gl"):
5141 f.write(" %s(%s);\n" %
5142 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
5143 f.write(" }\n")
5146 class StateSetFrontBackSeparateHandler(TypeHandler):
5147 """Handler for commands that simply set state that have front/back."""
5149 def WriteHandlerImplementation(self, func, f):
5150 """Overrriden from TypeHandler."""
5151 state_name = func.GetInfo('state')
5152 state = _STATES[state_name]
5153 states = state['states']
5154 args = func.GetOriginalArgs()
5155 face = args[0].name
5156 num_args = len(args)
5157 f.write(" bool changed = false;\n")
5158 for group_ndx, group in enumerate(Grouper(num_args - 1, states)):
5159 f.write(" if (%s == %s || %s == GL_FRONT_AND_BACK) {\n" %
5160 (face, ('GL_FRONT', 'GL_BACK')[group_ndx], face))
5161 code = []
5162 for ndx, item in enumerate(group):
5163 code.append("state_.%s != %s" % (item['name'], args[ndx + 1].name))
5164 f.write(" changed |= %s;\n" % " ||\n ".join(code))
5165 f.write(" }\n")
5166 f.write(" if (changed) {\n")
5167 for group_ndx, group in enumerate(Grouper(num_args - 1, states)):
5168 f.write(" if (%s == %s || %s == GL_FRONT_AND_BACK) {\n" %
5169 (face, ('GL_FRONT', 'GL_BACK')[group_ndx], face))
5170 for ndx, item in enumerate(group):
5171 f.write(" state_.%s = %s;\n" %
5172 (item['name'], args[ndx + 1].name))
5173 f.write(" }\n")
5174 if 'state_flag' in state:
5175 f.write(" %s = true;\n" % state['state_flag'])
5176 if not func.GetInfo("no_gl"):
5177 f.write(" %s(%s);\n" %
5178 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
5179 f.write(" }\n")
5182 class StateSetFrontBackHandler(TypeHandler):
5183 """Handler for commands that simply set state that set both front/back."""
5185 def WriteHandlerImplementation(self, func, f):
5186 """Overrriden from TypeHandler."""
5187 state_name = func.GetInfo('state')
5188 state = _STATES[state_name]
5189 states = state['states']
5190 args = func.GetOriginalArgs()
5191 num_args = len(args)
5192 code = []
5193 for group_ndx, group in enumerate(Grouper(num_args, states)):
5194 for ndx, item in enumerate(group):
5195 code.append("state_.%s != %s" % (item['name'], args[ndx].name))
5196 f.write(" if (%s) {\n" % " ||\n ".join(code))
5197 for group_ndx, group in enumerate(Grouper(num_args, states)):
5198 for ndx, item in enumerate(group):
5199 f.write(" state_.%s = %s;\n" % (item['name'], args[ndx].name))
5200 if 'state_flag' in state:
5201 f.write(" %s = true;\n" % state['state_flag'])
5202 if not func.GetInfo("no_gl"):
5203 f.write(" %s(%s);\n" %
5204 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
5205 f.write(" }\n")
5208 class StateSetNamedParameter(TypeHandler):
5209 """Handler for commands that set a state chosen with an enum parameter."""
5211 def WriteHandlerImplementation(self, func, f):
5212 """Overridden from TypeHandler."""
5213 state_name = func.GetInfo('state')
5214 state = _STATES[state_name]
5215 states = state['states']
5216 args = func.GetOriginalArgs()
5217 num_args = len(args)
5218 assert num_args == 2
5219 f.write(" switch (%s) {\n" % args[0].name)
5220 for state in states:
5221 f.write(" case %s:\n" % state['enum'])
5222 f.write(" if (state_.%s != %s) {\n" %
5223 (state['name'], args[1].name))
5224 f.write(" state_.%s = %s;\n" % (state['name'], args[1].name))
5225 if not func.GetInfo("no_gl"):
5226 f.write(" %s(%s);\n" %
5227 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
5228 f.write(" }\n")
5229 f.write(" break;\n")
5230 f.write(" default:\n")
5231 f.write(" NOTREACHED();\n")
5232 f.write(" }\n")
5235 class CustomHandler(TypeHandler):
5236 """Handler for commands that are auto-generated but require minor tweaks."""
5238 def WriteServiceImplementation(self, func, f):
5239 """Overrriden from TypeHandler."""
5240 pass
5242 def WriteImmediateServiceImplementation(self, func, f):
5243 """Overrriden from TypeHandler."""
5244 pass
5246 def WriteBucketServiceImplementation(self, func, f):
5247 """Overrriden from TypeHandler."""
5248 pass
5250 def WriteServiceUnitTest(self, func, f, *extras):
5251 """Overrriden from TypeHandler."""
5252 f.write("// TODO(gman): %s\n\n" % func.name)
5254 def WriteImmediateServiceUnitTest(self, func, f, *extras):
5255 """Overrriden from TypeHandler."""
5256 f.write("// TODO(gman): %s\n\n" % func.name)
5258 def WriteImmediateCmdGetTotalSize(self, func, f):
5259 """Overrriden from TypeHandler."""
5260 f.write(
5261 " uint32_t total_size = 0; // TODO(gman): get correct size.\n")
5263 def WriteImmediateCmdInit(self, func, f):
5264 """Overrriden from TypeHandler."""
5265 f.write(" void Init(%s) {\n" % func.MakeTypedCmdArgString("_"))
5266 self.WriteImmediateCmdGetTotalSize(func, f)
5267 f.write(" SetHeader(total_size);\n")
5268 args = func.GetCmdArgs()
5269 for arg in args:
5270 f.write(" %s = _%s;\n" % (arg.name, arg.name))
5271 f.write(" }\n")
5272 f.write("\n")
5274 def WriteImmediateCmdSet(self, func, f):
5275 """Overrriden from TypeHandler."""
5276 copy_args = func.MakeCmdArgString("_", False)
5277 f.write(" void* Set(void* cmd%s) {\n" %
5278 func.MakeTypedCmdArgString("_", True))
5279 self.WriteImmediateCmdGetTotalSize(func, f)
5280 f.write(" static_cast<ValueType*>(cmd)->Init(%s);\n" % copy_args)
5281 f.write(" return NextImmediateCmdAddressTotalSize<ValueType>("
5282 "cmd, total_size);\n")
5283 f.write(" }\n")
5284 f.write("\n")
5287 class HandWrittenHandler(CustomHandler):
5288 """Handler for comands where everything must be written by hand."""
5290 def InitFunction(self, func):
5291 """Add or adjust anything type specific for this function."""
5292 CustomHandler.InitFunction(self, func)
5293 func.can_auto_generate = False
5295 def NeedsDataTransferFunction(self, func):
5296 """Overriden from TypeHandler."""
5297 # If specified explicitly, force the data transfer method.
5298 if func.GetInfo('data_transfer_methods'):
5299 return True
5300 return False
5302 def WriteStruct(self, func, f):
5303 """Overrriden from TypeHandler."""
5304 pass
5306 def WriteDocs(self, func, f):
5307 """Overrriden from TypeHandler."""
5308 pass
5310 def WriteServiceUnitTest(self, func, f, *extras):
5311 """Overrriden from TypeHandler."""
5312 f.write("// TODO(gman): %s\n\n" % func.name)
5314 def WriteImmediateServiceUnitTest(self, func, f, *extras):
5315 """Overrriden from TypeHandler."""
5316 f.write("// TODO(gman): %s\n\n" % func.name)
5318 def WriteBucketServiceUnitTest(self, func, f, *extras):
5319 """Overrriden from TypeHandler."""
5320 f.write("// TODO(gman): %s\n\n" % func.name)
5322 def WriteServiceImplementation(self, func, f):
5323 """Overrriden from TypeHandler."""
5324 pass
5326 def WriteImmediateServiceImplementation(self, func, f):
5327 """Overrriden from TypeHandler."""
5328 pass
5330 def WriteBucketServiceImplementation(self, func, f):
5331 """Overrriden from TypeHandler."""
5332 pass
5334 def WriteImmediateCmdHelper(self, func, f):
5335 """Overrriden from TypeHandler."""
5336 pass
5338 def WriteCmdHelper(self, func, f):
5339 """Overrriden from TypeHandler."""
5340 pass
5342 def WriteFormatTest(self, func, f):
5343 """Overrriden from TypeHandler."""
5344 f.write("// TODO(gman): Write test for %s\n" % func.name)
5346 def WriteImmediateFormatTest(self, func, f):
5347 """Overrriden from TypeHandler."""
5348 f.write("// TODO(gman): Write test for %s\n" % func.name)
5351 class ManualHandler(CustomHandler):
5352 """Handler for commands who's handlers must be written by hand."""
5354 def InitFunction(self, func):
5355 """Overrriden from TypeHandler."""
5356 if (func.name == 'CompressedTexImage2DBucket' or
5357 func.name == 'CompressedTexImage3DBucket'):
5358 func.cmd_args = func.cmd_args[:-1]
5359 func.AddCmdArg(Argument('bucket_id', 'GLuint'))
5360 else:
5361 CustomHandler.InitFunction(self, func)
5363 def WriteServiceImplementation(self, func, f):
5364 """Overrriden from TypeHandler."""
5365 pass
5367 def WriteBucketServiceImplementation(self, func, f):
5368 """Overrriden from TypeHandler."""
5369 pass
5371 def WriteServiceUnitTest(self, func, f, *extras):
5372 """Overrriden from TypeHandler."""
5373 f.write("// TODO(gman): %s\n\n" % func.name)
5375 def WriteImmediateServiceUnitTest(self, func, f, *extras):
5376 """Overrriden from TypeHandler."""
5377 f.write("// TODO(gman): %s\n\n" % func.name)
5379 def WriteImmediateServiceImplementation(self, func, f):
5380 """Overrriden from TypeHandler."""
5381 pass
5383 def WriteImmediateFormatTest(self, func, f):
5384 """Overrriden from TypeHandler."""
5385 f.write("// TODO(gman): Implement test for %s\n" % func.name)
5387 def WriteGLES2Implementation(self, func, f):
5388 """Overrriden from TypeHandler."""
5389 if func.GetInfo('impl_func'):
5390 super(ManualHandler, self).WriteGLES2Implementation(func, f)
5392 def WriteGLES2ImplementationHeader(self, func, f):
5393 """Overrriden from TypeHandler."""
5394 f.write("%s %s(%s) override;\n" %
5395 (func.return_type, func.original_name,
5396 func.MakeTypedOriginalArgString("")))
5397 f.write("\n")
5399 def WriteImmediateCmdGetTotalSize(self, func, f):
5400 """Overrriden from TypeHandler."""
5401 # TODO(gman): Move this data to _FUNCTION_INFO?
5402 CustomHandler.WriteImmediateCmdGetTotalSize(self, func, f)
5405 class DataHandler(TypeHandler):
5406 """Handler for glBufferData, glBufferSubData, glTexImage*D, glTexSubImage*D,
5407 glCompressedTexImage*D, glCompressedTexImageSub*D."""
5409 def InitFunction(self, func):
5410 """Overrriden from TypeHandler."""
5411 if (func.name == 'CompressedTexSubImage2DBucket' or
5412 func.name == 'CompressedTexSubImage3DBucket'):
5413 func.cmd_args = func.cmd_args[:-1]
5414 func.AddCmdArg(Argument('bucket_id', 'GLuint'))
5416 def WriteGetDataSizeCode(self, func, f):
5417 """Overrriden from TypeHandler."""
5418 # TODO(gman): Move this data to _FUNCTION_INFO?
5419 name = func.name
5420 if name.endswith("Immediate"):
5421 name = name[0:-9]
5422 if name == 'BufferData' or name == 'BufferSubData':
5423 f.write(" uint32_t data_size = size;\n")
5424 elif (name == 'CompressedTexImage2D' or
5425 name == 'CompressedTexSubImage2D' or
5426 name == 'CompressedTexImage3D' or
5427 name == 'CompressedTexSubImage3D'):
5428 f.write(" uint32_t data_size = imageSize;\n")
5429 elif (name == 'CompressedTexSubImage2DBucket' or
5430 name == 'CompressedTexSubImage3DBucket'):
5431 f.write(" Bucket* bucket = GetBucket(c.bucket_id);\n")
5432 f.write(" uint32_t data_size = bucket->size();\n")
5433 f.write(" GLsizei imageSize = data_size;\n")
5434 elif name == 'TexImage2D' or name == 'TexSubImage2D':
5435 code = """ uint32_t data_size;
5436 if (!GLES2Util::ComputeImageDataSize(
5437 width, height, format, type, unpack_alignment_, &data_size)) {
5438 return error::kOutOfBounds;
5441 f.write(code)
5442 else:
5443 f.write(
5444 "// uint32_t data_size = 0; // TODO(gman): get correct size!\n")
5446 def WriteImmediateCmdGetTotalSize(self, func, f):
5447 """Overrriden from TypeHandler."""
5448 pass
5450 def WriteImmediateCmdInit(self, func, f):
5451 """Overrriden from TypeHandler."""
5452 f.write(" void Init(%s) {\n" % func.MakeTypedCmdArgString("_"))
5453 self.WriteImmediateCmdGetTotalSize(func, f)
5454 f.write(" SetHeader(total_size);\n")
5455 args = func.GetCmdArgs()
5456 for arg in args:
5457 f.write(" %s = _%s;\n" % (arg.name, arg.name))
5458 f.write(" }\n")
5459 f.write("\n")
5461 def WriteImmediateCmdSet(self, func, f):
5462 """Overrriden from TypeHandler."""
5463 copy_args = func.MakeCmdArgString("_", False)
5464 f.write(" void* Set(void* cmd%s) {\n" %
5465 func.MakeTypedCmdArgString("_", True))
5466 self.WriteImmediateCmdGetTotalSize(func, f)
5467 f.write(" static_cast<ValueType*>(cmd)->Init(%s);\n" % copy_args)
5468 f.write(" return NextImmediateCmdAddressTotalSize<ValueType>("
5469 "cmd, total_size);\n")
5470 f.write(" }\n")
5471 f.write("\n")
5473 def WriteImmediateFormatTest(self, func, f):
5474 """Overrriden from TypeHandler."""
5475 # TODO(gman): Remove this exception.
5476 f.write("// TODO(gman): Implement test for %s\n" % func.name)
5477 return
5479 def WriteServiceUnitTest(self, func, f, *extras):
5480 """Overrriden from TypeHandler."""
5481 f.write("// TODO(gman): %s\n\n" % func.name)
5483 def WriteImmediateServiceUnitTest(self, func, f, *extras):
5484 """Overrriden from TypeHandler."""
5485 f.write("// TODO(gman): %s\n\n" % func.name)
5487 def WriteBucketServiceImplementation(self, func, f):
5488 """Overrriden from TypeHandler."""
5489 if ((not func.name == 'CompressedTexSubImage2DBucket') and
5490 (not func.name == 'CompressedTexSubImage3DBucket')):
5491 TypeHandler.WriteBucketServiceImplemenation(self, func, f)
5494 class BindHandler(TypeHandler):
5495 """Handler for glBind___ type functions."""
5497 def WriteServiceUnitTest(self, func, f, *extras):
5498 """Overrriden from TypeHandler."""
5500 if len(func.GetOriginalArgs()) == 1:
5501 valid_test = """
5502 TEST_P(%(test_name)s, %(name)sValidArgs) {
5503 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
5504 SpecializedSetup<cmds::%(name)s, 0>(true);
5505 cmds::%(name)s cmd;
5506 cmd.Init(%(args)s);"""
5507 if func.IsUnsafe():
5508 valid_test += """
5509 decoder_->set_unsafe_es3_apis_enabled(true);
5510 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5511 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5512 decoder_->set_unsafe_es3_apis_enabled(false);
5513 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));
5516 else:
5517 valid_test += """
5518 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5519 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5522 if func.GetInfo("gen_func"):
5523 valid_test += """
5524 TEST_P(%(test_name)s, %(name)sValidArgsNewId) {
5525 EXPECT_CALL(*gl_, %(gl_func_name)s(kNewServiceId));
5526 EXPECT_CALL(*gl_, %(gl_gen_func_name)s(1, _))
5527 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
5528 SpecializedSetup<cmds::%(name)s, 0>(true);
5529 cmds::%(name)s cmd;
5530 cmd.Init(kNewClientId);
5531 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5532 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5533 EXPECT_TRUE(Get%(resource_type)s(kNewClientId) != NULL);
5536 self.WriteValidUnitTest(func, f, valid_test, {
5537 'resource_type': func.GetOriginalArgs()[0].resource_type,
5538 'gl_gen_func_name': func.GetInfo("gen_func"),
5539 }, *extras)
5540 else:
5541 valid_test = """
5542 TEST_P(%(test_name)s, %(name)sValidArgs) {
5543 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
5544 SpecializedSetup<cmds::%(name)s, 0>(true);
5545 cmds::%(name)s cmd;
5546 cmd.Init(%(args)s);"""
5547 if func.IsUnsafe():
5548 valid_test += """
5549 decoder_->set_unsafe_es3_apis_enabled(true);
5550 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5551 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5552 decoder_->set_unsafe_es3_apis_enabled(false);
5553 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));
5556 else:
5557 valid_test += """
5558 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5559 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5562 if func.GetInfo("gen_func"):
5563 valid_test += """
5564 TEST_P(%(test_name)s, %(name)sValidArgsNewId) {
5565 EXPECT_CALL(*gl_,
5566 %(gl_func_name)s(%(gl_args_with_new_id)s));
5567 EXPECT_CALL(*gl_, %(gl_gen_func_name)s(1, _))
5568 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
5569 SpecializedSetup<cmds::%(name)s, 0>(true);
5570 cmds::%(name)s cmd;
5571 cmd.Init(%(args_with_new_id)s);"""
5572 if func.IsUnsafe():
5573 valid_test += """
5574 decoder_->set_unsafe_es3_apis_enabled(true);
5575 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5576 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5577 EXPECT_TRUE(Get%(resource_type)s(kNewClientId) != NULL);
5578 decoder_->set_unsafe_es3_apis_enabled(false);
5579 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));
5582 else:
5583 valid_test += """
5584 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5585 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5586 EXPECT_TRUE(Get%(resource_type)s(kNewClientId) != NULL);
5590 gl_args_with_new_id = []
5591 args_with_new_id = []
5592 for arg in func.GetOriginalArgs():
5593 if hasattr(arg, 'resource_type'):
5594 gl_args_with_new_id.append('kNewServiceId')
5595 args_with_new_id.append('kNewClientId')
5596 else:
5597 gl_args_with_new_id.append(arg.GetValidGLArg(func))
5598 args_with_new_id.append(arg.GetValidArg(func))
5599 self.WriteValidUnitTest(func, f, valid_test, {
5600 'args_with_new_id': ", ".join(args_with_new_id),
5601 'gl_args_with_new_id': ", ".join(gl_args_with_new_id),
5602 'resource_type': func.GetResourceIdArg().resource_type,
5603 'gl_gen_func_name': func.GetInfo("gen_func"),
5604 }, *extras)
5606 invalid_test = """
5607 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
5608 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
5609 SpecializedSetup<cmds::%(name)s, 0>(false);
5610 cmds::%(name)s cmd;
5611 cmd.Init(%(args)s);
5612 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
5615 self.WriteInvalidUnitTest(func, f, invalid_test, *extras)
5617 def WriteGLES2Implementation(self, func, f):
5618 """Writes the GLES2 Implemention."""
5620 impl_func = func.GetInfo('impl_func')
5621 impl_decl = func.GetInfo('impl_decl')
5623 if (func.can_auto_generate and
5624 (impl_func == None or impl_func == True) and
5625 (impl_decl == None or impl_decl == True)):
5627 f.write("%s GLES2Implementation::%s(%s) {\n" %
5628 (func.return_type, func.original_name,
5629 func.MakeTypedOriginalArgString("")))
5630 f.write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
5631 func.WriteDestinationInitalizationValidation(f)
5632 self.WriteClientGLCallLog(func, f)
5633 for arg in func.GetOriginalArgs():
5634 arg.WriteClientSideValidationCode(f, func)
5636 code = """ if (Is%(type)sReservedId(%(id)s)) {
5637 SetGLError(GL_INVALID_OPERATION, "%(name)s\", \"%(id)s reserved id");
5638 return;
5640 %(name)sHelper(%(arg_string)s);
5641 CheckGLError();
5645 name_arg = func.GetResourceIdArg()
5646 f.write(code % {
5647 'name': func.name,
5648 'arg_string': func.MakeOriginalArgString(""),
5649 'id': name_arg.name,
5650 'type': name_arg.resource_type,
5651 'lc_type': name_arg.resource_type.lower(),
5654 def WriteGLES2ImplementationUnitTest(self, func, f):
5655 """Overrriden from TypeHandler."""
5656 client_test = func.GetInfo('client_test')
5657 if client_test == False:
5658 return
5659 code = """
5660 TEST_F(GLES2ImplementationTest, %(name)s) {
5661 struct Cmds {
5662 cmds::%(name)s cmd;
5664 Cmds expected;
5665 expected.cmd.Init(%(cmd_args)s);
5667 gl_->%(name)s(%(args)s);
5668 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));"""
5669 if not func.IsUnsafe():
5670 code += """
5671 ClearCommands();
5672 gl_->%(name)s(%(args)s);
5673 EXPECT_TRUE(NoCommandsWritten());"""
5674 code += """
5677 cmd_arg_strings = [
5678 arg.GetValidClientSideCmdArg(func) for arg in func.GetCmdArgs()
5680 gl_arg_strings = [
5681 arg.GetValidClientSideArg(func) for arg in func.GetOriginalArgs()
5684 f.write(code % {
5685 'name': func.name,
5686 'args': ", ".join(gl_arg_strings),
5687 'cmd_args': ", ".join(cmd_arg_strings),
5691 class GENnHandler(TypeHandler):
5692 """Handler for glGen___ type functions."""
5694 def InitFunction(self, func):
5695 """Overrriden from TypeHandler."""
5696 pass
5698 def WriteGetDataSizeCode(self, func, f):
5699 """Overrriden from TypeHandler."""
5700 code = """ uint32_t data_size;
5701 if (!SafeMultiplyUint32(n, sizeof(GLuint), &data_size)) {
5702 return error::kOutOfBounds;
5705 f.write(code)
5707 def WriteHandlerImplementation (self, func, f):
5708 """Overrriden from TypeHandler."""
5709 f.write(" if (!%sHelper(n, %s)) {\n"
5710 " return error::kInvalidArguments;\n"
5711 " }\n" %
5712 (func.name, func.GetLastOriginalArg().name))
5714 def WriteImmediateHandlerImplementation(self, func, f):
5715 """Overrriden from TypeHandler."""
5716 if func.IsUnsafe():
5717 f.write(""" for (GLsizei ii = 0; ii < n; ++ii) {
5718 if (group_->Get%(resource_name)sServiceId(%(last_arg_name)s[ii], NULL)) {
5719 return error::kInvalidArguments;
5722 scoped_ptr<GLuint[]> service_ids(new GLuint[n]);
5723 gl%(func_name)s(n, service_ids.get());
5724 for (GLsizei ii = 0; ii < n; ++ii) {
5725 group_->Add%(resource_name)sId(%(last_arg_name)s[ii], service_ids[ii]);
5727 """ % { 'func_name': func.original_name,
5728 'last_arg_name': func.GetLastOriginalArg().name,
5729 'resource_name': func.GetInfo('resource_type') })
5730 else:
5731 f.write(" if (!%sHelper(n, %s)) {\n"
5732 " return error::kInvalidArguments;\n"
5733 " }\n" %
5734 (func.original_name, func.GetLastOriginalArg().name))
5736 def WriteGLES2Implementation(self, func, f):
5737 """Overrriden from TypeHandler."""
5738 log_code = (""" GPU_CLIENT_LOG_CODE_BLOCK({
5739 for (GLsizei i = 0; i < n; ++i) {
5740 GPU_CLIENT_LOG(" " << i << ": " << %s[i]);
5742 });""" % func.GetOriginalArgs()[1].name)
5743 args = {
5744 'log_code': log_code,
5745 'return_type': func.return_type,
5746 'name': func.original_name,
5747 'typed_args': func.MakeTypedOriginalArgString(""),
5748 'args': func.MakeOriginalArgString(""),
5749 'resource_types': func.GetInfo('resource_types'),
5750 'count_name': func.GetOriginalArgs()[0].name,
5752 f.write(
5753 "%(return_type)s GLES2Implementation::%(name)s(%(typed_args)s) {\n" %
5754 args)
5755 func.WriteDestinationInitalizationValidation(f)
5756 self.WriteClientGLCallLog(func, f)
5757 for arg in func.GetOriginalArgs():
5758 arg.WriteClientSideValidationCode(f, func)
5759 not_shared = func.GetInfo('not_shared')
5760 if not_shared:
5761 alloc_code = (
5763 """ IdAllocator* id_allocator = GetIdAllocator(id_namespaces::k%s);
5764 for (GLsizei ii = 0; ii < n; ++ii)
5765 %s[ii] = id_allocator->AllocateID();""" %
5766 (func.GetInfo('resource_types'), func.GetOriginalArgs()[1].name))
5767 else:
5768 alloc_code = (""" GetIdHandler(id_namespaces::k%(resource_types)s)->
5769 MakeIds(this, 0, %(args)s);""" % args)
5770 args['alloc_code'] = alloc_code
5772 code = """ GPU_CLIENT_SINGLE_THREAD_CHECK();
5773 %(alloc_code)s
5774 %(name)sHelper(%(args)s);
5775 helper_->%(name)sImmediate(%(args)s);
5776 if (share_group_->bind_generates_resource())
5777 helper_->CommandBufferHelper::Flush();
5778 %(log_code)s
5779 CheckGLError();
5783 f.write(code % args)
5785 def WriteGLES2ImplementationUnitTest(self, func, f):
5786 """Overrriden from TypeHandler."""
5787 code = """
5788 TEST_F(GLES2ImplementationTest, %(name)s) {
5789 GLuint ids[2] = { 0, };
5790 struct Cmds {
5791 cmds::%(name)sImmediate gen;
5792 GLuint data[2];
5794 Cmds expected;
5795 expected.gen.Init(arraysize(ids), &ids[0]);
5796 expected.data[0] = k%(types)sStartId;
5797 expected.data[1] = k%(types)sStartId + 1;
5798 gl_->%(name)s(arraysize(ids), &ids[0]);
5799 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
5800 EXPECT_EQ(k%(types)sStartId, ids[0]);
5801 EXPECT_EQ(k%(types)sStartId + 1, ids[1]);
5804 f.write(code % {
5805 'name': func.name,
5806 'types': func.GetInfo('resource_types'),
5809 def WriteServiceUnitTest(self, func, f, *extras):
5810 """Overrriden from TypeHandler."""
5811 valid_test = """
5812 TEST_P(%(test_name)s, %(name)sValidArgs) {
5813 EXPECT_CALL(*gl_, %(gl_func_name)s(1, _))
5814 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
5815 GetSharedMemoryAs<GLuint*>()[0] = kNewClientId;
5816 SpecializedSetup<cmds::%(name)s, 0>(true);
5817 cmds::%(name)s cmd;
5818 cmd.Init(%(args)s);
5819 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5820 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
5821 if func.IsUnsafe():
5822 valid_test += """
5823 GLuint service_id;
5824 EXPECT_TRUE(Get%(resource_name)sServiceId(kNewClientId, &service_id));
5825 EXPECT_EQ(kNewServiceId, service_id)
5828 else:
5829 valid_test += """
5830 EXPECT_TRUE(Get%(resource_name)s(kNewClientId, &service_id) != NULL);
5833 self.WriteValidUnitTest(func, f, valid_test, {
5834 'resource_name': func.GetInfo('resource_type'),
5835 }, *extras)
5836 invalid_test = """
5837 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
5838 EXPECT_CALL(*gl_, %(gl_func_name)s(_, _)).Times(0);
5839 GetSharedMemoryAs<GLuint*>()[0] = client_%(resource_name)s_id_;
5840 SpecializedSetup<cmds::%(name)s, 0>(false);
5841 cmds::%(name)s cmd;
5842 cmd.Init(%(args)s);
5843 EXPECT_EQ(error::kInvalidArguments, ExecuteCmd(cmd));
5846 self.WriteValidUnitTest(func, f, invalid_test, {
5847 'resource_name': func.GetInfo('resource_type').lower(),
5848 }, *extras)
5850 def WriteImmediateServiceUnitTest(self, func, f, *extras):
5851 """Overrriden from TypeHandler."""
5852 valid_test = """
5853 TEST_P(%(test_name)s, %(name)sValidArgs) {
5854 EXPECT_CALL(*gl_, %(gl_func_name)s(1, _))
5855 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
5856 cmds::%(name)s* cmd = GetImmediateAs<cmds::%(name)s>();
5857 GLuint temp = kNewClientId;
5858 SpecializedSetup<cmds::%(name)s, 0>(true);"""
5859 if func.IsUnsafe():
5860 valid_test += """
5861 decoder_->set_unsafe_es3_apis_enabled(true);"""
5862 valid_test += """
5863 cmd->Init(1, &temp);
5864 EXPECT_EQ(error::kNoError,
5865 ExecuteImmediateCmd(*cmd, sizeof(temp)));
5866 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
5867 if func.IsUnsafe():
5868 valid_test += """
5869 GLuint service_id;
5870 EXPECT_TRUE(Get%(resource_name)sServiceId(kNewClientId, &service_id));
5871 EXPECT_EQ(kNewServiceId, service_id);
5872 decoder_->set_unsafe_es3_apis_enabled(false);
5873 EXPECT_EQ(error::kUnknownCommand,
5874 ExecuteImmediateCmd(*cmd, sizeof(temp)));
5877 else:
5878 valid_test += """
5879 EXPECT_TRUE(Get%(resource_name)s(kNewClientId) != NULL);
5882 self.WriteValidUnitTest(func, f, valid_test, {
5883 'resource_name': func.GetInfo('resource_type'),
5884 }, *extras)
5885 invalid_test = """
5886 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
5887 EXPECT_CALL(*gl_, %(gl_func_name)s(_, _)).Times(0);
5888 cmds::%(name)s* cmd = GetImmediateAs<cmds::%(name)s>();
5889 SpecializedSetup<cmds::%(name)s, 0>(false);
5890 cmd->Init(1, &client_%(resource_name)s_id_);"""
5891 if func.IsUnsafe():
5892 invalid_test += """
5893 decoder_->set_unsafe_es3_apis_enabled(true);
5894 EXPECT_EQ(error::kInvalidArguments,
5895 ExecuteImmediateCmd(*cmd, sizeof(&client_%(resource_name)s_id_)));
5896 decoder_->set_unsafe_es3_apis_enabled(false);
5899 else:
5900 invalid_test += """
5901 EXPECT_EQ(error::kInvalidArguments,
5902 ExecuteImmediateCmd(*cmd, sizeof(&client_%(resource_name)s_id_)));
5905 self.WriteValidUnitTest(func, f, invalid_test, {
5906 'resource_name': func.GetInfo('resource_type').lower(),
5907 }, *extras)
5909 def WriteImmediateCmdComputeSize(self, func, f):
5910 """Overrriden from TypeHandler."""
5911 f.write(" static uint32_t ComputeDataSize(GLsizei n) {\n")
5912 f.write(
5913 " return static_cast<uint32_t>(sizeof(GLuint) * n); // NOLINT\n")
5914 f.write(" }\n")
5915 f.write("\n")
5916 f.write(" static uint32_t ComputeSize(GLsizei n) {\n")
5917 f.write(" return static_cast<uint32_t>(\n")
5918 f.write(" sizeof(ValueType) + ComputeDataSize(n)); // NOLINT\n")
5919 f.write(" }\n")
5920 f.write("\n")
5922 def WriteImmediateCmdSetHeader(self, func, f):
5923 """Overrriden from TypeHandler."""
5924 f.write(" void SetHeader(GLsizei n) {\n")
5925 f.write(" header.SetCmdByTotalSize<ValueType>(ComputeSize(n));\n")
5926 f.write(" }\n")
5927 f.write("\n")
5929 def WriteImmediateCmdInit(self, func, f):
5930 """Overrriden from TypeHandler."""
5931 last_arg = func.GetLastOriginalArg()
5932 f.write(" void Init(%s, %s _%s) {\n" %
5933 (func.MakeTypedCmdArgString("_"),
5934 last_arg.type, last_arg.name))
5935 f.write(" SetHeader(_n);\n")
5936 args = func.GetCmdArgs()
5937 for arg in args:
5938 f.write(" %s = _%s;\n" % (arg.name, arg.name))
5939 f.write(" memcpy(ImmediateDataAddress(this),\n")
5940 f.write(" _%s, ComputeDataSize(_n));\n" % last_arg.name)
5941 f.write(" }\n")
5942 f.write("\n")
5944 def WriteImmediateCmdSet(self, func, f):
5945 """Overrriden from TypeHandler."""
5946 last_arg = func.GetLastOriginalArg()
5947 copy_args = func.MakeCmdArgString("_", False)
5948 f.write(" void* Set(void* cmd%s, %s _%s) {\n" %
5949 (func.MakeTypedCmdArgString("_", True),
5950 last_arg.type, last_arg.name))
5951 f.write(" static_cast<ValueType*>(cmd)->Init(%s, _%s);\n" %
5952 (copy_args, last_arg.name))
5953 f.write(" const uint32_t size = ComputeSize(_n);\n")
5954 f.write(" return NextImmediateCmdAddressTotalSize<ValueType>("
5955 "cmd, size);\n")
5956 f.write(" }\n")
5957 f.write("\n")
5959 def WriteImmediateCmdHelper(self, func, f):
5960 """Overrriden from TypeHandler."""
5961 code = """ void %(name)s(%(typed_args)s) {
5962 const uint32_t size = gles2::cmds::%(name)s::ComputeSize(n);
5963 gles2::cmds::%(name)s* c =
5964 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
5965 if (c) {
5966 c->Init(%(args)s);
5971 f.write(code % {
5972 "name": func.name,
5973 "typed_args": func.MakeTypedOriginalArgString(""),
5974 "args": func.MakeOriginalArgString(""),
5977 def WriteImmediateFormatTest(self, func, f):
5978 """Overrriden from TypeHandler."""
5979 f.write("TEST_F(GLES2FormatTest, %s) {\n" % func.name)
5980 f.write(" static GLuint ids[] = { 12, 23, 34, };\n")
5981 f.write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
5982 (func.name, func.name))
5983 f.write(" void* next_cmd = cmd.Set(\n")
5984 f.write(" &cmd, static_cast<GLsizei>(arraysize(ids)), ids);\n")
5985 f.write(" EXPECT_EQ(static_cast<uint32_t>(cmds::%s::kCmdId),\n" %
5986 func.name)
5987 f.write(" cmd.header.command);\n")
5988 f.write(" EXPECT_EQ(sizeof(cmd) +\n")
5989 f.write(" RoundSizeToMultipleOfEntries(cmd.n * 4u),\n")
5990 f.write(" cmd.header.size * 4u);\n")
5991 f.write(" EXPECT_EQ(static_cast<GLsizei>(arraysize(ids)), cmd.n);\n");
5992 f.write(" CheckBytesWrittenMatchesExpectedSize(\n")
5993 f.write(" next_cmd, sizeof(cmd) +\n")
5994 f.write(" RoundSizeToMultipleOfEntries(arraysize(ids) * 4u));\n")
5995 f.write(" // TODO(gman): Check that ids were inserted;\n")
5996 f.write("}\n")
5997 f.write("\n")
6000 class CreateHandler(TypeHandler):
6001 """Handler for glCreate___ type functions."""
6003 def InitFunction(self, func):
6004 """Overrriden from TypeHandler."""
6005 func.AddCmdArg(Argument("client_id", 'uint32_t'))
6007 def __GetResourceType(self, func):
6008 if func.return_type == "GLsync":
6009 return "Sync"
6010 else:
6011 return func.name[6:] # Create*
6013 def WriteServiceUnitTest(self, func, f, *extras):
6014 """Overrriden from TypeHandler."""
6015 valid_test = """
6016 TEST_P(%(test_name)s, %(name)sValidArgs) {
6017 %(id_type_cast)sEXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s))
6018 .WillOnce(Return(%(const_service_id)s));
6019 SpecializedSetup<cmds::%(name)s, 0>(true);
6020 cmds::%(name)s cmd;
6021 cmd.Init(%(args)s%(comma)skNewClientId);"""
6022 if func.IsUnsafe():
6023 valid_test += """
6024 decoder_->set_unsafe_es3_apis_enabled(true);"""
6025 valid_test += """
6026 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
6027 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
6028 if func.IsUnsafe():
6029 valid_test += """
6030 %(return_type)s service_id = 0;
6031 EXPECT_TRUE(Get%(resource_type)sServiceId(kNewClientId, &service_id));
6032 EXPECT_EQ(%(const_service_id)s, service_id);
6033 decoder_->set_unsafe_es3_apis_enabled(false);
6034 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));
6037 else:
6038 valid_test += """
6039 EXPECT_TRUE(Get%(resource_type)s(kNewClientId));
6042 comma = ""
6043 cmd_arg_count = 0
6044 for arg in func.GetOriginalArgs():
6045 if not arg.IsConstant():
6046 cmd_arg_count += 1
6047 if cmd_arg_count:
6048 comma = ", "
6049 if func.return_type == 'GLsync':
6050 id_type_cast = ("const GLsync kNewServiceIdGLuint = reinterpret_cast"
6051 "<GLsync>(kNewServiceId);\n ")
6052 const_service_id = "kNewServiceIdGLuint"
6053 else:
6054 id_type_cast = ""
6055 const_service_id = "kNewServiceId"
6056 self.WriteValidUnitTest(func, f, valid_test, {
6057 'comma': comma,
6058 'resource_type': self.__GetResourceType(func),
6059 'return_type': func.return_type,
6060 'id_type_cast': id_type_cast,
6061 'const_service_id': const_service_id,
6062 }, *extras)
6063 invalid_test = """
6064 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
6065 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
6066 SpecializedSetup<cmds::%(name)s, 0>(false);
6067 cmds::%(name)s cmd;
6068 cmd.Init(%(args)s%(comma)skNewClientId);
6069 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));%(gl_error_test)s
6072 self.WriteInvalidUnitTest(func, f, invalid_test, {
6073 'comma': comma,
6074 }, *extras)
6076 def WriteHandlerImplementation (self, func, f):
6077 """Overrriden from TypeHandler."""
6078 if func.IsUnsafe():
6079 code = """ uint32_t client_id = c.client_id;
6080 %(return_type)s service_id = 0;
6081 if (group_->Get%(resource_name)sServiceId(client_id, &service_id)) {
6082 return error::kInvalidArguments;
6084 service_id = %(gl_func_name)s(%(gl_args)s);
6085 if (service_id) {
6086 group_->Add%(resource_name)sId(client_id, service_id);
6089 else:
6090 code = """ uint32_t client_id = c.client_id;
6091 if (Get%(resource_name)s(client_id)) {
6092 return error::kInvalidArguments;
6094 %(return_type)s service_id = %(gl_func_name)s(%(gl_args)s);
6095 if (service_id) {
6096 Create%(resource_name)s(client_id, service_id%(gl_args_with_comma)s);
6099 f.write(code % {
6100 'resource_name': self.__GetResourceType(func),
6101 'return_type': func.return_type,
6102 'gl_func_name': func.GetGLFunctionName(),
6103 'gl_args': func.MakeOriginalArgString(""),
6104 'gl_args_with_comma': func.MakeOriginalArgString("", True) })
6106 def WriteGLES2Implementation(self, func, f):
6107 """Overrriden from TypeHandler."""
6108 f.write("%s GLES2Implementation::%s(%s) {\n" %
6109 (func.return_type, func.original_name,
6110 func.MakeTypedOriginalArgString("")))
6111 f.write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
6112 func.WriteDestinationInitalizationValidation(f)
6113 self.WriteClientGLCallLog(func, f)
6114 for arg in func.GetOriginalArgs():
6115 arg.WriteClientSideValidationCode(f, func)
6116 f.write(" GLuint client_id;\n")
6117 if func.return_type == "GLsync":
6118 f.write(
6119 " GetIdHandler(id_namespaces::kSyncs)->\n")
6120 else:
6121 f.write(
6122 " GetIdHandler(id_namespaces::kProgramsAndShaders)->\n")
6123 f.write(" MakeIds(this, 0, 1, &client_id);\n")
6124 f.write(" helper_->%s(%s);\n" %
6125 (func.name, func.MakeCmdArgString("")))
6126 f.write(' GPU_CLIENT_LOG("returned " << client_id);\n')
6127 f.write(" CheckGLError();\n")
6128 if func.return_type == "GLsync":
6129 f.write(" return reinterpret_cast<GLsync>(client_id);\n")
6130 else:
6131 f.write(" return client_id;\n")
6132 f.write("}\n")
6133 f.write("\n")
6136 class DeleteHandler(TypeHandler):
6137 """Handler for glDelete___ single resource type functions."""
6139 def WriteServiceImplementation(self, func, f):
6140 """Overrriden from TypeHandler."""
6141 if func.IsUnsafe():
6142 TypeHandler.WriteServiceImplementation(self, func, f)
6143 # HandleDeleteShader and HandleDeleteProgram are manually written.
6144 pass
6146 def WriteGLES2Implementation(self, func, f):
6147 """Overrriden from TypeHandler."""
6148 f.write("%s GLES2Implementation::%s(%s) {\n" %
6149 (func.return_type, func.original_name,
6150 func.MakeTypedOriginalArgString("")))
6151 f.write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
6152 func.WriteDestinationInitalizationValidation(f)
6153 self.WriteClientGLCallLog(func, f)
6154 for arg in func.GetOriginalArgs():
6155 arg.WriteClientSideValidationCode(f, func)
6156 f.write(
6157 " GPU_CLIENT_DCHECK(%s != 0);\n" % func.GetOriginalArgs()[-1].name)
6158 f.write(" %sHelper(%s);\n" %
6159 (func.original_name, func.GetOriginalArgs()[-1].name))
6160 f.write(" CheckGLError();\n")
6161 f.write("}\n")
6162 f.write("\n")
6164 def WriteHandlerImplementation (self, func, f):
6165 """Overrriden from TypeHandler."""
6166 assert len(func.GetOriginalArgs()) == 1
6167 arg = func.GetOriginalArgs()[0]
6168 if func.IsUnsafe():
6169 f.write(""" %(arg_type)s service_id = 0;
6170 if (group_->Get%(resource_type)sServiceId(%(arg_name)s, &service_id)) {
6171 glDelete%(resource_type)s(service_id);
6172 group_->Remove%(resource_type)sId(%(arg_name)s);
6173 } else {
6174 LOCAL_SET_GL_ERROR(
6175 GL_INVALID_VALUE, "gl%(func_name)s", "unknown %(arg_name)s");
6177 """ % { 'resource_type': func.GetInfo('resource_type'),
6178 'arg_name': arg.name,
6179 'arg_type': arg.type,
6180 'func_name': func.original_name })
6181 else:
6182 f.write(" %sHelper(%s);\n" % (func.original_name, arg.name))
6184 class DELnHandler(TypeHandler):
6185 """Handler for glDelete___ type functions."""
6187 def WriteGetDataSizeCode(self, func, f):
6188 """Overrriden from TypeHandler."""
6189 code = """ uint32_t data_size;
6190 if (!SafeMultiplyUint32(n, sizeof(GLuint), &data_size)) {
6191 return error::kOutOfBounds;
6194 f.write(code)
6196 def WriteGLES2ImplementationUnitTest(self, func, f):
6197 """Overrriden from TypeHandler."""
6198 code = """
6199 TEST_F(GLES2ImplementationTest, %(name)s) {
6200 GLuint ids[2] = { k%(types)sStartId, k%(types)sStartId + 1 };
6201 struct Cmds {
6202 cmds::%(name)sImmediate del;
6203 GLuint data[2];
6205 Cmds expected;
6206 expected.del.Init(arraysize(ids), &ids[0]);
6207 expected.data[0] = k%(types)sStartId;
6208 expected.data[1] = k%(types)sStartId + 1;
6209 gl_->%(name)s(arraysize(ids), &ids[0]);
6210 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
6213 f.write(code % {
6214 'name': func.name,
6215 'types': func.GetInfo('resource_types'),
6218 def WriteServiceUnitTest(self, func, f, *extras):
6219 """Overrriden from TypeHandler."""
6220 valid_test = """
6221 TEST_P(%(test_name)s, %(name)sValidArgs) {
6222 EXPECT_CALL(
6223 *gl_,
6224 %(gl_func_name)s(1, Pointee(kService%(upper_resource_name)sId)))
6225 .Times(1);
6226 GetSharedMemoryAs<GLuint*>()[0] = client_%(resource_name)s_id_;
6227 SpecializedSetup<cmds::%(name)s, 0>(true);
6228 cmds::%(name)s cmd;
6229 cmd.Init(%(args)s);
6230 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
6231 EXPECT_EQ(GL_NO_ERROR, GetGLError());
6232 EXPECT_TRUE(
6233 Get%(upper_resource_name)s(client_%(resource_name)s_id_) == NULL);
6236 self.WriteValidUnitTest(func, f, valid_test, {
6237 'resource_name': func.GetInfo('resource_type').lower(),
6238 'upper_resource_name': func.GetInfo('resource_type'),
6239 }, *extras)
6240 invalid_test = """
6241 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
6242 GetSharedMemoryAs<GLuint*>()[0] = kInvalidClientId;
6243 SpecializedSetup<cmds::%(name)s, 0>(false);
6244 cmds::%(name)s cmd;
6245 cmd.Init(%(args)s);
6246 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
6249 self.WriteValidUnitTest(func, f, invalid_test, *extras)
6251 def WriteImmediateServiceUnitTest(self, func, f, *extras):
6252 """Overrriden from TypeHandler."""
6253 valid_test = """
6254 TEST_P(%(test_name)s, %(name)sValidArgs) {
6255 EXPECT_CALL(
6256 *gl_,
6257 %(gl_func_name)s(1, Pointee(kService%(upper_resource_name)sId)))
6258 .Times(1);
6259 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
6260 SpecializedSetup<cmds::%(name)s, 0>(true);
6261 cmd.Init(1, &client_%(resource_name)s_id_);"""
6262 if func.IsUnsafe():
6263 valid_test += """
6264 decoder_->set_unsafe_es3_apis_enabled(true);"""
6265 valid_test += """
6266 EXPECT_EQ(error::kNoError,
6267 ExecuteImmediateCmd(cmd, sizeof(client_%(resource_name)s_id_)));
6268 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
6269 if func.IsUnsafe():
6270 valid_test += """
6271 EXPECT_FALSE(Get%(upper_resource_name)sServiceId(
6272 client_%(resource_name)s_id_, NULL));
6273 decoder_->set_unsafe_es3_apis_enabled(false);
6274 EXPECT_EQ(error::kUnknownCommand,
6275 ExecuteImmediateCmd(cmd, sizeof(client_%(resource_name)s_id_)));
6278 else:
6279 valid_test += """
6280 EXPECT_TRUE(
6281 Get%(upper_resource_name)s(client_%(resource_name)s_id_) == NULL);
6284 self.WriteValidUnitTest(func, f, valid_test, {
6285 'resource_name': func.GetInfo('resource_type').lower(),
6286 'upper_resource_name': func.GetInfo('resource_type'),
6287 }, *extras)
6288 invalid_test = """
6289 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
6290 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
6291 SpecializedSetup<cmds::%(name)s, 0>(false);
6292 GLuint temp = kInvalidClientId;
6293 cmd.Init(1, &temp);"""
6294 if func.IsUnsafe():
6295 invalid_test += """
6296 decoder_->set_unsafe_es3_apis_enabled(true);
6297 EXPECT_EQ(error::kNoError,
6298 ExecuteImmediateCmd(cmd, sizeof(temp)));
6299 decoder_->set_unsafe_es3_apis_enabled(false);
6300 EXPECT_EQ(error::kUnknownCommand,
6301 ExecuteImmediateCmd(cmd, sizeof(temp)));
6304 else:
6305 invalid_test += """
6306 EXPECT_EQ(error::kNoError,
6307 ExecuteImmediateCmd(cmd, sizeof(temp)));
6310 self.WriteValidUnitTest(func, f, invalid_test, *extras)
6312 def WriteHandlerImplementation (self, func, f):
6313 """Overrriden from TypeHandler."""
6314 f.write(" %sHelper(n, %s);\n" %
6315 (func.name, func.GetLastOriginalArg().name))
6317 def WriteImmediateHandlerImplementation (self, func, f):
6318 """Overrriden from TypeHandler."""
6319 if func.IsUnsafe():
6320 f.write(""" for (GLsizei ii = 0; ii < n; ++ii) {
6321 GLuint service_id = 0;
6322 if (group_->Get%(resource_type)sServiceId(
6323 %(last_arg_name)s[ii], &service_id)) {
6324 glDelete%(resource_type)ss(1, &service_id);
6325 group_->Remove%(resource_type)sId(%(last_arg_name)s[ii]);
6328 """ % { 'resource_type': func.GetInfo('resource_type'),
6329 'last_arg_name': func.GetLastOriginalArg().name })
6330 else:
6331 f.write(" %sHelper(n, %s);\n" %
6332 (func.original_name, func.GetLastOriginalArg().name))
6334 def WriteGLES2Implementation(self, func, f):
6335 """Overrriden from TypeHandler."""
6336 impl_decl = func.GetInfo('impl_decl')
6337 if impl_decl == None or impl_decl == True:
6338 args = {
6339 'return_type': func.return_type,
6340 'name': func.original_name,
6341 'typed_args': func.MakeTypedOriginalArgString(""),
6342 'args': func.MakeOriginalArgString(""),
6343 'resource_type': func.GetInfo('resource_type').lower(),
6344 'count_name': func.GetOriginalArgs()[0].name,
6346 f.write(
6347 "%(return_type)s GLES2Implementation::%(name)s(%(typed_args)s) {\n" %
6348 args)
6349 f.write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
6350 func.WriteDestinationInitalizationValidation(f)
6351 self.WriteClientGLCallLog(func, f)
6352 f.write(""" GPU_CLIENT_LOG_CODE_BLOCK({
6353 for (GLsizei i = 0; i < n; ++i) {
6354 GPU_CLIENT_LOG(" " << i << ": " << %s[i]);
6357 """ % func.GetOriginalArgs()[1].name)
6358 f.write(""" GPU_CLIENT_DCHECK_CODE_BLOCK({
6359 for (GLsizei i = 0; i < n; ++i) {
6360 DCHECK(%s[i] != 0);
6363 """ % func.GetOriginalArgs()[1].name)
6364 for arg in func.GetOriginalArgs():
6365 arg.WriteClientSideValidationCode(f, func)
6366 code = """ %(name)sHelper(%(args)s);
6367 CheckGLError();
6371 f.write(code % args)
6373 def WriteImmediateCmdComputeSize(self, func, f):
6374 """Overrriden from TypeHandler."""
6375 f.write(" static uint32_t ComputeDataSize(GLsizei n) {\n")
6376 f.write(
6377 " return static_cast<uint32_t>(sizeof(GLuint) * n); // NOLINT\n")
6378 f.write(" }\n")
6379 f.write("\n")
6380 f.write(" static uint32_t ComputeSize(GLsizei n) {\n")
6381 f.write(" return static_cast<uint32_t>(\n")
6382 f.write(" sizeof(ValueType) + ComputeDataSize(n)); // NOLINT\n")
6383 f.write(" }\n")
6384 f.write("\n")
6386 def WriteImmediateCmdSetHeader(self, func, f):
6387 """Overrriden from TypeHandler."""
6388 f.write(" void SetHeader(GLsizei n) {\n")
6389 f.write(" header.SetCmdByTotalSize<ValueType>(ComputeSize(n));\n")
6390 f.write(" }\n")
6391 f.write("\n")
6393 def WriteImmediateCmdInit(self, func, f):
6394 """Overrriden from TypeHandler."""
6395 last_arg = func.GetLastOriginalArg()
6396 f.write(" void Init(%s, %s _%s) {\n" %
6397 (func.MakeTypedCmdArgString("_"),
6398 last_arg.type, last_arg.name))
6399 f.write(" SetHeader(_n);\n")
6400 args = func.GetCmdArgs()
6401 for arg in args:
6402 f.write(" %s = _%s;\n" % (arg.name, arg.name))
6403 f.write(" memcpy(ImmediateDataAddress(this),\n")
6404 f.write(" _%s, ComputeDataSize(_n));\n" % last_arg.name)
6405 f.write(" }\n")
6406 f.write("\n")
6408 def WriteImmediateCmdSet(self, func, f):
6409 """Overrriden from TypeHandler."""
6410 last_arg = func.GetLastOriginalArg()
6411 copy_args = func.MakeCmdArgString("_", False)
6412 f.write(" void* Set(void* cmd%s, %s _%s) {\n" %
6413 (func.MakeTypedCmdArgString("_", True),
6414 last_arg.type, last_arg.name))
6415 f.write(" static_cast<ValueType*>(cmd)->Init(%s, _%s);\n" %
6416 (copy_args, last_arg.name))
6417 f.write(" const uint32_t size = ComputeSize(_n);\n")
6418 f.write(" return NextImmediateCmdAddressTotalSize<ValueType>("
6419 "cmd, size);\n")
6420 f.write(" }\n")
6421 f.write("\n")
6423 def WriteImmediateCmdHelper(self, func, f):
6424 """Overrriden from TypeHandler."""
6425 code = """ void %(name)s(%(typed_args)s) {
6426 const uint32_t size = gles2::cmds::%(name)s::ComputeSize(n);
6427 gles2::cmds::%(name)s* c =
6428 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
6429 if (c) {
6430 c->Init(%(args)s);
6435 f.write(code % {
6436 "name": func.name,
6437 "typed_args": func.MakeTypedOriginalArgString(""),
6438 "args": func.MakeOriginalArgString(""),
6441 def WriteImmediateFormatTest(self, func, f):
6442 """Overrriden from TypeHandler."""
6443 f.write("TEST_F(GLES2FormatTest, %s) {\n" % func.name)
6444 f.write(" static GLuint ids[] = { 12, 23, 34, };\n")
6445 f.write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
6446 (func.name, func.name))
6447 f.write(" void* next_cmd = cmd.Set(\n")
6448 f.write(" &cmd, static_cast<GLsizei>(arraysize(ids)), ids);\n")
6449 f.write(" EXPECT_EQ(static_cast<uint32_t>(cmds::%s::kCmdId),\n" %
6450 func.name)
6451 f.write(" cmd.header.command);\n")
6452 f.write(" EXPECT_EQ(sizeof(cmd) +\n")
6453 f.write(" RoundSizeToMultipleOfEntries(cmd.n * 4u),\n")
6454 f.write(" cmd.header.size * 4u);\n")
6455 f.write(" EXPECT_EQ(static_cast<GLsizei>(arraysize(ids)), cmd.n);\n");
6456 f.write(" CheckBytesWrittenMatchesExpectedSize(\n")
6457 f.write(" next_cmd, sizeof(cmd) +\n")
6458 f.write(" RoundSizeToMultipleOfEntries(arraysize(ids) * 4u));\n")
6459 f.write(" // TODO(gman): Check that ids were inserted;\n")
6460 f.write("}\n")
6461 f.write("\n")
6464 class GETnHandler(TypeHandler):
6465 """Handler for GETn for glGetBooleanv, glGetFloatv, ... type functions."""
6467 def NeedsDataTransferFunction(self, func):
6468 """Overriden from TypeHandler."""
6469 return False
6471 def WriteServiceImplementation(self, func, f):
6472 """Overrriden from TypeHandler."""
6473 self.WriteServiceHandlerFunctionHeader(func, f)
6474 last_arg = func.GetLastOriginalArg()
6475 # All except shm_id and shm_offset.
6476 all_but_last_args = func.GetCmdArgs()[:-2]
6477 for arg in all_but_last_args:
6478 arg.WriteGetCode(f)
6480 code = """ typedef cmds::%(func_name)s::Result Result;
6481 GLsizei num_values = 0;
6482 GetNumValuesReturnedForGLGet(pname, &num_values);
6483 Result* result = GetSharedMemoryAs<Result*>(
6484 c.%(last_arg_name)s_shm_id, c.%(last_arg_name)s_shm_offset,
6485 Result::ComputeSize(num_values));
6486 %(last_arg_type)s %(last_arg_name)s = result ? result->GetData() : NULL;
6488 f.write(code % {
6489 'last_arg_type': last_arg.type,
6490 'last_arg_name': last_arg.name,
6491 'func_name': func.name,
6493 func.WriteHandlerValidation(f)
6494 code = """ // Check that the client initialized the result.
6495 if (result->size != 0) {
6496 return error::kInvalidArguments;
6499 shadowed = func.GetInfo('shadowed')
6500 if not shadowed:
6501 f.write(' LOCAL_COPY_REAL_GL_ERRORS_TO_WRAPPER("%s");\n' % func.name)
6502 f.write(code)
6503 func.WriteHandlerImplementation(f)
6504 if shadowed:
6505 code = """ result->SetNumResults(num_values);
6506 return error::kNoError;
6509 else:
6510 code = """ GLenum error = LOCAL_PEEK_GL_ERROR("%(func_name)s");
6511 if (error == GL_NO_ERROR) {
6512 result->SetNumResults(num_values);
6514 return error::kNoError;
6518 f.write(code % {'func_name': func.name})
6520 def WriteGLES2Implementation(self, func, f):
6521 """Overrriden from TypeHandler."""
6522 impl_decl = func.GetInfo('impl_decl')
6523 if impl_decl == None or impl_decl == True:
6524 f.write("%s GLES2Implementation::%s(%s) {\n" %
6525 (func.return_type, func.original_name,
6526 func.MakeTypedOriginalArgString("")))
6527 f.write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
6528 func.WriteDestinationInitalizationValidation(f)
6529 self.WriteClientGLCallLog(func, f)
6530 for arg in func.GetOriginalArgs():
6531 arg.WriteClientSideValidationCode(f, func)
6532 all_but_last_args = func.GetOriginalArgs()[:-1]
6533 args = []
6534 has_length_arg = False
6535 for arg in all_but_last_args:
6536 if arg.type == 'GLsync':
6537 args.append('ToGLuint(%s)' % arg.name)
6538 elif arg.name.endswith('size') and arg.type == 'GLsizei':
6539 continue
6540 elif arg.name == 'length':
6541 has_length_arg = True
6542 continue
6543 else:
6544 args.append(arg.name)
6545 arg_string = ", ".join(args)
6546 all_arg_string = (
6547 ", ".join([
6548 "%s" % arg.name
6549 for arg in func.GetOriginalArgs() if not arg.IsConstant()]))
6550 self.WriteTraceEvent(func, f)
6551 code = """ if (%(func_name)sHelper(%(all_arg_string)s)) {
6552 return;
6554 typedef cmds::%(func_name)s::Result Result;
6555 Result* result = GetResultAs<Result*>();
6556 if (!result) {
6557 return;
6559 result->SetNumResults(0);
6560 helper_->%(func_name)s(%(arg_string)s,
6561 GetResultShmId(), GetResultShmOffset());
6562 WaitForCmd();
6563 result->CopyResult(%(last_arg_name)s);
6564 GPU_CLIENT_LOG_CODE_BLOCK({
6565 for (int32_t i = 0; i < result->GetNumResults(); ++i) {
6566 GPU_CLIENT_LOG(" " << i << ": " << result->GetData()[i]);
6568 });"""
6569 if has_length_arg:
6570 code += """
6571 if (length) {
6572 *length = result->GetNumResults();
6573 }"""
6574 code += """
6575 CheckGLError();
6578 f.write(code % {
6579 'func_name': func.name,
6580 'arg_string': arg_string,
6581 'all_arg_string': all_arg_string,
6582 'last_arg_name': func.GetLastOriginalArg().name,
6585 def WriteGLES2ImplementationUnitTest(self, func, f):
6586 """Writes the GLES2 Implemention unit test."""
6587 code = """
6588 TEST_F(GLES2ImplementationTest, %(name)s) {
6589 struct Cmds {
6590 cmds::%(name)s cmd;
6592 typedef cmds::%(name)s::Result::Type ResultType;
6593 ResultType result = 0;
6594 Cmds expected;
6595 ExpectedMemoryInfo result1 = GetExpectedResultMemory(
6596 sizeof(uint32_t) + sizeof(ResultType));
6597 expected.cmd.Init(%(cmd_args)s, result1.id, result1.offset);
6598 EXPECT_CALL(*command_buffer(), OnFlush())
6599 .WillOnce(SetMemory(result1.ptr, SizedResultHelper<ResultType>(1)))
6600 .RetiresOnSaturation();
6601 gl_->%(name)s(%(args)s, &result);
6602 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
6603 EXPECT_EQ(static_cast<ResultType>(1), result);
6606 first_cmd_arg = func.GetCmdArgs()[0].GetValidNonCachedClientSideCmdArg(func)
6607 if not first_cmd_arg:
6608 return
6610 first_gl_arg = func.GetOriginalArgs()[0].GetValidNonCachedClientSideArg(
6611 func)
6613 cmd_arg_strings = [first_cmd_arg]
6614 for arg in func.GetCmdArgs()[1:-2]:
6615 cmd_arg_strings.append(arg.GetValidClientSideCmdArg(func))
6616 gl_arg_strings = [first_gl_arg]
6617 for arg in func.GetOriginalArgs()[1:-1]:
6618 gl_arg_strings.append(arg.GetValidClientSideArg(func))
6620 f.write(code % {
6621 'name': func.name,
6622 'args': ", ".join(gl_arg_strings),
6623 'cmd_args': ", ".join(cmd_arg_strings),
6626 def WriteServiceUnitTest(self, func, f, *extras):
6627 """Overrriden from TypeHandler."""
6628 valid_test = """
6629 TEST_P(%(test_name)s, %(name)sValidArgs) {
6630 EXPECT_CALL(*gl_, GetError())
6631 .WillOnce(Return(GL_NO_ERROR))
6632 .WillOnce(Return(GL_NO_ERROR))
6633 .RetiresOnSaturation();
6634 SpecializedSetup<cmds::%(name)s, 0>(true);
6635 typedef cmds::%(name)s::Result Result;
6636 Result* result = static_cast<Result*>(shared_memory_address_);
6637 EXPECT_CALL(*gl_, %(gl_func_name)s(%(local_gl_args)s));
6638 result->size = 0;
6639 cmds::%(name)s cmd;
6640 cmd.Init(%(cmd_args)s);"""
6641 if func.IsUnsafe():
6642 valid_test += """
6643 decoder_->set_unsafe_es3_apis_enabled(true);"""
6644 valid_test += """
6645 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
6646 EXPECT_EQ(decoder_->GetGLES2Util()->GLGetNumValuesReturned(
6647 %(valid_pname)s),
6648 result->GetNumResults());
6649 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
6650 if func.IsUnsafe():
6651 valid_test += """
6652 decoder_->set_unsafe_es3_apis_enabled(false);
6653 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));"""
6654 valid_test += """
6657 gl_arg_strings = []
6658 cmd_arg_strings = []
6659 valid_pname = ''
6660 for arg in func.GetOriginalArgs()[:-1]:
6661 if arg.name == 'length':
6662 gl_arg_value = 'nullptr'
6663 elif arg.name.endswith('size'):
6664 gl_arg_value = ("decoder_->GetGLES2Util()->GLGetNumValuesReturned(%s)" %
6665 valid_pname)
6666 elif arg.type == 'GLsync':
6667 gl_arg_value = 'reinterpret_cast<GLsync>(kServiceSyncId)'
6668 else:
6669 gl_arg_value = arg.GetValidGLArg(func)
6670 gl_arg_strings.append(gl_arg_value)
6671 if arg.name == 'pname':
6672 valid_pname = gl_arg_value
6673 if arg.name.endswith('size') or arg.name == 'length':
6674 continue
6675 if arg.type == 'GLsync':
6676 arg_value = 'client_sync_id_'
6677 else:
6678 arg_value = arg.GetValidArg(func)
6679 cmd_arg_strings.append(arg_value)
6680 if func.GetInfo('gl_test_func') == 'glGetIntegerv':
6681 gl_arg_strings.append("_")
6682 else:
6683 gl_arg_strings.append("result->GetData()")
6684 cmd_arg_strings.append("shared_memory_id_")
6685 cmd_arg_strings.append("shared_memory_offset_")
6687 self.WriteValidUnitTest(func, f, valid_test, {
6688 'local_gl_args': ", ".join(gl_arg_strings),
6689 'cmd_args': ", ".join(cmd_arg_strings),
6690 'valid_pname': valid_pname,
6691 }, *extras)
6693 if not func.IsUnsafe():
6694 invalid_test = """
6695 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
6696 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
6697 SpecializedSetup<cmds::%(name)s, 0>(false);
6698 cmds::%(name)s::Result* result =
6699 static_cast<cmds::%(name)s::Result*>(shared_memory_address_);
6700 result->size = 0;
6701 cmds::%(name)s cmd;
6702 cmd.Init(%(args)s);
6703 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));
6704 EXPECT_EQ(0u, result->size);%(gl_error_test)s
6707 self.WriteInvalidUnitTest(func, f, invalid_test, *extras)
6709 class ArrayArgTypeHandler(TypeHandler):
6710 """Base class for type handlers that handle args that are arrays"""
6712 def GetArrayType(self, func):
6713 """Returns the type of the element in the element array being PUT to."""
6714 for arg in func.GetOriginalArgs():
6715 if arg.IsPointer():
6716 element_type = arg.GetPointedType()
6717 return element_type
6719 # Special case: array type handler is used for a function that is forwarded
6720 # to the actual array type implementation
6721 element_type = func.GetOriginalArgs()[-1].type
6722 assert all(arg.type == element_type \
6723 for arg in func.GetOriginalArgs()[-self.GetArrayCount(func):])
6724 return element_type
6726 def GetArrayCount(self, func):
6727 """Returns the count of the elements in the array being PUT to."""
6728 return func.GetInfo('count')
6730 class PUTHandler(ArrayArgTypeHandler):
6731 """Handler for glTexParameter_v, glVertexAttrib_v functions."""
6733 def WriteServiceUnitTest(self, func, f, *extras):
6734 """Writes the service unit test for a command."""
6735 expected_call = "EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));"
6736 if func.GetInfo("first_element_only"):
6737 gl_arg_strings = [
6738 arg.GetValidGLArg(func) for arg in func.GetOriginalArgs()
6740 gl_arg_strings[-1] = "*" + gl_arg_strings[-1]
6741 expected_call = ("EXPECT_CALL(*gl_, %%(gl_func_name)s(%s));" %
6742 ", ".join(gl_arg_strings))
6743 valid_test = """
6744 TEST_P(%(test_name)s, %(name)sValidArgs) {
6745 SpecializedSetup<cmds::%(name)s, 0>(true);
6746 cmds::%(name)s cmd;
6747 cmd.Init(%(args)s);
6748 GetSharedMemoryAs<%(data_type)s*>()[0] = %(data_value)s;
6749 %(expected_call)s
6750 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
6751 EXPECT_EQ(GL_NO_ERROR, GetGLError());
6754 extra = {
6755 'data_type': self.GetArrayType(func),
6756 'data_value': func.GetInfo('data_value') or '0',
6757 'expected_call': expected_call,
6759 self.WriteValidUnitTest(func, f, valid_test, extra, *extras)
6761 invalid_test = """
6762 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
6763 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
6764 SpecializedSetup<cmds::%(name)s, 0>(false);
6765 cmds::%(name)s cmd;
6766 cmd.Init(%(args)s);
6767 GetSharedMemoryAs<%(data_type)s*>()[0] = %(data_value)s;
6768 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
6771 self.WriteInvalidUnitTest(func, f, invalid_test, extra, *extras)
6773 def WriteImmediateServiceUnitTest(self, func, f, *extras):
6774 """Writes the service unit test for a command."""
6775 valid_test = """
6776 TEST_P(%(test_name)s, %(name)sValidArgs) {
6777 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
6778 SpecializedSetup<cmds::%(name)s, 0>(true);
6779 %(data_type)s temp[%(data_count)s] = { %(data_value)s, };
6780 cmd.Init(%(gl_args)s, &temp[0]);
6781 EXPECT_CALL(
6782 *gl_,
6783 %(gl_func_name)s(%(gl_args)s, %(data_ref)sreinterpret_cast<
6784 %(data_type)s*>(ImmediateDataAddress(&cmd))));"""
6785 if func.IsUnsafe():
6786 valid_test += """
6787 decoder_->set_unsafe_es3_apis_enabled(true);"""
6788 valid_test += """
6789 EXPECT_EQ(error::kNoError,
6790 ExecuteImmediateCmd(cmd, sizeof(temp)));
6791 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
6792 if func.IsUnsafe():
6793 valid_test += """
6794 decoder_->set_unsafe_es3_apis_enabled(false);
6795 EXPECT_EQ(error::kUnknownCommand,
6796 ExecuteImmediateCmd(cmd, sizeof(temp)));"""
6797 valid_test += """
6800 gl_arg_strings = [
6801 arg.GetValidGLArg(func) for arg in func.GetOriginalArgs()[0:-1]
6803 gl_any_strings = ["_"] * len(gl_arg_strings)
6805 extra = {
6806 'data_ref': ("*" if func.GetInfo('first_element_only') else ""),
6807 'data_type': self.GetArrayType(func),
6808 'data_count': self.GetArrayCount(func),
6809 'data_value': func.GetInfo('data_value') or '0',
6810 'gl_args': ", ".join(gl_arg_strings),
6811 'gl_any_args': ", ".join(gl_any_strings),
6813 self.WriteValidUnitTest(func, f, valid_test, extra, *extras)
6815 invalid_test = """
6816 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
6817 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();"""
6818 if func.IsUnsafe():
6819 invalid_test += """
6820 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_any_args)s, _)).Times(1);
6822 else:
6823 invalid_test += """
6824 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_any_args)s, _)).Times(0);
6826 invalid_test += """
6827 SpecializedSetup<cmds::%(name)s, 0>(false);
6828 %(data_type)s temp[%(data_count)s] = { %(data_value)s, };
6829 cmd.Init(%(all_but_last_args)s, &temp[0]);"""
6830 if func.IsUnsafe():
6831 invalid_test += """
6832 decoder_->set_unsafe_es3_apis_enabled(true);
6833 EXPECT_EQ(error::%(parse_result)s,
6834 ExecuteImmediateCmd(cmd, sizeof(temp)));
6835 decoder_->set_unsafe_es3_apis_enabled(false);
6838 else:
6839 invalid_test += """
6840 EXPECT_EQ(error::%(parse_result)s,
6841 ExecuteImmediateCmd(cmd, sizeof(temp)));
6842 %(gl_error_test)s
6845 self.WriteInvalidUnitTest(func, f, invalid_test, extra, *extras)
6847 def WriteGetDataSizeCode(self, func, f):
6848 """Overrriden from TypeHandler."""
6849 code = """ uint32_t data_size;
6850 if (!ComputeDataSize(1, sizeof(%s), %d, &data_size)) {
6851 return error::kOutOfBounds;
6854 f.write(code % (self.GetArrayType(func), self.GetArrayCount(func)))
6855 if func.IsImmediate():
6856 f.write(" if (data_size > immediate_data_size) {\n")
6857 f.write(" return error::kOutOfBounds;\n")
6858 f.write(" }\n")
6860 def __NeedsToCalcDataCount(self, func):
6861 use_count_func = func.GetInfo('use_count_func')
6862 return use_count_func != None and use_count_func != False
6864 def WriteGLES2Implementation(self, func, f):
6865 """Overrriden from TypeHandler."""
6866 impl_func = func.GetInfo('impl_func')
6867 if (impl_func != None and impl_func != True):
6868 return;
6869 f.write("%s GLES2Implementation::%s(%s) {\n" %
6870 (func.return_type, func.original_name,
6871 func.MakeTypedOriginalArgString("")))
6872 f.write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
6873 func.WriteDestinationInitalizationValidation(f)
6874 self.WriteClientGLCallLog(func, f)
6876 if self.__NeedsToCalcDataCount(func):
6877 f.write(" size_t count = GLES2Util::Calc%sDataCount(%s);\n" %
6878 (func.name, func.GetOriginalArgs()[0].name))
6879 f.write(" DCHECK_LE(count, %du);\n" % self.GetArrayCount(func))
6880 else:
6881 f.write(" size_t count = %d;" % self.GetArrayCount(func))
6882 f.write(" for (size_t ii = 0; ii < count; ++ii)\n")
6883 f.write(' GPU_CLIENT_LOG("value[" << ii << "]: " << %s[ii]);\n' %
6884 func.GetLastOriginalArg().name)
6885 for arg in func.GetOriginalArgs():
6886 arg.WriteClientSideValidationCode(f, func)
6887 f.write(" helper_->%sImmediate(%s);\n" %
6888 (func.name, func.MakeOriginalArgString("")))
6889 f.write(" CheckGLError();\n")
6890 f.write("}\n")
6891 f.write("\n")
6893 def WriteGLES2ImplementationUnitTest(self, func, f):
6894 """Writes the GLES2 Implemention unit test."""
6895 client_test = func.GetInfo('client_test')
6896 if (client_test != None and client_test != True):
6897 return;
6898 code = """
6899 TEST_F(GLES2ImplementationTest, %(name)s) {
6900 %(type)s data[%(count)d] = {0};
6901 struct Cmds {
6902 cmds::%(name)sImmediate cmd;
6903 %(type)s data[%(count)d];
6906 for (int jj = 0; jj < %(count)d; ++jj) {
6907 data[jj] = static_cast<%(type)s>(jj);
6909 Cmds expected;
6910 expected.cmd.Init(%(cmd_args)s, &data[0]);
6911 gl_->%(name)s(%(args)s, &data[0]);
6912 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
6915 cmd_arg_strings = [
6916 arg.GetValidClientSideCmdArg(func) for arg in func.GetCmdArgs()[0:-2]
6918 gl_arg_strings = [
6919 arg.GetValidClientSideArg(func) for arg in func.GetOriginalArgs()[0:-1]
6922 f.write(code % {
6923 'name': func.name,
6924 'type': self.GetArrayType(func),
6925 'count': self.GetArrayCount(func),
6926 'args': ", ".join(gl_arg_strings),
6927 'cmd_args': ", ".join(cmd_arg_strings),
6930 def WriteImmediateCmdComputeSize(self, func, f):
6931 """Overrriden from TypeHandler."""
6932 f.write(" static uint32_t ComputeDataSize() {\n")
6933 f.write(" return static_cast<uint32_t>(\n")
6934 f.write(" sizeof(%s) * %d);\n" %
6935 (self.GetArrayType(func), self.GetArrayCount(func)))
6936 f.write(" }\n")
6937 f.write("\n")
6938 if self.__NeedsToCalcDataCount(func):
6939 f.write(" static uint32_t ComputeEffectiveDataSize(%s %s) {\n" %
6940 (func.GetOriginalArgs()[0].type,
6941 func.GetOriginalArgs()[0].name))
6942 f.write(" return static_cast<uint32_t>(\n")
6943 f.write(" sizeof(%s) * GLES2Util::Calc%sDataCount(%s));\n" %
6944 (self.GetArrayType(func), func.original_name,
6945 func.GetOriginalArgs()[0].name))
6946 f.write(" }\n")
6947 f.write("\n")
6948 f.write(" static uint32_t ComputeSize() {\n")
6949 f.write(" return static_cast<uint32_t>(\n")
6950 f.write(
6951 " sizeof(ValueType) + ComputeDataSize());\n")
6952 f.write(" }\n")
6953 f.write("\n")
6955 def WriteImmediateCmdSetHeader(self, func, f):
6956 """Overrriden from TypeHandler."""
6957 f.write(" void SetHeader() {\n")
6958 f.write(
6959 " header.SetCmdByTotalSize<ValueType>(ComputeSize());\n")
6960 f.write(" }\n")
6961 f.write("\n")
6963 def WriteImmediateCmdInit(self, func, f):
6964 """Overrriden from TypeHandler."""
6965 last_arg = func.GetLastOriginalArg()
6966 f.write(" void Init(%s, %s _%s) {\n" %
6967 (func.MakeTypedCmdArgString("_"),
6968 last_arg.type, last_arg.name))
6969 f.write(" SetHeader();\n")
6970 args = func.GetCmdArgs()
6971 for arg in args:
6972 f.write(" %s = _%s;\n" % (arg.name, arg.name))
6973 f.write(" memcpy(ImmediateDataAddress(this),\n")
6974 if self.__NeedsToCalcDataCount(func):
6975 f.write(" _%s, ComputeEffectiveDataSize(%s));" %
6976 (last_arg.name, func.GetOriginalArgs()[0].name))
6977 f.write("""
6978 DCHECK_GE(ComputeDataSize(), ComputeEffectiveDataSize(%(arg)s));
6979 char* pointer = reinterpret_cast<char*>(ImmediateDataAddress(this)) +
6980 ComputeEffectiveDataSize(%(arg)s);
6981 memset(pointer, 0, ComputeDataSize() - ComputeEffectiveDataSize(%(arg)s));
6982 """ % { 'arg': func.GetOriginalArgs()[0].name, })
6983 else:
6984 f.write(" _%s, ComputeDataSize());\n" % last_arg.name)
6985 f.write(" }\n")
6986 f.write("\n")
6988 def WriteImmediateCmdSet(self, func, f):
6989 """Overrriden from TypeHandler."""
6990 last_arg = func.GetLastOriginalArg()
6991 copy_args = func.MakeCmdArgString("_", False)
6992 f.write(" void* Set(void* cmd%s, %s _%s) {\n" %
6993 (func.MakeTypedCmdArgString("_", True),
6994 last_arg.type, last_arg.name))
6995 f.write(" static_cast<ValueType*>(cmd)->Init(%s, _%s);\n" %
6996 (copy_args, last_arg.name))
6997 f.write(" const uint32_t size = ComputeSize();\n")
6998 f.write(" return NextImmediateCmdAddressTotalSize<ValueType>("
6999 "cmd, size);\n")
7000 f.write(" }\n")
7001 f.write("\n")
7003 def WriteImmediateCmdHelper(self, func, f):
7004 """Overrriden from TypeHandler."""
7005 code = """ void %(name)s(%(typed_args)s) {
7006 const uint32_t size = gles2::cmds::%(name)s::ComputeSize();
7007 gles2::cmds::%(name)s* c =
7008 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
7009 if (c) {
7010 c->Init(%(args)s);
7015 f.write(code % {
7016 "name": func.name,
7017 "typed_args": func.MakeTypedOriginalArgString(""),
7018 "args": func.MakeOriginalArgString(""),
7021 def WriteImmediateFormatTest(self, func, f):
7022 """Overrriden from TypeHandler."""
7023 f.write("TEST_F(GLES2FormatTest, %s) {\n" % func.name)
7024 f.write(" const int kSomeBaseValueToTestWith = 51;\n")
7025 f.write(" static %s data[] = {\n" % self.GetArrayType(func))
7026 for v in range(0, self.GetArrayCount(func)):
7027 f.write(" static_cast<%s>(kSomeBaseValueToTestWith + %d),\n" %
7028 (self.GetArrayType(func), v))
7029 f.write(" };\n")
7030 f.write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
7031 (func.name, func.name))
7032 f.write(" void* next_cmd = cmd.Set(\n")
7033 f.write(" &cmd")
7034 args = func.GetCmdArgs()
7035 for value, arg in enumerate(args):
7036 f.write(",\n static_cast<%s>(%d)" % (arg.type, value + 11))
7037 f.write(",\n data);\n")
7038 args = func.GetCmdArgs()
7039 f.write(" EXPECT_EQ(static_cast<uint32_t>(cmds::%s::kCmdId),\n"
7040 % func.name)
7041 f.write(" cmd.header.command);\n")
7042 f.write(" EXPECT_EQ(sizeof(cmd) +\n")
7043 f.write(" RoundSizeToMultipleOfEntries(sizeof(data)),\n")
7044 f.write(" cmd.header.size * 4u);\n")
7045 for value, arg in enumerate(args):
7046 f.write(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);\n" %
7047 (arg.type, value + 11, arg.name))
7048 f.write(" CheckBytesWrittenMatchesExpectedSize(\n")
7049 f.write(" next_cmd, sizeof(cmd) +\n")
7050 f.write(" RoundSizeToMultipleOfEntries(sizeof(data)));\n")
7051 f.write(" // TODO(gman): Check that data was inserted;\n")
7052 f.write("}\n")
7053 f.write("\n")
7056 class PUTnHandler(ArrayArgTypeHandler):
7057 """Handler for PUTn 'glUniform__v' type functions."""
7059 def WriteServiceUnitTest(self, func, f, *extras):
7060 """Overridden from TypeHandler."""
7061 ArrayArgTypeHandler.WriteServiceUnitTest(self, func, f, *extras)
7063 valid_test = """
7064 TEST_P(%(test_name)s, %(name)sValidArgsCountTooLarge) {
7065 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
7066 SpecializedSetup<cmds::%(name)s, 0>(true);
7067 cmds::%(name)s cmd;
7068 cmd.Init(%(args)s);
7069 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
7070 EXPECT_EQ(GL_NO_ERROR, GetGLError());
7073 gl_arg_strings = []
7074 arg_strings = []
7075 for count, arg in enumerate(func.GetOriginalArgs()):
7076 # hardcoded to match unit tests.
7077 if count == 0:
7078 # the location of the second element of the 2nd uniform.
7079 # defined in GLES2DecoderBase::SetupShaderForUniform
7080 gl_arg_strings.append("3")
7081 arg_strings.append("ProgramManager::MakeFakeLocation(1, 1)")
7082 elif count == 1:
7083 # the number of elements that gl will be called with.
7084 gl_arg_strings.append("3")
7085 # the number of elements requested in the command.
7086 arg_strings.append("5")
7087 else:
7088 gl_arg_strings.append(arg.GetValidGLArg(func))
7089 if not arg.IsConstant():
7090 arg_strings.append(arg.GetValidArg(func))
7091 extra = {
7092 'gl_args': ", ".join(gl_arg_strings),
7093 'args': ", ".join(arg_strings),
7095 self.WriteValidUnitTest(func, f, valid_test, extra, *extras)
7097 def WriteImmediateServiceUnitTest(self, func, f, *extras):
7098 """Overridden from TypeHandler."""
7099 valid_test = """
7100 TEST_P(%(test_name)s, %(name)sValidArgs) {
7101 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
7102 EXPECT_CALL(
7103 *gl_,
7104 %(gl_func_name)s(%(gl_args)s,
7105 reinterpret_cast<%(data_type)s*>(ImmediateDataAddress(&cmd))));
7106 SpecializedSetup<cmds::%(name)s, 0>(true);
7107 %(data_type)s temp[%(data_count)s * 2] = { 0, };
7108 cmd.Init(%(args)s, &temp[0]);"""
7109 if func.IsUnsafe():
7110 valid_test += """
7111 decoder_->set_unsafe_es3_apis_enabled(true);"""
7112 valid_test += """
7113 EXPECT_EQ(error::kNoError,
7114 ExecuteImmediateCmd(cmd, sizeof(temp)));
7115 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
7116 if func.IsUnsafe():
7117 valid_test += """
7118 decoder_->set_unsafe_es3_apis_enabled(false);
7119 EXPECT_EQ(error::kUnknownCommand,
7120 ExecuteImmediateCmd(cmd, sizeof(temp)));"""
7121 valid_test += """
7124 gl_arg_strings = []
7125 gl_any_strings = []
7126 arg_strings = []
7127 for arg in func.GetOriginalArgs()[0:-1]:
7128 gl_arg_strings.append(arg.GetValidGLArg(func))
7129 gl_any_strings.append("_")
7130 if not arg.IsConstant():
7131 arg_strings.append(arg.GetValidArg(func))
7132 extra = {
7133 'data_type': self.GetArrayType(func),
7134 'data_count': self.GetArrayCount(func),
7135 'args': ", ".join(arg_strings),
7136 'gl_args': ", ".join(gl_arg_strings),
7137 'gl_any_args': ", ".join(gl_any_strings),
7139 self.WriteValidUnitTest(func, f, valid_test, extra, *extras)
7141 invalid_test = """
7142 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
7143 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
7144 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_any_args)s, _)).Times(0);
7145 SpecializedSetup<cmds::%(name)s, 0>(false);
7146 %(data_type)s temp[%(data_count)s * 2] = { 0, };
7147 cmd.Init(%(all_but_last_args)s, &temp[0]);
7148 EXPECT_EQ(error::%(parse_result)s,
7149 ExecuteImmediateCmd(cmd, sizeof(temp)));%(gl_error_test)s
7152 self.WriteInvalidUnitTest(func, f, invalid_test, extra, *extras)
7154 def WriteGetDataSizeCode(self, func, f):
7155 """Overrriden from TypeHandler."""
7156 code = """ uint32_t data_size;
7157 if (!ComputeDataSize(count, sizeof(%s), %d, &data_size)) {
7158 return error::kOutOfBounds;
7161 f.write(code % (self.GetArrayType(func), self.GetArrayCount(func)))
7162 if func.IsImmediate():
7163 f.write(" if (data_size > immediate_data_size) {\n")
7164 f.write(" return error::kOutOfBounds;\n")
7165 f.write(" }\n")
7167 def WriteGLES2Implementation(self, func, f):
7168 """Overrriden from TypeHandler."""
7169 f.write("%s GLES2Implementation::%s(%s) {\n" %
7170 (func.return_type, func.original_name,
7171 func.MakeTypedOriginalArgString("")))
7172 f.write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
7173 func.WriteDestinationInitalizationValidation(f)
7174 self.WriteClientGLCallLog(func, f)
7175 last_pointer_name = func.GetLastOriginalPointerArg().name
7176 f.write(""" GPU_CLIENT_LOG_CODE_BLOCK({
7177 for (GLsizei i = 0; i < count; ++i) {
7178 """)
7179 values_str = ' << ", " << '.join(
7180 ["%s[%d + i * %d]" % (
7181 last_pointer_name, ndx, self.GetArrayCount(func)) for ndx in range(
7182 0, self.GetArrayCount(func))])
7183 f.write(' GPU_CLIENT_LOG(" " << i << ": " << %s);\n' % values_str)
7184 f.write(" }\n });\n")
7185 for arg in func.GetOriginalArgs():
7186 arg.WriteClientSideValidationCode(f, func)
7187 f.write(" helper_->%sImmediate(%s);\n" %
7188 (func.name, func.MakeInitString("")))
7189 f.write(" CheckGLError();\n")
7190 f.write("}\n")
7191 f.write("\n")
7193 def WriteGLES2ImplementationUnitTest(self, func, f):
7194 """Writes the GLES2 Implemention unit test."""
7195 code = """
7196 TEST_F(GLES2ImplementationTest, %(name)s) {
7197 %(type)s data[%(count_param)d][%(count)d] = {{0}};
7198 struct Cmds {
7199 cmds::%(name)sImmediate cmd;
7200 %(type)s data[%(count_param)d][%(count)d];
7203 Cmds expected;
7204 for (int ii = 0; ii < %(count_param)d; ++ii) {
7205 for (int jj = 0; jj < %(count)d; ++jj) {
7206 data[ii][jj] = static_cast<%(type)s>(ii * %(count)d + jj);
7209 expected.cmd.Init(%(cmd_args)s);
7210 gl_->%(name)s(%(args)s);
7211 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
7214 cmd_arg_strings = []
7215 for arg in func.GetCmdArgs():
7216 if arg.name.endswith("_shm_id"):
7217 cmd_arg_strings.append("&data[0][0]")
7218 elif arg.name.endswith("_shm_offset"):
7219 continue
7220 else:
7221 cmd_arg_strings.append(arg.GetValidClientSideCmdArg(func))
7222 gl_arg_strings = []
7223 count_param = 0
7224 for arg in func.GetOriginalArgs():
7225 if arg.IsPointer():
7226 valid_value = "&data[0][0]"
7227 else:
7228 valid_value = arg.GetValidClientSideArg(func)
7229 gl_arg_strings.append(valid_value)
7230 if arg.name == "count":
7231 count_param = int(valid_value)
7232 f.write(code % {
7233 'name': func.name,
7234 'type': self.GetArrayType(func),
7235 'count': self.GetArrayCount(func),
7236 'args': ", ".join(gl_arg_strings),
7237 'cmd_args': ", ".join(cmd_arg_strings),
7238 'count_param': count_param,
7241 # Test constants for invalid values, as they are not tested by the
7242 # service.
7243 constants = [
7244 arg for arg in func.GetOriginalArgs()[0:-1] if arg.IsConstant()
7246 if not constants:
7247 return
7249 code = """
7250 TEST_F(GLES2ImplementationTest, %(name)sInvalidConstantArg%(invalid_index)d) {
7251 %(type)s data[%(count_param)d][%(count)d] = {{0}};
7252 for (int ii = 0; ii < %(count_param)d; ++ii) {
7253 for (int jj = 0; jj < %(count)d; ++jj) {
7254 data[ii][jj] = static_cast<%(type)s>(ii * %(count)d + jj);
7257 gl_->%(name)s(%(args)s);
7258 EXPECT_TRUE(NoCommandsWritten());
7259 EXPECT_EQ(%(gl_error)s, CheckError());
7262 for invalid_arg in constants:
7263 gl_arg_strings = []
7264 invalid = invalid_arg.GetInvalidArg(func)
7265 for arg in func.GetOriginalArgs():
7266 if arg is invalid_arg:
7267 gl_arg_strings.append(invalid[0])
7268 elif arg.IsPointer():
7269 gl_arg_strings.append("&data[0][0]")
7270 else:
7271 valid_value = arg.GetValidClientSideArg(func)
7272 gl_arg_strings.append(valid_value)
7273 if arg.name == "count":
7274 count_param = int(valid_value)
7276 f.write(code % {
7277 'name': func.name,
7278 'invalid_index': func.GetOriginalArgs().index(invalid_arg),
7279 'type': self.GetArrayType(func),
7280 'count': self.GetArrayCount(func),
7281 'args': ", ".join(gl_arg_strings),
7282 'gl_error': invalid[2],
7283 'count_param': count_param,
7287 def WriteImmediateCmdComputeSize(self, func, f):
7288 """Overrriden from TypeHandler."""
7289 f.write(" static uint32_t ComputeDataSize(GLsizei count) {\n")
7290 f.write(" return static_cast<uint32_t>(\n")
7291 f.write(" sizeof(%s) * %d * count); // NOLINT\n" %
7292 (self.GetArrayType(func), self.GetArrayCount(func)))
7293 f.write(" }\n")
7294 f.write("\n")
7295 f.write(" static uint32_t ComputeSize(GLsizei count) {\n")
7296 f.write(" return static_cast<uint32_t>(\n")
7297 f.write(
7298 " sizeof(ValueType) + ComputeDataSize(count)); // NOLINT\n")
7299 f.write(" }\n")
7300 f.write("\n")
7302 def WriteImmediateCmdSetHeader(self, func, f):
7303 """Overrriden from TypeHandler."""
7304 f.write(" void SetHeader(GLsizei count) {\n")
7305 f.write(
7306 " header.SetCmdByTotalSize<ValueType>(ComputeSize(count));\n")
7307 f.write(" }\n")
7308 f.write("\n")
7310 def WriteImmediateCmdInit(self, func, f):
7311 """Overrriden from TypeHandler."""
7312 f.write(" void Init(%s) {\n" %
7313 func.MakeTypedInitString("_"))
7314 f.write(" SetHeader(_count);\n")
7315 args = func.GetCmdArgs()
7316 for arg in args:
7317 f.write(" %s = _%s;\n" % (arg.name, arg.name))
7318 f.write(" memcpy(ImmediateDataAddress(this),\n")
7319 pointer_arg = func.GetLastOriginalPointerArg()
7320 f.write(" _%s, ComputeDataSize(_count));\n" % pointer_arg.name)
7321 f.write(" }\n")
7322 f.write("\n")
7324 def WriteImmediateCmdSet(self, func, f):
7325 """Overrriden from TypeHandler."""
7326 f.write(" void* Set(void* cmd%s) {\n" %
7327 func.MakeTypedInitString("_", True))
7328 f.write(" static_cast<ValueType*>(cmd)->Init(%s);\n" %
7329 func.MakeInitString("_"))
7330 f.write(" const uint32_t size = ComputeSize(_count);\n")
7331 f.write(" return NextImmediateCmdAddressTotalSize<ValueType>("
7332 "cmd, size);\n")
7333 f.write(" }\n")
7334 f.write("\n")
7336 def WriteImmediateCmdHelper(self, func, f):
7337 """Overrriden from TypeHandler."""
7338 code = """ void %(name)s(%(typed_args)s) {
7339 const uint32_t size = gles2::cmds::%(name)s::ComputeSize(count);
7340 gles2::cmds::%(name)s* c =
7341 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
7342 if (c) {
7343 c->Init(%(args)s);
7348 f.write(code % {
7349 "name": func.name,
7350 "typed_args": func.MakeTypedInitString(""),
7351 "args": func.MakeInitString("")
7354 def WriteImmediateFormatTest(self, func, f):
7355 """Overrriden from TypeHandler."""
7356 args = func.GetOriginalArgs()
7357 count_param = 0
7358 for arg in args:
7359 if arg.name == "count":
7360 count_param = int(arg.GetValidClientSideCmdArg(func))
7361 f.write("TEST_F(GLES2FormatTest, %s) {\n" % func.name)
7362 f.write(" const int kSomeBaseValueToTestWith = 51;\n")
7363 f.write(" static %s data[] = {\n" % self.GetArrayType(func))
7364 for v in range(0, self.GetArrayCount(func) * count_param):
7365 f.write(" static_cast<%s>(kSomeBaseValueToTestWith + %d),\n" %
7366 (self.GetArrayType(func), v))
7367 f.write(" };\n")
7368 f.write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
7369 (func.name, func.name))
7370 f.write(" const GLsizei kNumElements = %d;\n" % count_param)
7371 f.write(" const size_t kExpectedCmdSize =\n")
7372 f.write(" sizeof(cmd) + kNumElements * sizeof(%s) * %d;\n" %
7373 (self.GetArrayType(func), self.GetArrayCount(func)))
7374 f.write(" void* next_cmd = cmd.Set(\n")
7375 f.write(" &cmd")
7376 for value, arg in enumerate(args):
7377 if arg.IsPointer():
7378 f.write(",\n data")
7379 elif arg.IsConstant():
7380 continue
7381 else:
7382 f.write(",\n static_cast<%s>(%d)" % (arg.type, value + 1))
7383 f.write(");\n")
7384 f.write(" EXPECT_EQ(static_cast<uint32_t>(cmds::%s::kCmdId),\n" %
7385 func.name)
7386 f.write(" cmd.header.command);\n")
7387 f.write(" EXPECT_EQ(kExpectedCmdSize, cmd.header.size * 4u);\n")
7388 for value, arg in enumerate(args):
7389 if arg.IsPointer() or arg.IsConstant():
7390 continue
7391 f.write(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);\n" %
7392 (arg.type, value + 1, arg.name))
7393 f.write(" CheckBytesWrittenMatchesExpectedSize(\n")
7394 f.write(" next_cmd, sizeof(cmd) +\n")
7395 f.write(" RoundSizeToMultipleOfEntries(sizeof(data)));\n")
7396 f.write(" // TODO(gman): Check that data was inserted;\n")
7397 f.write("}\n")
7398 f.write("\n")
7400 class PUTSTRHandler(ArrayArgTypeHandler):
7401 """Handler for functions that pass a string array."""
7403 def __GetDataArg(self, func):
7404 """Return the argument that points to the 2D char arrays"""
7405 for arg in func.GetOriginalArgs():
7406 if arg.IsPointer2D():
7407 return arg
7408 return None
7410 def __GetLengthArg(self, func):
7411 """Return the argument that holds length for each char array"""
7412 for arg in func.GetOriginalArgs():
7413 if arg.IsPointer() and not arg.IsPointer2D():
7414 return arg
7415 return None
7417 def WriteGLES2Implementation(self, func, f):
7418 """Overrriden from TypeHandler."""
7419 f.write("%s GLES2Implementation::%s(%s) {\n" %
7420 (func.return_type, func.original_name,
7421 func.MakeTypedOriginalArgString("")))
7422 f.write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
7423 func.WriteDestinationInitalizationValidation(f)
7424 self.WriteClientGLCallLog(func, f)
7425 data_arg = self.__GetDataArg(func)
7426 length_arg = self.__GetLengthArg(func)
7427 log_code_block = """ GPU_CLIENT_LOG_CODE_BLOCK({
7428 for (GLsizei ii = 0; ii < count; ++ii) {
7429 if (%(data)s[ii]) {"""
7430 if length_arg == None:
7431 log_code_block += """
7432 GPU_CLIENT_LOG(" " << ii << ": ---\\n" << %(data)s[ii] << "\\n---");"""
7433 else:
7434 log_code_block += """
7435 if (%(length)s && %(length)s[ii] >= 0) {
7436 const std::string my_str(%(data)s[ii], %(length)s[ii]);
7437 GPU_CLIENT_LOG(" " << ii << ": ---\\n" << my_str << "\\n---");
7438 } else {
7439 GPU_CLIENT_LOG(" " << ii << ": ---\\n" << %(data)s[ii] << "\\n---");
7440 }"""
7441 log_code_block += """
7442 } else {
7443 GPU_CLIENT_LOG(" " << ii << ": NULL");
7448 f.write(log_code_block % {
7449 'data': data_arg.name,
7450 'length': length_arg.name if not length_arg == None else ''
7452 for arg in func.GetOriginalArgs():
7453 arg.WriteClientSideValidationCode(f, func)
7455 bucket_args = []
7456 for arg in func.GetOriginalArgs():
7457 if arg.name == 'count' or arg == self.__GetLengthArg(func):
7458 continue
7459 if arg == self.__GetDataArg(func):
7460 bucket_args.append('kResultBucketId')
7461 else:
7462 bucket_args.append(arg.name)
7463 code_block = """
7464 if (!PackStringsToBucket(count, %(data)s, %(length)s, "gl%(func_name)s")) {
7465 return;
7467 helper_->%(func_name)sBucket(%(bucket_args)s);
7468 helper_->SetBucketSize(kResultBucketId, 0);
7469 CheckGLError();
7473 f.write(code_block % {
7474 'data': data_arg.name,
7475 'length': length_arg.name if not length_arg == None else 'NULL',
7476 'func_name': func.name,
7477 'bucket_args': ', '.join(bucket_args),
7480 def WriteGLES2ImplementationUnitTest(self, func, f):
7481 """Overrriden from TypeHandler."""
7482 code = """
7483 TEST_F(GLES2ImplementationTest, %(name)s) {
7484 const uint32 kBucketId = GLES2Implementation::kResultBucketId;
7485 const char* kString1 = "happy";
7486 const char* kString2 = "ending";
7487 const size_t kString1Size = ::strlen(kString1) + 1;
7488 const size_t kString2Size = ::strlen(kString2) + 1;
7489 const size_t kHeaderSize = sizeof(GLint) * 3;
7490 const size_t kSourceSize = kHeaderSize + kString1Size + kString2Size;
7491 const size_t kPaddedHeaderSize =
7492 transfer_buffer_->RoundToAlignment(kHeaderSize);
7493 const size_t kPaddedString1Size =
7494 transfer_buffer_->RoundToAlignment(kString1Size);
7495 const size_t kPaddedString2Size =
7496 transfer_buffer_->RoundToAlignment(kString2Size);
7497 struct Cmds {
7498 cmd::SetBucketSize set_bucket_size;
7499 cmd::SetBucketData set_bucket_header;
7500 cmd::SetToken set_token1;
7501 cmd::SetBucketData set_bucket_data1;
7502 cmd::SetToken set_token2;
7503 cmd::SetBucketData set_bucket_data2;
7504 cmd::SetToken set_token3;
7505 cmds::%(name)sBucket cmd_bucket;
7506 cmd::SetBucketSize clear_bucket_size;
7509 ExpectedMemoryInfo mem0 = GetExpectedMemory(kPaddedHeaderSize);
7510 ExpectedMemoryInfo mem1 = GetExpectedMemory(kPaddedString1Size);
7511 ExpectedMemoryInfo mem2 = GetExpectedMemory(kPaddedString2Size);
7513 Cmds expected;
7514 expected.set_bucket_size.Init(kBucketId, kSourceSize);
7515 expected.set_bucket_header.Init(
7516 kBucketId, 0, kHeaderSize, mem0.id, mem0.offset);
7517 expected.set_token1.Init(GetNextToken());
7518 expected.set_bucket_data1.Init(
7519 kBucketId, kHeaderSize, kString1Size, mem1.id, mem1.offset);
7520 expected.set_token2.Init(GetNextToken());
7521 expected.set_bucket_data2.Init(
7522 kBucketId, kHeaderSize + kString1Size, kString2Size, mem2.id,
7523 mem2.offset);
7524 expected.set_token3.Init(GetNextToken());
7525 expected.cmd_bucket.Init(%(bucket_args)s);
7526 expected.clear_bucket_size.Init(kBucketId, 0);
7527 const char* kStrings[] = { kString1, kString2 };
7528 gl_->%(name)s(%(gl_args)s);
7529 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
7532 gl_args = []
7533 bucket_args = []
7534 for arg in func.GetOriginalArgs():
7535 if arg == self.__GetDataArg(func):
7536 gl_args.append('kStrings')
7537 bucket_args.append('kBucketId')
7538 elif arg == self.__GetLengthArg(func):
7539 gl_args.append('NULL')
7540 elif arg.name == 'count':
7541 gl_args.append('2')
7542 else:
7543 gl_args.append(arg.GetValidClientSideArg(func))
7544 bucket_args.append(arg.GetValidClientSideArg(func))
7545 f.write(code % {
7546 'name': func.name,
7547 'gl_args': ", ".join(gl_args),
7548 'bucket_args': ", ".join(bucket_args),
7551 if self.__GetLengthArg(func) == None:
7552 return
7553 code = """
7554 TEST_F(GLES2ImplementationTest, %(name)sWithLength) {
7555 const uint32 kBucketId = GLES2Implementation::kResultBucketId;
7556 const char* kString = "foobar******";
7557 const size_t kStringSize = 6; // We only need "foobar".
7558 const size_t kHeaderSize = sizeof(GLint) * 2;
7559 const size_t kSourceSize = kHeaderSize + kStringSize + 1;
7560 const size_t kPaddedHeaderSize =
7561 transfer_buffer_->RoundToAlignment(kHeaderSize);
7562 const size_t kPaddedStringSize =
7563 transfer_buffer_->RoundToAlignment(kStringSize + 1);
7564 struct Cmds {
7565 cmd::SetBucketSize set_bucket_size;
7566 cmd::SetBucketData set_bucket_header;
7567 cmd::SetToken set_token1;
7568 cmd::SetBucketData set_bucket_data;
7569 cmd::SetToken set_token2;
7570 cmds::ShaderSourceBucket shader_source_bucket;
7571 cmd::SetBucketSize clear_bucket_size;
7574 ExpectedMemoryInfo mem0 = GetExpectedMemory(kPaddedHeaderSize);
7575 ExpectedMemoryInfo mem1 = GetExpectedMemory(kPaddedStringSize);
7577 Cmds expected;
7578 expected.set_bucket_size.Init(kBucketId, kSourceSize);
7579 expected.set_bucket_header.Init(
7580 kBucketId, 0, kHeaderSize, mem0.id, mem0.offset);
7581 expected.set_token1.Init(GetNextToken());
7582 expected.set_bucket_data.Init(
7583 kBucketId, kHeaderSize, kStringSize + 1, mem1.id, mem1.offset);
7584 expected.set_token2.Init(GetNextToken());
7585 expected.shader_source_bucket.Init(%(bucket_args)s);
7586 expected.clear_bucket_size.Init(kBucketId, 0);
7587 const char* kStrings[] = { kString };
7588 const GLint kLength[] = { kStringSize };
7589 gl_->%(name)s(%(gl_args)s);
7590 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
7593 gl_args = []
7594 for arg in func.GetOriginalArgs():
7595 if arg == self.__GetDataArg(func):
7596 gl_args.append('kStrings')
7597 elif arg == self.__GetLengthArg(func):
7598 gl_args.append('kLength')
7599 elif arg.name == 'count':
7600 gl_args.append('1')
7601 else:
7602 gl_args.append(arg.GetValidClientSideArg(func))
7603 f.write(code % {
7604 'name': func.name,
7605 'gl_args': ", ".join(gl_args),
7606 'bucket_args': ", ".join(bucket_args),
7609 def WriteBucketServiceUnitTest(self, func, f, *extras):
7610 """Overrriden from TypeHandler."""
7611 cmd_args = []
7612 cmd_args_with_invalid_id = []
7613 gl_args = []
7614 for index, arg in enumerate(func.GetOriginalArgs()):
7615 if arg == self.__GetLengthArg(func):
7616 gl_args.append('_')
7617 elif arg.name == 'count':
7618 gl_args.append('1')
7619 elif arg == self.__GetDataArg(func):
7620 cmd_args.append('kBucketId')
7621 cmd_args_with_invalid_id.append('kBucketId')
7622 gl_args.append('_')
7623 elif index == 0: # Resource ID arg
7624 cmd_args.append(arg.GetValidArg(func))
7625 cmd_args_with_invalid_id.append('kInvalidClientId')
7626 gl_args.append(arg.GetValidGLArg(func))
7627 else:
7628 cmd_args.append(arg.GetValidArg(func))
7629 cmd_args_with_invalid_id.append(arg.GetValidArg(func))
7630 gl_args.append(arg.GetValidGLArg(func))
7632 test = """
7633 TEST_P(%(test_name)s, %(name)sValidArgs) {
7634 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
7635 const uint32 kBucketId = 123;
7636 const char kSource0[] = "hello";
7637 const char* kSource[] = { kSource0 };
7638 const char kValidStrEnd = 0;
7639 SetBucketAsCStrings(kBucketId, 1, kSource, 1, kValidStrEnd);
7640 cmds::%(name)s cmd;
7641 cmd.Init(%(cmd_args)s);
7642 decoder_->set_unsafe_es3_apis_enabled(true);
7643 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));"""
7644 if func.IsUnsafe():
7645 test += """
7646 decoder_->set_unsafe_es3_apis_enabled(false);
7647 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));
7649 test += """
7652 self.WriteValidUnitTest(func, f, test, {
7653 'cmd_args': ", ".join(cmd_args),
7654 'gl_args': ", ".join(gl_args),
7655 }, *extras)
7657 test = """
7658 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
7659 const uint32 kBucketId = 123;
7660 const char kSource0[] = "hello";
7661 const char* kSource[] = { kSource0 };
7662 const char kValidStrEnd = 0;
7663 decoder_->set_unsafe_es3_apis_enabled(true);
7664 cmds::%(name)s cmd;
7665 // Test no bucket.
7666 cmd.Init(%(cmd_args)s);
7667 EXPECT_NE(error::kNoError, ExecuteCmd(cmd));
7668 // Test invalid client.
7669 SetBucketAsCStrings(kBucketId, 1, kSource, 1, kValidStrEnd);
7670 cmd.Init(%(cmd_args_with_invalid_id)s);
7671 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
7672 EXPECT_EQ(GL_INVALID_VALUE, GetGLError());
7675 self.WriteValidUnitTest(func, f, test, {
7676 'cmd_args': ", ".join(cmd_args),
7677 'cmd_args_with_invalid_id': ", ".join(cmd_args_with_invalid_id),
7678 }, *extras)
7680 test = """
7681 TEST_P(%(test_name)s, %(name)sInvalidHeader) {
7682 const uint32 kBucketId = 123;
7683 const char kSource0[] = "hello";
7684 const char* kSource[] = { kSource0 };
7685 const char kValidStrEnd = 0;
7686 const GLsizei kCount = static_cast<GLsizei>(arraysize(kSource));
7687 const GLsizei kTests[] = {
7688 kCount + 1,
7690 std::numeric_limits<GLsizei>::max(),
7693 decoder_->set_unsafe_es3_apis_enabled(true);
7694 for (size_t ii = 0; ii < arraysize(kTests); ++ii) {
7695 SetBucketAsCStrings(kBucketId, 1, kSource, kTests[ii], kValidStrEnd);
7696 cmds::%(name)s cmd;
7697 cmd.Init(%(cmd_args)s);
7698 EXPECT_EQ(error::kInvalidArguments, ExecuteCmd(cmd));
7702 self.WriteValidUnitTest(func, f, test, {
7703 'cmd_args': ", ".join(cmd_args),
7704 }, *extras)
7706 test = """
7707 TEST_P(%(test_name)s, %(name)sInvalidStringEnding) {
7708 const uint32 kBucketId = 123;
7709 const char kSource0[] = "hello";
7710 const char* kSource[] = { kSource0 };
7711 const char kInvalidStrEnd = '*';
7712 SetBucketAsCStrings(kBucketId, 1, kSource, 1, kInvalidStrEnd);
7713 cmds::%(name)s cmd;
7714 cmd.Init(%(cmd_args)s);
7715 decoder_->set_unsafe_es3_apis_enabled(true);
7716 EXPECT_EQ(error::kInvalidArguments, ExecuteCmd(cmd));
7719 self.WriteValidUnitTest(func, f, test, {
7720 'cmd_args': ", ".join(cmd_args),
7721 }, *extras)
7724 class PUTXnHandler(ArrayArgTypeHandler):
7725 """Handler for glUniform?f functions."""
7727 def WriteHandlerImplementation(self, func, f):
7728 """Overrriden from TypeHandler."""
7729 code = """ %(type)s temp[%(count)s] = { %(values)s};"""
7730 if func.IsUnsafe():
7731 code += """
7732 gl%(name)sv(%(location)s, 1, &temp[0]);
7734 else:
7735 code += """
7736 Do%(name)sv(%(location)s, 1, &temp[0]);
7738 values = ""
7739 args = func.GetOriginalArgs()
7740 count = int(self.GetArrayCount(func))
7741 num_args = len(args)
7742 for ii in range(count):
7743 values += "%s, " % args[len(args) - count + ii].name
7745 f.write(code % {
7746 'name': func.name,
7747 'count': self.GetArrayCount(func),
7748 'type': self.GetArrayType(func),
7749 'location': args[0].name,
7750 'args': func.MakeOriginalArgString(""),
7751 'values': values,
7754 def WriteServiceUnitTest(self, func, f, *extras):
7755 """Overrriden from TypeHandler."""
7756 valid_test = """
7757 TEST_P(%(test_name)s, %(name)sValidArgs) {
7758 EXPECT_CALL(*gl_, %(name)sv(%(local_args)s));
7759 SpecializedSetup<cmds::%(name)s, 0>(true);
7760 cmds::%(name)s cmd;
7761 cmd.Init(%(args)s);"""
7762 if func.IsUnsafe():
7763 valid_test += """
7764 decoder_->set_unsafe_es3_apis_enabled(true);"""
7765 valid_test += """
7766 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
7767 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
7768 if func.IsUnsafe():
7769 valid_test += """
7770 decoder_->set_unsafe_es3_apis_enabled(false);
7771 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));"""
7772 valid_test += """
7775 args = func.GetOriginalArgs()
7776 local_args = "%s, 1, _" % args[0].GetValidGLArg(func)
7777 self.WriteValidUnitTest(func, f, valid_test, {
7778 'name': func.name,
7779 'count': self.GetArrayCount(func),
7780 'local_args': local_args,
7781 }, *extras)
7783 invalid_test = """
7784 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
7785 EXPECT_CALL(*gl_, %(name)sv(_, _, _).Times(0);
7786 SpecializedSetup<cmds::%(name)s, 0>(false);
7787 cmds::%(name)s cmd;
7788 cmd.Init(%(args)s);
7789 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
7792 self.WriteInvalidUnitTest(func, f, invalid_test, {
7793 'name': func.GetInfo('name'),
7794 'count': self.GetArrayCount(func),
7798 class GLcharHandler(CustomHandler):
7799 """Handler for functions that pass a single string ."""
7801 def WriteImmediateCmdComputeSize(self, func, f):
7802 """Overrriden from TypeHandler."""
7803 f.write(" static uint32_t ComputeSize(uint32_t data_size) {\n")
7804 f.write(" return static_cast<uint32_t>(\n")
7805 f.write(" sizeof(ValueType) + data_size); // NOLINT\n")
7806 f.write(" }\n")
7808 def WriteImmediateCmdSetHeader(self, func, f):
7809 """Overrriden from TypeHandler."""
7810 code = """
7811 void SetHeader(uint32_t data_size) {
7812 header.SetCmdBySize<ValueType>(data_size);
7815 f.write(code)
7817 def WriteImmediateCmdInit(self, func, f):
7818 """Overrriden from TypeHandler."""
7819 last_arg = func.GetLastOriginalArg()
7820 args = func.GetCmdArgs()
7821 set_code = []
7822 for arg in args:
7823 set_code.append(" %s = _%s;" % (arg.name, arg.name))
7824 code = """
7825 void Init(%(typed_args)s, uint32_t _data_size) {
7826 SetHeader(_data_size);
7827 %(set_code)s
7828 memcpy(ImmediateDataAddress(this), _%(last_arg)s, _data_size);
7832 f.write(code % {
7833 "typed_args": func.MakeTypedArgString("_"),
7834 "set_code": "\n".join(set_code),
7835 "last_arg": last_arg.name
7838 def WriteImmediateCmdSet(self, func, f):
7839 """Overrriden from TypeHandler."""
7840 last_arg = func.GetLastOriginalArg()
7841 f.write(" void* Set(void* cmd%s, uint32_t _data_size) {\n" %
7842 func.MakeTypedCmdArgString("_", True))
7843 f.write(" static_cast<ValueType*>(cmd)->Init(%s, _data_size);\n" %
7844 func.MakeCmdArgString("_"))
7845 f.write(" return NextImmediateCmdAddress<ValueType>("
7846 "cmd, _data_size);\n")
7847 f.write(" }\n")
7848 f.write("\n")
7850 def WriteImmediateCmdHelper(self, func, f):
7851 """Overrriden from TypeHandler."""
7852 code = """ void %(name)s(%(typed_args)s) {
7853 const uint32_t data_size = strlen(name);
7854 gles2::cmds::%(name)s* c =
7855 GetImmediateCmdSpace<gles2::cmds::%(name)s>(data_size);
7856 if (c) {
7857 c->Init(%(args)s, data_size);
7862 f.write(code % {
7863 "name": func.name,
7864 "typed_args": func.MakeTypedOriginalArgString(""),
7865 "args": func.MakeOriginalArgString(""),
7869 def WriteImmediateFormatTest(self, func, f):
7870 """Overrriden from TypeHandler."""
7871 init_code = []
7872 check_code = []
7873 all_but_last_arg = func.GetCmdArgs()[:-1]
7874 for value, arg in enumerate(all_but_last_arg):
7875 init_code.append(" static_cast<%s>(%d)," % (arg.type, value + 11))
7876 for value, arg in enumerate(all_but_last_arg):
7877 check_code.append(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);" %
7878 (arg.type, value + 11, arg.name))
7879 code = """
7880 TEST_F(GLES2FormatTest, %(func_name)s) {
7881 cmds::%(func_name)s& cmd = *GetBufferAs<cmds::%(func_name)s>();
7882 static const char* const test_str = \"test string\";
7883 void* next_cmd = cmd.Set(
7884 &cmd,
7885 %(init_code)s
7886 test_str,
7887 strlen(test_str));
7888 EXPECT_EQ(static_cast<uint32_t>(cmds::%(func_name)s::kCmdId),
7889 cmd.header.command);
7890 EXPECT_EQ(sizeof(cmd) +
7891 RoundSizeToMultipleOfEntries(strlen(test_str)),
7892 cmd.header.size * 4u);
7893 EXPECT_EQ(static_cast<char*>(next_cmd),
7894 reinterpret_cast<char*>(&cmd) + sizeof(cmd) +
7895 RoundSizeToMultipleOfEntries(strlen(test_str)));
7896 %(check_code)s
7897 EXPECT_EQ(static_cast<uint32_t>(strlen(test_str)), cmd.data_size);
7898 EXPECT_EQ(0, memcmp(test_str, ImmediateDataAddress(&cmd), strlen(test_str)));
7899 CheckBytesWritten(
7900 next_cmd,
7901 sizeof(cmd) + RoundSizeToMultipleOfEntries(strlen(test_str)),
7902 sizeof(cmd) + strlen(test_str));
7906 f.write(code % {
7907 'func_name': func.name,
7908 'init_code': "\n".join(init_code),
7909 'check_code': "\n".join(check_code),
7913 class GLcharNHandler(CustomHandler):
7914 """Handler for functions that pass a single string with an optional len."""
7916 def InitFunction(self, func):
7917 """Overrriden from TypeHandler."""
7918 func.cmd_args = []
7919 func.AddCmdArg(Argument('bucket_id', 'GLuint'))
7921 def NeedsDataTransferFunction(self, func):
7922 """Overriden from TypeHandler."""
7923 return False
7925 def WriteServiceImplementation(self, func, f):
7926 """Overrriden from TypeHandler."""
7927 self.WriteServiceHandlerFunctionHeader(func, f)
7928 f.write("""
7929 GLuint bucket_id = static_cast<GLuint>(c.%(bucket_id)s);
7930 Bucket* bucket = GetBucket(bucket_id);
7931 if (!bucket || bucket->size() == 0) {
7932 return error::kInvalidArguments;
7934 std::string str;
7935 if (!bucket->GetAsString(&str)) {
7936 return error::kInvalidArguments;
7938 %(gl_func_name)s(0, str.c_str());
7939 return error::kNoError;
7942 """ % {
7943 'name': func.name,
7944 'gl_func_name': func.GetGLFunctionName(),
7945 'bucket_id': func.cmd_args[0].name,
7949 class IsHandler(TypeHandler):
7950 """Handler for glIs____ type and glGetError functions."""
7952 def InitFunction(self, func):
7953 """Overrriden from TypeHandler."""
7954 func.AddCmdArg(Argument("result_shm_id", 'uint32_t'))
7955 func.AddCmdArg(Argument("result_shm_offset", 'uint32_t'))
7956 if func.GetInfo('result') == None:
7957 func.AddInfo('result', ['uint32_t'])
7959 def WriteServiceUnitTest(self, func, f, *extras):
7960 """Overrriden from TypeHandler."""
7961 valid_test = """
7962 TEST_P(%(test_name)s, %(name)sValidArgs) {
7963 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
7964 SpecializedSetup<cmds::%(name)s, 0>(true);
7965 cmds::%(name)s cmd;
7966 cmd.Init(%(args)s%(comma)sshared_memory_id_, shared_memory_offset_);"""
7967 if func.IsUnsafe():
7968 valid_test += """
7969 decoder_->set_unsafe_es3_apis_enabled(true);"""
7970 valid_test += """
7971 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
7972 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
7973 if func.IsUnsafe():
7974 valid_test += """
7975 decoder_->set_unsafe_es3_apis_enabled(false);
7976 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));"""
7977 valid_test += """
7980 comma = ""
7981 if len(func.GetOriginalArgs()):
7982 comma =", "
7983 self.WriteValidUnitTest(func, f, valid_test, {
7984 'comma': comma,
7985 }, *extras)
7987 invalid_test = """
7988 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
7989 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
7990 SpecializedSetup<cmds::%(name)s, 0>(false);
7991 cmds::%(name)s cmd;
7992 cmd.Init(%(args)s%(comma)sshared_memory_id_, shared_memory_offset_);
7993 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
7996 self.WriteInvalidUnitTest(func, f, invalid_test, {
7997 'comma': comma,
7998 }, *extras)
8000 invalid_test = """
8001 TEST_P(%(test_name)s, %(name)sInvalidArgsBadSharedMemoryId) {
8002 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
8003 SpecializedSetup<cmds::%(name)s, 0>(false);"""
8004 if func.IsUnsafe():
8005 invalid_test += """
8006 decoder_->set_unsafe_es3_apis_enabled(true);"""
8007 invalid_test += """
8008 cmds::%(name)s cmd;
8009 cmd.Init(%(args)s%(comma)skInvalidSharedMemoryId, shared_memory_offset_);
8010 EXPECT_EQ(error::kOutOfBounds, ExecuteCmd(cmd));
8011 cmd.Init(%(args)s%(comma)sshared_memory_id_, kInvalidSharedMemoryOffset);
8012 EXPECT_EQ(error::kOutOfBounds, ExecuteCmd(cmd));"""
8013 if func.IsUnsafe():
8014 invalid_test += """
8015 decoder_->set_unsafe_es3_apis_enabled(true);"""
8016 invalid_test += """
8019 self.WriteValidUnitTest(func, f, invalid_test, {
8020 'comma': comma,
8021 }, *extras)
8023 def WriteServiceImplementation(self, func, f):
8024 """Overrriden from TypeHandler."""
8025 self.WriteServiceHandlerFunctionHeader(func, f)
8026 self.WriteHandlerExtensionCheck(func, f)
8027 args = func.GetOriginalArgs()
8028 for arg in args:
8029 arg.WriteGetCode(f)
8031 code = """ typedef cmds::%(func_name)s::Result Result;
8032 Result* result_dst = GetSharedMemoryAs<Result*>(
8033 c.result_shm_id, c.result_shm_offset, sizeof(*result_dst));
8034 if (!result_dst) {
8035 return error::kOutOfBounds;
8038 f.write(code % {'func_name': func.name})
8039 func.WriteHandlerValidation(f)
8040 if func.IsUnsafe():
8041 assert func.GetInfo('id_mapping')
8042 assert len(func.GetInfo('id_mapping')) == 1
8043 assert len(args) == 1
8044 id_type = func.GetInfo('id_mapping')[0]
8045 f.write(" %s service_%s = 0;\n" % (args[0].type, id_type.lower()))
8046 f.write(" *result_dst = group_->Get%sServiceId(%s, &service_%s);\n" %
8047 (id_type, id_type.lower(), id_type.lower()))
8048 else:
8049 f.write(" *result_dst = %s(%s);\n" %
8050 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
8051 f.write(" return error::kNoError;\n")
8052 f.write("}\n")
8053 f.write("\n")
8055 def WriteGLES2Implementation(self, func, f):
8056 """Overrriden from TypeHandler."""
8057 impl_func = func.GetInfo('impl_func')
8058 if impl_func == None or impl_func == True:
8059 error_value = func.GetInfo("error_value") or "GL_FALSE"
8060 f.write("%s GLES2Implementation::%s(%s) {\n" %
8061 (func.return_type, func.original_name,
8062 func.MakeTypedOriginalArgString("")))
8063 f.write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
8064 self.WriteTraceEvent(func, f)
8065 func.WriteDestinationInitalizationValidation(f)
8066 self.WriteClientGLCallLog(func, f)
8067 f.write(" typedef cmds::%s::Result Result;\n" % func.name)
8068 f.write(" Result* result = GetResultAs<Result*>();\n")
8069 f.write(" if (!result) {\n")
8070 f.write(" return %s;\n" % error_value)
8071 f.write(" }\n")
8072 f.write(" *result = 0;\n")
8073 assert len(func.GetOriginalArgs()) == 1
8074 id_arg = func.GetOriginalArgs()[0]
8075 if id_arg.type == 'GLsync':
8076 arg_string = "ToGLuint(%s)" % func.MakeOriginalArgString("")
8077 else:
8078 arg_string = func.MakeOriginalArgString("")
8079 f.write(
8080 " helper_->%s(%s, GetResultShmId(), GetResultShmOffset());\n" %
8081 (func.name, arg_string))
8082 f.write(" WaitForCmd();\n")
8083 f.write(" %s result_value = *result" % func.return_type)
8084 if func.return_type == "GLboolean":
8085 f.write(" != 0")
8086 f.write(';\n GPU_CLIENT_LOG("returned " << result_value);\n')
8087 f.write(" CheckGLError();\n")
8088 f.write(" return result_value;\n")
8089 f.write("}\n")
8090 f.write("\n")
8092 def WriteGLES2ImplementationUnitTest(self, func, f):
8093 """Overrriden from TypeHandler."""
8094 client_test = func.GetInfo('client_test')
8095 if client_test == None or client_test == True:
8096 code = """
8097 TEST_F(GLES2ImplementationTest, %(name)s) {
8098 struct Cmds {
8099 cmds::%(name)s cmd;
8102 Cmds expected;
8103 ExpectedMemoryInfo result1 =
8104 GetExpectedResultMemory(sizeof(cmds::%(name)s::Result));
8105 expected.cmd.Init(%(cmd_id_value)s, result1.id, result1.offset);
8107 EXPECT_CALL(*command_buffer(), OnFlush())
8108 .WillOnce(SetMemory(result1.ptr, uint32_t(GL_TRUE)))
8109 .RetiresOnSaturation();
8111 GLboolean result = gl_->%(name)s(%(gl_id_value)s);
8112 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
8113 EXPECT_TRUE(result);
8116 args = func.GetOriginalArgs()
8117 assert len(args) == 1
8118 f.write(code % {
8119 'name': func.name,
8120 'cmd_id_value': args[0].GetValidClientSideCmdArg(func),
8121 'gl_id_value': args[0].GetValidClientSideArg(func) })
8124 class STRnHandler(TypeHandler):
8125 """Handler for GetProgramInfoLog, GetShaderInfoLog, GetShaderSource, and
8126 GetTranslatedShaderSourceANGLE."""
8128 def InitFunction(self, func):
8129 """Overrriden from TypeHandler."""
8130 # remove all but the first cmd args.
8131 cmd_args = func.GetCmdArgs()
8132 func.ClearCmdArgs()
8133 func.AddCmdArg(cmd_args[0])
8134 # add on a bucket id.
8135 func.AddCmdArg(Argument('bucket_id', 'uint32_t'))
8137 def WriteGLES2Implementation(self, func, f):
8138 """Overrriden from TypeHandler."""
8139 code_1 = """%(return_type)s GLES2Implementation::%(func_name)s(%(args)s) {
8140 GPU_CLIENT_SINGLE_THREAD_CHECK();
8142 code_2 = """ GPU_CLIENT_LOG("[" << GetLogPrefix()
8143 << "] gl%(func_name)s" << "("
8144 << %(arg0)s << ", "
8145 << %(arg1)s << ", "
8146 << static_cast<void*>(%(arg2)s) << ", "
8147 << static_cast<void*>(%(arg3)s) << ")");
8148 helper_->SetBucketSize(kResultBucketId, 0);
8149 helper_->%(func_name)s(%(id_name)s, kResultBucketId);
8150 std::string str;
8151 GLsizei max_size = 0;
8152 if (GetBucketAsString(kResultBucketId, &str)) {
8153 if (bufsize > 0) {
8154 max_size =
8155 std::min(static_cast<size_t>(%(bufsize_name)s) - 1, str.size());
8156 memcpy(%(dest_name)s, str.c_str(), max_size);
8157 %(dest_name)s[max_size] = '\\0';
8158 GPU_CLIENT_LOG("------\\n" << %(dest_name)s << "\\n------");
8161 if (%(length_name)s != NULL) {
8162 *%(length_name)s = max_size;
8164 CheckGLError();
8167 args = func.GetOriginalArgs()
8168 str_args = {
8169 'return_type': func.return_type,
8170 'func_name': func.original_name,
8171 'args': func.MakeTypedOriginalArgString(""),
8172 'id_name': args[0].name,
8173 'bufsize_name': args[1].name,
8174 'length_name': args[2].name,
8175 'dest_name': args[3].name,
8176 'arg0': args[0].name,
8177 'arg1': args[1].name,
8178 'arg2': args[2].name,
8179 'arg3': args[3].name,
8181 f.write(code_1 % str_args)
8182 func.WriteDestinationInitalizationValidation(f)
8183 f.write(code_2 % str_args)
8185 def WriteServiceUnitTest(self, func, f, *extras):
8186 """Overrriden from TypeHandler."""
8187 valid_test = """
8188 TEST_P(%(test_name)s, %(name)sValidArgs) {
8189 const char* kInfo = "hello";
8190 const uint32_t kBucketId = 123;
8191 SpecializedSetup<cmds::%(name)s, 0>(true);
8192 %(expect_len_code)s
8193 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s))
8194 .WillOnce(DoAll(SetArgumentPointee<2>(strlen(kInfo)),
8195 SetArrayArgument<3>(kInfo, kInfo + strlen(kInfo) + 1)));
8196 cmds::%(name)s cmd;
8197 cmd.Init(%(args)s);
8198 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
8199 CommonDecoder::Bucket* bucket = decoder_->GetBucket(kBucketId);
8200 ASSERT_TRUE(bucket != NULL);
8201 EXPECT_EQ(strlen(kInfo) + 1, bucket->size());
8202 EXPECT_EQ(0, memcmp(bucket->GetData(0, bucket->size()), kInfo,
8203 bucket->size()));
8204 EXPECT_EQ(GL_NO_ERROR, GetGLError());
8207 args = func.GetOriginalArgs()
8208 id_name = args[0].GetValidGLArg(func)
8209 get_len_func = func.GetInfo('get_len_func')
8210 get_len_enum = func.GetInfo('get_len_enum')
8211 sub = {
8212 'id_name': id_name,
8213 'get_len_func': get_len_func,
8214 'get_len_enum': get_len_enum,
8215 'gl_args': '%s, strlen(kInfo) + 1, _, _' %
8216 args[0].GetValidGLArg(func),
8217 'args': '%s, kBucketId' % args[0].GetValidArg(func),
8218 'expect_len_code': '',
8220 if get_len_func and get_len_func[0:2] == 'gl':
8221 sub['expect_len_code'] = (
8222 " EXPECT_CALL(*gl_, %s(%s, %s, _))\n"
8223 " .WillOnce(SetArgumentPointee<2>(strlen(kInfo) + 1));") % (
8224 get_len_func[2:], id_name, get_len_enum)
8225 self.WriteValidUnitTest(func, f, valid_test, sub, *extras)
8227 invalid_test = """
8228 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
8229 const uint32_t kBucketId = 123;
8230 EXPECT_CALL(*gl_, %(gl_func_name)s(_, _, _, _))
8231 .Times(0);
8232 cmds::%(name)s cmd;
8233 cmd.Init(kInvalidClientId, kBucketId);
8234 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
8235 EXPECT_EQ(GL_INVALID_VALUE, GetGLError());
8238 self.WriteValidUnitTest(func, f, invalid_test, *extras)
8240 def WriteServiceImplementation(self, func, f):
8241 """Overrriden from TypeHandler."""
8242 pass
8244 class NamedType(object):
8245 """A class that represents a type of an argument in a client function.
8247 A type of an argument that is to be passed through in the command buffer
8248 command. Currently used only for the arguments that are specificly named in
8249 the 'cmd_buffer_functions.txt' f, mostly enums.
8252 def __init__(self, info):
8253 assert not 'is_complete' in info or info['is_complete'] == True
8254 self.info = info
8255 self.valid = info['valid']
8256 if 'invalid' in info:
8257 self.invalid = info['invalid']
8258 else:
8259 self.invalid = []
8260 if 'valid_es3' in info:
8261 self.valid_es3 = info['valid_es3']
8262 else:
8263 self.valid_es3 = []
8264 if 'deprecated_es3' in info:
8265 self.deprecated_es3 = info['deprecated_es3']
8266 else:
8267 self.deprecated_es3 = []
8269 def GetType(self):
8270 return self.info['type']
8272 def GetInvalidValues(self):
8273 return self.invalid
8275 def GetValidValues(self):
8276 return self.valid
8278 def GetValidValuesES3(self):
8279 return self.valid_es3
8281 def GetDeprecatedValuesES3(self):
8282 return self.deprecated_es3
8284 def IsConstant(self):
8285 if not 'is_complete' in self.info:
8286 return False
8288 return len(self.GetValidValues()) == 1
8290 def GetConstantValue(self):
8291 return self.GetValidValues()[0]
8293 class Argument(object):
8294 """A class that represents a function argument."""
8296 cmd_type_map_ = {
8297 'GLenum': 'uint32_t',
8298 'GLint': 'int32_t',
8299 'GLintptr': 'int32_t',
8300 'GLsizei': 'int32_t',
8301 'GLsizeiptr': 'int32_t',
8302 'GLfloat': 'float',
8303 'GLclampf': 'float',
8305 need_validation_ = ['GLsizei*', 'GLboolean*', 'GLenum*', 'GLint*']
8307 def __init__(self, name, type):
8308 self.name = name
8309 self.optional = type.endswith("Optional*")
8310 if self.optional:
8311 type = type[:-9] + "*"
8312 self.type = type
8314 if type in self.cmd_type_map_:
8315 self.cmd_type = self.cmd_type_map_[type]
8316 else:
8317 self.cmd_type = 'uint32_t'
8319 def IsPointer(self):
8320 """Returns true if argument is a pointer."""
8321 return False
8323 def IsPointer2D(self):
8324 """Returns true if argument is a 2D pointer."""
8325 return False
8327 def IsConstant(self):
8328 """Returns true if the argument has only one valid value."""
8329 return False
8331 def AddCmdArgs(self, args):
8332 """Adds command arguments for this argument to the given list."""
8333 if not self.IsConstant():
8334 return args.append(self)
8336 def AddInitArgs(self, args):
8337 """Adds init arguments for this argument to the given list."""
8338 if not self.IsConstant():
8339 return args.append(self)
8341 def GetValidArg(self, func):
8342 """Gets a valid value for this argument."""
8343 valid_arg = func.GetValidArg(self)
8344 if valid_arg != None:
8345 return valid_arg
8347 index = func.GetOriginalArgs().index(self)
8348 return str(index + 1)
8350 def GetValidClientSideArg(self, func):
8351 """Gets a valid value for this argument."""
8352 valid_arg = func.GetValidArg(self)
8353 if valid_arg != None:
8354 return valid_arg
8356 if self.IsPointer():
8357 return 'nullptr'
8358 index = func.GetOriginalArgs().index(self)
8359 if self.type == 'GLsync':
8360 return ("reinterpret_cast<GLsync>(%d)" % (index + 1))
8361 return str(index + 1)
8363 def GetValidClientSideCmdArg(self, func):
8364 """Gets a valid value for this argument."""
8365 valid_arg = func.GetValidArg(self)
8366 if valid_arg != None:
8367 return valid_arg
8368 try:
8369 index = func.GetOriginalArgs().index(self)
8370 return str(index + 1)
8371 except ValueError:
8372 pass
8373 index = func.GetCmdArgs().index(self)
8374 return str(index + 1)
8376 def GetValidGLArg(self, func):
8377 """Gets a valid GL value for this argument."""
8378 value = self.GetValidArg(func)
8379 if self.type == 'GLsync':
8380 return ("reinterpret_cast<GLsync>(%s)" % value)
8381 return value
8383 def GetValidNonCachedClientSideArg(self, func):
8384 """Returns a valid value for this argument in a GL call.
8385 Using the value will produce a command buffer service invocation.
8386 Returns None if there is no such value."""
8387 value = '123'
8388 if self.type == 'GLsync':
8389 return ("reinterpret_cast<GLsync>(%s)" % value)
8390 return value
8392 def GetValidNonCachedClientSideCmdArg(self, func):
8393 """Returns a valid value for this argument in a command buffer command.
8394 Calling the GL function with the value returned by
8395 GetValidNonCachedClientSideArg will result in a command buffer command
8396 that contains the value returned by this function. """
8397 return '123'
8399 def GetNumInvalidValues(self, func):
8400 """returns the number of invalid values to be tested."""
8401 return 0
8403 def GetInvalidArg(self, index):
8404 """returns an invalid value and expected parse result by index."""
8405 return ("---ERROR0---", "---ERROR2---", None)
8407 def GetLogArg(self):
8408 """Get argument appropriate for LOG macro."""
8409 if self.type == 'GLboolean':
8410 return 'GLES2Util::GetStringBool(%s)' % self.name
8411 if self.type == 'GLenum':
8412 return 'GLES2Util::GetStringEnum(%s)' % self.name
8413 return self.name
8415 def WriteGetCode(self, f):
8416 """Writes the code to get an argument from a command structure."""
8417 if self.type == 'GLsync':
8418 my_type = 'GLuint'
8419 else:
8420 my_type = self.type
8421 f.write(" %s %s = static_cast<%s>(c.%s);\n" %
8422 (my_type, self.name, my_type, self.name))
8424 def WriteValidationCode(self, f, func):
8425 """Writes the validation code for an argument."""
8426 pass
8428 def WriteClientSideValidationCode(self, f, func):
8429 """Writes the validation code for an argument."""
8430 pass
8432 def WriteDestinationInitalizationValidation(self, f, func):
8433 """Writes the client side destintion initialization validation."""
8434 pass
8436 def WriteDestinationInitalizationValidatationIfNeeded(self, f, func):
8437 """Writes the client side destintion initialization validation if needed."""
8438 parts = self.type.split(" ")
8439 if len(parts) > 1:
8440 return
8441 if parts[0] in self.need_validation_:
8442 f.write(
8443 " GPU_CLIENT_VALIDATE_DESTINATION_%sINITALIZATION(%s, %s);\n" %
8444 ("OPTIONAL_" if self.optional else "", self.type[:-1], self.name))
8446 def GetImmediateVersion(self):
8447 """Gets the immediate version of this argument."""
8448 return self
8450 def GetBucketVersion(self):
8451 """Gets the bucket version of this argument."""
8452 return self
8455 class BoolArgument(Argument):
8456 """class for GLboolean"""
8458 def __init__(self, name, type):
8459 Argument.__init__(self, name, 'GLboolean')
8461 def GetValidArg(self, func):
8462 """Gets a valid value for this argument."""
8463 return 'true'
8465 def GetValidClientSideArg(self, func):
8466 """Gets a valid value for this argument."""
8467 return 'true'
8469 def GetValidClientSideCmdArg(self, func):
8470 """Gets a valid value for this argument."""
8471 return 'true'
8473 def GetValidGLArg(self, func):
8474 """Gets a valid GL value for this argument."""
8475 return 'true'
8478 class UniformLocationArgument(Argument):
8479 """class for uniform locations."""
8481 def __init__(self, name):
8482 Argument.__init__(self, name, "GLint")
8484 def WriteGetCode(self, f):
8485 """Writes the code to get an argument from a command structure."""
8486 code = """ %s %s = static_cast<%s>(c.%s);
8488 f.write(code % (self.type, self.name, self.type, self.name))
8490 class DataSizeArgument(Argument):
8491 """class for data_size which Bucket commands do not need."""
8493 def __init__(self, name):
8494 Argument.__init__(self, name, "uint32_t")
8496 def GetBucketVersion(self):
8497 return None
8500 class SizeArgument(Argument):
8501 """class for GLsizei and GLsizeiptr."""
8503 def GetNumInvalidValues(self, func):
8504 """overridden from Argument."""
8505 if func.IsImmediate():
8506 return 0
8507 return 1
8509 def GetInvalidArg(self, index):
8510 """overridden from Argument."""
8511 return ("-1", "kNoError", "GL_INVALID_VALUE")
8513 def WriteValidationCode(self, f, func):
8514 """overridden from Argument."""
8515 if func.IsUnsafe():
8516 return
8517 code = """ if (%(var_name)s < 0) {
8518 LOCAL_SET_GL_ERROR(GL_INVALID_VALUE, "gl%(func_name)s", "%(var_name)s < 0");
8519 return error::kNoError;
8522 f.write(code % {
8523 "var_name": self.name,
8524 "func_name": func.original_name,
8527 def WriteClientSideValidationCode(self, f, func):
8528 """overridden from Argument."""
8529 code = """ if (%(var_name)s < 0) {
8530 SetGLError(GL_INVALID_VALUE, "gl%(func_name)s", "%(var_name)s < 0");
8531 return;
8534 f.write(code % {
8535 "var_name": self.name,
8536 "func_name": func.original_name,
8540 class SizeNotNegativeArgument(SizeArgument):
8541 """class for GLsizeiNotNegative. It's NEVER allowed to be negative"""
8543 def __init__(self, name, type, gl_type):
8544 SizeArgument.__init__(self, name, gl_type)
8546 def GetInvalidArg(self, index):
8547 """overridden from SizeArgument."""
8548 return ("-1", "kOutOfBounds", "GL_NO_ERROR")
8550 def WriteValidationCode(self, f, func):
8551 """overridden from SizeArgument."""
8552 pass
8555 class EnumBaseArgument(Argument):
8556 """Base class for EnumArgument, IntArgument, BitfieldArgument, and
8557 ValidatedBoolArgument."""
8559 def __init__(self, name, gl_type, type, gl_error):
8560 Argument.__init__(self, name, gl_type)
8562 self.gl_error = gl_error
8563 name = type[len(gl_type):]
8564 self.type_name = name
8565 self.named_type = NamedType(_NAMED_TYPE_INFO[name])
8567 def IsConstant(self):
8568 return self.named_type.IsConstant()
8570 def GetConstantValue(self):
8571 return self.named_type.GetConstantValue()
8573 def WriteValidationCode(self, f, func):
8574 if func.IsUnsafe():
8575 return
8576 if self.named_type.IsConstant():
8577 return
8578 f.write(" if (!validators_->%s.IsValid(%s)) {\n" %
8579 (ToUnderscore(self.type_name), self.name))
8580 if self.gl_error == "GL_INVALID_ENUM":
8581 f.write(
8582 " LOCAL_SET_GL_ERROR_INVALID_ENUM(\"gl%s\", %s, \"%s\");\n" %
8583 (func.original_name, self.name, self.name))
8584 else:
8585 f.write(
8586 " LOCAL_SET_GL_ERROR(%s, \"gl%s\", \"%s %s\");\n" %
8587 (self.gl_error, func.original_name, self.name, self.gl_error))
8588 f.write(" return error::kNoError;\n")
8589 f.write(" }\n")
8591 def WriteClientSideValidationCode(self, f, func):
8592 if not self.named_type.IsConstant():
8593 return
8594 f.write(" if (%s != %s) {" % (self.name,
8595 self.GetConstantValue()))
8596 f.write(
8597 " SetGLError(%s, \"gl%s\", \"%s %s\");\n" %
8598 (self.gl_error, func.original_name, self.name, self.gl_error))
8599 if func.return_type == "void":
8600 f.write(" return;\n")
8601 else:
8602 f.write(" return %s;\n" % func.GetErrorReturnString())
8603 f.write(" }\n")
8605 def GetValidArg(self, func):
8606 valid_arg = func.GetValidArg(self)
8607 if valid_arg != None:
8608 return valid_arg
8609 valid = self.named_type.GetValidValues()
8610 if valid:
8611 return valid[0]
8613 index = func.GetOriginalArgs().index(self)
8614 return str(index + 1)
8616 def GetValidClientSideArg(self, func):
8617 """Gets a valid value for this argument."""
8618 return self.GetValidArg(func)
8620 def GetValidClientSideCmdArg(self, func):
8621 """Gets a valid value for this argument."""
8622 valid_arg = func.GetValidArg(self)
8623 if valid_arg != None:
8624 return valid_arg
8626 valid = self.named_type.GetValidValues()
8627 if valid:
8628 return valid[0]
8630 try:
8631 index = func.GetOriginalArgs().index(self)
8632 return str(index + 1)
8633 except ValueError:
8634 pass
8635 index = func.GetCmdArgs().index(self)
8636 return str(index + 1)
8638 def GetValidGLArg(self, func):
8639 """Gets a valid value for this argument."""
8640 return self.GetValidArg(func)
8642 def GetNumInvalidValues(self, func):
8643 """returns the number of invalid values to be tested."""
8644 return len(self.named_type.GetInvalidValues())
8646 def GetInvalidArg(self, index):
8647 """returns an invalid value by index."""
8648 invalid = self.named_type.GetInvalidValues()
8649 if invalid:
8650 num_invalid = len(invalid)
8651 if index >= num_invalid:
8652 index = num_invalid - 1
8653 return (invalid[index], "kNoError", self.gl_error)
8654 return ("---ERROR1---", "kNoError", self.gl_error)
8657 class EnumArgument(EnumBaseArgument):
8658 """A class that represents a GLenum argument"""
8660 def __init__(self, name, type):
8661 EnumBaseArgument.__init__(self, name, "GLenum", type, "GL_INVALID_ENUM")
8663 def GetLogArg(self):
8664 """Overridden from Argument."""
8665 return ("GLES2Util::GetString%s(%s)" %
8666 (self.type_name, self.name))
8669 class IntArgument(EnumBaseArgument):
8670 """A class for a GLint argument that can only accept specific values.
8672 For example glTexImage2D takes a GLint for its internalformat
8673 argument instead of a GLenum.
8676 def __init__(self, name, type):
8677 EnumBaseArgument.__init__(self, name, "GLint", type, "GL_INVALID_VALUE")
8680 class ValidatedBoolArgument(EnumBaseArgument):
8681 """A class for a GLboolean argument that can only accept specific values.
8683 For example glUniformMatrix takes a GLboolean for it's transpose but it
8684 must be false.
8687 def __init__(self, name, type):
8688 EnumBaseArgument.__init__(self, name, "GLboolean", type, "GL_INVALID_VALUE")
8690 def GetLogArg(self):
8691 """Overridden from Argument."""
8692 return 'GLES2Util::GetStringBool(%s)' % self.name
8695 class BitFieldArgument(EnumBaseArgument):
8696 """A class for a GLbitfield argument that can only accept specific values.
8698 For example glFenceSync takes a GLbitfield for its flags argument bit it
8699 must be 0.
8702 def __init__(self, name, type):
8703 EnumBaseArgument.__init__(self, name, "GLbitfield", type,
8704 "GL_INVALID_VALUE")
8707 class ImmediatePointerArgument(Argument):
8708 """A class that represents an immediate argument to a function.
8710 An immediate argument is one where the data follows the command.
8713 def IsPointer(self):
8714 return True
8716 def GetPointedType(self):
8717 match = re.match('(const\s+)?(?P<element_type>[\w]+)\s*\*', self.type)
8718 assert match
8719 return match.groupdict()['element_type']
8721 def AddCmdArgs(self, args):
8722 """Overridden from Argument."""
8723 pass
8725 def WriteGetCode(self, f):
8726 """Overridden from Argument."""
8727 f.write(
8728 " %s %s = GetImmediateDataAs<%s>(\n" %
8729 (self.type, self.name, self.type))
8730 f.write(" c, data_size, immediate_data_size);\n")
8732 def WriteValidationCode(self, f, func):
8733 """Overridden from Argument."""
8734 if self.optional:
8735 return
8736 f.write(" if (%s == NULL) {\n" % self.name)
8737 f.write(" return error::kOutOfBounds;\n")
8738 f.write(" }\n")
8740 def GetImmediateVersion(self):
8741 """Overridden from Argument."""
8742 return None
8744 def WriteDestinationInitalizationValidation(self, f, func):
8745 """Overridden from Argument."""
8746 self.WriteDestinationInitalizationValidatationIfNeeded(f, func)
8748 def GetLogArg(self):
8749 """Overridden from Argument."""
8750 return "static_cast<const void*>(%s)" % self.name
8753 class PointerArgument(Argument):
8754 """A class that represents a pointer argument to a function."""
8756 def IsPointer(self):
8757 """Overridden from Argument."""
8758 return True
8760 def IsPointer2D(self):
8761 """Overridden from Argument."""
8762 return self.type.count('*') == 2
8764 def GetPointedType(self):
8765 match = re.match('(const\s+)?(?P<element_type>[\w]+)\s*\*', self.type)
8766 assert match
8767 return match.groupdict()['element_type']
8769 def GetValidArg(self, func):
8770 """Overridden from Argument."""
8771 return "shared_memory_id_, shared_memory_offset_"
8773 def GetValidGLArg(self, func):
8774 """Overridden from Argument."""
8775 return "reinterpret_cast<%s>(shared_memory_address_)" % self.type
8777 def GetNumInvalidValues(self, func):
8778 """Overridden from Argument."""
8779 return 2
8781 def GetInvalidArg(self, index):
8782 """Overridden from Argument."""
8783 if index == 0:
8784 return ("kInvalidSharedMemoryId, 0", "kOutOfBounds", None)
8785 else:
8786 return ("shared_memory_id_, kInvalidSharedMemoryOffset",
8787 "kOutOfBounds", None)
8789 def GetLogArg(self):
8790 """Overridden from Argument."""
8791 return "static_cast<const void*>(%s)" % self.name
8793 def AddCmdArgs(self, args):
8794 """Overridden from Argument."""
8795 args.append(Argument("%s_shm_id" % self.name, 'uint32_t'))
8796 args.append(Argument("%s_shm_offset" % self.name, 'uint32_t'))
8798 def WriteGetCode(self, f):
8799 """Overridden from Argument."""
8800 f.write(
8801 " %s %s = GetSharedMemoryAs<%s>(\n" %
8802 (self.type, self.name, self.type))
8803 f.write(
8804 " c.%s_shm_id, c.%s_shm_offset, data_size);\n" %
8805 (self.name, self.name))
8807 def WriteValidationCode(self, f, func):
8808 """Overridden from Argument."""
8809 if self.optional:
8810 return
8811 f.write(" if (%s == NULL) {\n" % self.name)
8812 f.write(" return error::kOutOfBounds;\n")
8813 f.write(" }\n")
8815 def GetImmediateVersion(self):
8816 """Overridden from Argument."""
8817 return ImmediatePointerArgument(self.name, self.type)
8819 def GetBucketVersion(self):
8820 """Overridden from Argument."""
8821 if self.type.find('char') >= 0:
8822 if self.IsPointer2D():
8823 return InputStringArrayBucketArgument(self.name, self.type)
8824 return InputStringBucketArgument(self.name, self.type)
8825 return BucketPointerArgument(self.name, self.type)
8827 def WriteDestinationInitalizationValidation(self, f, func):
8828 """Overridden from Argument."""
8829 self.WriteDestinationInitalizationValidatationIfNeeded(f, func)
8832 class BucketPointerArgument(PointerArgument):
8833 """A class that represents an bucket argument to a function."""
8835 def AddCmdArgs(self, args):
8836 """Overridden from Argument."""
8837 pass
8839 def WriteGetCode(self, f):
8840 """Overridden from Argument."""
8841 f.write(
8842 " %s %s = bucket->GetData(0, data_size);\n" %
8843 (self.type, self.name))
8845 def WriteValidationCode(self, f, func):
8846 """Overridden from Argument."""
8847 pass
8849 def GetImmediateVersion(self):
8850 """Overridden from Argument."""
8851 return None
8853 def WriteDestinationInitalizationValidation(self, f, func):
8854 """Overridden from Argument."""
8855 self.WriteDestinationInitalizationValidatationIfNeeded(f, func)
8857 def GetLogArg(self):
8858 """Overridden from Argument."""
8859 return "static_cast<const void*>(%s)" % self.name
8862 class InputStringBucketArgument(Argument):
8863 """A string input argument where the string is passed in a bucket."""
8865 def __init__(self, name, type):
8866 Argument.__init__(self, name + "_bucket_id", "uint32_t")
8868 def IsPointer(self):
8869 """Overridden from Argument."""
8870 return True
8872 def IsPointer2D(self):
8873 """Overridden from Argument."""
8874 return False
8877 class InputStringArrayBucketArgument(Argument):
8878 """A string array input argument where the strings are passed in a bucket."""
8880 def __init__(self, name, type):
8881 Argument.__init__(self, name + "_bucket_id", "uint32_t")
8882 self._original_name = name
8884 def WriteGetCode(self, f):
8885 """Overridden from Argument."""
8886 code = """
8887 Bucket* bucket = GetBucket(c.%(name)s);
8888 if (!bucket) {
8889 return error::kInvalidArguments;
8891 GLsizei count = 0;
8892 std::vector<char*> strs;
8893 std::vector<GLint> len;
8894 if (!bucket->GetAsStrings(&count, &strs, &len)) {
8895 return error::kInvalidArguments;
8897 const char** %(original_name)s =
8898 strs.size() > 0 ? const_cast<const char**>(&strs[0]) : NULL;
8899 const GLint* length =
8900 len.size() > 0 ? const_cast<const GLint*>(&len[0]) : NULL;
8901 (void)length;
8903 f.write(code % {
8904 'name': self.name,
8905 'original_name': self._original_name,
8908 def GetValidArg(self, func):
8909 return "kNameBucketId"
8911 def GetValidGLArg(self, func):
8912 return "_"
8914 def IsPointer(self):
8915 """Overridden from Argument."""
8916 return True
8918 def IsPointer2D(self):
8919 """Overridden from Argument."""
8920 return True
8923 class ResourceIdArgument(Argument):
8924 """A class that represents a resource id argument to a function."""
8926 def __init__(self, name, type):
8927 match = re.match("(GLid\w+)", type)
8928 self.resource_type = match.group(1)[4:]
8929 if self.resource_type == "Sync":
8930 type = type.replace(match.group(1), "GLsync")
8931 else:
8932 type = type.replace(match.group(1), "GLuint")
8933 Argument.__init__(self, name, type)
8935 def WriteGetCode(self, f):
8936 """Overridden from Argument."""
8937 if self.type == "GLsync":
8938 my_type = "GLuint"
8939 else:
8940 my_type = self.type
8941 f.write(" %s %s = c.%s;\n" % (my_type, self.name, self.name))
8943 def GetValidArg(self, func):
8944 return "client_%s_id_" % self.resource_type.lower()
8946 def GetValidGLArg(self, func):
8947 if self.resource_type == "Sync":
8948 return "reinterpret_cast<GLsync>(kService%sId)" % self.resource_type
8949 return "kService%sId" % self.resource_type
8952 class ResourceIdBindArgument(Argument):
8953 """Represents a resource id argument to a bind function."""
8955 def __init__(self, name, type):
8956 match = re.match("(GLidBind\w+)", type)
8957 self.resource_type = match.group(1)[8:]
8958 type = type.replace(match.group(1), "GLuint")
8959 Argument.__init__(self, name, type)
8961 def WriteGetCode(self, f):
8962 """Overridden from Argument."""
8963 code = """ %(type)s %(name)s = c.%(name)s;
8965 f.write(code % {'type': self.type, 'name': self.name})
8967 def GetValidArg(self, func):
8968 return "client_%s_id_" % self.resource_type.lower()
8970 def GetValidGLArg(self, func):
8971 return "kService%sId" % self.resource_type
8974 class ResourceIdZeroArgument(Argument):
8975 """Represents a resource id argument to a function that can be zero."""
8977 def __init__(self, name, type):
8978 match = re.match("(GLidZero\w+)", type)
8979 self.resource_type = match.group(1)[8:]
8980 type = type.replace(match.group(1), "GLuint")
8981 Argument.__init__(self, name, type)
8983 def WriteGetCode(self, f):
8984 """Overridden from Argument."""
8985 f.write(" %s %s = c.%s;\n" % (self.type, self.name, self.name))
8987 def GetValidArg(self, func):
8988 return "client_%s_id_" % self.resource_type.lower()
8990 def GetValidGLArg(self, func):
8991 return "kService%sId" % self.resource_type
8993 def GetNumInvalidValues(self, func):
8994 """returns the number of invalid values to be tested."""
8995 return 1
8997 def GetInvalidArg(self, index):
8998 """returns an invalid value by index."""
8999 return ("kInvalidClientId", "kNoError", "GL_INVALID_VALUE")
9002 class Function(object):
9003 """A class that represents a function."""
9005 type_handlers = {
9006 '': TypeHandler(),
9007 'Bind': BindHandler(),
9008 'Create': CreateHandler(),
9009 'Custom': CustomHandler(),
9010 'Data': DataHandler(),
9011 'Delete': DeleteHandler(),
9012 'DELn': DELnHandler(),
9013 'GENn': GENnHandler(),
9014 'GETn': GETnHandler(),
9015 'GLchar': GLcharHandler(),
9016 'GLcharN': GLcharNHandler(),
9017 'HandWritten': HandWrittenHandler(),
9018 'Is': IsHandler(),
9019 'Manual': ManualHandler(),
9020 'PUT': PUTHandler(),
9021 'PUTn': PUTnHandler(),
9022 'PUTSTR': PUTSTRHandler(),
9023 'PUTXn': PUTXnHandler(),
9024 'StateSet': StateSetHandler(),
9025 'StateSetRGBAlpha': StateSetRGBAlphaHandler(),
9026 'StateSetFrontBack': StateSetFrontBackHandler(),
9027 'StateSetFrontBackSeparate': StateSetFrontBackSeparateHandler(),
9028 'StateSetNamedParameter': StateSetNamedParameter(),
9029 'STRn': STRnHandler(),
9032 def __init__(self, name, info):
9033 self.name = name
9034 self.original_name = info['original_name']
9036 self.original_args = self.ParseArgs(info['original_args'])
9038 if 'cmd_args' in info:
9039 self.args_for_cmds = self.ParseArgs(info['cmd_args'])
9040 else:
9041 self.args_for_cmds = self.original_args[:]
9043 self.return_type = info['return_type']
9044 if self.return_type != 'void':
9045 self.return_arg = CreateArg(info['return_type'] + " result")
9046 else:
9047 self.return_arg = None
9049 self.num_pointer_args = sum(
9050 [1 for arg in self.args_for_cmds if arg.IsPointer()])
9051 if self.num_pointer_args > 0:
9052 for arg in reversed(self.original_args):
9053 if arg.IsPointer():
9054 self.last_original_pointer_arg = arg
9055 break
9056 else:
9057 self.last_original_pointer_arg = None
9058 self.info = info
9059 self.type_handler = self.type_handlers[info['type']]
9060 self.can_auto_generate = (self.num_pointer_args == 0 and
9061 info['return_type'] == "void")
9062 self.InitFunction()
9064 def ParseArgs(self, arg_string):
9065 """Parses a function arg string."""
9066 args = []
9067 parts = arg_string.split(',')
9068 for arg_string in parts:
9069 arg = CreateArg(arg_string)
9070 if arg:
9071 args.append(arg)
9072 return args
9074 def IsType(self, type_name):
9075 """Returns true if function is a certain type."""
9076 return self.info['type'] == type_name
9078 def InitFunction(self):
9079 """Creates command args and calls the init function for the type handler.
9081 Creates argument lists for command buffer commands, eg. self.cmd_args and
9082 self.init_args.
9083 Calls the type function initialization.
9084 Override to create different kind of command buffer command argument lists.
9086 self.cmd_args = []
9087 for arg in self.args_for_cmds:
9088 arg.AddCmdArgs(self.cmd_args)
9090 self.init_args = []
9091 for arg in self.args_for_cmds:
9092 arg.AddInitArgs(self.init_args)
9094 if self.return_arg:
9095 self.init_args.append(self.return_arg)
9097 self.type_handler.InitFunction(self)
9099 def IsImmediate(self):
9100 """Returns whether the function is immediate data function or not."""
9101 return False
9103 def IsUnsafe(self):
9104 """Returns whether the function has service side validation or not."""
9105 return self.GetInfo('unsafe', False)
9107 def GetInfo(self, name, default = None):
9108 """Returns a value from the function info for this function."""
9109 if name in self.info:
9110 return self.info[name]
9111 return default
9113 def GetValidArg(self, arg):
9114 """Gets a valid argument value for the parameter arg from the function info
9115 if one exists."""
9116 try:
9117 index = self.GetOriginalArgs().index(arg)
9118 except ValueError:
9119 return None
9121 valid_args = self.GetInfo('valid_args')
9122 if valid_args and str(index) in valid_args:
9123 return valid_args[str(index)]
9124 return None
9126 def AddInfo(self, name, value):
9127 """Adds an info."""
9128 self.info[name] = value
9130 def IsExtension(self):
9131 return self.GetInfo('extension') or self.GetInfo('extension_flag')
9133 def IsCoreGLFunction(self):
9134 return (not self.IsExtension() and
9135 not self.GetInfo('pepper_interface') and
9136 not self.IsUnsafe())
9138 def InPepperInterface(self, interface):
9139 ext = self.GetInfo('pepper_interface')
9140 if not interface.GetName():
9141 return self.IsCoreGLFunction()
9142 return ext == interface.GetName()
9144 def InAnyPepperExtension(self):
9145 return self.IsCoreGLFunction() or self.GetInfo('pepper_interface')
9147 def GetErrorReturnString(self):
9148 if self.GetInfo("error_return"):
9149 return self.GetInfo("error_return")
9150 elif self.return_type == "GLboolean":
9151 return "GL_FALSE"
9152 elif "*" in self.return_type:
9153 return "NULL"
9154 return "0"
9156 def GetGLFunctionName(self):
9157 """Gets the function to call to execute GL for this command."""
9158 if self.GetInfo('decoder_func'):
9159 return self.GetInfo('decoder_func')
9160 return "gl%s" % self.original_name
9162 def GetGLTestFunctionName(self):
9163 gl_func_name = self.GetInfo('gl_test_func')
9164 if gl_func_name == None:
9165 gl_func_name = self.GetGLFunctionName()
9166 if gl_func_name.startswith("gl"):
9167 gl_func_name = gl_func_name[2:]
9168 else:
9169 gl_func_name = self.original_name
9170 return gl_func_name
9172 def GetDataTransferMethods(self):
9173 return self.GetInfo('data_transfer_methods',
9174 ['immediate' if self.num_pointer_args == 1 else 'shm'])
9176 def AddCmdArg(self, arg):
9177 """Adds a cmd argument to this function."""
9178 self.cmd_args.append(arg)
9180 def GetCmdArgs(self):
9181 """Gets the command args for this function."""
9182 return self.cmd_args
9184 def ClearCmdArgs(self):
9185 """Clears the command args for this function."""
9186 self.cmd_args = []
9188 def GetCmdConstants(self):
9189 """Gets the constants for this function."""
9190 return [arg for arg in self.args_for_cmds if arg.IsConstant()]
9192 def GetInitArgs(self):
9193 """Gets the init args for this function."""
9194 return self.init_args
9196 def GetOriginalArgs(self):
9197 """Gets the original arguments to this function."""
9198 return self.original_args
9200 def GetLastOriginalArg(self):
9201 """Gets the last original argument to this function."""
9202 return self.original_args[len(self.original_args) - 1]
9204 def GetLastOriginalPointerArg(self):
9205 return self.last_original_pointer_arg
9207 def GetResourceIdArg(self):
9208 for arg in self.original_args:
9209 if hasattr(arg, 'resource_type'):
9210 return arg
9211 return None
9213 def _MaybePrependComma(self, arg_string, add_comma):
9214 """Adds a comma if arg_string is not empty and add_comma is true."""
9215 comma = ""
9216 if add_comma and len(arg_string):
9217 comma = ", "
9218 return "%s%s" % (comma, arg_string)
9220 def MakeTypedOriginalArgString(self, prefix, add_comma = False):
9221 """Gets a list of arguments as they are in GL."""
9222 args = self.GetOriginalArgs()
9223 arg_string = ", ".join(
9224 ["%s %s%s" % (arg.type, prefix, arg.name) for arg in args])
9225 return self._MaybePrependComma(arg_string, add_comma)
9227 def MakeOriginalArgString(self, prefix, add_comma = False, separator = ", "):
9228 """Gets the list of arguments as they are in GL."""
9229 args = self.GetOriginalArgs()
9230 arg_string = separator.join(
9231 ["%s%s" % (prefix, arg.name) for arg in args])
9232 return self._MaybePrependComma(arg_string, add_comma)
9234 def MakeHelperArgString(self, prefix, add_comma = False, separator = ", "):
9235 """Gets a list of GL arguments after removing unneeded arguments."""
9236 args = self.GetOriginalArgs()
9237 arg_string = separator.join(
9238 ["%s%s" % (prefix, arg.name)
9239 for arg in args if not arg.IsConstant()])
9240 return self._MaybePrependComma(arg_string, add_comma)
9242 def MakeTypedPepperArgString(self, prefix):
9243 """Gets a list of arguments as they need to be for Pepper."""
9244 if self.GetInfo("pepper_args"):
9245 return self.GetInfo("pepper_args")
9246 else:
9247 return self.MakeTypedOriginalArgString(prefix, False)
9249 def MapCTypeToPepperIdlType(self, ctype, is_for_return_type=False):
9250 """Converts a C type name to the corresponding Pepper IDL type."""
9251 idltype = {
9252 'char*': '[out] str_t',
9253 'const GLchar* const*': '[out] cstr_t',
9254 'const char*': 'cstr_t',
9255 'const void*': 'mem_t',
9256 'void*': '[out] mem_t',
9257 'void**': '[out] mem_ptr_t',
9258 }.get(ctype, ctype)
9259 # We use "GLxxx_ptr_t" for "GLxxx*".
9260 matched = re.match(r'(const )?(GL\w+)\*$', ctype)
9261 if matched:
9262 idltype = matched.group(2) + '_ptr_t'
9263 if not matched.group(1):
9264 idltype = '[out] ' + idltype
9265 # If an in/out specifier is not specified yet, prepend [in].
9266 if idltype[0] != '[':
9267 idltype = '[in] ' + idltype
9268 # Strip the in/out specifier for a return type.
9269 if is_for_return_type:
9270 idltype = re.sub(r'\[\w+\] ', '', idltype)
9271 return idltype
9273 def MakeTypedPepperIdlArgStrings(self):
9274 """Gets a list of arguments as they need to be for Pepper IDL."""
9275 args = self.GetOriginalArgs()
9276 return ["%s %s" % (self.MapCTypeToPepperIdlType(arg.type), arg.name)
9277 for arg in args]
9279 def GetPepperName(self):
9280 if self.GetInfo("pepper_name"):
9281 return self.GetInfo("pepper_name")
9282 return self.name
9284 def MakeTypedCmdArgString(self, prefix, add_comma = False):
9285 """Gets a typed list of arguments as they need to be for command buffers."""
9286 args = self.GetCmdArgs()
9287 arg_string = ", ".join(
9288 ["%s %s%s" % (arg.type, prefix, arg.name) for arg in args])
9289 return self._MaybePrependComma(arg_string, add_comma)
9291 def MakeCmdArgString(self, prefix, add_comma = False):
9292 """Gets the list of arguments as they need to be for command buffers."""
9293 args = self.GetCmdArgs()
9294 arg_string = ", ".join(
9295 ["%s%s" % (prefix, arg.name) for arg in args])
9296 return self._MaybePrependComma(arg_string, add_comma)
9298 def MakeTypedInitString(self, prefix, add_comma = False):
9299 """Gets a typed list of arguments as they need to be for cmd Init/Set."""
9300 args = self.GetInitArgs()
9301 arg_string = ", ".join(
9302 ["%s %s%s" % (arg.type, prefix, arg.name) for arg in args])
9303 return self._MaybePrependComma(arg_string, add_comma)
9305 def MakeInitString(self, prefix, add_comma = False):
9306 """Gets the list of arguments as they need to be for cmd Init/Set."""
9307 args = self.GetInitArgs()
9308 arg_string = ", ".join(
9309 ["%s%s" % (prefix, arg.name) for arg in args])
9310 return self._MaybePrependComma(arg_string, add_comma)
9312 def MakeLogArgString(self):
9313 """Makes a string of the arguments for the LOG macros"""
9314 args = self.GetOriginalArgs()
9315 return ' << ", " << '.join([arg.GetLogArg() for arg in args])
9317 def WriteHandlerValidation(self, f):
9318 """Writes validation code for the function."""
9319 for arg in self.GetOriginalArgs():
9320 arg.WriteValidationCode(f, self)
9321 self.WriteValidationCode(f)
9323 def WriteHandlerImplementation(self, f):
9324 """Writes the handler implementation for this command."""
9325 self.type_handler.WriteHandlerImplementation(self, f)
9327 def WriteValidationCode(self, f):
9328 """Writes the validation code for a command."""
9329 pass
9331 def WriteCmdFlag(self, f):
9332 """Writes the cmd cmd_flags constant."""
9333 flags = []
9334 # By default trace only at the highest level 3.
9335 trace_level = int(self.GetInfo('trace_level', default = 3))
9336 if trace_level not in xrange(0, 4):
9337 raise KeyError("Unhandled trace_level: %d" % trace_level)
9339 flags.append('CMD_FLAG_SET_TRACE_LEVEL(%d)' % trace_level)
9341 if len(flags) > 0:
9342 cmd_flags = ' | '.join(flags)
9343 else:
9344 cmd_flags = 0
9346 f.write(" static const uint8 cmd_flags = %s;\n" % cmd_flags)
9349 def WriteCmdArgFlag(self, f):
9350 """Writes the cmd kArgFlags constant."""
9351 f.write(" static const cmd::ArgFlags kArgFlags = cmd::kFixed;\n")
9353 def WriteCmdComputeSize(self, f):
9354 """Writes the ComputeSize function for the command."""
9355 f.write(" static uint32_t ComputeSize() {\n")
9356 f.write(
9357 " return static_cast<uint32_t>(sizeof(ValueType)); // NOLINT\n")
9358 f.write(" }\n")
9359 f.write("\n")
9361 def WriteCmdSetHeader(self, f):
9362 """Writes the cmd's SetHeader function."""
9363 f.write(" void SetHeader() {\n")
9364 f.write(" header.SetCmd<ValueType>();\n")
9365 f.write(" }\n")
9366 f.write("\n")
9368 def WriteCmdInit(self, f):
9369 """Writes the cmd's Init function."""
9370 f.write(" void Init(%s) {\n" % self.MakeTypedCmdArgString("_"))
9371 f.write(" SetHeader();\n")
9372 args = self.GetCmdArgs()
9373 for arg in args:
9374 f.write(" %s = _%s;\n" % (arg.name, arg.name))
9375 f.write(" }\n")
9376 f.write("\n")
9378 def WriteCmdSet(self, f):
9379 """Writes the cmd's Set function."""
9380 copy_args = self.MakeCmdArgString("_", False)
9381 f.write(" void* Set(void* cmd%s) {\n" %
9382 self.MakeTypedCmdArgString("_", True))
9383 f.write(" static_cast<ValueType*>(cmd)->Init(%s);\n" % copy_args)
9384 f.write(" return NextCmdAddress<ValueType>(cmd);\n")
9385 f.write(" }\n")
9386 f.write("\n")
9388 def WriteStruct(self, f):
9389 self.type_handler.WriteStruct(self, f)
9391 def WriteDocs(self, f):
9392 self.type_handler.WriteDocs(self, f)
9394 def WriteCmdHelper(self, f):
9395 """Writes the cmd's helper."""
9396 self.type_handler.WriteCmdHelper(self, f)
9398 def WriteServiceImplementation(self, f):
9399 """Writes the service implementation for a command."""
9400 self.type_handler.WriteServiceImplementation(self, f)
9402 def WriteServiceUnitTest(self, f, *extras):
9403 """Writes the service implementation for a command."""
9404 self.type_handler.WriteServiceUnitTest(self, f, *extras)
9406 def WriteGLES2CLibImplementation(self, f):
9407 """Writes the GLES2 C Lib Implemention."""
9408 self.type_handler.WriteGLES2CLibImplementation(self, f)
9410 def WriteGLES2InterfaceHeader(self, f):
9411 """Writes the GLES2 Interface declaration."""
9412 self.type_handler.WriteGLES2InterfaceHeader(self, f)
9414 def WriteMojoGLES2ImplHeader(self, f):
9415 """Writes the Mojo GLES2 implementation header declaration."""
9416 self.type_handler.WriteMojoGLES2ImplHeader(self, f)
9418 def WriteMojoGLES2Impl(self, f):
9419 """Writes the Mojo GLES2 implementation declaration."""
9420 self.type_handler.WriteMojoGLES2Impl(self, f)
9422 def WriteGLES2InterfaceStub(self, f):
9423 """Writes the GLES2 Interface Stub declaration."""
9424 self.type_handler.WriteGLES2InterfaceStub(self, f)
9426 def WriteGLES2InterfaceStubImpl(self, f):
9427 """Writes the GLES2 Interface Stub declaration."""
9428 self.type_handler.WriteGLES2InterfaceStubImpl(self, f)
9430 def WriteGLES2ImplementationHeader(self, f):
9431 """Writes the GLES2 Implemention declaration."""
9432 self.type_handler.WriteGLES2ImplementationHeader(self, f)
9434 def WriteGLES2Implementation(self, f):
9435 """Writes the GLES2 Implemention definition."""
9436 self.type_handler.WriteGLES2Implementation(self, f)
9438 def WriteGLES2TraceImplementationHeader(self, f):
9439 """Writes the GLES2 Trace Implemention declaration."""
9440 self.type_handler.WriteGLES2TraceImplementationHeader(self, f)
9442 def WriteGLES2TraceImplementation(self, f):
9443 """Writes the GLES2 Trace Implemention definition."""
9444 self.type_handler.WriteGLES2TraceImplementation(self, f)
9446 def WriteGLES2Header(self, f):
9447 """Writes the GLES2 Implemention unit test."""
9448 self.type_handler.WriteGLES2Header(self, f)
9450 def WriteGLES2ImplementationUnitTest(self, f):
9451 """Writes the GLES2 Implemention unit test."""
9452 self.type_handler.WriteGLES2ImplementationUnitTest(self, f)
9454 def WriteDestinationInitalizationValidation(self, f):
9455 """Writes the client side destintion initialization validation."""
9456 self.type_handler.WriteDestinationInitalizationValidation(self, f)
9458 def WriteFormatTest(self, f):
9459 """Writes the cmd's format test."""
9460 self.type_handler.WriteFormatTest(self, f)
9463 class PepperInterface(object):
9464 """A class that represents a function."""
9466 def __init__(self, info):
9467 self.name = info["name"]
9468 self.dev = info["dev"]
9470 def GetName(self):
9471 return self.name
9473 def GetInterfaceName(self):
9474 upperint = ""
9475 dev = ""
9476 if self.name:
9477 upperint = "_" + self.name.upper()
9478 if self.dev:
9479 dev = "_DEV"
9480 return "PPB_OPENGLES2%s%s_INTERFACE" % (upperint, dev)
9482 def GetStructName(self):
9483 dev = ""
9484 if self.dev:
9485 dev = "_Dev"
9486 return "PPB_OpenGLES2%s%s" % (self.name, dev)
9489 class ImmediateFunction(Function):
9490 """A class that represnets an immediate function command."""
9492 def __init__(self, func):
9493 Function.__init__(
9494 self,
9495 "%sImmediate" % func.name,
9496 func.info)
9498 def InitFunction(self):
9499 # Override args in original_args and args_for_cmds with immediate versions
9500 # of the args.
9502 new_original_args = []
9503 for arg in self.original_args:
9504 new_arg = arg.GetImmediateVersion()
9505 if new_arg:
9506 new_original_args.append(new_arg)
9507 self.original_args = new_original_args
9509 new_args_for_cmds = []
9510 for arg in self.args_for_cmds:
9511 new_arg = arg.GetImmediateVersion()
9512 if new_arg:
9513 new_args_for_cmds.append(new_arg)
9515 self.args_for_cmds = new_args_for_cmds
9517 Function.InitFunction(self)
9519 def IsImmediate(self):
9520 return True
9522 def WriteServiceImplementation(self, f):
9523 """Overridden from Function"""
9524 self.type_handler.WriteImmediateServiceImplementation(self, f)
9526 def WriteHandlerImplementation(self, f):
9527 """Overridden from Function"""
9528 self.type_handler.WriteImmediateHandlerImplementation(self, f)
9530 def WriteServiceUnitTest(self, f, *extras):
9531 """Writes the service implementation for a command."""
9532 self.type_handler.WriteImmediateServiceUnitTest(self, f, *extras)
9534 def WriteValidationCode(self, f):
9535 """Overridden from Function"""
9536 self.type_handler.WriteImmediateValidationCode(self, f)
9538 def WriteCmdArgFlag(self, f):
9539 """Overridden from Function"""
9540 f.write(" static const cmd::ArgFlags kArgFlags = cmd::kAtLeastN;\n")
9542 def WriteCmdComputeSize(self, f):
9543 """Overridden from Function"""
9544 self.type_handler.WriteImmediateCmdComputeSize(self, f)
9546 def WriteCmdSetHeader(self, f):
9547 """Overridden from Function"""
9548 self.type_handler.WriteImmediateCmdSetHeader(self, f)
9550 def WriteCmdInit(self, f):
9551 """Overridden from Function"""
9552 self.type_handler.WriteImmediateCmdInit(self, f)
9554 def WriteCmdSet(self, f):
9555 """Overridden from Function"""
9556 self.type_handler.WriteImmediateCmdSet(self, f)
9558 def WriteCmdHelper(self, f):
9559 """Overridden from Function"""
9560 self.type_handler.WriteImmediateCmdHelper(self, f)
9562 def WriteFormatTest(self, f):
9563 """Overridden from Function"""
9564 self.type_handler.WriteImmediateFormatTest(self, f)
9567 class BucketFunction(Function):
9568 """A class that represnets a bucket version of a function command."""
9570 def __init__(self, func):
9571 Function.__init__(
9572 self,
9573 "%sBucket" % func.name,
9574 func.info)
9576 def InitFunction(self):
9577 # Override args in original_args and args_for_cmds with bucket versions
9578 # of the args.
9580 new_original_args = []
9581 for arg in self.original_args:
9582 new_arg = arg.GetBucketVersion()
9583 if new_arg:
9584 new_original_args.append(new_arg)
9585 self.original_args = new_original_args
9587 new_args_for_cmds = []
9588 for arg in self.args_for_cmds:
9589 new_arg = arg.GetBucketVersion()
9590 if new_arg:
9591 new_args_for_cmds.append(new_arg)
9593 self.args_for_cmds = new_args_for_cmds
9595 Function.InitFunction(self)
9597 def WriteServiceImplementation(self, f):
9598 """Overridden from Function"""
9599 self.type_handler.WriteBucketServiceImplementation(self, f)
9601 def WriteHandlerImplementation(self, f):
9602 """Overridden from Function"""
9603 self.type_handler.WriteBucketHandlerImplementation(self, f)
9605 def WriteServiceUnitTest(self, f, *extras):
9606 """Overridden from Function"""
9607 self.type_handler.WriteBucketServiceUnitTest(self, f, *extras)
9609 def MakeOriginalArgString(self, prefix, add_comma = False, separator = ", "):
9610 """Overridden from Function"""
9611 args = self.GetOriginalArgs()
9612 arg_string = separator.join(
9613 ["%s%s" % (prefix, arg.name[0:-10] if arg.name.endswith("_bucket_id")
9614 else arg.name) for arg in args])
9615 return super(BucketFunction, self)._MaybePrependComma(arg_string, add_comma)
9618 def CreateArg(arg_string):
9619 """Creates an Argument."""
9620 arg_parts = arg_string.split()
9621 if len(arg_parts) == 1 and arg_parts[0] == 'void':
9622 return None
9623 # Is this a pointer argument?
9624 elif arg_string.find('*') >= 0:
9625 return PointerArgument(
9626 arg_parts[-1],
9627 " ".join(arg_parts[0:-1]))
9628 # Is this a resource argument? Must come after pointer check.
9629 elif arg_parts[0].startswith('GLidBind'):
9630 return ResourceIdBindArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
9631 elif arg_parts[0].startswith('GLidZero'):
9632 return ResourceIdZeroArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
9633 elif arg_parts[0].startswith('GLid'):
9634 return ResourceIdArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
9635 elif arg_parts[0].startswith('GLenum') and len(arg_parts[0]) > 6:
9636 return EnumArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
9637 elif arg_parts[0].startswith('GLbitfield') and len(arg_parts[0]) > 10:
9638 return BitFieldArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
9639 elif arg_parts[0].startswith('GLboolean') and len(arg_parts[0]) > 9:
9640 return ValidatedBoolArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
9641 elif arg_parts[0].startswith('GLboolean'):
9642 return BoolArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
9643 elif arg_parts[0].startswith('GLintUniformLocation'):
9644 return UniformLocationArgument(arg_parts[-1])
9645 elif (arg_parts[0].startswith('GLint') and len(arg_parts[0]) > 5 and
9646 not arg_parts[0].startswith('GLintptr')):
9647 return IntArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
9648 elif (arg_parts[0].startswith('GLsizeiNotNegative') or
9649 arg_parts[0].startswith('GLintptrNotNegative')):
9650 return SizeNotNegativeArgument(arg_parts[-1],
9651 " ".join(arg_parts[0:-1]),
9652 arg_parts[0][0:-11])
9653 elif arg_parts[0].startswith('GLsize'):
9654 return SizeArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
9655 else:
9656 return Argument(arg_parts[-1], " ".join(arg_parts[0:-1]))
9659 class GLGenerator(object):
9660 """A class to generate GL command buffers."""
9662 _function_re = re.compile(r'GL_APICALL(.*?)GL_APIENTRY (.*?) \((.*?)\);')
9664 def __init__(self, verbose):
9665 self.original_functions = []
9666 self.functions = []
9667 self.verbose = verbose
9668 self.errors = 0
9669 self.pepper_interfaces = []
9670 self.interface_info = {}
9671 self.generated_cpp_filenames = []
9673 for interface in _PEPPER_INTERFACES:
9674 interface = PepperInterface(interface)
9675 self.pepper_interfaces.append(interface)
9676 self.interface_info[interface.GetName()] = interface
9678 def AddFunction(self, func):
9679 """Adds a function."""
9680 self.functions.append(func)
9682 def GetFunctionInfo(self, name):
9683 """Gets a type info for the given function name."""
9684 if name in _FUNCTION_INFO:
9685 func_info = _FUNCTION_INFO[name].copy()
9686 else:
9687 func_info = {}
9689 if not 'type' in func_info:
9690 func_info['type'] = ''
9692 return func_info
9694 def Log(self, msg):
9695 """Prints something if verbose is true."""
9696 if self.verbose:
9697 print msg
9699 def Error(self, msg):
9700 """Prints an error."""
9701 print "Error: %s" % msg
9702 self.errors += 1
9704 def ParseGLH(self, filename):
9705 """Parses the cmd_buffer_functions.txt file and extracts the functions"""
9706 with open(filename, "r") as f:
9707 functions = f.read()
9708 for line in functions.splitlines():
9709 match = self._function_re.match(line)
9710 if match:
9711 func_name = match.group(2)[2:]
9712 func_info = self.GetFunctionInfo(func_name)
9713 if func_info['type'] == 'Noop':
9714 continue
9716 parsed_func_info = {
9717 'original_name': func_name,
9718 'original_args': match.group(3),
9719 'return_type': match.group(1).strip(),
9722 for k in parsed_func_info.keys():
9723 if not k in func_info:
9724 func_info[k] = parsed_func_info[k]
9726 f = Function(func_name, func_info)
9727 self.original_functions.append(f)
9729 #for arg in f.GetOriginalArgs():
9730 # if not isinstance(arg, EnumArgument) and arg.type == 'GLenum':
9731 # self.Log("%s uses bare GLenum %s." % (func_name, arg.name))
9733 gen_cmd = f.GetInfo('gen_cmd')
9734 if gen_cmd == True or gen_cmd == None:
9735 if f.type_handler.NeedsDataTransferFunction(f):
9736 methods = f.GetDataTransferMethods()
9737 if 'immediate' in methods:
9738 self.AddFunction(ImmediateFunction(f))
9739 if 'bucket' in methods:
9740 self.AddFunction(BucketFunction(f))
9741 if 'shm' in methods:
9742 self.AddFunction(f)
9743 else:
9744 self.AddFunction(f)
9746 self.Log("Auto Generated Functions : %d" %
9747 len([f for f in self.functions if f.can_auto_generate or
9748 (not f.IsType('') and not f.IsType('Custom') and
9749 not f.IsType('Todo'))]))
9751 funcs = [f for f in self.functions if not f.can_auto_generate and
9752 (f.IsType('') or f.IsType('Custom') or f.IsType('Todo'))]
9753 self.Log("Non Auto Generated Functions: %d" % len(funcs))
9755 for f in funcs:
9756 self.Log(" %-10s %-20s gl%s" % (f.info['type'], f.return_type, f.name))
9758 def WriteCommandIds(self, filename):
9759 """Writes the command buffer format"""
9760 with CHeaderWriter(filename) as f:
9761 f.write("#define GLES2_COMMAND_LIST(OP) \\\n")
9762 id = 256
9763 for func in self.functions:
9764 f.write(" %-60s /* %d */ \\\n" %
9765 ("OP(%s)" % func.name, id))
9766 id += 1
9767 f.write("\n")
9769 f.write("enum CommandId {\n")
9770 f.write(" kStartPoint = cmd::kLastCommonId, "
9771 "// All GLES2 commands start after this.\n")
9772 f.write("#define GLES2_CMD_OP(name) k ## name,\n")
9773 f.write(" GLES2_COMMAND_LIST(GLES2_CMD_OP)\n")
9774 f.write("#undef GLES2_CMD_OP\n")
9775 f.write(" kNumCommands\n")
9776 f.write("};\n")
9777 f.write("\n")
9778 self.generated_cpp_filenames.append(filename)
9780 def WriteFormat(self, filename):
9781 """Writes the command buffer format"""
9782 with CHeaderWriter(filename) as f:
9783 # Forward declaration of a few enums used in constant argument
9784 # to avoid including GL header files.
9785 enum_defines = {
9786 'GL_SYNC_GPU_COMMANDS_COMPLETE': '0x9117',
9787 'GL_SYNC_FLUSH_COMMANDS_BIT': '0x00000001',
9789 f.write('\n')
9790 for enum in enum_defines:
9791 f.write("#define %s %s\n" % (enum, enum_defines[enum]))
9792 f.write('\n')
9793 for func in self.functions:
9794 if True:
9795 #gen_cmd = func.GetInfo('gen_cmd')
9796 #if gen_cmd == True or gen_cmd == None:
9797 func.WriteStruct(f)
9798 f.write("\n")
9799 self.generated_cpp_filenames.append(filename)
9801 def WriteDocs(self, filename):
9802 """Writes the command buffer doc version of the commands"""
9803 with CHeaderWriter(filename) as f:
9804 for func in self.functions:
9805 if True:
9806 #gen_cmd = func.GetInfo('gen_cmd')
9807 #if gen_cmd == True or gen_cmd == None:
9808 func.WriteDocs(f)
9809 f.write("\n")
9810 self.generated_cpp_filenames.append(filename)
9812 def WriteFormatTest(self, filename):
9813 """Writes the command buffer format test."""
9814 comment = ("// This file contains unit tests for gles2 commmands\n"
9815 "// It is included by gles2_cmd_format_test.cc\n\n")
9816 with CHeaderWriter(filename, comment) as f:
9817 for func in self.functions:
9818 if True:
9819 #gen_cmd = func.GetInfo('gen_cmd')
9820 #if gen_cmd == True or gen_cmd == None:
9821 func.WriteFormatTest(f)
9822 self.generated_cpp_filenames.append(filename)
9824 def WriteCmdHelperHeader(self, filename):
9825 """Writes the gles2 command helper."""
9826 with CHeaderWriter(filename) as f:
9827 for func in self.functions:
9828 if True:
9829 #gen_cmd = func.GetInfo('gen_cmd')
9830 #if gen_cmd == True or gen_cmd == None:
9831 func.WriteCmdHelper(f)
9832 self.generated_cpp_filenames.append(filename)
9834 def WriteServiceContextStateHeader(self, filename):
9835 """Writes the service context state header."""
9836 comment = "// It is included by context_state.h\n"
9837 with CHeaderWriter(filename, comment) as f:
9838 f.write("struct EnableFlags {\n")
9839 f.write(" EnableFlags();\n")
9840 for capability in _CAPABILITY_FLAGS:
9841 f.write(" bool %s;\n" % capability['name'])
9842 f.write(" bool cached_%s;\n" % capability['name'])
9843 f.write("};\n\n")
9845 for state_name in sorted(_STATES.keys()):
9846 state = _STATES[state_name]
9847 for item in state['states']:
9848 if isinstance(item['default'], list):
9849 f.write("%s %s[%d];\n" % (item['type'], item['name'],
9850 len(item['default'])))
9851 else:
9852 f.write("%s %s;\n" % (item['type'], item['name']))
9854 if item.get('cached', False):
9855 if isinstance(item['default'], list):
9856 f.write("%s cached_%s[%d];\n" % (item['type'], item['name'],
9857 len(item['default'])))
9858 else:
9859 f.write("%s cached_%s;\n" % (item['type'], item['name']))
9861 f.write("\n")
9862 f.write("""
9863 inline void SetDeviceCapabilityState(GLenum cap, bool enable) {
9864 switch (cap) {
9865 """)
9866 for capability in _CAPABILITY_FLAGS:
9867 f.write("""\
9868 case GL_%s:
9869 """ % capability['name'].upper())
9870 f.write("""\
9871 if (enable_flags.cached_%(name)s == enable &&
9872 !ignore_cached_state)
9873 return;
9874 enable_flags.cached_%(name)s = enable;
9875 break;
9876 """ % capability)
9878 f.write("""\
9879 default:
9880 NOTREACHED();
9881 return;
9883 if (enable)
9884 glEnable(cap);
9885 else
9886 glDisable(cap);
9888 """)
9889 self.generated_cpp_filenames.append(filename)
9891 def WriteClientContextStateHeader(self, filename):
9892 """Writes the client context state header."""
9893 comment = "// It is included by client_context_state.h\n"
9894 with CHeaderWriter(filename, comment) as f:
9895 f.write("struct EnableFlags {\n")
9896 f.write(" EnableFlags();\n")
9897 for capability in _CAPABILITY_FLAGS:
9898 f.write(" bool %s;\n" % capability['name'])
9899 f.write("};\n\n")
9900 self.generated_cpp_filenames.append(filename)
9902 def WriteContextStateGetters(self, f, class_name):
9903 """Writes the state getters."""
9904 for gl_type in ["GLint", "GLfloat"]:
9905 f.write("""
9906 bool %s::GetStateAs%s(
9907 GLenum pname, %s* params, GLsizei* num_written) const {
9908 switch (pname) {
9909 """ % (class_name, gl_type, gl_type))
9910 for state_name in sorted(_STATES.keys()):
9911 state = _STATES[state_name]
9912 if 'enum' in state:
9913 f.write(" case %s:\n" % state['enum'])
9914 f.write(" *num_written = %d;\n" % len(state['states']))
9915 f.write(" if (params) {\n")
9916 for ndx,item in enumerate(state['states']):
9917 f.write(" params[%d] = static_cast<%s>(%s);\n" %
9918 (ndx, gl_type, item['name']))
9919 f.write(" }\n")
9920 f.write(" return true;\n")
9921 else:
9922 for item in state['states']:
9923 f.write(" case %s:\n" % item['enum'])
9924 if isinstance(item['default'], list):
9925 item_len = len(item['default'])
9926 f.write(" *num_written = %d;\n" % item_len)
9927 f.write(" if (params) {\n")
9928 if item['type'] == gl_type:
9929 f.write(" memcpy(params, %s, sizeof(%s) * %d);\n" %
9930 (item['name'], item['type'], item_len))
9931 else:
9932 f.write(" for (size_t i = 0; i < %s; ++i) {\n" %
9933 item_len)
9934 f.write(" params[i] = %s;\n" %
9935 (GetGLGetTypeConversion(gl_type, item['type'],
9936 "%s[i]" % item['name'])))
9937 f.write(" }\n");
9938 else:
9939 f.write(" *num_written = 1;\n")
9940 f.write(" if (params) {\n")
9941 f.write(" params[0] = %s;\n" %
9942 (GetGLGetTypeConversion(gl_type, item['type'],
9943 item['name'])))
9944 f.write(" }\n")
9945 f.write(" return true;\n")
9946 for capability in _CAPABILITY_FLAGS:
9947 f.write(" case GL_%s:\n" % capability['name'].upper())
9948 f.write(" *num_written = 1;\n")
9949 f.write(" if (params) {\n")
9950 f.write(
9951 " params[0] = static_cast<%s>(enable_flags.%s);\n" %
9952 (gl_type, capability['name']))
9953 f.write(" }\n")
9954 f.write(" return true;\n")
9955 f.write(""" default:
9956 return false;
9959 """)
9961 def WriteServiceContextStateImpl(self, filename):
9962 """Writes the context state service implementation."""
9963 comment = "// It is included by context_state.cc\n"
9964 with CHeaderWriter(filename, comment) as f:
9965 code = []
9966 for capability in _CAPABILITY_FLAGS:
9967 code.append("%s(%s)" %
9968 (capability['name'],
9969 ('false', 'true')['default' in capability]))
9970 code.append("cached_%s(%s)" %
9971 (capability['name'],
9972 ('false', 'true')['default' in capability]))
9973 f.write("ContextState::EnableFlags::EnableFlags()\n : %s {\n}\n" %
9974 ",\n ".join(code))
9975 f.write("\n")
9977 f.write("void ContextState::Initialize() {\n")
9978 for state_name in sorted(_STATES.keys()):
9979 state = _STATES[state_name]
9980 for item in state['states']:
9981 if isinstance(item['default'], list):
9982 for ndx, value in enumerate(item['default']):
9983 f.write(" %s[%d] = %s;\n" % (item['name'], ndx, value))
9984 else:
9985 f.write(" %s = %s;\n" % (item['name'], item['default']))
9986 if item.get('cached', False):
9987 if isinstance(item['default'], list):
9988 for ndx, value in enumerate(item['default']):
9989 f.write(" cached_%s[%d] = %s;\n" % (item['name'], ndx, value))
9990 else:
9991 f.write(" cached_%s = %s;\n" % (item['name'], item['default']))
9992 f.write("}\n")
9994 f.write("""
9995 void ContextState::InitCapabilities(const ContextState* prev_state) const {
9996 """)
9997 def WriteCapabilities(test_prev, es3_caps):
9998 for capability in _CAPABILITY_FLAGS:
9999 capability_name = capability['name']
10000 capability_es3 = 'es3' in capability and capability['es3'] == True
10001 if capability_es3 and not es3_caps or not capability_es3 and es3_caps:
10002 continue
10003 if test_prev:
10004 f.write(""" if (prev_state->enable_flags.cached_%s !=
10005 enable_flags.cached_%s) {\n""" %
10006 (capability_name, capability_name))
10007 f.write(" EnableDisable(GL_%s, enable_flags.cached_%s);\n" %
10008 (capability_name.upper(), capability_name))
10009 if test_prev:
10010 f.write(" }")
10012 f.write(" if (prev_state) {")
10013 WriteCapabilities(True, False)
10014 f.write(" if (feature_info_->IsES3Capable()) {\n")
10015 WriteCapabilities(True, True)
10016 f.write(" }\n")
10017 f.write(" } else {")
10018 WriteCapabilities(False, False)
10019 f.write(" if (feature_info_->IsES3Capable()) {\n")
10020 WriteCapabilities(False, True)
10021 f.write(" }\n")
10022 f.write(" }")
10023 f.write("""}
10025 void ContextState::InitState(const ContextState *prev_state) const {
10026 """)
10028 def WriteStates(test_prev):
10029 # We need to sort the keys so the expectations match
10030 for state_name in sorted(_STATES.keys()):
10031 state = _STATES[state_name]
10032 if state['type'] == 'FrontBack':
10033 num_states = len(state['states'])
10034 for ndx, group in enumerate(Grouper(num_states / 2,
10035 state['states'])):
10036 if test_prev:
10037 f.write(" if (")
10038 args = []
10039 for place, item in enumerate(group):
10040 item_name = CachedStateName(item)
10041 args.append('%s' % item_name)
10042 if test_prev:
10043 if place > 0:
10044 f.write(' ||\n')
10045 f.write("(%s != prev_state->%s)" % (item_name, item_name))
10046 if test_prev:
10047 f.write(")\n")
10048 f.write(
10049 " gl%s(%s, %s);\n" %
10050 (state['func'], ('GL_FRONT', 'GL_BACK')[ndx],
10051 ", ".join(args)))
10052 elif state['type'] == 'NamedParameter':
10053 for item in state['states']:
10054 item_name = CachedStateName(item)
10056 if 'extension_flag' in item:
10057 f.write(" if (feature_info_->feature_flags().%s) {\n " %
10058 item['extension_flag'])
10059 if test_prev:
10060 if isinstance(item['default'], list):
10061 f.write(" if (memcmp(prev_state->%s, %s, "
10062 "sizeof(%s) * %d)) {\n" %
10063 (item_name, item_name, item['type'],
10064 len(item['default'])))
10065 else:
10066 f.write(" if (prev_state->%s != %s) {\n " %
10067 (item_name, item_name))
10068 if 'gl_version_flag' in item:
10069 item_name = item['gl_version_flag']
10070 inverted = ''
10071 if item_name[0] == '!':
10072 inverted = '!'
10073 item_name = item_name[1:]
10074 f.write(" if (%sfeature_info_->gl_version_info().%s) {\n" %
10075 (inverted, item_name))
10076 f.write(" gl%s(%s, %s);\n" %
10077 (state['func'],
10078 (item['enum_set']
10079 if 'enum_set' in item else item['enum']),
10080 item['name']))
10081 if 'gl_version_flag' in item:
10082 f.write(" }\n")
10083 if test_prev:
10084 if 'extension_flag' in item:
10085 f.write(" ")
10086 f.write(" }")
10087 if 'extension_flag' in item:
10088 f.write(" }")
10089 else:
10090 if 'extension_flag' in state:
10091 f.write(" if (feature_info_->feature_flags().%s)\n " %
10092 state['extension_flag'])
10093 if test_prev:
10094 f.write(" if (")
10095 args = []
10096 for place, item in enumerate(state['states']):
10097 item_name = CachedStateName(item)
10098 args.append('%s' % item_name)
10099 if test_prev:
10100 if place > 0:
10101 f.write(' ||\n')
10102 f.write("(%s != prev_state->%s)" %
10103 (item_name, item_name))
10104 if test_prev:
10105 f.write(" )\n")
10106 f.write(" gl%s(%s);\n" % (state['func'], ", ".join(args)))
10108 f.write(" if (prev_state) {")
10109 WriteStates(True)
10110 f.write(" } else {")
10111 WriteStates(False)
10112 f.write(" }")
10113 f.write("}\n")
10115 f.write("""bool ContextState::GetEnabled(GLenum cap) const {
10116 switch (cap) {
10117 """)
10118 for capability in _CAPABILITY_FLAGS:
10119 f.write(" case GL_%s:\n" % capability['name'].upper())
10120 f.write(" return enable_flags.%s;\n" % capability['name'])
10121 f.write(""" default:
10122 NOTREACHED();
10123 return false;
10126 """)
10127 self.WriteContextStateGetters(f, "ContextState")
10128 self.generated_cpp_filenames.append(filename)
10130 def WriteClientContextStateImpl(self, filename):
10131 """Writes the context state client side implementation."""
10132 comment = "// It is included by client_context_state.cc\n"
10133 with CHeaderWriter(filename, comment) as f:
10134 code = []
10135 for capability in _CAPABILITY_FLAGS:
10136 code.append("%s(%s)" %
10137 (capability['name'],
10138 ('false', 'true')['default' in capability]))
10139 f.write(
10140 "ClientContextState::EnableFlags::EnableFlags()\n : %s {\n}\n" %
10141 ",\n ".join(code))
10142 f.write("\n")
10144 f.write("""
10145 bool ClientContextState::SetCapabilityState(
10146 GLenum cap, bool enabled, bool* changed) {
10147 *changed = false;
10148 switch (cap) {
10149 """)
10150 for capability in _CAPABILITY_FLAGS:
10151 f.write(" case GL_%s:\n" % capability['name'].upper())
10152 f.write(""" if (enable_flags.%(name)s != enabled) {
10153 *changed = true;
10154 enable_flags.%(name)s = enabled;
10156 return true;
10157 """ % capability)
10158 f.write(""" default:
10159 return false;
10162 """)
10163 f.write("""bool ClientContextState::GetEnabled(
10164 GLenum cap, bool* enabled) const {
10165 switch (cap) {
10166 """)
10167 for capability in _CAPABILITY_FLAGS:
10168 f.write(" case GL_%s:\n" % capability['name'].upper())
10169 f.write(" *enabled = enable_flags.%s;\n" % capability['name'])
10170 f.write(" return true;\n")
10171 f.write(""" default:
10172 return false;
10175 """)
10176 self.generated_cpp_filenames.append(filename)
10178 def WriteServiceImplementation(self, filename):
10179 """Writes the service decorder implementation."""
10180 comment = "// It is included by gles2_cmd_decoder.cc\n"
10181 with CHeaderWriter(filename, comment) as f:
10182 for func in self.functions:
10183 if True:
10184 #gen_cmd = func.GetInfo('gen_cmd')
10185 #if gen_cmd == True or gen_cmd == None:
10186 func.WriteServiceImplementation(f)
10188 f.write("""
10189 bool GLES2DecoderImpl::SetCapabilityState(GLenum cap, bool enabled) {
10190 switch (cap) {
10191 """)
10192 for capability in _CAPABILITY_FLAGS:
10193 f.write(" case GL_%s:\n" % capability['name'].upper())
10194 if 'state_flag' in capability:
10196 f.write("""\
10197 state_.enable_flags.%(name)s = enabled;
10198 if (state_.enable_flags.cached_%(name)s != enabled
10199 || state_.ignore_cached_state) {
10200 %(state_flag)s = true;
10202 return false;
10203 """ % capability)
10204 else:
10205 f.write("""\
10206 state_.enable_flags.%(name)s = enabled;
10207 if (state_.enable_flags.cached_%(name)s != enabled
10208 || state_.ignore_cached_state) {
10209 state_.enable_flags.cached_%(name)s = enabled;
10210 return true;
10212 return false;
10213 """ % capability)
10214 f.write(""" default:
10215 NOTREACHED();
10216 return false;
10219 """)
10220 self.generated_cpp_filenames.append(filename)
10222 def WriteServiceUnitTests(self, filename_pattern):
10223 """Writes the service decorder unit tests."""
10224 num_tests = len(self.functions)
10225 FUNCTIONS_PER_FILE = 98 # hard code this so it doesn't change.
10226 count = 0
10227 for test_num in range(0, num_tests, FUNCTIONS_PER_FILE):
10228 count += 1
10229 filename = filename_pattern % count
10230 comment = "// It is included by gles2_cmd_decoder_unittest_%d.cc\n" \
10231 % count
10232 with CHeaderWriter(filename, comment) as f:
10233 test_name = 'GLES2DecoderTest%d' % count
10234 end = test_num + FUNCTIONS_PER_FILE
10235 if end > num_tests:
10236 end = num_tests
10237 for idx in range(test_num, end):
10238 func = self.functions[idx]
10240 # Do any filtering of the functions here, so that the functions
10241 # will not move between the numbered files if filtering properties
10242 # are changed.
10243 if func.GetInfo('extension_flag'):
10244 continue
10246 if True:
10247 #gen_cmd = func.GetInfo('gen_cmd')
10248 #if gen_cmd == True or gen_cmd == None:
10249 if func.GetInfo('unit_test') == False:
10250 f.write("// TODO(gman): %s\n" % func.name)
10251 else:
10252 func.WriteServiceUnitTest(f, {
10253 'test_name': test_name
10255 self.generated_cpp_filenames.append(filename)
10257 comment = "// It is included by gles2_cmd_decoder_unittest_base.cc\n"
10258 filename = filename_pattern % 0
10259 with CHeaderWriter(filename, comment) as f:
10260 f.write(
10261 """void GLES2DecoderTestBase::SetupInitCapabilitiesExpectations(
10262 bool es3_capable) {""")
10263 for capability in _CAPABILITY_FLAGS:
10264 capability_es3 = 'es3' in capability and capability['es3'] == True
10265 if not capability_es3:
10266 f.write(" ExpectEnableDisable(GL_%s, %s);\n" %
10267 (capability['name'].upper(),
10268 ('false', 'true')['default' in capability]))
10270 f.write(" if (es3_capable) {")
10271 for capability in _CAPABILITY_FLAGS:
10272 capability_es3 = 'es3' in capability and capability['es3'] == True
10273 if capability_es3:
10274 f.write(" ExpectEnableDisable(GL_%s, %s);\n" %
10275 (capability['name'].upper(),
10276 ('false', 'true')['default' in capability]))
10277 f.write(""" }
10280 void GLES2DecoderTestBase::SetupInitStateExpectations() {
10281 """)
10282 # We need to sort the keys so the expectations match
10283 for state_name in sorted(_STATES.keys()):
10284 state = _STATES[state_name]
10285 if state['type'] == 'FrontBack':
10286 num_states = len(state['states'])
10287 for ndx, group in enumerate(Grouper(num_states / 2, state['states'])):
10288 args = []
10289 for item in group:
10290 if 'expected' in item:
10291 args.append(item['expected'])
10292 else:
10293 args.append(item['default'])
10294 f.write(
10295 " EXPECT_CALL(*gl_, %s(%s, %s))\n" %
10296 (state['func'], ('GL_FRONT', 'GL_BACK')[ndx], ", ".join(args)))
10297 f.write(" .Times(1)\n")
10298 f.write(" .RetiresOnSaturation();\n")
10299 elif state['type'] == 'NamedParameter':
10300 for item in state['states']:
10301 if 'extension_flag' in item:
10302 f.write(" if (group_->feature_info()->feature_flags().%s) {\n" %
10303 item['extension_flag'])
10304 f.write(" ")
10305 expect_value = item['default']
10306 if isinstance(expect_value, list):
10307 # TODO: Currently we do not check array values.
10308 expect_value = "_"
10310 f.write(
10311 " EXPECT_CALL(*gl_, %s(%s, %s))\n" %
10312 (state['func'],
10313 (item['enum_set']
10314 if 'enum_set' in item else item['enum']),
10315 expect_value))
10316 f.write(" .Times(1)\n")
10317 f.write(" .RetiresOnSaturation();\n")
10318 if 'extension_flag' in item:
10319 f.write(" }\n")
10320 else:
10321 if 'extension_flag' in state:
10322 f.write(" if (group_->feature_info()->feature_flags().%s) {\n" %
10323 state['extension_flag'])
10324 f.write(" ")
10325 args = []
10326 for item in state['states']:
10327 if 'expected' in item:
10328 args.append(item['expected'])
10329 else:
10330 args.append(item['default'])
10331 # TODO: Currently we do not check array values.
10332 args = ["_" if isinstance(arg, list) else arg for arg in args]
10333 f.write(" EXPECT_CALL(*gl_, %s(%s))\n" %
10334 (state['func'], ", ".join(args)))
10335 f.write(" .Times(1)\n")
10336 f.write(" .RetiresOnSaturation();\n")
10337 if 'extension_flag' in state:
10338 f.write(" }\n")
10339 f.write("}\n")
10340 self.generated_cpp_filenames.append(filename)
10342 def WriteServiceUnitTestsForExtensions(self, filename):
10343 """Writes the service decorder unit tests for functions with extension_flag.
10345 The functions are special in that they need a specific unit test
10346 baseclass to turn on the extension.
10348 functions = [f for f in self.functions if f.GetInfo('extension_flag')]
10349 comment = "// It is included by gles2_cmd_decoder_unittest_extensions.cc\n"
10350 with CHeaderWriter(filename, comment) as f:
10351 for func in functions:
10352 if True:
10353 if func.GetInfo('unit_test') == False:
10354 f.write("// TODO(gman): %s\n" % func.name)
10355 else:
10356 extension = ToCamelCase(
10357 ToGLExtensionString(func.GetInfo('extension_flag')))
10358 func.WriteServiceUnitTest(f, {
10359 'test_name': 'GLES2DecoderTestWith%s' % extension
10361 self.generated_cpp_filenames.append(filename)
10363 def WriteGLES2Header(self, filename):
10364 """Writes the GLES2 header."""
10365 comment = "// This file contains Chromium-specific GLES2 declarations.\n\n"
10366 with CHeaderWriter(filename, comment) as f:
10367 for func in self.original_functions:
10368 func.WriteGLES2Header(f)
10369 f.write("\n")
10370 self.generated_cpp_filenames.append(filename)
10372 def WriteGLES2CLibImplementation(self, filename):
10373 """Writes the GLES2 c lib implementation."""
10374 comment = "// These functions emulate GLES2 over command buffers.\n"
10375 with CHeaderWriter(filename, comment) as f:
10376 for func in self.original_functions:
10377 func.WriteGLES2CLibImplementation(f)
10378 f.write("""
10379 namespace gles2 {
10381 extern const NameToFunc g_gles2_function_table[] = {
10382 """)
10383 for func in self.original_functions:
10384 f.write(
10385 ' { "gl%s", reinterpret_cast<GLES2FunctionPointer>(gl%s), },\n' %
10386 (func.name, func.name))
10387 f.write(""" { NULL, NULL, },
10390 } // namespace gles2
10391 """)
10392 self.generated_cpp_filenames.append(filename)
10394 def WriteGLES2InterfaceHeader(self, filename):
10395 """Writes the GLES2 interface header."""
10396 comment = ("// This file is included by gles2_interface.h to declare the\n"
10397 "// GL api functions.\n")
10398 with CHeaderWriter(filename, comment) as f:
10399 for func in self.original_functions:
10400 func.WriteGLES2InterfaceHeader(f)
10401 self.generated_cpp_filenames.append(filename)
10403 def WriteMojoGLES2ImplHeader(self, filename):
10404 """Writes the Mojo GLES2 implementation header."""
10405 comment = ("// This file is included by gles2_interface.h to declare the\n"
10406 "// GL api functions.\n")
10407 code = """
10408 #include "gpu/command_buffer/client/gles2_interface.h"
10409 #include "third_party/mojo/src/mojo/public/c/gles2/gles2.h"
10411 namespace mojo {
10413 class MojoGLES2Impl : public gpu::gles2::GLES2Interface {
10414 public:
10415 explicit MojoGLES2Impl(MojoGLES2Context context) {
10416 context_ = context;
10418 ~MojoGLES2Impl() override {}
10420 with CHeaderWriter(filename, comment) as f:
10421 f.write(code);
10422 for func in self.original_functions:
10423 func.WriteMojoGLES2ImplHeader(f)
10424 code = """
10425 private:
10426 MojoGLES2Context context_;
10429 } // namespace mojo
10431 f.write(code);
10432 self.generated_cpp_filenames.append(filename)
10434 def WriteMojoGLES2Impl(self, filename):
10435 """Writes the Mojo GLES2 implementation."""
10436 code = """
10437 #include "mojo/gpu/mojo_gles2_impl_autogen.h"
10439 #include "base/logging.h"
10440 #include "third_party/mojo/src/mojo/public/c/gles2/chromium_copy_texture.h"
10441 #include "third_party/mojo/src/mojo/public/c/gles2/chromium_image.h"
10442 #include "third_party/mojo/src/mojo/public/c/gles2/chromium_miscellaneous.h"
10443 #include "third_party/mojo/src/mojo/public/c/gles2/chromium_pixel_transfer_buffer_object.h"
10444 #include "third_party/mojo/src/mojo/public/c/gles2/chromium_sub_image.h"
10445 #include "third_party/mojo/src/mojo/public/c/gles2/chromium_sync_point.h"
10446 #include "third_party/mojo/src/mojo/public/c/gles2/chromium_texture_mailbox.h"
10447 #include "third_party/mojo/src/mojo/public/c/gles2/gles2.h"
10448 #include "third_party/mojo/src/mojo/public/c/gles2/occlusion_query_ext.h"
10450 namespace mojo {
10453 with CWriter(filename) as f:
10454 f.write(code);
10455 for func in self.original_functions:
10456 func.WriteMojoGLES2Impl(f)
10457 code = """
10459 } // namespace mojo
10461 f.write(code);
10462 self.generated_cpp_filenames.append(filename)
10464 def WriteGLES2InterfaceStub(self, filename):
10465 """Writes the GLES2 interface stub header."""
10466 comment = "// This file is included by gles2_interface_stub.h.\n"
10467 with CHeaderWriter(filename, comment) as f:
10468 for func in self.original_functions:
10469 func.WriteGLES2InterfaceStub(f)
10470 self.generated_cpp_filenames.append(filename)
10472 def WriteGLES2InterfaceStubImpl(self, filename):
10473 """Writes the GLES2 interface header."""
10474 comment = "// This file is included by gles2_interface_stub.cc.\n"
10475 with CHeaderWriter(filename, comment) as f:
10476 for func in self.original_functions:
10477 func.WriteGLES2InterfaceStubImpl(f)
10478 self.generated_cpp_filenames.append(filename)
10480 def WriteGLES2ImplementationHeader(self, filename):
10481 """Writes the GLES2 Implementation header."""
10482 comment = \
10483 ("// This file is included by gles2_implementation.h to declare the\n"
10484 "// GL api functions.\n")
10485 with CHeaderWriter(filename, comment) as f:
10486 for func in self.original_functions:
10487 func.WriteGLES2ImplementationHeader(f)
10488 self.generated_cpp_filenames.append(filename)
10490 def WriteGLES2Implementation(self, filename):
10491 """Writes the GLES2 Implementation."""
10492 comment = \
10493 ("// This file is included by gles2_implementation.cc to define the\n"
10494 "// GL api functions.\n")
10495 with CHeaderWriter(filename, comment) as f:
10496 for func in self.original_functions:
10497 func.WriteGLES2Implementation(f)
10498 self.generated_cpp_filenames.append(filename)
10500 def WriteGLES2TraceImplementationHeader(self, filename):
10501 """Writes the GLES2 Trace Implementation header."""
10502 comment = "// This file is included by gles2_trace_implementation.h\n"
10503 with CHeaderWriter(filename, comment) as f:
10504 for func in self.original_functions:
10505 func.WriteGLES2TraceImplementationHeader(f)
10506 self.generated_cpp_filenames.append(filename)
10508 def WriteGLES2TraceImplementation(self, filename):
10509 """Writes the GLES2 Trace Implementation."""
10510 comment = "// This file is included by gles2_trace_implementation.cc\n"
10511 with CHeaderWriter(filename, comment) as f:
10512 for func in self.original_functions:
10513 func.WriteGLES2TraceImplementation(f)
10514 self.generated_cpp_filenames.append(filename)
10516 def WriteGLES2ImplementationUnitTests(self, filename):
10517 """Writes the GLES2 helper header."""
10518 comment = \
10519 ("// This file is included by gles2_implementation.h to declare the\n"
10520 "// GL api functions.\n")
10521 with CHeaderWriter(filename, comment) as f:
10522 for func in self.original_functions:
10523 func.WriteGLES2ImplementationUnitTest(f)
10524 self.generated_cpp_filenames.append(filename)
10526 def WriteServiceUtilsHeader(self, filename):
10527 """Writes the gles2 auto generated utility header."""
10528 with CHeaderWriter(filename) as f:
10529 for name in sorted(_NAMED_TYPE_INFO.keys()):
10530 named_type = NamedType(_NAMED_TYPE_INFO[name])
10531 if named_type.IsConstant():
10532 continue
10533 f.write("ValueValidator<%s> %s;\n" %
10534 (named_type.GetType(), ToUnderscore(name)))
10535 f.write("\n")
10536 self.generated_cpp_filenames.append(filename)
10538 def WriteServiceUtilsImplementation(self, filename):
10539 """Writes the gles2 auto generated utility implementation."""
10540 with CHeaderWriter(filename) as f:
10541 names = sorted(_NAMED_TYPE_INFO.keys())
10542 for name in names:
10543 named_type = NamedType(_NAMED_TYPE_INFO[name])
10544 if named_type.IsConstant():
10545 continue
10546 if named_type.GetValidValues():
10547 f.write("static const %s valid_%s_table[] = {\n" %
10548 (named_type.GetType(), ToUnderscore(name)))
10549 for value in named_type.GetValidValues():
10550 f.write(" %s,\n" % value)
10551 f.write("};\n")
10552 f.write("\n")
10553 if named_type.GetValidValuesES3():
10554 f.write("static const %s valid_%s_table_es3[] = {\n" %
10555 (named_type.GetType(), ToUnderscore(name)))
10556 for value in named_type.GetValidValuesES3():
10557 f.write(" %s,\n" % value)
10558 f.write("};\n")
10559 f.write("\n")
10560 if named_type.GetDeprecatedValuesES3():
10561 f.write("static const %s deprecated_%s_table_es3[] = {\n" %
10562 (named_type.GetType(), ToUnderscore(name)))
10563 for value in named_type.GetDeprecatedValuesES3():
10564 f.write(" %s,\n" % value)
10565 f.write("};\n")
10566 f.write("\n")
10567 f.write("Validators::Validators()")
10568 pre = ' : '
10569 for count, name in enumerate(names):
10570 named_type = NamedType(_NAMED_TYPE_INFO[name])
10571 if named_type.IsConstant():
10572 continue
10573 if named_type.GetValidValues():
10574 code = """%(pre)s%(name)s(
10575 valid_%(name)s_table, arraysize(valid_%(name)s_table))"""
10576 else:
10577 code = "%(pre)s%(name)s()"
10578 f.write(code % {
10579 'name': ToUnderscore(name),
10580 'pre': pre,
10582 pre = ',\n '
10583 f.write(" {\n");
10584 f.write("}\n\n");
10586 f.write("void Validators::UpdateValuesES3() {\n")
10587 for name in names:
10588 named_type = NamedType(_NAMED_TYPE_INFO[name])
10589 if named_type.GetDeprecatedValuesES3():
10590 code = """ %(name)s.RemoveValues(
10591 deprecated_%(name)s_table_es3, arraysize(deprecated_%(name)s_table_es3));
10593 f.write(code % {
10594 'name': ToUnderscore(name),
10596 if named_type.GetValidValuesES3():
10597 code = """ %(name)s.AddValues(
10598 valid_%(name)s_table_es3, arraysize(valid_%(name)s_table_es3));
10600 f.write(code % {
10601 'name': ToUnderscore(name),
10603 f.write("}\n\n");
10604 self.generated_cpp_filenames.append(filename)
10606 def WriteCommonUtilsHeader(self, filename):
10607 """Writes the gles2 common utility header."""
10608 with CHeaderWriter(filename) as f:
10609 type_infos = sorted(_NAMED_TYPE_INFO.keys())
10610 for type_info in type_infos:
10611 if _NAMED_TYPE_INFO[type_info]['type'] == 'GLenum':
10612 f.write("static std::string GetString%s(uint32_t value);\n" %
10613 type_info)
10614 f.write("\n")
10615 self.generated_cpp_filenames.append(filename)
10617 def WriteCommonUtilsImpl(self, filename):
10618 """Writes the gles2 common utility header."""
10619 enum_re = re.compile(r'\#define\s+(GL_[a-zA-Z0-9_]+)\s+([0-9A-Fa-fx]+)')
10620 dict = {}
10621 for fname in ['third_party/khronos/GLES2/gl2.h',
10622 'third_party/khronos/GLES2/gl2ext.h',
10623 'third_party/khronos/GLES3/gl3.h',
10624 'gpu/GLES2/gl2chromium.h',
10625 'gpu/GLES2/gl2extchromium.h']:
10626 lines = open(fname).readlines()
10627 for line in lines:
10628 m = enum_re.match(line)
10629 if m:
10630 name = m.group(1)
10631 value = m.group(2)
10632 if len(value) <= 10:
10633 if not value in dict:
10634 dict[value] = name
10635 # check our own _CHROMIUM macro conflicts with khronos GL headers.
10636 elif dict[value] != name and (name.endswith('_CHROMIUM') or
10637 dict[value].endswith('_CHROMIUM')):
10638 self.Error("code collision: %s and %s have the same code %s" %
10639 (dict[value], name, value))
10641 with CHeaderWriter(filename) as f:
10642 f.write("static const GLES2Util::EnumToString "
10643 "enum_to_string_table[] = {\n")
10644 for value in dict:
10645 f.write(' { %s, "%s", },\n' % (value, dict[value]))
10646 f.write("""};
10648 const GLES2Util::EnumToString* const GLES2Util::enum_to_string_table_ =
10649 enum_to_string_table;
10650 const size_t GLES2Util::enum_to_string_table_len_ =
10651 sizeof(enum_to_string_table) / sizeof(enum_to_string_table[0]);
10653 """)
10655 enums = sorted(_NAMED_TYPE_INFO.keys())
10656 for enum in enums:
10657 if _NAMED_TYPE_INFO[enum]['type'] == 'GLenum':
10658 f.write("std::string GLES2Util::GetString%s(uint32_t value) {\n" %
10659 enum)
10660 valid_list = _NAMED_TYPE_INFO[enum]['valid']
10661 if 'valid_es3' in _NAMED_TYPE_INFO[enum]:
10662 valid_list = valid_list + _NAMED_TYPE_INFO[enum]['valid_es3']
10663 assert len(valid_list) == len(set(valid_list))
10664 if len(valid_list) > 0:
10665 f.write(" static const EnumToString string_table[] = {\n")
10666 for value in valid_list:
10667 f.write(' { %s, "%s" },\n' % (value, value))
10668 f.write(""" };
10669 return GLES2Util::GetQualifiedEnumString(
10670 string_table, arraysize(string_table), value);
10673 """)
10674 else:
10675 f.write(""" return GLES2Util::GetQualifiedEnumString(
10676 NULL, 0, value);
10679 """)
10680 self.generated_cpp_filenames.append(filename)
10682 def WritePepperGLES2Interface(self, filename, dev):
10683 """Writes the Pepper OpenGLES interface definition."""
10684 with CWriter(filename) as f:
10685 f.write("label Chrome {\n")
10686 f.write(" M39 = 1.0\n")
10687 f.write("};\n\n")
10689 if not dev:
10690 # Declare GL types.
10691 f.write("[version=1.0]\n")
10692 f.write("describe {\n")
10693 for gltype in ['GLbitfield', 'GLboolean', 'GLbyte', 'GLclampf',
10694 'GLclampx', 'GLenum', 'GLfixed', 'GLfloat', 'GLint',
10695 'GLintptr', 'GLshort', 'GLsizei', 'GLsizeiptr',
10696 'GLubyte', 'GLuint', 'GLushort']:
10697 f.write(" %s;\n" % gltype)
10698 f.write(" %s_ptr_t;\n" % gltype)
10699 f.write("};\n\n")
10701 # C level typedefs.
10702 f.write("#inline c\n")
10703 f.write("#include \"ppapi/c/pp_resource.h\"\n")
10704 if dev:
10705 f.write("#include \"ppapi/c/ppb_opengles2.h\"\n\n")
10706 else:
10707 f.write("\n#ifndef __gl2_h_\n")
10708 for (k, v) in _GL_TYPES.iteritems():
10709 f.write("typedef %s %s;\n" % (v, k))
10710 f.write("#ifdef _WIN64\n")
10711 for (k, v) in _GL_TYPES_64.iteritems():
10712 f.write("typedef %s %s;\n" % (v, k))
10713 f.write("#else\n")
10714 for (k, v) in _GL_TYPES_32.iteritems():
10715 f.write("typedef %s %s;\n" % (v, k))
10716 f.write("#endif // _WIN64\n")
10717 f.write("#endif // __gl2_h_\n\n")
10718 f.write("#endinl\n")
10720 for interface in self.pepper_interfaces:
10721 if interface.dev != dev:
10722 continue
10723 # Historically, we provide OpenGLES2 interfaces with struct
10724 # namespace. Not to break code which uses the interface as
10725 # "struct OpenGLES2", we put it in struct namespace.
10726 f.write('\n[macro="%s", force_struct_namespace]\n' %
10727 interface.GetInterfaceName())
10728 f.write("interface %s {\n" % interface.GetStructName())
10729 for func in self.original_functions:
10730 if not func.InPepperInterface(interface):
10731 continue
10733 ret_type = func.MapCTypeToPepperIdlType(func.return_type,
10734 is_for_return_type=True)
10735 func_prefix = " %s %s(" % (ret_type, func.GetPepperName())
10736 f.write(func_prefix)
10737 f.write("[in] PP_Resource context")
10738 for arg in func.MakeTypedPepperIdlArgStrings():
10739 f.write(",\n" + " " * len(func_prefix) + arg)
10740 f.write(");\n")
10741 f.write("};\n\n")
10743 def WritePepperGLES2Implementation(self, filename):
10744 """Writes the Pepper OpenGLES interface implementation."""
10745 with CWriter(filename) as f:
10746 f.write("#include \"ppapi/shared_impl/ppb_opengles2_shared.h\"\n\n")
10747 f.write("#include \"base/logging.h\"\n")
10748 f.write("#include \"gpu/command_buffer/client/gles2_implementation.h\"\n")
10749 f.write("#include \"ppapi/shared_impl/ppb_graphics_3d_shared.h\"\n")
10750 f.write("#include \"ppapi/thunk/enter.h\"\n\n")
10752 f.write("namespace ppapi {\n\n")
10753 f.write("namespace {\n\n")
10755 f.write("typedef thunk::EnterResource<thunk::PPB_Graphics3D_API>"
10756 " Enter3D;\n\n")
10758 f.write("gpu::gles2::GLES2Implementation* ToGles2Impl(Enter3D*"
10759 " enter) {\n")
10760 f.write(" DCHECK(enter);\n")
10761 f.write(" DCHECK(enter->succeeded());\n")
10762 f.write(" return static_cast<PPB_Graphics3D_Shared*>(enter->object())->"
10763 "gles2_impl();\n");
10764 f.write("}\n\n");
10766 for func in self.original_functions:
10767 if not func.InAnyPepperExtension():
10768 continue
10770 original_arg = func.MakeTypedPepperArgString("")
10771 context_arg = "PP_Resource context_id"
10772 if len(original_arg):
10773 arg = context_arg + ", " + original_arg
10774 else:
10775 arg = context_arg
10776 f.write("%s %s(%s) {\n" %
10777 (func.return_type, func.GetPepperName(), arg))
10778 f.write(" Enter3D enter(context_id, true);\n")
10779 f.write(" if (enter.succeeded()) {\n")
10781 return_str = "" if func.return_type == "void" else "return "
10782 f.write(" %sToGles2Impl(&enter)->%s(%s);\n" %
10783 (return_str, func.original_name,
10784 func.MakeOriginalArgString("")))
10785 f.write(" }")
10786 if func.return_type == "void":
10787 f.write("\n")
10788 else:
10789 f.write(" else {\n")
10790 f.write(" return %s;\n" % func.GetErrorReturnString())
10791 f.write(" }\n")
10792 f.write("}\n\n")
10794 f.write("} // namespace\n")
10796 for interface in self.pepper_interfaces:
10797 f.write("const %s* PPB_OpenGLES2_Shared::Get%sInterface() {\n" %
10798 (interface.GetStructName(), interface.GetName()))
10799 f.write(" static const struct %s "
10800 "ppb_opengles2 = {\n" % interface.GetStructName())
10801 f.write(" &")
10802 f.write(",\n &".join(
10803 f.GetPepperName() for f in self.original_functions
10804 if f.InPepperInterface(interface)))
10805 f.write("\n")
10807 f.write(" };\n")
10808 f.write(" return &ppb_opengles2;\n")
10809 f.write("}\n")
10811 f.write("} // namespace ppapi\n")
10812 self.generated_cpp_filenames.append(filename)
10814 def WriteGLES2ToPPAPIBridge(self, filename):
10815 """Connects GLES2 helper library to PPB_OpenGLES2 interface"""
10816 with CWriter(filename) as f:
10817 f.write("#ifndef GL_GLEXT_PROTOTYPES\n")
10818 f.write("#define GL_GLEXT_PROTOTYPES\n")
10819 f.write("#endif\n")
10820 f.write("#include <GLES2/gl2.h>\n")
10821 f.write("#include <GLES2/gl2ext.h>\n")
10822 f.write("#include \"ppapi/lib/gl/gles2/gl2ext_ppapi.h\"\n\n")
10824 for func in self.original_functions:
10825 if not func.InAnyPepperExtension():
10826 continue
10828 interface = self.interface_info[func.GetInfo('pepper_interface') or '']
10830 f.write("%s GL_APIENTRY gl%s(%s) {\n" %
10831 (func.return_type, func.GetPepperName(),
10832 func.MakeTypedPepperArgString("")))
10833 return_str = "" if func.return_type == "void" else "return "
10834 interface_str = "glGet%sInterfacePPAPI()" % interface.GetName()
10835 original_arg = func.MakeOriginalArgString("")
10836 context_arg = "glGetCurrentContextPPAPI()"
10837 if len(original_arg):
10838 arg = context_arg + ", " + original_arg
10839 else:
10840 arg = context_arg
10841 if interface.GetName():
10842 f.write(" const struct %s* ext = %s;\n" %
10843 (interface.GetStructName(), interface_str))
10844 f.write(" if (ext)\n")
10845 f.write(" %sext->%s(%s);\n" %
10846 (return_str, func.GetPepperName(), arg))
10847 if return_str:
10848 f.write(" %s0;\n" % return_str)
10849 else:
10850 f.write(" %s%s->%s(%s);\n" %
10851 (return_str, interface_str, func.GetPepperName(), arg))
10852 f.write("}\n\n")
10853 self.generated_cpp_filenames.append(filename)
10855 def WriteMojoGLCallVisitor(self, filename):
10856 """Provides the GL implementation for mojo"""
10857 with CWriter(filename) as f:
10858 for func in self.original_functions:
10859 if not func.IsCoreGLFunction():
10860 continue
10861 f.write("VISIT_GL_CALL(%s, %s, (%s), (%s))\n" %
10862 (func.name, func.return_type,
10863 func.MakeTypedOriginalArgString(""),
10864 func.MakeOriginalArgString("")))
10865 self.generated_cpp_filenames.append(filename)
10867 def WriteMojoGLCallVisitorForExtension(self, filename, extension):
10868 """Provides the GL implementation for mojo for a particular extension"""
10869 with CWriter(filename) as f:
10870 for func in self.original_functions:
10871 if func.GetInfo("extension") != extension:
10872 continue
10873 f.write("VISIT_GL_CALL(%s, %s, (%s), (%s))\n" %
10874 (func.name, func.return_type,
10875 func.MakeTypedOriginalArgString(""),
10876 func.MakeOriginalArgString("")))
10877 self.generated_cpp_filenames.append(filename)
10879 def Format(generated_files):
10880 formatter = "clang-format"
10881 if platform.system() == "Windows":
10882 formatter += ".bat"
10883 for filename in generated_files:
10884 call([formatter, "-i", "-style=chromium", filename])
10886 def main(argv):
10887 """This is the main function."""
10888 parser = OptionParser()
10889 parser.add_option(
10890 "--output-dir",
10891 help="base directory for resulting files, under chrome/src. default is "
10892 "empty. Use this if you want the result stored under gen.")
10893 parser.add_option(
10894 "-v", "--verbose", action="store_true",
10895 help="prints more output.")
10897 (options, args) = parser.parse_args(args=argv)
10899 # Add in states and capabilites to GLState
10900 gl_state_valid = _NAMED_TYPE_INFO['GLState']['valid']
10901 for state_name in sorted(_STATES.keys()):
10902 state = _STATES[state_name]
10903 if 'extension_flag' in state:
10904 continue
10905 if 'enum' in state:
10906 if not state['enum'] in gl_state_valid:
10907 gl_state_valid.append(state['enum'])
10908 else:
10909 for item in state['states']:
10910 if 'extension_flag' in item:
10911 continue
10912 if not item['enum'] in gl_state_valid:
10913 gl_state_valid.append(item['enum'])
10914 for capability in _CAPABILITY_FLAGS:
10915 valid_value = "GL_%s" % capability['name'].upper()
10916 if not valid_value in gl_state_valid:
10917 gl_state_valid.append(valid_value)
10919 # This script lives under gpu/command_buffer, cd to base directory.
10920 os.chdir(os.path.dirname(__file__) + "/../..")
10921 base_dir = os.getcwd()
10922 gen = GLGenerator(options.verbose)
10923 gen.ParseGLH("gpu/command_buffer/cmd_buffer_functions.txt")
10925 # Support generating files under gen/
10926 if options.output_dir != None:
10927 os.chdir(options.output_dir)
10929 gen.WritePepperGLES2Interface("ppapi/api/ppb_opengles2.idl", False)
10930 gen.WritePepperGLES2Interface("ppapi/api/dev/ppb_opengles2ext_dev.idl", True)
10931 gen.WriteGLES2ToPPAPIBridge("ppapi/lib/gl/gles2/gles2.c")
10932 gen.WritePepperGLES2Implementation(
10933 "ppapi/shared_impl/ppb_opengles2_shared.cc")
10934 os.chdir(base_dir)
10935 gen.WriteCommandIds("gpu/command_buffer/common/gles2_cmd_ids_autogen.h")
10936 gen.WriteFormat("gpu/command_buffer/common/gles2_cmd_format_autogen.h")
10937 gen.WriteFormatTest(
10938 "gpu/command_buffer/common/gles2_cmd_format_test_autogen.h")
10939 gen.WriteGLES2InterfaceHeader(
10940 "gpu/command_buffer/client/gles2_interface_autogen.h")
10941 gen.WriteMojoGLES2ImplHeader(
10942 "mojo/gpu/mojo_gles2_impl_autogen.h")
10943 gen.WriteMojoGLES2Impl(
10944 "mojo/gpu/mojo_gles2_impl_autogen.cc")
10945 gen.WriteGLES2InterfaceStub(
10946 "gpu/command_buffer/client/gles2_interface_stub_autogen.h")
10947 gen.WriteGLES2InterfaceStubImpl(
10948 "gpu/command_buffer/client/gles2_interface_stub_impl_autogen.h")
10949 gen.WriteGLES2ImplementationHeader(
10950 "gpu/command_buffer/client/gles2_implementation_autogen.h")
10951 gen.WriteGLES2Implementation(
10952 "gpu/command_buffer/client/gles2_implementation_impl_autogen.h")
10953 gen.WriteGLES2ImplementationUnitTests(
10954 "gpu/command_buffer/client/gles2_implementation_unittest_autogen.h")
10955 gen.WriteGLES2TraceImplementationHeader(
10956 "gpu/command_buffer/client/gles2_trace_implementation_autogen.h")
10957 gen.WriteGLES2TraceImplementation(
10958 "gpu/command_buffer/client/gles2_trace_implementation_impl_autogen.h")
10959 gen.WriteGLES2CLibImplementation(
10960 "gpu/command_buffer/client/gles2_c_lib_autogen.h")
10961 gen.WriteCmdHelperHeader(
10962 "gpu/command_buffer/client/gles2_cmd_helper_autogen.h")
10963 gen.WriteServiceImplementation(
10964 "gpu/command_buffer/service/gles2_cmd_decoder_autogen.h")
10965 gen.WriteServiceContextStateHeader(
10966 "gpu/command_buffer/service/context_state_autogen.h")
10967 gen.WriteServiceContextStateImpl(
10968 "gpu/command_buffer/service/context_state_impl_autogen.h")
10969 gen.WriteClientContextStateHeader(
10970 "gpu/command_buffer/client/client_context_state_autogen.h")
10971 gen.WriteClientContextStateImpl(
10972 "gpu/command_buffer/client/client_context_state_impl_autogen.h")
10973 gen.WriteServiceUnitTests(
10974 "gpu/command_buffer/service/gles2_cmd_decoder_unittest_%d_autogen.h")
10975 gen.WriteServiceUnitTestsForExtensions(
10976 "gpu/command_buffer/service/"
10977 "gles2_cmd_decoder_unittest_extensions_autogen.h")
10978 gen.WriteServiceUtilsHeader(
10979 "gpu/command_buffer/service/gles2_cmd_validation_autogen.h")
10980 gen.WriteServiceUtilsImplementation(
10981 "gpu/command_buffer/service/"
10982 "gles2_cmd_validation_implementation_autogen.h")
10983 gen.WriteCommonUtilsHeader(
10984 "gpu/command_buffer/common/gles2_cmd_utils_autogen.h")
10985 gen.WriteCommonUtilsImpl(
10986 "gpu/command_buffer/common/gles2_cmd_utils_implementation_autogen.h")
10987 gen.WriteGLES2Header("gpu/GLES2/gl2chromium_autogen.h")
10988 mojo_gles2_prefix = ("third_party/mojo/src/mojo/public/c/gles2/"
10989 "gles2_call_visitor")
10990 gen.WriteMojoGLCallVisitor(mojo_gles2_prefix + "_autogen.h")
10991 gen.WriteMojoGLCallVisitorForExtension(
10992 mojo_gles2_prefix + "_chromium_texture_mailbox_autogen.h",
10993 "CHROMIUM_texture_mailbox")
10994 gen.WriteMojoGLCallVisitorForExtension(
10995 mojo_gles2_prefix + "_chromium_sync_point_autogen.h",
10996 "CHROMIUM_sync_point")
10997 gen.WriteMojoGLCallVisitorForExtension(
10998 mojo_gles2_prefix + "_chromium_sub_image_autogen.h",
10999 "CHROMIUM_sub_image")
11000 gen.WriteMojoGLCallVisitorForExtension(
11001 mojo_gles2_prefix + "_chromium_miscellaneous_autogen.h",
11002 "CHROMIUM_miscellaneous")
11003 gen.WriteMojoGLCallVisitorForExtension(
11004 mojo_gles2_prefix + "_occlusion_query_ext_autogen.h",
11005 "occlusion_query_EXT")
11006 gen.WriteMojoGLCallVisitorForExtension(
11007 mojo_gles2_prefix + "_chromium_image_autogen.h",
11008 "CHROMIUM_image")
11009 gen.WriteMojoGLCallVisitorForExtension(
11010 mojo_gles2_prefix + "_chromium_copy_texture_autogen.h",
11011 "CHROMIUM_copy_texture")
11012 gen.WriteMojoGLCallVisitorForExtension(
11013 mojo_gles2_prefix + "_chromium_pixel_transfer_buffer_object_autogen.h",
11014 "CHROMIUM_pixel_transfer_buffer_object")
11016 Format(gen.generated_cpp_filenames)
11018 if gen.errors > 0:
11019 print "%d errors" % gen.errors
11020 return 1
11021 return 0
11024 if __name__ == '__main__':
11025 sys.exit(main(sys.argv[1:]))