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