Pin Chrome's shortcut to the Win10 Start menu on install and OS upgrade.
[chromium-blink-merge.git] / gpu / command_buffer / build_gles2_cmd_buffer.py
bloba01d1b911ac3a10c4be1f224536e0fec38f7138a
1 #!/usr/bin/env python
2 # Copyright (c) 2012 The Chromium Authors. All rights reserved.
3 # Use of this source code is governed by a BSD-style license that can be
4 # found in the LICENSE file.
6 """code generator for GLES2 command buffers."""
8 import itertools
9 import os
10 import os.path
11 import sys
12 import re
13 import platform
14 from optparse import OptionParser
15 from subprocess import call
17 _SIZE_OF_UINT32 = 4
18 _SIZE_OF_COMMAND_HEADER = 4
19 _FIRST_SPECIFIC_COMMAND_ID = 256
21 _LICENSE = """// Copyright 2014 The Chromium Authors. All rights reserved.
22 // Use of this source code is governed by a BSD-style license that can be
23 // found in the LICENSE file.
25 """
27 _DO_NOT_EDIT_WARNING = """// This file is auto-generated from
28 // gpu/command_buffer/build_gles2_cmd_buffer.py
29 // It's formatted by clang-format using chromium coding style:
30 // clang-format -i -style=chromium filename
31 // DO NOT EDIT!
33 """
35 # This string is copied directly out of the gl2.h file from GLES2.0
37 # Edits:
39 # *) Any argument that is a resourceID has been changed to GLid<Type>.
40 # (not pointer arguments) and if it's allowed to be zero it's GLidZero<Type>
41 # If it's allowed to not exist it's GLidBind<Type>
43 # *) All GLenums have been changed to GLenumTypeOfEnum
45 _GL_TYPES = {
46 'GLenum': 'unsigned int',
47 'GLboolean': 'unsigned char',
48 'GLbitfield': 'unsigned int',
49 'GLbyte': 'signed char',
50 'GLshort': 'short',
51 'GLint': 'int',
52 'GLsizei': 'int',
53 'GLubyte': 'unsigned char',
54 'GLushort': 'unsigned short',
55 'GLuint': 'unsigned int',
56 'GLfloat': 'float',
57 'GLclampf': 'float',
58 'GLvoid': 'void',
59 'GLfixed': 'int',
60 'GLclampx': 'int'
63 _GL_TYPES_32 = {
64 'GLintptr': 'long int',
65 'GLsizeiptr': 'long int'
68 _GL_TYPES_64 = {
69 'GLintptr': 'long long int',
70 'GLsizeiptr': 'long long int'
73 # Capabilites selected with glEnable
74 _CAPABILITY_FLAGS = [
75 {'name': 'blend'},
76 {'name': 'cull_face'},
77 {'name': 'depth_test', 'state_flag': 'framebuffer_state_.clear_state_dirty'},
78 {'name': 'dither', 'default': True},
79 {'name': 'polygon_offset_fill'},
80 {'name': 'sample_alpha_to_coverage'},
81 {'name': 'sample_coverage'},
82 {'name': 'scissor_test'},
83 {'name': 'stencil_test',
84 'state_flag': 'framebuffer_state_.clear_state_dirty'},
85 {'name': 'rasterizer_discard', 'es3': True},
86 {'name': 'primitive_restart_fixed_index', 'es3': True},
89 _STATES = {
90 'ClearColor': {
91 'type': 'Normal',
92 'func': 'ClearColor',
93 'enum': 'GL_COLOR_CLEAR_VALUE',
94 'states': [
95 {'name': 'color_clear_red', 'type': 'GLfloat', 'default': '0.0f'},
96 {'name': 'color_clear_green', 'type': 'GLfloat', 'default': '0.0f'},
97 {'name': 'color_clear_blue', 'type': 'GLfloat', 'default': '0.0f'},
98 {'name': 'color_clear_alpha', 'type': 'GLfloat', 'default': '0.0f'},
101 'ClearDepthf': {
102 'type': 'Normal',
103 'func': 'ClearDepth',
104 'enum': 'GL_DEPTH_CLEAR_VALUE',
105 'states': [
106 {'name': 'depth_clear', 'type': 'GLclampf', 'default': '1.0f'},
109 'ColorMask': {
110 'type': 'Normal',
111 'func': 'ColorMask',
112 'enum': 'GL_COLOR_WRITEMASK',
113 'states': [
115 'name': 'color_mask_red',
116 'type': 'GLboolean',
117 'default': 'true',
118 'cached': True
121 'name': 'color_mask_green',
122 'type': 'GLboolean',
123 'default': 'true',
124 'cached': True
127 'name': 'color_mask_blue',
128 'type': 'GLboolean',
129 'default': 'true',
130 'cached': True
133 'name': 'color_mask_alpha',
134 'type': 'GLboolean',
135 'default': 'true',
136 'cached': True
139 'state_flag': 'framebuffer_state_.clear_state_dirty',
141 'ClearStencil': {
142 'type': 'Normal',
143 'func': 'ClearStencil',
144 'enum': 'GL_STENCIL_CLEAR_VALUE',
145 'states': [
146 {'name': 'stencil_clear', 'type': 'GLint', 'default': '0'},
149 'BlendColor': {
150 'type': 'Normal',
151 'func': 'BlendColor',
152 'enum': 'GL_BLEND_COLOR',
153 'states': [
154 {'name': 'blend_color_red', 'type': 'GLfloat', 'default': '0.0f'},
155 {'name': 'blend_color_green', 'type': 'GLfloat', 'default': '0.0f'},
156 {'name': 'blend_color_blue', 'type': 'GLfloat', 'default': '0.0f'},
157 {'name': 'blend_color_alpha', 'type': 'GLfloat', 'default': '0.0f'},
160 'BlendEquation': {
161 'type': 'SrcDst',
162 'func': 'BlendEquationSeparate',
163 'states': [
165 'name': 'blend_equation_rgb',
166 'type': 'GLenum',
167 'enum': 'GL_BLEND_EQUATION_RGB',
168 'default': 'GL_FUNC_ADD',
171 'name': 'blend_equation_alpha',
172 'type': 'GLenum',
173 'enum': 'GL_BLEND_EQUATION_ALPHA',
174 'default': 'GL_FUNC_ADD',
178 'BlendFunc': {
179 'type': 'SrcDst',
180 'func': 'BlendFuncSeparate',
181 'states': [
183 'name': 'blend_source_rgb',
184 'type': 'GLenum',
185 'enum': 'GL_BLEND_SRC_RGB',
186 'default': 'GL_ONE',
189 'name': 'blend_dest_rgb',
190 'type': 'GLenum',
191 'enum': 'GL_BLEND_DST_RGB',
192 'default': 'GL_ZERO',
195 'name': 'blend_source_alpha',
196 'type': 'GLenum',
197 'enum': 'GL_BLEND_SRC_ALPHA',
198 'default': 'GL_ONE',
201 'name': 'blend_dest_alpha',
202 'type': 'GLenum',
203 'enum': 'GL_BLEND_DST_ALPHA',
204 'default': 'GL_ZERO',
208 'PolygonOffset': {
209 'type': 'Normal',
210 'func': 'PolygonOffset',
211 'states': [
213 'name': 'polygon_offset_factor',
214 'type': 'GLfloat',
215 'enum': 'GL_POLYGON_OFFSET_FACTOR',
216 'default': '0.0f',
219 'name': 'polygon_offset_units',
220 'type': 'GLfloat',
221 'enum': 'GL_POLYGON_OFFSET_UNITS',
222 'default': '0.0f',
226 'CullFace': {
227 'type': 'Normal',
228 'func': 'CullFace',
229 'enum': 'GL_CULL_FACE_MODE',
230 'states': [
232 'name': 'cull_mode',
233 'type': 'GLenum',
234 'default': 'GL_BACK',
238 'FrontFace': {
239 'type': 'Normal',
240 'func': 'FrontFace',
241 'enum': 'GL_FRONT_FACE',
242 'states': [{'name': 'front_face', 'type': 'GLenum', 'default': 'GL_CCW'}],
244 'DepthFunc': {
245 'type': 'Normal',
246 'func': 'DepthFunc',
247 'enum': 'GL_DEPTH_FUNC',
248 'states': [{'name': 'depth_func', 'type': 'GLenum', 'default': 'GL_LESS'}],
250 'DepthRange': {
251 'type': 'Normal',
252 'func': 'DepthRange',
253 'enum': 'GL_DEPTH_RANGE',
254 'states': [
255 {'name': 'z_near', 'type': 'GLclampf', 'default': '0.0f'},
256 {'name': 'z_far', 'type': 'GLclampf', 'default': '1.0f'},
259 'SampleCoverage': {
260 'type': 'Normal',
261 'func': 'SampleCoverage',
262 'states': [
264 'name': 'sample_coverage_value',
265 'type': 'GLclampf',
266 'enum': 'GL_SAMPLE_COVERAGE_VALUE',
267 'default': '1.0f',
270 'name': 'sample_coverage_invert',
271 'type': 'GLboolean',
272 'enum': 'GL_SAMPLE_COVERAGE_INVERT',
273 'default': 'false',
277 'StencilMask': {
278 'type': 'FrontBack',
279 'func': 'StencilMaskSeparate',
280 'state_flag': 'framebuffer_state_.clear_state_dirty',
281 'states': [
283 'name': 'stencil_front_writemask',
284 'type': 'GLuint',
285 'enum': 'GL_STENCIL_WRITEMASK',
286 'default': '0xFFFFFFFFU',
287 'cached': True,
290 'name': 'stencil_back_writemask',
291 'type': 'GLuint',
292 'enum': 'GL_STENCIL_BACK_WRITEMASK',
293 'default': '0xFFFFFFFFU',
294 'cached': True,
298 'StencilOp': {
299 'type': 'FrontBack',
300 'func': 'StencilOpSeparate',
301 'states': [
303 'name': 'stencil_front_fail_op',
304 'type': 'GLenum',
305 'enum': 'GL_STENCIL_FAIL',
306 'default': 'GL_KEEP',
309 'name': 'stencil_front_z_fail_op',
310 'type': 'GLenum',
311 'enum': 'GL_STENCIL_PASS_DEPTH_FAIL',
312 'default': 'GL_KEEP',
315 'name': 'stencil_front_z_pass_op',
316 'type': 'GLenum',
317 'enum': 'GL_STENCIL_PASS_DEPTH_PASS',
318 'default': 'GL_KEEP',
321 'name': 'stencil_back_fail_op',
322 'type': 'GLenum',
323 'enum': 'GL_STENCIL_BACK_FAIL',
324 'default': 'GL_KEEP',
327 'name': 'stencil_back_z_fail_op',
328 'type': 'GLenum',
329 'enum': 'GL_STENCIL_BACK_PASS_DEPTH_FAIL',
330 'default': 'GL_KEEP',
333 'name': 'stencil_back_z_pass_op',
334 'type': 'GLenum',
335 'enum': 'GL_STENCIL_BACK_PASS_DEPTH_PASS',
336 'default': 'GL_KEEP',
340 'StencilFunc': {
341 'type': 'FrontBack',
342 'func': 'StencilFuncSeparate',
343 'states': [
345 'name': 'stencil_front_func',
346 'type': 'GLenum',
347 'enum': 'GL_STENCIL_FUNC',
348 'default': 'GL_ALWAYS',
351 'name': 'stencil_front_ref',
352 'type': 'GLint',
353 'enum': 'GL_STENCIL_REF',
354 'default': '0',
357 'name': 'stencil_front_mask',
358 'type': 'GLuint',
359 'enum': 'GL_STENCIL_VALUE_MASK',
360 'default': '0xFFFFFFFFU',
363 'name': 'stencil_back_func',
364 'type': 'GLenum',
365 'enum': 'GL_STENCIL_BACK_FUNC',
366 'default': 'GL_ALWAYS',
369 'name': 'stencil_back_ref',
370 'type': 'GLint',
371 'enum': 'GL_STENCIL_BACK_REF',
372 'default': '0',
375 'name': 'stencil_back_mask',
376 'type': 'GLuint',
377 'enum': 'GL_STENCIL_BACK_VALUE_MASK',
378 'default': '0xFFFFFFFFU',
382 'Hint': {
383 'type': 'NamedParameter',
384 'func': 'Hint',
385 'states': [
387 'name': 'hint_generate_mipmap',
388 'type': 'GLenum',
389 'enum': 'GL_GENERATE_MIPMAP_HINT',
390 'default': 'GL_DONT_CARE',
391 'gl_version_flag': '!is_desktop_core_profile'
394 'name': 'hint_fragment_shader_derivative',
395 'type': 'GLenum',
396 'enum': 'GL_FRAGMENT_SHADER_DERIVATIVE_HINT_OES',
397 'default': 'GL_DONT_CARE',
398 'extension_flag': 'oes_standard_derivatives'
402 'PixelStore': {
403 'type': 'NamedParameter',
404 'func': 'PixelStorei',
405 'states': [
407 'name': 'pack_alignment',
408 'type': 'GLint',
409 'enum': 'GL_PACK_ALIGNMENT',
410 'default': '4'
413 'name': 'unpack_alignment',
414 'type': 'GLint',
415 'enum': 'GL_UNPACK_ALIGNMENT',
416 'default': '4'
420 # TODO: Consider implemenenting these states
421 # GL_ACTIVE_TEXTURE
422 'LineWidth': {
423 'type': 'Normal',
424 'func': 'LineWidth',
425 'enum': 'GL_LINE_WIDTH',
426 'states': [
428 'name': 'line_width',
429 'type': 'GLfloat',
430 'default': '1.0f',
431 'range_checks': [{'check': "<= 0.0f", 'test_value': "0.0f"}],
432 'nan_check': True,
435 'DepthMask': {
436 'type': 'Normal',
437 'func': 'DepthMask',
438 'enum': 'GL_DEPTH_WRITEMASK',
439 'states': [
441 'name': 'depth_mask',
442 'type': 'GLboolean',
443 'default': 'true',
444 'cached': True
447 'state_flag': 'framebuffer_state_.clear_state_dirty',
449 'Scissor': {
450 'type': 'Normal',
451 'func': 'Scissor',
452 'enum': 'GL_SCISSOR_BOX',
453 'states': [
454 # NOTE: These defaults reset at GLES2DecoderImpl::Initialization.
456 'name': 'scissor_x',
457 'type': 'GLint',
458 'default': '0',
459 'expected': 'kViewportX',
462 'name': 'scissor_y',
463 'type': 'GLint',
464 'default': '0',
465 'expected': 'kViewportY',
468 'name': 'scissor_width',
469 'type': 'GLsizei',
470 'default': '1',
471 'expected': 'kViewportWidth',
474 'name': 'scissor_height',
475 'type': 'GLsizei',
476 'default': '1',
477 'expected': 'kViewportHeight',
481 'Viewport': {
482 'type': 'Normal',
483 'func': 'Viewport',
484 'enum': 'GL_VIEWPORT',
485 'states': [
486 # NOTE: These defaults reset at GLES2DecoderImpl::Initialization.
488 'name': 'viewport_x',
489 'type': 'GLint',
490 'default': '0',
491 'expected': 'kViewportX',
494 'name': 'viewport_y',
495 'type': 'GLint',
496 'default': '0',
497 'expected': 'kViewportY',
500 'name': 'viewport_width',
501 'type': 'GLsizei',
502 'default': '1',
503 'expected': 'kViewportWidth',
506 'name': 'viewport_height',
507 'type': 'GLsizei',
508 'default': '1',
509 'expected': 'kViewportHeight',
513 'MatrixValuesCHROMIUM': {
514 'type': 'NamedParameter',
515 'func': 'MatrixLoadfEXT',
516 'states': [
517 { 'enum': 'GL_PATH_MODELVIEW_MATRIX_CHROMIUM',
518 'enum_set': 'GL_PATH_MODELVIEW_CHROMIUM',
519 'name': 'modelview_matrix',
520 'type': 'GLfloat',
521 'default': [
522 '1.0f', '0.0f','0.0f','0.0f',
523 '0.0f', '1.0f','0.0f','0.0f',
524 '0.0f', '0.0f','1.0f','0.0f',
525 '0.0f', '0.0f','0.0f','1.0f',
527 'extension_flag': 'chromium_path_rendering',
529 { 'enum': 'GL_PATH_PROJECTION_MATRIX_CHROMIUM',
530 'enum_set': 'GL_PATH_PROJECTION_CHROMIUM',
531 'name': 'projection_matrix',
532 'type': 'GLfloat',
533 'default': [
534 '1.0f', '0.0f','0.0f','0.0f',
535 '0.0f', '1.0f','0.0f','0.0f',
536 '0.0f', '0.0f','1.0f','0.0f',
537 '0.0f', '0.0f','0.0f','1.0f',
539 'extension_flag': 'chromium_path_rendering',
543 'PathStencilFuncCHROMIUM': {
544 'type': 'Normal',
545 'func': 'PathStencilFuncNV',
546 'extension_flag': 'chromium_path_rendering',
547 'states': [
549 'name': 'stencil_path_func',
550 'type': 'GLenum',
551 'enum': 'GL_PATH_STENCIL_FUNC_CHROMIUM',
552 'default': 'GL_ALWAYS',
555 'name': 'stencil_path_ref',
556 'type': 'GLint',
557 'enum': 'GL_PATH_STENCIL_REF_CHROMIUM',
558 'default': '0',
561 'name': 'stencil_path_mask',
562 'type': 'GLuint',
563 'enum': 'GL_PATH_STENCIL_VALUE_MASK_CHROMIUM',
564 'default': '0xFFFFFFFFU',
570 # Named type info object represents a named type that is used in OpenGL call
571 # arguments. Each named type defines a set of valid OpenGL call arguments. The
572 # named types are used in 'cmd_buffer_functions.txt'.
573 # type: The actual GL type of the named type.
574 # valid: The list of values that are valid for both the client and the service.
575 # valid_es3: The list of values that are valid in OpenGL ES 3, but not ES 2.
576 # invalid: Examples of invalid values for the type. At least these values
577 # should be tested to be invalid.
578 # deprecated_es3: The list of values that are valid in OpenGL ES 2, but
579 # deprecated in ES 3.
580 # is_complete: The list of valid values of type are final and will not be
581 # modified during runtime.
582 _NAMED_TYPE_INFO = {
583 'BlitFilter': {
584 'type': 'GLenum',
585 'valid': [
586 'GL_NEAREST',
587 'GL_LINEAR',
589 'invalid': [
590 'GL_LINEAR_MIPMAP_LINEAR',
593 'FrameBufferTarget': {
594 'type': 'GLenum',
595 'valid': [
596 'GL_FRAMEBUFFER',
598 'valid_es3': [
599 'GL_DRAW_FRAMEBUFFER' ,
600 'GL_READ_FRAMEBUFFER' ,
602 'invalid': [
603 'GL_RENDERBUFFER',
606 'InvalidateFrameBufferTarget': {
607 'type': 'GLenum',
608 'valid': [
609 'GL_FRAMEBUFFER',
611 'invalid': [
612 'GL_DRAW_FRAMEBUFFER' ,
613 'GL_READ_FRAMEBUFFER' ,
616 'RenderBufferTarget': {
617 'type': 'GLenum',
618 'valid': [
619 'GL_RENDERBUFFER',
621 'invalid': [
622 'GL_FRAMEBUFFER',
625 'BufferTarget': {
626 'type': 'GLenum',
627 'valid': [
628 'GL_ARRAY_BUFFER',
629 'GL_ELEMENT_ARRAY_BUFFER',
631 'valid_es3': [
632 'GL_COPY_READ_BUFFER',
633 'GL_COPY_WRITE_BUFFER',
634 'GL_PIXEL_PACK_BUFFER',
635 'GL_PIXEL_UNPACK_BUFFER',
636 'GL_TRANSFORM_FEEDBACK_BUFFER',
637 'GL_UNIFORM_BUFFER',
639 'invalid': [
640 'GL_RENDERBUFFER',
643 'IndexedBufferTarget': {
644 'type': 'GLenum',
645 'valid': [
646 'GL_TRANSFORM_FEEDBACK_BUFFER',
647 'GL_UNIFORM_BUFFER',
649 'invalid': [
650 'GL_RENDERBUFFER',
653 'MapBufferAccess': {
654 'type': 'GLenum',
655 'valid': [
656 'GL_MAP_READ_BIT',
657 'GL_MAP_WRITE_BIT',
658 'GL_MAP_INVALIDATE_RANGE_BIT',
659 'GL_MAP_INVALIDATE_BUFFER_BIT',
660 'GL_MAP_FLUSH_EXPLICIT_BIT',
661 'GL_MAP_UNSYNCHRONIZED_BIT',
663 'invalid': [
664 'GL_SYNC_FLUSH_COMMANDS_BIT',
667 'Bufferiv': {
668 'type': 'GLenum',
669 'valid': [
670 'GL_COLOR',
671 'GL_STENCIL',
673 'invalid': [
674 'GL_RENDERBUFFER',
677 'Bufferuiv': {
678 'type': 'GLenum',
679 'valid': [
680 'GL_COLOR',
682 'invalid': [
683 'GL_RENDERBUFFER',
686 'Bufferfv': {
687 'type': 'GLenum',
688 'valid': [
689 'GL_COLOR',
690 'GL_DEPTH',
692 'invalid': [
693 'GL_RENDERBUFFER',
696 'Bufferfi': {
697 'type': 'GLenum',
698 'valid': [
699 'GL_DEPTH_STENCIL',
701 'invalid': [
702 'GL_RENDERBUFFER',
705 'BufferUsage': {
706 'type': 'GLenum',
707 'valid': [
708 'GL_STREAM_DRAW',
709 'GL_STATIC_DRAW',
710 'GL_DYNAMIC_DRAW',
712 'valid_es3': [
713 'GL_STREAM_READ',
714 'GL_STREAM_COPY',
715 'GL_STATIC_READ',
716 'GL_STATIC_COPY',
717 'GL_DYNAMIC_READ',
718 'GL_DYNAMIC_COPY',
720 'invalid': [
721 'GL_NONE',
724 'CompressedTextureFormat': {
725 'type': 'GLenum',
726 'valid': [
728 'valid_es3': [
729 'GL_COMPRESSED_R11_EAC',
730 'GL_COMPRESSED_SIGNED_R11_EAC',
731 'GL_COMPRESSED_RG11_EAC',
732 'GL_COMPRESSED_SIGNED_RG11_EAC',
733 'GL_COMPRESSED_RGB8_ETC2',
734 'GL_COMPRESSED_SRGB8_ETC2',
735 'GL_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2',
736 'GL_COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2',
737 'GL_COMPRESSED_RGBA8_ETC2_EAC',
738 'GL_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC',
741 'GLState': {
742 'type': 'GLenum',
743 'valid': [
744 # NOTE: State an Capability entries added later.
745 'GL_ACTIVE_TEXTURE',
746 'GL_ALIASED_LINE_WIDTH_RANGE',
747 'GL_ALIASED_POINT_SIZE_RANGE',
748 'GL_ALPHA_BITS',
749 'GL_ARRAY_BUFFER_BINDING',
750 'GL_BLUE_BITS',
751 'GL_COMPRESSED_TEXTURE_FORMATS',
752 'GL_CURRENT_PROGRAM',
753 'GL_DEPTH_BITS',
754 'GL_DEPTH_RANGE',
755 'GL_ELEMENT_ARRAY_BUFFER_BINDING',
756 'GL_FRAMEBUFFER_BINDING',
757 'GL_GENERATE_MIPMAP_HINT',
758 'GL_GREEN_BITS',
759 'GL_IMPLEMENTATION_COLOR_READ_FORMAT',
760 'GL_IMPLEMENTATION_COLOR_READ_TYPE',
761 'GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS',
762 'GL_MAX_CUBE_MAP_TEXTURE_SIZE',
763 'GL_MAX_FRAGMENT_UNIFORM_VECTORS',
764 'GL_MAX_RENDERBUFFER_SIZE',
765 'GL_MAX_TEXTURE_IMAGE_UNITS',
766 'GL_MAX_TEXTURE_SIZE',
767 'GL_MAX_VARYING_VECTORS',
768 'GL_MAX_VERTEX_ATTRIBS',
769 'GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS',
770 'GL_MAX_VERTEX_UNIFORM_VECTORS',
771 'GL_MAX_VIEWPORT_DIMS',
772 'GL_NUM_COMPRESSED_TEXTURE_FORMATS',
773 'GL_NUM_SHADER_BINARY_FORMATS',
774 'GL_PACK_ALIGNMENT',
775 'GL_RED_BITS',
776 'GL_RENDERBUFFER_BINDING',
777 'GL_SAMPLE_BUFFERS',
778 'GL_SAMPLE_COVERAGE_INVERT',
779 'GL_SAMPLE_COVERAGE_VALUE',
780 'GL_SAMPLES',
781 'GL_SCISSOR_BOX',
782 'GL_SHADER_BINARY_FORMATS',
783 'GL_SHADER_COMPILER',
784 'GL_SUBPIXEL_BITS',
785 'GL_STENCIL_BITS',
786 'GL_TEXTURE_BINDING_2D',
787 'GL_TEXTURE_BINDING_CUBE_MAP',
788 'GL_UNPACK_ALIGNMENT',
789 'GL_BIND_GENERATES_RESOURCE_CHROMIUM',
790 # we can add this because we emulate it if the driver does not support it.
791 'GL_VERTEX_ARRAY_BINDING_OES',
792 'GL_VIEWPORT',
794 'valid_es3': [
795 'GL_COPY_READ_BUFFER_BINDING',
796 'GL_COPY_WRITE_BUFFER_BINDING',
797 'GL_DRAW_BUFFER0',
798 'GL_DRAW_BUFFER1',
799 'GL_DRAW_BUFFER2',
800 'GL_DRAW_BUFFER3',
801 'GL_DRAW_BUFFER4',
802 'GL_DRAW_BUFFER5',
803 'GL_DRAW_BUFFER6',
804 'GL_DRAW_BUFFER7',
805 'GL_DRAW_BUFFER8',
806 'GL_DRAW_BUFFER9',
807 'GL_DRAW_BUFFER10',
808 'GL_DRAW_BUFFER11',
809 'GL_DRAW_BUFFER12',
810 'GL_DRAW_BUFFER13',
811 'GL_DRAW_BUFFER14',
812 'GL_DRAW_BUFFER15',
813 'GL_DRAW_FRAMEBUFFER_BINDING',
814 'GL_FRAGMENT_SHADER_DERIVATIVE_HINT',
815 'GL_MAJOR_VERSION',
816 'GL_MAX_3D_TEXTURE_SIZE',
817 'GL_MAX_ARRAY_TEXTURE_LAYERS',
818 'GL_MAX_COLOR_ATTACHMENTS',
819 'GL_MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS',
820 'GL_MAX_COMBINED_UNIFORM_BLOCKS',
821 'GL_MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS',
822 'GL_MAX_DRAW_BUFFERS',
823 'GL_MAX_ELEMENT_INDEX',
824 'GL_MAX_ELEMENTS_INDICES',
825 'GL_MAX_ELEMENTS_VERTICES',
826 'GL_MAX_FRAGMENT_INPUT_COMPONENTS',
827 'GL_MAX_FRAGMENT_UNIFORM_BLOCKS',
828 'GL_MAX_FRAGMENT_UNIFORM_COMPONENTS',
829 'GL_MAX_PROGRAM_TEXEL_OFFSET',
830 'GL_MAX_SAMPLES',
831 'GL_MAX_SERVER_WAIT_TIMEOUT',
832 'GL_MAX_TEXTURE_LOD_BIAS',
833 'GL_MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS',
834 'GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS',
835 'GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS',
836 'GL_MAX_UNIFORM_BLOCK_SIZE',
837 'GL_MAX_UNIFORM_BUFFER_BINDINGS',
838 'GL_MAX_VARYING_COMPONENTS',
839 'GL_MAX_VERTEX_OUTPUT_COMPONENTS',
840 'GL_MAX_VERTEX_UNIFORM_BLOCKS',
841 'GL_MAX_VERTEX_UNIFORM_COMPONENTS',
842 'GL_MIN_PROGRAM_TEXEL_OFFSET',
843 'GL_MINOR_VERSION',
844 'GL_NUM_EXTENSIONS',
845 'GL_NUM_PROGRAM_BINARY_FORMATS',
846 'GL_PACK_ROW_LENGTH',
847 'GL_PACK_SKIP_PIXELS',
848 'GL_PACK_SKIP_ROWS',
849 'GL_PIXEL_PACK_BUFFER_BINDING',
850 'GL_PIXEL_UNPACK_BUFFER_BINDING',
851 'GL_PROGRAM_BINARY_FORMATS',
852 'GL_READ_BUFFER',
853 'GL_READ_FRAMEBUFFER_BINDING',
854 'GL_SAMPLER_BINDING',
855 'GL_TEXTURE_BINDING_2D_ARRAY',
856 'GL_TEXTURE_BINDING_3D',
857 'GL_TRANSFORM_FEEDBACK_BINDING',
858 'GL_TRANSFORM_FEEDBACK_ACTIVE',
859 'GL_TRANSFORM_FEEDBACK_BUFFER_BINDING',
860 'GL_TRANSFORM_FEEDBACK_PAUSED',
861 'GL_TRANSFORM_FEEDBACK_BUFFER_SIZE',
862 'GL_TRANSFORM_FEEDBACK_BUFFER_START',
863 'GL_UNIFORM_BUFFER_BINDING',
864 'GL_UNIFORM_BUFFER_OFFSET_ALIGNMENT',
865 'GL_UNIFORM_BUFFER_SIZE',
866 'GL_UNIFORM_BUFFER_START',
867 'GL_UNPACK_IMAGE_HEIGHT',
868 'GL_UNPACK_ROW_LENGTH',
869 'GL_UNPACK_SKIP_IMAGES',
870 'GL_UNPACK_SKIP_PIXELS',
871 'GL_UNPACK_SKIP_ROWS',
872 # GL_VERTEX_ARRAY_BINDING is the same as GL_VERTEX_ARRAY_BINDING_OES
873 # 'GL_VERTEX_ARRAY_BINDING',
875 'invalid': [
876 'GL_FOG_HINT',
879 'IndexedGLState': {
880 'type': 'GLenum',
881 'valid': [
882 'GL_TRANSFORM_FEEDBACK_BUFFER_BINDING',
883 'GL_TRANSFORM_FEEDBACK_BUFFER_SIZE',
884 'GL_TRANSFORM_FEEDBACK_BUFFER_START',
885 'GL_UNIFORM_BUFFER_BINDING',
886 'GL_UNIFORM_BUFFER_SIZE',
887 'GL_UNIFORM_BUFFER_START',
889 'invalid': [
890 'GL_FOG_HINT',
893 'GetTexParamTarget': {
894 'type': 'GLenum',
895 'valid': [
896 'GL_TEXTURE_2D',
897 'GL_TEXTURE_CUBE_MAP',
899 'valid_es3': [
900 'GL_TEXTURE_2D_ARRAY',
901 'GL_TEXTURE_3D',
903 'invalid': [
904 'GL_PROXY_TEXTURE_CUBE_MAP',
907 'TextureTarget': {
908 'type': 'GLenum',
909 'valid': [
910 'GL_TEXTURE_2D',
911 'GL_TEXTURE_CUBE_MAP_POSITIVE_X',
912 'GL_TEXTURE_CUBE_MAP_NEGATIVE_X',
913 'GL_TEXTURE_CUBE_MAP_POSITIVE_Y',
914 'GL_TEXTURE_CUBE_MAP_NEGATIVE_Y',
915 'GL_TEXTURE_CUBE_MAP_POSITIVE_Z',
916 'GL_TEXTURE_CUBE_MAP_NEGATIVE_Z',
918 'invalid': [
919 'GL_PROXY_TEXTURE_CUBE_MAP',
922 'Texture3DTarget': {
923 'type': 'GLenum',
924 'valid': [
925 'GL_TEXTURE_3D',
926 'GL_TEXTURE_2D_ARRAY',
928 'invalid': [
929 'GL_TEXTURE_2D',
932 'TextureBindTarget': {
933 'type': 'GLenum',
934 'valid': [
935 'GL_TEXTURE_2D',
936 'GL_TEXTURE_CUBE_MAP',
938 'valid_es3': [
939 'GL_TEXTURE_3D',
940 'GL_TEXTURE_2D_ARRAY',
942 'invalid': [
943 'GL_TEXTURE_1D',
944 'GL_TEXTURE_3D',
947 'TransformFeedbackBindTarget': {
948 'type': 'GLenum',
949 'valid': [
950 'GL_TRANSFORM_FEEDBACK',
952 'invalid': [
953 'GL_TEXTURE_2D',
956 'TransformFeedbackPrimitiveMode': {
957 'type': 'GLenum',
958 'valid': [
959 'GL_POINTS',
960 'GL_LINES',
961 'GL_TRIANGLES',
963 'invalid': [
964 'GL_LINE_LOOP',
967 'ShaderType': {
968 'type': 'GLenum',
969 'valid': [
970 'GL_VERTEX_SHADER',
971 'GL_FRAGMENT_SHADER',
973 'invalid': [
974 'GL_GEOMETRY_SHADER',
977 'FaceType': {
978 'type': 'GLenum',
979 'valid': [
980 'GL_FRONT',
981 'GL_BACK',
982 'GL_FRONT_AND_BACK',
985 'FaceMode': {
986 'type': 'GLenum',
987 'valid': [
988 'GL_CW',
989 'GL_CCW',
992 'CmpFunction': {
993 'type': 'GLenum',
994 'valid': [
995 'GL_NEVER',
996 'GL_LESS',
997 'GL_EQUAL',
998 'GL_LEQUAL',
999 'GL_GREATER',
1000 'GL_NOTEQUAL',
1001 'GL_GEQUAL',
1002 'GL_ALWAYS',
1005 'Equation': {
1006 'type': 'GLenum',
1007 'valid': [
1008 'GL_FUNC_ADD',
1009 'GL_FUNC_SUBTRACT',
1010 'GL_FUNC_REVERSE_SUBTRACT',
1012 'valid_es3': [
1013 'GL_MIN',
1014 'GL_MAX',
1016 'invalid': [
1017 'GL_NONE',
1020 'SrcBlendFactor': {
1021 'type': 'GLenum',
1022 'valid': [
1023 'GL_ZERO',
1024 'GL_ONE',
1025 'GL_SRC_COLOR',
1026 'GL_ONE_MINUS_SRC_COLOR',
1027 'GL_DST_COLOR',
1028 'GL_ONE_MINUS_DST_COLOR',
1029 'GL_SRC_ALPHA',
1030 'GL_ONE_MINUS_SRC_ALPHA',
1031 'GL_DST_ALPHA',
1032 'GL_ONE_MINUS_DST_ALPHA',
1033 'GL_CONSTANT_COLOR',
1034 'GL_ONE_MINUS_CONSTANT_COLOR',
1035 'GL_CONSTANT_ALPHA',
1036 'GL_ONE_MINUS_CONSTANT_ALPHA',
1037 'GL_SRC_ALPHA_SATURATE',
1040 'DstBlendFactor': {
1041 'type': 'GLenum',
1042 'valid': [
1043 'GL_ZERO',
1044 'GL_ONE',
1045 'GL_SRC_COLOR',
1046 'GL_ONE_MINUS_SRC_COLOR',
1047 'GL_DST_COLOR',
1048 'GL_ONE_MINUS_DST_COLOR',
1049 'GL_SRC_ALPHA',
1050 'GL_ONE_MINUS_SRC_ALPHA',
1051 'GL_DST_ALPHA',
1052 'GL_ONE_MINUS_DST_ALPHA',
1053 'GL_CONSTANT_COLOR',
1054 'GL_ONE_MINUS_CONSTANT_COLOR',
1055 'GL_CONSTANT_ALPHA',
1056 'GL_ONE_MINUS_CONSTANT_ALPHA',
1059 'Capability': {
1060 'type': 'GLenum',
1061 'valid': ["GL_%s" % cap['name'].upper() for cap in _CAPABILITY_FLAGS
1062 if 'es3' not in cap or cap['es3'] != True],
1063 'valid_es3': ["GL_%s" % cap['name'].upper() for cap in _CAPABILITY_FLAGS
1064 if 'es3' in cap and cap['es3'] == True],
1065 'invalid': [
1066 'GL_CLIP_PLANE0',
1067 'GL_POINT_SPRITE',
1070 'DrawMode': {
1071 'type': 'GLenum',
1072 'valid': [
1073 'GL_POINTS',
1074 'GL_LINE_STRIP',
1075 'GL_LINE_LOOP',
1076 'GL_LINES',
1077 'GL_TRIANGLE_STRIP',
1078 'GL_TRIANGLE_FAN',
1079 'GL_TRIANGLES',
1081 'invalid': [
1082 'GL_QUADS',
1083 'GL_POLYGON',
1086 'IndexType': {
1087 'type': 'GLenum',
1088 'valid': [
1089 'GL_UNSIGNED_BYTE',
1090 'GL_UNSIGNED_SHORT',
1092 'valid_es3': [
1093 'GL_UNSIGNED_INT',
1095 'invalid': [
1096 'GL_INT',
1099 'GetMaxIndexType': {
1100 'type': 'GLenum',
1101 'valid': [
1102 'GL_UNSIGNED_BYTE',
1103 'GL_UNSIGNED_SHORT',
1104 'GL_UNSIGNED_INT',
1106 'invalid': [
1107 'GL_INT',
1110 'Attachment': {
1111 'type': 'GLenum',
1112 'valid': [
1113 'GL_COLOR_ATTACHMENT0',
1114 'GL_DEPTH_ATTACHMENT',
1115 'GL_STENCIL_ATTACHMENT',
1117 'valid_es3': [
1118 'GL_DEPTH_STENCIL_ATTACHMENT',
1121 'BackbufferAttachment': {
1122 'type': 'GLenum',
1123 'valid': [
1124 'GL_COLOR_EXT',
1125 'GL_DEPTH_EXT',
1126 'GL_STENCIL_EXT',
1129 'BufferParameter': {
1130 'type': 'GLenum',
1131 'valid': [
1132 'GL_BUFFER_SIZE',
1133 'GL_BUFFER_USAGE',
1135 'valid_es3': [
1136 'GL_BUFFER_ACCESS_FLAGS',
1137 'GL_BUFFER_MAPPED',
1138 'GL_BUFFER_MAP_LENGTH',
1139 'GL_BUFFER_MAP_OFFSET',
1141 'invalid': [
1142 'GL_PIXEL_PACK_BUFFER',
1145 'BufferMode': {
1146 'type': 'GLenum',
1147 'valid': [
1148 'GL_INTERLEAVED_ATTRIBS',
1149 'GL_SEPARATE_ATTRIBS',
1151 'invalid': [
1152 'GL_PIXEL_PACK_BUFFER',
1155 'FrameBufferParameter': {
1156 'type': 'GLenum',
1157 'valid': [
1158 'GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE',
1159 'GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME',
1160 'GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL',
1161 'GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE',
1163 'valid_es3': [
1164 'GL_FRAMEBUFFER_ATTACHMENT_RED_SIZE',
1165 'GL_FRAMEBUFFER_ATTACHMENT_GREEN_SIZE',
1166 'GL_FRAMEBUFFER_ATTACHMENT_BLUE_SIZE',
1167 'GL_FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE',
1168 'GL_FRAMEBUFFER_ATTACHMENT_DEPTH_SIZE',
1169 'GL_FRAMEBUFFER_ATTACHMENT_STENCIL_SIZE',
1170 'GL_FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE',
1171 'GL_FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING',
1172 'GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER',
1175 'MatrixMode': {
1176 'type': 'GLenum',
1177 'valid': [
1178 'GL_PATH_PROJECTION_CHROMIUM',
1179 'GL_PATH_MODELVIEW_CHROMIUM',
1182 'ProgramParameter': {
1183 'type': 'GLenum',
1184 'valid': [
1185 'GL_DELETE_STATUS',
1186 'GL_LINK_STATUS',
1187 'GL_VALIDATE_STATUS',
1188 'GL_INFO_LOG_LENGTH',
1189 'GL_ATTACHED_SHADERS',
1190 'GL_ACTIVE_ATTRIBUTES',
1191 'GL_ACTIVE_ATTRIBUTE_MAX_LENGTH',
1192 'GL_ACTIVE_UNIFORMS',
1193 'GL_ACTIVE_UNIFORM_MAX_LENGTH',
1195 'valid_es3': [
1196 'GL_ACTIVE_UNIFORM_BLOCKS',
1197 'GL_ACTIVE_UNIFORM_BLOCK_MAX_NAME_LENGTH',
1198 'GL_TRANSFORM_FEEDBACK_BUFFER_MODE',
1199 'GL_TRANSFORM_FEEDBACK_VARYINGS',
1200 'GL_TRANSFORM_FEEDBACK_VARYING_MAX_LENGTH',
1202 'invalid': [
1203 'GL_PROGRAM_BINARY_RETRIEVABLE_HINT', # not supported in Chromium.
1206 'QueryObjectParameter': {
1207 'type': 'GLenum',
1208 'valid': [
1209 'GL_QUERY_RESULT_EXT',
1210 'GL_QUERY_RESULT_AVAILABLE_EXT',
1213 'QueryParameter': {
1214 'type': 'GLenum',
1215 'valid': [
1216 'GL_CURRENT_QUERY_EXT',
1219 'QueryTarget': {
1220 'type': 'GLenum',
1221 'valid': [
1222 'GL_ANY_SAMPLES_PASSED_EXT',
1223 'GL_ANY_SAMPLES_PASSED_CONSERVATIVE_EXT',
1224 'GL_COMMANDS_ISSUED_CHROMIUM',
1225 'GL_LATENCY_QUERY_CHROMIUM',
1226 'GL_ASYNC_PIXEL_UNPACK_COMPLETED_CHROMIUM',
1227 'GL_ASYNC_PIXEL_PACK_COMPLETED_CHROMIUM',
1228 'GL_COMMANDS_COMPLETED_CHROMIUM',
1231 'RenderBufferParameter': {
1232 'type': 'GLenum',
1233 'valid': [
1234 'GL_RENDERBUFFER_RED_SIZE',
1235 'GL_RENDERBUFFER_GREEN_SIZE',
1236 'GL_RENDERBUFFER_BLUE_SIZE',
1237 'GL_RENDERBUFFER_ALPHA_SIZE',
1238 'GL_RENDERBUFFER_DEPTH_SIZE',
1239 'GL_RENDERBUFFER_STENCIL_SIZE',
1240 'GL_RENDERBUFFER_WIDTH',
1241 'GL_RENDERBUFFER_HEIGHT',
1242 'GL_RENDERBUFFER_INTERNAL_FORMAT',
1244 'valid_es3': [
1245 'GL_RENDERBUFFER_SAMPLES',
1248 'InternalFormatParameter': {
1249 'type': 'GLenum',
1250 'valid': [
1251 'GL_NUM_SAMPLE_COUNTS',
1252 'GL_SAMPLES',
1255 'SamplerParameter': {
1256 'type': 'GLenum',
1257 'valid': [
1258 'GL_TEXTURE_MAG_FILTER',
1259 'GL_TEXTURE_MIN_FILTER',
1260 'GL_TEXTURE_MIN_LOD',
1261 'GL_TEXTURE_MAX_LOD',
1262 'GL_TEXTURE_WRAP_S',
1263 'GL_TEXTURE_WRAP_T',
1264 'GL_TEXTURE_WRAP_R',
1265 'GL_TEXTURE_COMPARE_MODE',
1266 'GL_TEXTURE_COMPARE_FUNC',
1268 'invalid': [
1269 'GL_GENERATE_MIPMAP',
1272 'ShaderParameter': {
1273 'type': 'GLenum',
1274 'valid': [
1275 'GL_SHADER_TYPE',
1276 'GL_DELETE_STATUS',
1277 'GL_COMPILE_STATUS',
1278 'GL_INFO_LOG_LENGTH',
1279 'GL_SHADER_SOURCE_LENGTH',
1280 'GL_TRANSLATED_SHADER_SOURCE_LENGTH_ANGLE',
1283 'ShaderPrecision': {
1284 'type': 'GLenum',
1285 'valid': [
1286 'GL_LOW_FLOAT',
1287 'GL_MEDIUM_FLOAT',
1288 'GL_HIGH_FLOAT',
1289 'GL_LOW_INT',
1290 'GL_MEDIUM_INT',
1291 'GL_HIGH_INT',
1294 'StringType': {
1295 'type': 'GLenum',
1296 'valid': [
1297 'GL_VENDOR',
1298 'GL_RENDERER',
1299 'GL_VERSION',
1300 'GL_SHADING_LANGUAGE_VERSION',
1301 'GL_EXTENSIONS',
1304 'TextureParameter': {
1305 'type': 'GLenum',
1306 'valid': [
1307 'GL_TEXTURE_MAG_FILTER',
1308 'GL_TEXTURE_MIN_FILTER',
1309 'GL_TEXTURE_POOL_CHROMIUM',
1310 'GL_TEXTURE_WRAP_S',
1311 'GL_TEXTURE_WRAP_T',
1313 'valid_es3': [
1314 'GL_TEXTURE_BASE_LEVEL',
1315 'GL_TEXTURE_COMPARE_FUNC',
1316 'GL_TEXTURE_COMPARE_MODE',
1317 'GL_TEXTURE_IMMUTABLE_FORMAT',
1318 'GL_TEXTURE_IMMUTABLE_LEVELS',
1319 'GL_TEXTURE_MAX_LEVEL',
1320 'GL_TEXTURE_MAX_LOD',
1321 'GL_TEXTURE_MIN_LOD',
1322 'GL_TEXTURE_WRAP_R',
1324 'invalid': [
1325 'GL_GENERATE_MIPMAP',
1328 'TexturePool': {
1329 'type': 'GLenum',
1330 'valid': [
1331 'GL_TEXTURE_POOL_MANAGED_CHROMIUM',
1332 'GL_TEXTURE_POOL_UNMANAGED_CHROMIUM',
1335 'TextureWrapMode': {
1336 'type': 'GLenum',
1337 'valid': [
1338 'GL_CLAMP_TO_EDGE',
1339 'GL_MIRRORED_REPEAT',
1340 'GL_REPEAT',
1343 'TextureMinFilterMode': {
1344 'type': 'GLenum',
1345 'valid': [
1346 'GL_NEAREST',
1347 'GL_LINEAR',
1348 'GL_NEAREST_MIPMAP_NEAREST',
1349 'GL_LINEAR_MIPMAP_NEAREST',
1350 'GL_NEAREST_MIPMAP_LINEAR',
1351 'GL_LINEAR_MIPMAP_LINEAR',
1354 'TextureMagFilterMode': {
1355 'type': 'GLenum',
1356 'valid': [
1357 'GL_NEAREST',
1358 'GL_LINEAR',
1361 'TextureCompareFunc': {
1362 'type': 'GLenum',
1363 'valid': [
1364 'GL_LEQUAL',
1365 'GL_GEQUAL',
1366 'GL_LESS',
1367 'GL_GREATER',
1368 'GL_EQUAL',
1369 'GL_NOTEQUAL',
1370 'GL_ALWAYS',
1371 'GL_NEVER',
1374 'TextureCompareMode': {
1375 'type': 'GLenum',
1376 'valid': [
1377 'GL_NONE',
1378 'GL_COMPARE_REF_TO_TEXTURE',
1381 'TextureUsage': {
1382 'type': 'GLenum',
1383 'valid': [
1384 'GL_NONE',
1385 'GL_FRAMEBUFFER_ATTACHMENT_ANGLE',
1388 'VertexAttribute': {
1389 'type': 'GLenum',
1390 'valid': [
1391 # some enum that the decoder actually passes through to GL needs
1392 # to be the first listed here since it's used in unit tests.
1393 'GL_VERTEX_ATTRIB_ARRAY_NORMALIZED',
1394 'GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING',
1395 'GL_VERTEX_ATTRIB_ARRAY_ENABLED',
1396 'GL_VERTEX_ATTRIB_ARRAY_SIZE',
1397 'GL_VERTEX_ATTRIB_ARRAY_STRIDE',
1398 'GL_VERTEX_ATTRIB_ARRAY_TYPE',
1399 'GL_CURRENT_VERTEX_ATTRIB',
1401 'valid_es3': [
1402 'GL_VERTEX_ATTRIB_ARRAY_INTEGER',
1403 'GL_VERTEX_ATTRIB_ARRAY_DIVISOR',
1406 'VertexPointer': {
1407 'type': 'GLenum',
1408 'valid': [
1409 'GL_VERTEX_ATTRIB_ARRAY_POINTER',
1412 'HintTarget': {
1413 'type': 'GLenum',
1414 'valid': [
1415 'GL_GENERATE_MIPMAP_HINT',
1417 'valid_es3': [
1418 'GL_FRAGMENT_SHADER_DERIVATIVE_HINT',
1420 'invalid': [
1421 'GL_PERSPECTIVE_CORRECTION_HINT',
1424 'HintMode': {
1425 'type': 'GLenum',
1426 'valid': [
1427 'GL_FASTEST',
1428 'GL_NICEST',
1429 'GL_DONT_CARE',
1432 'PixelStore': {
1433 'type': 'GLenum',
1434 'valid': [
1435 'GL_PACK_ALIGNMENT',
1436 'GL_UNPACK_ALIGNMENT',
1438 'valid_es3': [
1439 'GL_PACK_ROW_LENGTH',
1440 'GL_PACK_SKIP_PIXELS',
1441 'GL_PACK_SKIP_ROWS',
1442 'GL_UNPACK_ROW_LENGTH',
1443 'GL_UNPACK_IMAGE_HEIGHT',
1444 'GL_UNPACK_SKIP_PIXELS',
1445 'GL_UNPACK_SKIP_ROWS',
1446 'GL_UNPACK_SKIP_IMAGES',
1448 'invalid': [
1449 'GL_PACK_SWAP_BYTES',
1450 'GL_UNPACK_SWAP_BYTES',
1453 'PixelStoreAlignment': {
1454 'type': 'GLint',
1455 'valid': [
1456 '1',
1457 '2',
1458 '4',
1459 '8',
1461 'invalid': [
1462 '3',
1463 '9',
1466 'ReadPixelFormat': {
1467 'type': 'GLenum',
1468 'valid': [
1469 'GL_ALPHA',
1470 'GL_RGB',
1471 'GL_RGBA',
1473 'valid_es3': [
1474 'GL_RGBA_INTEGER',
1476 'deprecated_es3': [
1477 'GL_ALPHA',
1478 'GL_RGB',
1481 'PixelType': {
1482 'type': 'GLenum',
1483 'valid': [
1484 'GL_UNSIGNED_BYTE',
1485 'GL_UNSIGNED_SHORT_5_6_5',
1486 'GL_UNSIGNED_SHORT_4_4_4_4',
1487 'GL_UNSIGNED_SHORT_5_5_5_1',
1489 'valid_es3': [
1490 'GL_BYTE',
1491 'GL_UNSIGNED_SHORT',
1492 'GL_SHORT',
1493 'GL_UNSIGNED_INT',
1494 'GL_INT',
1495 'GL_HALF_FLOAT',
1496 'GL_FLOAT',
1497 'GL_UNSIGNED_INT_2_10_10_10_REV',
1498 'GL_UNSIGNED_INT_10F_11F_11F_REV',
1499 'GL_UNSIGNED_INT_5_9_9_9_REV',
1500 'GL_UNSIGNED_INT_24_8',
1501 'GL_FLOAT_32_UNSIGNED_INT_24_8_REV',
1503 'invalid': [
1504 'GL_UNSIGNED_BYTE_3_3_2',
1507 'PathCoordType': {
1508 'type': 'GLenum',
1509 'valid': [
1510 'GL_BYTE',
1511 'GL_UNSIGNED_BYTE',
1512 'GL_SHORT',
1513 'GL_UNSIGNED_SHORT',
1514 'GL_FLOAT',
1517 'PathCoverMode': {
1518 'type': 'GLenum',
1519 'valid': [
1520 'GL_CONVEX_HULL_CHROMIUM',
1521 'GL_BOUNDING_BOX_CHROMIUM',
1524 'PathFillMode': {
1525 'type': 'GLenum',
1526 'valid': [
1527 'GL_INVERT',
1528 'GL_COUNT_UP_CHROMIUM',
1529 'GL_COUNT_DOWN_CHROMIUM',
1532 'PathParameter': {
1533 'type': 'GLenum',
1534 'valid': [
1535 'GL_PATH_STROKE_WIDTH_CHROMIUM',
1536 'GL_PATH_END_CAPS_CHROMIUM',
1537 'GL_PATH_JOIN_STYLE_CHROMIUM',
1538 'GL_PATH_MITER_LIMIT_CHROMIUM',
1539 'GL_PATH_STROKE_BOUND_CHROMIUM',
1542 'PathParameterCapValues': {
1543 'type': 'GLint',
1544 'valid': [
1545 'GL_FLAT',
1546 'GL_SQUARE_CHROMIUM',
1547 'GL_ROUND_CHROMIUM',
1550 'PathParameterJoinValues': {
1551 'type': 'GLint',
1552 'valid': [
1553 'GL_MITER_REVERT_CHROMIUM',
1554 'GL_BEVEL_CHROMIUM',
1555 'GL_ROUND_CHROMIUM',
1558 'ReadPixelType': {
1559 'type': 'GLenum',
1560 'valid': [
1561 'GL_UNSIGNED_BYTE',
1562 'GL_UNSIGNED_SHORT_5_6_5',
1563 'GL_UNSIGNED_SHORT_4_4_4_4',
1564 'GL_UNSIGNED_SHORT_5_5_5_1',
1566 'invalid': [
1567 'GL_SHORT',
1569 'valid_es3': [
1570 'GL_UNSIGNED_INT',
1571 'GL_INT',
1572 'GL_FLOAT',
1574 'deprecated_es3': [
1575 'GL_UNSIGNED_SHORT_5_6_5',
1576 'GL_UNSIGNED_SHORT_4_4_4_4',
1577 'GL_UNSIGNED_SHORT_5_5_5_1',
1580 'RenderBufferFormat': {
1581 'type': 'GLenum',
1582 'valid': [
1583 'GL_RGBA4',
1584 'GL_RGB565',
1585 'GL_RGB5_A1',
1586 'GL_DEPTH_COMPONENT16',
1587 'GL_STENCIL_INDEX8',
1589 'valid_es3': [
1590 'GL_R8',
1591 'GL_R8UI',
1592 'GL_R8I',
1593 'GL_R16UI',
1594 'GL_R16I',
1595 'GL_R32UI',
1596 'GL_R32I',
1597 'GL_RG8',
1598 'GL_RG8UI',
1599 'GL_RG8I',
1600 'GL_RG16UI',
1601 'GL_RG16I',
1602 'GL_RG32UI',
1603 'GL_RG32I',
1604 'GL_RGB8',
1605 'GL_RGBA8',
1606 'GL_SRGB8_ALPHA8',
1607 'GL_RGB10_A2',
1608 'GL_RGBA8UI',
1609 'GL_RGBA8I',
1610 'GL_RGB10_A2UI',
1611 'GL_RGBA16UI',
1612 'GL_RGBA16I',
1613 'GL_RGBA32UI',
1614 'GL_RGBA32I',
1615 'GL_DEPTH_COMPONENT24',
1616 'GL_DEPTH_COMPONENT32F',
1617 'GL_DEPTH24_STENCIL8',
1618 'GL_DEPTH32F_STENCIL8',
1621 'ShaderBinaryFormat': {
1622 'type': 'GLenum',
1623 'valid': [
1626 'StencilOp': {
1627 'type': 'GLenum',
1628 'valid': [
1629 'GL_KEEP',
1630 'GL_ZERO',
1631 'GL_REPLACE',
1632 'GL_INCR',
1633 'GL_INCR_WRAP',
1634 'GL_DECR',
1635 'GL_DECR_WRAP',
1636 'GL_INVERT',
1639 'TextureFormat': {
1640 'type': 'GLenum',
1641 'valid': [
1642 'GL_ALPHA',
1643 'GL_LUMINANCE',
1644 'GL_LUMINANCE_ALPHA',
1645 'GL_RGB',
1646 'GL_RGBA',
1648 'valid_es3': [
1649 'GL_RED',
1650 'GL_RED_INTEGER',
1651 'GL_RG',
1652 'GL_RG_INTEGER',
1653 'GL_RGB_INTEGER',
1654 'GL_RGBA_INTEGER',
1655 'GL_DEPTH_COMPONENT',
1656 'GL_DEPTH_STENCIL',
1658 'invalid': [
1659 'GL_BGRA',
1660 'GL_BGR',
1663 'TextureInternalFormat': {
1664 'type': 'GLenum',
1665 'valid': [
1666 'GL_ALPHA',
1667 'GL_LUMINANCE',
1668 'GL_LUMINANCE_ALPHA',
1669 'GL_RGB',
1670 'GL_RGBA',
1672 'valid_es3': [
1673 'GL_R8',
1674 'GL_R8_SNORM',
1675 'GL_R16F',
1676 'GL_R32F',
1677 'GL_R8UI',
1678 'GL_R8I',
1679 'GL_R16UI',
1680 'GL_R16I',
1681 'GL_R32UI',
1682 'GL_R32I',
1683 'GL_RG8',
1684 'GL_RG8_SNORM',
1685 'GL_RG16F',
1686 'GL_RG32F',
1687 'GL_RG8UI',
1688 'GL_RG8I',
1689 'GL_RG16UI',
1690 'GL_RG16I',
1691 'GL_RG32UI',
1692 'GL_RG32I',
1693 'GL_RGB8',
1694 'GL_SRGB8',
1695 'GL_RGB565',
1696 'GL_RGB8_SNORM',
1697 'GL_R11F_G11F_B10F',
1698 'GL_RGB9_E5',
1699 'GL_RGB16F',
1700 'GL_RGB32F',
1701 'GL_RGB8UI',
1702 'GL_RGB8I',
1703 'GL_RGB16UI',
1704 'GL_RGB16I',
1705 'GL_RGB32UI',
1706 'GL_RGB32I',
1707 'GL_RGBA8',
1708 'GL_SRGB8_ALPHA8',
1709 'GL_RGBA8_SNORM',
1710 'GL_RGB5_A1',
1711 'GL_RGBA4',
1712 'GL_RGB10_A2',
1713 'GL_RGBA16F',
1714 'GL_RGBA32F',
1715 'GL_RGBA8UI',
1716 'GL_RGBA8I',
1717 'GL_RGB10_A2UI',
1718 'GL_RGBA16UI',
1719 'GL_RGBA16I',
1720 'GL_RGBA32UI',
1721 'GL_RGBA32I',
1722 # The DEPTH/STENCIL formats are not supported in CopyTexImage2D.
1723 # We will reject them dynamically in GPU command buffer.
1724 'GL_DEPTH_COMPONENT16',
1725 'GL_DEPTH_COMPONENT24',
1726 'GL_DEPTH_COMPONENT32F',
1727 'GL_DEPTH24_STENCIL8',
1728 'GL_DEPTH32F_STENCIL8',
1730 'invalid': [
1731 'GL_BGRA',
1732 'GL_BGR',
1735 'TextureInternalFormatStorage': {
1736 'type': 'GLenum',
1737 'valid': [
1738 'GL_RGB565',
1739 'GL_RGBA4',
1740 'GL_RGB5_A1',
1741 'GL_ALPHA8_EXT',
1742 'GL_LUMINANCE8_EXT',
1743 'GL_LUMINANCE8_ALPHA8_EXT',
1744 'GL_RGB8_OES',
1745 'GL_RGBA8_OES',
1747 'valid_es3': [
1748 'GL_R8',
1749 'GL_R8_SNORM',
1750 'GL_R16F',
1751 'GL_R32F',
1752 'GL_R8UI',
1753 'GL_R8I',
1754 'GL_R16UI',
1755 'GL_R16I',
1756 'GL_R32UI',
1757 'GL_R32I',
1758 'GL_RG8',
1759 'GL_RG8_SNORM',
1760 'GL_RG16F',
1761 'GL_RG32F',
1762 'GL_RG8UI',
1763 'GL_RG8I',
1764 'GL_RG16UI',
1765 'GL_RG16I',
1766 'GL_RG32UI',
1767 'GL_RG32I',
1768 'GL_RGB8',
1769 'GL_SRGB8',
1770 'GL_RGB8_SNORM',
1771 'GL_R11F_G11F_B10F',
1772 'GL_RGB9_E5',
1773 'GL_RGB16F',
1774 'GL_RGB32F',
1775 'GL_RGB8UI',
1776 'GL_RGB8I',
1777 'GL_RGB16UI',
1778 'GL_RGB16I',
1779 'GL_RGB32UI',
1780 'GL_RGB32I',
1781 'GL_RGBA8',
1782 'GL_SRGB8_ALPHA8',
1783 'GL_RGBA8_SNORM',
1784 'GL_RGB10_A2',
1785 'GL_RGBA16F',
1786 'GL_RGBA32F',
1787 'GL_RGBA8UI',
1788 'GL_RGBA8I',
1789 'GL_RGB10_A2UI',
1790 'GL_RGBA16UI',
1791 'GL_RGBA16I',
1792 'GL_RGBA32UI',
1793 'GL_RGBA32I',
1794 'GL_DEPTH_COMPONENT16',
1795 'GL_DEPTH_COMPONENT24',
1796 'GL_DEPTH_COMPONENT32F',
1797 'GL_DEPTH24_STENCIL8',
1798 'GL_DEPTH32F_STENCIL8',
1799 'GL_COMPRESSED_R11_EAC',
1800 'GL_COMPRESSED_SIGNED_R11_EAC',
1801 'GL_COMPRESSED_RG11_EAC',
1802 'GL_COMPRESSED_SIGNED_RG11_EAC',
1803 'GL_COMPRESSED_RGB8_ETC2',
1804 'GL_COMPRESSED_SRGB8_ETC2',
1805 'GL_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2',
1806 'GL_COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2',
1807 'GL_COMPRESSED_RGBA8_ETC2_EAC',
1808 'GL_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC',
1810 'deprecated_es3': [
1811 'GL_ALPHA8_EXT',
1812 'GL_LUMINANCE8_EXT',
1813 'GL_LUMINANCE8_ALPHA8_EXT',
1814 'GL_ALPHA16F_EXT',
1815 'GL_LUMINANCE16F_EXT',
1816 'GL_LUMINANCE_ALPHA16F_EXT',
1817 'GL_ALPHA32F_EXT',
1818 'GL_LUMINANCE32F_EXT',
1819 'GL_LUMINANCE_ALPHA32F_EXT',
1822 'ImageInternalFormat': {
1823 'type': 'GLenum',
1824 'valid': [
1825 'GL_RGB',
1826 'GL_RGB_YUV_420_CHROMIUM',
1827 'GL_RGBA',
1830 'ImageUsage': {
1831 'type': 'GLenum',
1832 'valid': [
1833 'GL_MAP_CHROMIUM',
1834 'GL_SCANOUT_CHROMIUM'
1837 'ValueBufferTarget': {
1838 'type': 'GLenum',
1839 'valid': [
1840 'GL_SUBSCRIBED_VALUES_BUFFER_CHROMIUM',
1843 'SubscriptionTarget': {
1844 'type': 'GLenum',
1845 'valid': [
1846 'GL_MOUSE_POSITION_CHROMIUM',
1849 'UniformParameter': {
1850 'type': 'GLenum',
1851 'valid': [
1852 'GL_UNIFORM_SIZE',
1853 'GL_UNIFORM_TYPE',
1854 'GL_UNIFORM_NAME_LENGTH',
1855 'GL_UNIFORM_BLOCK_INDEX',
1856 'GL_UNIFORM_OFFSET',
1857 'GL_UNIFORM_ARRAY_STRIDE',
1858 'GL_UNIFORM_MATRIX_STRIDE',
1859 'GL_UNIFORM_IS_ROW_MAJOR',
1861 'invalid': [
1862 'GL_UNIFORM_BLOCK_NAME_LENGTH',
1865 'UniformBlockParameter': {
1866 'type': 'GLenum',
1867 'valid': [
1868 'GL_UNIFORM_BLOCK_BINDING',
1869 'GL_UNIFORM_BLOCK_DATA_SIZE',
1870 'GL_UNIFORM_BLOCK_NAME_LENGTH',
1871 'GL_UNIFORM_BLOCK_ACTIVE_UNIFORMS',
1872 'GL_UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES',
1873 'GL_UNIFORM_BLOCK_REFERENCED_BY_VERTEX_SHADER',
1874 'GL_UNIFORM_BLOCK_REFERENCED_BY_FRAGMENT_SHADER',
1876 'invalid': [
1877 'GL_NEAREST',
1880 'VertexAttribType': {
1881 'type': 'GLenum',
1882 'valid': [
1883 'GL_BYTE',
1884 'GL_UNSIGNED_BYTE',
1885 'GL_SHORT',
1886 'GL_UNSIGNED_SHORT',
1887 # 'GL_FIXED', // This is not available on Desktop GL.
1888 'GL_FLOAT',
1890 'valid_es3': [
1891 'GL_INT',
1892 'GL_UNSIGNED_INT',
1893 'GL_HALF_FLOAT',
1894 'GL_INT_2_10_10_10_REV',
1895 'GL_UNSIGNED_INT_2_10_10_10_REV',
1897 'invalid': [
1898 'GL_DOUBLE',
1901 'VertexAttribIType': {
1902 'type': 'GLenum',
1903 'valid': [
1904 'GL_BYTE',
1905 'GL_UNSIGNED_BYTE',
1906 'GL_SHORT',
1907 'GL_UNSIGNED_SHORT',
1908 'GL_INT',
1909 'GL_UNSIGNED_INT',
1911 'invalid': [
1912 'GL_FLOAT',
1913 'GL_DOUBLE',
1916 'TextureBorder': {
1917 'type': 'GLint',
1918 'is_complete': True,
1919 'valid': [
1920 '0',
1922 'invalid': [
1923 '1',
1926 'VertexAttribSize': {
1927 'type': 'GLint',
1928 'valid': [
1929 '1',
1930 '2',
1931 '3',
1932 '4',
1934 'invalid': [
1935 '0',
1936 '5',
1939 'ZeroOnly': {
1940 'type': 'GLint',
1941 'is_complete': True,
1942 'valid': [
1943 '0',
1945 'invalid': [
1946 '1',
1949 'FalseOnly': {
1950 'type': 'GLboolean',
1951 'is_complete': True,
1952 'valid': [
1953 'false',
1955 'invalid': [
1956 'true',
1959 'ResetStatus': {
1960 'type': 'GLenum',
1961 'valid': [
1962 'GL_GUILTY_CONTEXT_RESET_ARB',
1963 'GL_INNOCENT_CONTEXT_RESET_ARB',
1964 'GL_UNKNOWN_CONTEXT_RESET_ARB',
1967 'SyncCondition': {
1968 'type': 'GLenum',
1969 'is_complete': True,
1970 'valid': [
1971 'GL_SYNC_GPU_COMMANDS_COMPLETE',
1973 'invalid': [
1974 '0',
1977 'SyncFlags': {
1978 'type': 'GLbitfield',
1979 'is_complete': True,
1980 'valid': [
1981 '0',
1983 'invalid': [
1984 '1',
1987 'SyncFlushFlags': {
1988 'type': 'GLbitfield',
1989 'valid': [
1990 'GL_SYNC_FLUSH_COMMANDS_BIT',
1991 '0',
1993 'invalid': [
1994 '0xFFFFFFFF',
1997 'SyncParameter': {
1998 'type': 'GLenum',
1999 'valid': [
2000 'GL_SYNC_STATUS', # This needs to be the 1st; all others are cached.
2001 'GL_OBJECT_TYPE',
2002 'GL_SYNC_CONDITION',
2003 'GL_SYNC_FLAGS',
2005 'invalid': [
2006 'GL_SYNC_FENCE',
2011 # This table specifies the different pepper interfaces that are supported for
2012 # GL commands. 'dev' is true if it's a dev interface.
2013 _PEPPER_INTERFACES = [
2014 {'name': '', 'dev': False},
2015 {'name': 'InstancedArrays', 'dev': False},
2016 {'name': 'FramebufferBlit', 'dev': False},
2017 {'name': 'FramebufferMultisample', 'dev': False},
2018 {'name': 'ChromiumEnableFeature', 'dev': False},
2019 {'name': 'ChromiumMapSub', 'dev': False},
2020 {'name': 'Query', 'dev': False},
2021 {'name': 'VertexArrayObject', 'dev': False},
2022 {'name': 'DrawBuffers', 'dev': True},
2025 # A function info object specifies the type and other special data for the
2026 # command that will be generated. A base function info object is generated by
2027 # parsing the "cmd_buffer_functions.txt", one for each function in the
2028 # file. These function info objects can be augmented and their values can be
2029 # overridden by adding an object to the table below.
2031 # Must match function names specified in "cmd_buffer_functions.txt".
2033 # cmd_comment: A comment added to the cmd format.
2034 # type: defines which handler will be used to generate code.
2035 # decoder_func: defines which function to call in the decoder to execute the
2036 # corresponding GL command. If not specified the GL command will
2037 # be called directly.
2038 # gl_test_func: GL function that is expected to be called when testing.
2039 # cmd_args: The arguments to use for the command. This overrides generating
2040 # them based on the GL function arguments.
2041 # gen_cmd: Whether or not this function geneates a command. Default = True.
2042 # data_transfer_methods: Array of methods that are used for transfering the
2043 # pointer data. Possible values: 'immediate', 'shm', 'bucket'.
2044 # The default is 'immediate' if the command has one pointer
2045 # argument, otherwise 'shm'. One command is generated for each
2046 # transfer method. Affects only commands which are not of type
2047 # 'HandWritten', 'GETn' or 'GLcharN'.
2048 # Note: the command arguments that affect this are the final args,
2049 # taking cmd_args override into consideration.
2050 # impl_func: Whether or not to generate the GLES2Implementation part of this
2051 # command.
2052 # impl_decl: Whether or not to generate the GLES2Implementation declaration
2053 # for this command.
2054 # needs_size: If True a data_size field is added to the command.
2055 # count: The number of units per element. For PUTn or PUT types.
2056 # use_count_func: If True the actual data count needs to be computed; the count
2057 # argument specifies the maximum count.
2058 # unit_test: If False no service side unit test will be generated.
2059 # client_test: If False no client side unit test will be generated.
2060 # expectation: If False the unit test will have no expected calls.
2061 # gen_func: Name of function that generates GL resource for corresponding
2062 # bind function.
2063 # states: array of states that get set by this function corresponding to
2064 # the given arguments
2065 # state_flag: name of flag that is set to true when function is called.
2066 # no_gl: no GL function is called.
2067 # valid_args: A dictionary of argument indices to args to use in unit tests
2068 # when they can not be automatically determined.
2069 # pepper_interface: The pepper interface that is used for this extension
2070 # pepper_name: The name of the function as exposed to pepper.
2071 # pepper_args: A string representing the argument list (what would appear in
2072 # C/C++ between the parentheses for the function declaration)
2073 # that the Pepper API expects for this function. Use this only if
2074 # the stable Pepper API differs from the GLES2 argument list.
2075 # invalid_test: False if no invalid test needed.
2076 # shadowed: True = the value is shadowed so no glGetXXX call will be made.
2077 # first_element_only: For PUT types, True if only the first element of an
2078 # array is used and we end up calling the single value
2079 # corresponding function. eg. TexParameteriv -> TexParameteri
2080 # extension: Function is an extension to GL and should not be exposed to
2081 # pepper unless pepper_interface is defined.
2082 # extension_flag: Function is an extension and should be enabled only when
2083 # the corresponding feature info flag is enabled. Implies
2084 # 'extension': True.
2085 # not_shared: For GENn types, True if objects can't be shared between contexts
2086 # unsafe: True = no validation is implemented on the service side and the
2087 # command is only available with --enable-unsafe-es3-apis.
2088 # id_mapping: A list of resource type names whose client side IDs need to be
2089 # mapped to service side IDs. This is only used for unsafe APIs.
2091 _FUNCTION_INFO = {
2092 'ActiveTexture': {
2093 'decoder_func': 'DoActiveTexture',
2094 'unit_test': False,
2095 'impl_func': False,
2096 'client_test': False,
2098 'AttachShader': {'decoder_func': 'DoAttachShader'},
2099 'BindAttribLocation': {
2100 'type': 'GLchar',
2101 'data_transfer_methods': ['bucket'],
2102 'needs_size': True,
2104 'BindBuffer': {
2105 'type': 'Bind',
2106 'decoder_func': 'DoBindBuffer',
2107 'gen_func': 'GenBuffersARB',
2109 'BindBufferBase': {
2110 'type': 'Bind',
2111 'id_mapping': [ 'Buffer' ],
2112 'gen_func': 'GenBuffersARB',
2113 'unsafe': True,
2115 'BindBufferRange': {
2116 'type': 'Bind',
2117 'id_mapping': [ 'Buffer' ],
2118 'gen_func': 'GenBuffersARB',
2119 'valid_args': {
2120 '3': '4',
2121 '4': '4'
2123 'unsafe': True,
2125 'BindFramebuffer': {
2126 'type': 'Bind',
2127 'decoder_func': 'DoBindFramebuffer',
2128 'gl_test_func': 'glBindFramebufferEXT',
2129 'gen_func': 'GenFramebuffersEXT',
2130 'trace_level': 1,
2132 'BindRenderbuffer': {
2133 'type': 'Bind',
2134 'decoder_func': 'DoBindRenderbuffer',
2135 'gl_test_func': 'glBindRenderbufferEXT',
2136 'gen_func': 'GenRenderbuffersEXT',
2138 'BindSampler': {
2139 'type': 'Bind',
2140 'id_mapping': [ 'Sampler' ],
2141 'unsafe': True,
2143 'BindTexture': {
2144 'type': 'Bind',
2145 'decoder_func': 'DoBindTexture',
2146 'gen_func': 'GenTextures',
2147 # TODO(gman): remove this once client side caching works.
2148 'client_test': False,
2149 'trace_level': 2,
2151 'BindTransformFeedback': {
2152 'type': 'Bind',
2153 'id_mapping': [ 'TransformFeedback' ],
2154 'unsafe': True,
2156 'BlitFramebufferCHROMIUM': {
2157 'decoder_func': 'DoBlitFramebufferCHROMIUM',
2158 'unit_test': False,
2159 'extension_flag': 'chromium_framebuffer_multisample',
2160 'pepper_interface': 'FramebufferBlit',
2161 'pepper_name': 'BlitFramebufferEXT',
2162 'defer_reads': True,
2163 'defer_draws': True,
2164 'trace_level': 1,
2166 'BufferData': {
2167 'type': 'Manual',
2168 'data_transfer_methods': ['shm'],
2169 'client_test': False,
2170 'trace_level': 2,
2172 'BufferSubData': {
2173 'type': 'Data',
2174 'client_test': False,
2175 'decoder_func': 'DoBufferSubData',
2176 'data_transfer_methods': ['shm'],
2177 'trace_level': 2,
2179 'CheckFramebufferStatus': {
2180 'type': 'Is',
2181 'decoder_func': 'DoCheckFramebufferStatus',
2182 'gl_test_func': 'glCheckFramebufferStatusEXT',
2183 'error_value': 'GL_FRAMEBUFFER_UNSUPPORTED',
2184 'result': ['GLenum'],
2186 'Clear': {
2187 'decoder_func': 'DoClear',
2188 'defer_draws': True,
2189 'trace_level': 2,
2191 'ClearBufferiv': {
2192 'type': 'PUT',
2193 'use_count_func': True,
2194 'count': 4,
2195 'unsafe': True,
2196 'trace_level': 2,
2198 'ClearBufferuiv': {
2199 'type': 'PUT',
2200 'count': 4,
2201 'unsafe': True,
2202 'trace_level': 2,
2204 'ClearBufferfv': {
2205 'type': 'PUT',
2206 'use_count_func': True,
2207 'count': 4,
2208 'unsafe': True,
2209 'trace_level': 2,
2211 'ClearBufferfi': {
2212 'unsafe': True,
2213 'trace_level': 2,
2215 'ClearColor': {
2216 'type': 'StateSet',
2217 'state': 'ClearColor',
2219 'ClearDepthf': {
2220 'type': 'StateSet',
2221 'state': 'ClearDepthf',
2222 'decoder_func': 'glClearDepth',
2223 'gl_test_func': 'glClearDepth',
2224 'valid_args': {
2225 '0': '0.5f'
2228 'ClientWaitSync': {
2229 'type': 'Custom',
2230 'data_transfer_methods': ['shm'],
2231 'cmd_args': 'GLuint sync, GLbitfieldSyncFlushFlags flags, '
2232 'GLuint timeout_0, GLuint timeout_1, GLenum* result',
2233 'unsafe': True,
2234 'result': ['GLenum'],
2235 'trace_level': 2,
2237 'ColorMask': {
2238 'type': 'StateSet',
2239 'state': 'ColorMask',
2240 'no_gl': True,
2241 'expectation': False,
2243 'ConsumeTextureCHROMIUM': {
2244 'decoder_func': 'DoConsumeTextureCHROMIUM',
2245 'impl_func': False,
2246 'type': 'PUT',
2247 'count': 64, # GL_MAILBOX_SIZE_CHROMIUM
2248 'unit_test': False,
2249 'client_test': False,
2250 'extension': "CHROMIUM_texture_mailbox",
2251 'chromium': True,
2252 'trace_level': 2,
2254 'CopyBufferSubData': {
2255 'unsafe': True,
2257 'CreateAndConsumeTextureCHROMIUM': {
2258 'decoder_func': 'DoCreateAndConsumeTextureCHROMIUM',
2259 'impl_func': False,
2260 'type': 'HandWritten',
2261 'data_transfer_methods': ['immediate'],
2262 'unit_test': False,
2263 'client_test': False,
2264 'extension': "CHROMIUM_texture_mailbox",
2265 'chromium': True,
2266 'trace_level': 2,
2268 'GenValuebuffersCHROMIUM': {
2269 'type': 'GENn',
2270 'gl_test_func': 'glGenValuebuffersCHROMIUM',
2271 'resource_type': 'Valuebuffer',
2272 'resource_types': 'Valuebuffers',
2273 'unit_test': False,
2274 'extension': True,
2275 'chromium': True,
2277 'DeleteValuebuffersCHROMIUM': {
2278 'type': 'DELn',
2279 'gl_test_func': 'glDeleteValuebuffersCHROMIUM',
2280 'resource_type': 'Valuebuffer',
2281 'resource_types': 'Valuebuffers',
2282 'unit_test': False,
2283 'extension': True,
2284 'chromium': True,
2286 'IsValuebufferCHROMIUM': {
2287 'type': 'Is',
2288 'decoder_func': 'DoIsValuebufferCHROMIUM',
2289 'expectation': False,
2290 'extension': True,
2291 'chromium': True,
2293 'BindValuebufferCHROMIUM': {
2294 'type': 'Bind',
2295 'decoder_func': 'DoBindValueBufferCHROMIUM',
2296 'gen_func': 'GenValueBuffersCHROMIUM',
2297 'unit_test': False,
2298 'extension': True,
2299 'chromium': True,
2301 'SubscribeValueCHROMIUM': {
2302 'decoder_func': 'DoSubscribeValueCHROMIUM',
2303 'unit_test': False,
2304 'extension': True,
2305 'chromium': True,
2307 'PopulateSubscribedValuesCHROMIUM': {
2308 'decoder_func': 'DoPopulateSubscribedValuesCHROMIUM',
2309 'unit_test': False,
2310 'extension': True,
2311 'chromium': True,
2313 'UniformValuebufferCHROMIUM': {
2314 'decoder_func': 'DoUniformValueBufferCHROMIUM',
2315 'unit_test': False,
2316 'extension': True,
2317 'chromium': True,
2319 'ClearStencil': {
2320 'type': 'StateSet',
2321 'state': 'ClearStencil',
2323 'EnableFeatureCHROMIUM': {
2324 'type': 'Custom',
2325 'data_transfer_methods': ['shm'],
2326 'decoder_func': 'DoEnableFeatureCHROMIUM',
2327 'expectation': False,
2328 'cmd_args': 'GLuint bucket_id, GLint* result',
2329 'result': ['GLint'],
2330 'extension': True,
2331 'chromium': True,
2332 'pepper_interface': 'ChromiumEnableFeature',
2334 'CompileShader': {'decoder_func': 'DoCompileShader', 'unit_test': False},
2335 'CompressedTexImage2D': {
2336 'type': 'Manual',
2337 'data_transfer_methods': ['bucket', 'shm'],
2338 'trace_level': 1,
2340 'CompressedTexSubImage2D': {
2341 'type': 'Data',
2342 'data_transfer_methods': ['bucket', 'shm'],
2343 'decoder_func': 'DoCompressedTexSubImage2D',
2344 'trace_level': 1,
2346 'CopyTexImage2D': {
2347 'decoder_func': 'DoCopyTexImage2D',
2348 'unit_test': False,
2349 'defer_reads': True,
2350 'trace_level': 1,
2352 'CopyTexSubImage2D': {
2353 'decoder_func': 'DoCopyTexSubImage2D',
2354 'defer_reads': True,
2355 'trace_level': 1,
2357 'CompressedTexImage3D': {
2358 'type': 'Manual',
2359 'data_transfer_methods': ['bucket', 'shm'],
2360 'unsafe': True,
2361 'trace_level': 1,
2363 'CompressedTexSubImage3D': {
2364 'type': 'Data',
2365 'data_transfer_methods': ['bucket', 'shm'],
2366 'decoder_func': 'DoCompressedTexSubImage3D',
2367 'unsafe': True,
2368 'trace_level': 1,
2370 'CopyTexSubImage3D': {
2371 'defer_reads': True,
2372 'unsafe': True,
2373 'trace_level': 1,
2375 'CreateImageCHROMIUM': {
2376 'type': 'Manual',
2377 'cmd_args':
2378 'ClientBuffer buffer, GLsizei width, GLsizei height, '
2379 'GLenum internalformat',
2380 'result': ['GLuint'],
2381 'client_test': False,
2382 'gen_cmd': False,
2383 'expectation': False,
2384 'extension': "CHROMIUM_image",
2385 'chromium': True,
2386 'trace_level': 1,
2388 'DestroyImageCHROMIUM': {
2389 'type': 'Manual',
2390 'client_test': False,
2391 'gen_cmd': False,
2392 'extension': "CHROMIUM_image",
2393 'chromium': True,
2394 'trace_level': 1,
2396 'CreateGpuMemoryBufferImageCHROMIUM': {
2397 'type': 'Manual',
2398 'cmd_args':
2399 'GLsizei width, GLsizei height, GLenum internalformat, GLenum usage',
2400 'result': ['GLuint'],
2401 'client_test': False,
2402 'gen_cmd': False,
2403 'expectation': False,
2404 'extension': "CHROMIUM_image",
2405 'chromium': True,
2406 'trace_level': 1,
2408 'CreateProgram': {
2409 'type': 'Create',
2410 'client_test': False,
2412 'CreateShader': {
2413 'type': 'Create',
2414 'client_test': False,
2416 'BlendColor': {
2417 'type': 'StateSet',
2418 'state': 'BlendColor',
2420 'BlendEquation': {
2421 'type': 'StateSetRGBAlpha',
2422 'state': 'BlendEquation',
2423 'valid_args': {
2424 '0': 'GL_FUNC_SUBTRACT'
2427 'BlendEquationSeparate': {
2428 'type': 'StateSet',
2429 'state': 'BlendEquation',
2430 'valid_args': {
2431 '0': 'GL_FUNC_SUBTRACT'
2434 'BlendFunc': {
2435 'type': 'StateSetRGBAlpha',
2436 'state': 'BlendFunc',
2438 'BlendFuncSeparate': {
2439 'type': 'StateSet',
2440 'state': 'BlendFunc',
2442 'BlendBarrierKHR': {
2443 'gl_test_func': 'glBlendBarrierKHR',
2444 'extension': True,
2445 'extension_flag': 'blend_equation_advanced',
2446 'client_test': False,
2448 'SampleCoverage': {'decoder_func': 'DoSampleCoverage'},
2449 'StencilFunc': {
2450 'type': 'StateSetFrontBack',
2451 'state': 'StencilFunc',
2453 'StencilFuncSeparate': {
2454 'type': 'StateSetFrontBackSeparate',
2455 'state': 'StencilFunc',
2457 'StencilOp': {
2458 'type': 'StateSetFrontBack',
2459 'state': 'StencilOp',
2460 'valid_args': {
2461 '1': 'GL_INCR'
2464 'StencilOpSeparate': {
2465 'type': 'StateSetFrontBackSeparate',
2466 'state': 'StencilOp',
2467 'valid_args': {
2468 '1': 'GL_INCR'
2471 'Hint': {
2472 'type': 'StateSetNamedParameter',
2473 'state': 'Hint',
2475 'CullFace': {'type': 'StateSet', 'state': 'CullFace'},
2476 'FrontFace': {'type': 'StateSet', 'state': 'FrontFace'},
2477 'DepthFunc': {'type': 'StateSet', 'state': 'DepthFunc'},
2478 'LineWidth': {
2479 'type': 'StateSet',
2480 'state': 'LineWidth',
2481 'valid_args': {
2482 '0': '0.5f'
2485 'PolygonOffset': {
2486 'type': 'StateSet',
2487 'state': 'PolygonOffset',
2489 'DeleteBuffers': {
2490 'type': 'DELn',
2491 'gl_test_func': 'glDeleteBuffersARB',
2492 'resource_type': 'Buffer',
2493 'resource_types': 'Buffers',
2495 'DeleteFramebuffers': {
2496 'type': 'DELn',
2497 'gl_test_func': 'glDeleteFramebuffersEXT',
2498 'resource_type': 'Framebuffer',
2499 'resource_types': 'Framebuffers',
2500 'trace_level': 2,
2502 'DeleteProgram': { 'type': 'Delete' },
2503 'DeleteRenderbuffers': {
2504 'type': 'DELn',
2505 'gl_test_func': 'glDeleteRenderbuffersEXT',
2506 'resource_type': 'Renderbuffer',
2507 'resource_types': 'Renderbuffers',
2508 'trace_level': 2,
2510 'DeleteSamplers': {
2511 'type': 'DELn',
2512 'resource_type': 'Sampler',
2513 'resource_types': 'Samplers',
2514 'unsafe': True,
2516 'DeleteShader': { 'type': 'Delete' },
2517 'DeleteSync': {
2518 'type': 'Delete',
2519 'cmd_args': 'GLuint sync',
2520 'resource_type': 'Sync',
2521 'unsafe': True,
2523 'DeleteTextures': {
2524 'type': 'DELn',
2525 'resource_type': 'Texture',
2526 'resource_types': 'Textures',
2528 'DeleteTransformFeedbacks': {
2529 'type': 'DELn',
2530 'resource_type': 'TransformFeedback',
2531 'resource_types': 'TransformFeedbacks',
2532 'unsafe': True,
2534 'DepthRangef': {
2535 'decoder_func': 'DoDepthRangef',
2536 'gl_test_func': 'glDepthRange',
2538 'DepthMask': {
2539 'type': 'StateSet',
2540 'state': 'DepthMask',
2541 'no_gl': True,
2542 'expectation': False,
2544 'DetachShader': {'decoder_func': 'DoDetachShader'},
2545 'Disable': {
2546 'decoder_func': 'DoDisable',
2547 'impl_func': False,
2548 'client_test': False,
2550 'DisableVertexAttribArray': {
2551 'decoder_func': 'DoDisableVertexAttribArray',
2552 'impl_decl': False,
2554 'DrawArrays': {
2555 'type': 'Manual',
2556 'cmd_args': 'GLenumDrawMode mode, GLint first, GLsizei count',
2557 'defer_draws': True,
2558 'trace_level': 2,
2560 'DrawElements': {
2561 'type': 'Manual',
2562 'cmd_args': 'GLenumDrawMode mode, GLsizei count, '
2563 'GLenumIndexType type, GLuint index_offset',
2564 'client_test': False,
2565 'defer_draws': True,
2566 'trace_level': 2,
2568 'DrawRangeElements': {
2569 'type': 'Manual',
2570 'gen_cmd': 'False',
2571 'unsafe': True,
2573 'Enable': {
2574 'decoder_func': 'DoEnable',
2575 'impl_func': False,
2576 'client_test': False,
2578 'EnableVertexAttribArray': {
2579 'decoder_func': 'DoEnableVertexAttribArray',
2580 'impl_decl': False,
2582 'FenceSync': {
2583 'type': 'Create',
2584 'client_test': False,
2585 'unsafe': True,
2586 'trace_level': 1,
2588 'Finish': {
2589 'impl_func': False,
2590 'client_test': False,
2591 'decoder_func': 'DoFinish',
2592 'defer_reads': True,
2593 'trace_level': 1,
2595 'Flush': {
2596 'impl_func': False,
2597 'decoder_func': 'DoFlush',
2598 'trace_level': 1,
2600 'FramebufferRenderbuffer': {
2601 'decoder_func': 'DoFramebufferRenderbuffer',
2602 'gl_test_func': 'glFramebufferRenderbufferEXT',
2603 'trace_level': 1,
2605 'FramebufferTexture2D': {
2606 'decoder_func': 'DoFramebufferTexture2D',
2607 'gl_test_func': 'glFramebufferTexture2DEXT',
2608 'trace_level': 1,
2610 'FramebufferTexture2DMultisampleEXT': {
2611 'decoder_func': 'DoFramebufferTexture2DMultisample',
2612 'gl_test_func': 'glFramebufferTexture2DMultisampleEXT',
2613 'expectation': False,
2614 'unit_test': False,
2615 'extension_flag': 'multisampled_render_to_texture',
2616 'trace_level': 1,
2618 'FramebufferTextureLayer': {
2619 'decoder_func': 'DoFramebufferTextureLayer',
2620 'unsafe': True,
2621 'trace_level': 1,
2623 'GenerateMipmap': {
2624 'decoder_func': 'DoGenerateMipmap',
2625 'gl_test_func': 'glGenerateMipmapEXT',
2626 'trace_level': 1,
2628 'GenBuffers': {
2629 'type': 'GENn',
2630 'gl_test_func': 'glGenBuffersARB',
2631 'resource_type': 'Buffer',
2632 'resource_types': 'Buffers',
2634 'GenMailboxCHROMIUM': {
2635 'type': 'HandWritten',
2636 'impl_func': False,
2637 'extension': "CHROMIUM_texture_mailbox",
2638 'chromium': True,
2640 'GenFramebuffers': {
2641 'type': 'GENn',
2642 'gl_test_func': 'glGenFramebuffersEXT',
2643 'resource_type': 'Framebuffer',
2644 'resource_types': 'Framebuffers',
2646 'GenRenderbuffers': {
2647 'type': 'GENn', 'gl_test_func': 'glGenRenderbuffersEXT',
2648 'resource_type': 'Renderbuffer',
2649 'resource_types': 'Renderbuffers',
2651 'GenSamplers': {
2652 'type': 'GENn',
2653 'gl_test_func': 'glGenSamplers',
2654 'resource_type': 'Sampler',
2655 'resource_types': 'Samplers',
2656 'unsafe': True,
2658 'GenTextures': {
2659 'type': 'GENn',
2660 'gl_test_func': 'glGenTextures',
2661 'resource_type': 'Texture',
2662 'resource_types': 'Textures',
2664 'GenTransformFeedbacks': {
2665 'type': 'GENn',
2666 'gl_test_func': 'glGenTransformFeedbacks',
2667 'resource_type': 'TransformFeedback',
2668 'resource_types': 'TransformFeedbacks',
2669 'unsafe': True,
2671 'GetActiveAttrib': {
2672 'type': 'Custom',
2673 'data_transfer_methods': ['shm'],
2674 'cmd_args':
2675 'GLidProgram program, GLuint index, uint32_t name_bucket_id, '
2676 'void* result',
2677 'result': [
2678 'int32_t success',
2679 'int32_t size',
2680 'uint32_t type',
2683 'GetActiveUniform': {
2684 'type': 'Custom',
2685 'data_transfer_methods': ['shm'],
2686 'cmd_args':
2687 'GLidProgram program, GLuint index, uint32_t name_bucket_id, '
2688 'void* result',
2689 'result': [
2690 'int32_t success',
2691 'int32_t size',
2692 'uint32_t type',
2695 'GetActiveUniformBlockiv': {
2696 'type': 'Custom',
2697 'data_transfer_methods': ['shm'],
2698 'result': ['SizedResult<GLint>'],
2699 'unsafe': True,
2701 'GetActiveUniformBlockName': {
2702 'type': 'Custom',
2703 'data_transfer_methods': ['shm'],
2704 'cmd_args':
2705 'GLidProgram program, GLuint index, uint32_t name_bucket_id, '
2706 'void* result',
2707 'result': ['int32_t'],
2708 'unsafe': True,
2710 'GetActiveUniformsiv': {
2711 'type': 'Custom',
2712 'data_transfer_methods': ['shm'],
2713 'cmd_args':
2714 'GLidProgram program, uint32_t indices_bucket_id, GLenum pname, '
2715 'GLint* params',
2716 'result': ['SizedResult<GLint>'],
2717 'unsafe': True,
2719 'GetAttachedShaders': {
2720 'type': 'Custom',
2721 'data_transfer_methods': ['shm'],
2722 'cmd_args': 'GLidProgram program, void* result, uint32_t result_size',
2723 'result': ['SizedResult<GLuint>'],
2725 'GetAttribLocation': {
2726 'type': 'Custom',
2727 'data_transfer_methods': ['shm'],
2728 'cmd_args':
2729 'GLidProgram program, uint32_t name_bucket_id, GLint* location',
2730 'result': ['GLint'],
2731 'error_return': -1,
2733 'GetFragDataLocation': {
2734 'type': 'Custom',
2735 'data_transfer_methods': ['shm'],
2736 'cmd_args':
2737 'GLidProgram program, uint32_t name_bucket_id, GLint* location',
2738 'result': ['GLint'],
2739 'error_return': -1,
2740 'unsafe': True,
2742 'GetBooleanv': {
2743 'type': 'GETn',
2744 'result': ['SizedResult<GLboolean>'],
2745 'decoder_func': 'DoGetBooleanv',
2746 'gl_test_func': 'glGetBooleanv',
2748 'GetBufferParameteriv': {
2749 'type': 'GETn',
2750 'result': ['SizedResult<GLint>'],
2751 'decoder_func': 'DoGetBufferParameteriv',
2752 'expectation': False,
2753 'shadowed': True,
2755 'GetError': {
2756 'type': 'Is',
2757 'decoder_func': 'GetErrorState()->GetGLError',
2758 'impl_func': False,
2759 'result': ['GLenum'],
2760 'client_test': False,
2762 'GetFloatv': {
2763 'type': 'GETn',
2764 'result': ['SizedResult<GLfloat>'],
2765 'decoder_func': 'DoGetFloatv',
2766 'gl_test_func': 'glGetFloatv',
2768 'GetFramebufferAttachmentParameteriv': {
2769 'type': 'GETn',
2770 'decoder_func': 'DoGetFramebufferAttachmentParameteriv',
2771 'gl_test_func': 'glGetFramebufferAttachmentParameterivEXT',
2772 'result': ['SizedResult<GLint>'],
2774 'GetGraphicsResetStatusKHR': {
2775 'extension': True,
2776 'client_test': False,
2777 'gen_cmd': False,
2778 'trace_level': 1,
2780 'GetInteger64v': {
2781 'type': 'GETn',
2782 'result': ['SizedResult<GLint64>'],
2783 'client_test': False,
2784 'decoder_func': 'DoGetInteger64v',
2785 'unsafe': True
2787 'GetIntegerv': {
2788 'type': 'GETn',
2789 'result': ['SizedResult<GLint>'],
2790 'decoder_func': 'DoGetIntegerv',
2791 'client_test': False,
2793 'GetInteger64i_v': {
2794 'type': 'GETn',
2795 'result': ['SizedResult<GLint64>'],
2796 'client_test': False,
2797 'unsafe': True
2799 'GetIntegeri_v': {
2800 'type': 'GETn',
2801 'result': ['SizedResult<GLint>'],
2802 'client_test': False,
2803 'unsafe': True
2805 'GetInternalformativ': {
2806 'type': 'Custom',
2807 'data_transfer_methods': ['shm'],
2808 'result': ['SizedResult<GLint>'],
2809 'cmd_args':
2810 'GLenumRenderBufferTarget target, GLenumRenderBufferFormat format, '
2811 'GLenumInternalFormatParameter pname, GLint* params',
2812 'unsafe': True,
2814 'GetMaxValueInBufferCHROMIUM': {
2815 'type': 'Is',
2816 'decoder_func': 'DoGetMaxValueInBufferCHROMIUM',
2817 'result': ['GLuint'],
2818 'unit_test': False,
2819 'client_test': False,
2820 'extension': True,
2821 'chromium': True,
2822 'impl_func': False,
2824 'GetProgramiv': {
2825 'type': 'GETn',
2826 'decoder_func': 'DoGetProgramiv',
2827 'result': ['SizedResult<GLint>'],
2828 'expectation': False,
2830 'GetProgramInfoCHROMIUM': {
2831 'type': 'Custom',
2832 'expectation': False,
2833 'impl_func': False,
2834 'extension': True,
2835 'chromium': True,
2836 'client_test': False,
2837 'cmd_args': 'GLidProgram program, uint32_t bucket_id',
2838 'result': [
2839 'uint32_t link_status',
2840 'uint32_t num_attribs',
2841 'uint32_t num_uniforms',
2844 'GetProgramInfoLog': {
2845 'type': 'STRn',
2846 'expectation': False,
2848 'GetRenderbufferParameteriv': {
2849 'type': 'GETn',
2850 'decoder_func': 'DoGetRenderbufferParameteriv',
2851 'gl_test_func': 'glGetRenderbufferParameterivEXT',
2852 'result': ['SizedResult<GLint>'],
2854 'GetSamplerParameterfv': {
2855 'type': 'GETn',
2856 'result': ['SizedResult<GLfloat>'],
2857 'id_mapping': [ 'Sampler' ],
2858 'unsafe': True,
2860 'GetSamplerParameteriv': {
2861 'type': 'GETn',
2862 'result': ['SizedResult<GLint>'],
2863 'id_mapping': [ 'Sampler' ],
2864 'unsafe': True,
2866 'GetShaderiv': {
2867 'type': 'GETn',
2868 'decoder_func': 'DoGetShaderiv',
2869 'result': ['SizedResult<GLint>'],
2871 'GetShaderInfoLog': {
2872 'type': 'STRn',
2873 'get_len_func': 'glGetShaderiv',
2874 'get_len_enum': 'GL_INFO_LOG_LENGTH',
2875 'unit_test': False,
2877 'GetShaderPrecisionFormat': {
2878 'type': 'Custom',
2879 'data_transfer_methods': ['shm'],
2880 'cmd_args':
2881 'GLenumShaderType shadertype, GLenumShaderPrecision precisiontype, '
2882 'void* result',
2883 'result': [
2884 'int32_t success',
2885 'int32_t min_range',
2886 'int32_t max_range',
2887 'int32_t precision',
2890 'GetShaderSource': {
2891 'type': 'STRn',
2892 'get_len_func': 'DoGetShaderiv',
2893 'get_len_enum': 'GL_SHADER_SOURCE_LENGTH',
2894 'unit_test': False,
2895 'client_test': False,
2897 'GetString': {
2898 'type': 'Custom',
2899 'client_test': False,
2900 'cmd_args': 'GLenumStringType name, uint32_t bucket_id',
2902 'GetSynciv': {
2903 'type': 'GETn',
2904 'cmd_args': 'GLuint sync, GLenumSyncParameter pname, void* values',
2905 'result': ['SizedResult<GLint>'],
2906 'id_mapping': ['Sync'],
2907 'unsafe': True,
2909 'GetTexParameterfv': {
2910 'type': 'GETn',
2911 'decoder_func': 'DoGetTexParameterfv',
2912 'result': ['SizedResult<GLfloat>']
2914 'GetTexParameteriv': {
2915 'type': 'GETn',
2916 'decoder_func': 'DoGetTexParameteriv',
2917 'result': ['SizedResult<GLint>']
2919 'GetTranslatedShaderSourceANGLE': {
2920 'type': 'STRn',
2921 'get_len_func': 'DoGetShaderiv',
2922 'get_len_enum': 'GL_TRANSLATED_SHADER_SOURCE_LENGTH_ANGLE',
2923 'unit_test': False,
2924 'extension': True,
2926 'GetUniformBlockIndex': {
2927 'type': 'Custom',
2928 'data_transfer_methods': ['shm'],
2929 'cmd_args':
2930 'GLidProgram program, uint32_t name_bucket_id, GLuint* index',
2931 'result': ['GLuint'],
2932 'error_return': 'GL_INVALID_INDEX',
2933 'unsafe': True,
2935 'GetUniformBlocksCHROMIUM': {
2936 'type': 'Custom',
2937 'expectation': False,
2938 'impl_func': False,
2939 'extension': True,
2940 'chromium': True,
2941 'client_test': False,
2942 'cmd_args': 'GLidProgram program, uint32_t bucket_id',
2943 'result': ['uint32_t'],
2944 'unsafe': True,
2946 'GetUniformsES3CHROMIUM': {
2947 'type': 'Custom',
2948 'expectation': False,
2949 'impl_func': False,
2950 'extension': True,
2951 'chromium': True,
2952 'client_test': False,
2953 'cmd_args': 'GLidProgram program, uint32_t bucket_id',
2954 'result': ['uint32_t'],
2955 'unsafe': True,
2957 'GetTransformFeedbackVarying': {
2958 'type': 'Custom',
2959 'data_transfer_methods': ['shm'],
2960 'cmd_args':
2961 'GLidProgram program, GLuint index, uint32_t name_bucket_id, '
2962 'void* result',
2963 'result': [
2964 'int32_t success',
2965 'int32_t size',
2966 'uint32_t type',
2968 'unsafe': True,
2970 'GetTransformFeedbackVaryingsCHROMIUM': {
2971 'type': 'Custom',
2972 'expectation': False,
2973 'impl_func': False,
2974 'extension': True,
2975 'chromium': True,
2976 'client_test': False,
2977 'cmd_args': 'GLidProgram program, uint32_t bucket_id',
2978 'result': ['uint32_t'],
2979 'unsafe': True,
2981 'GetUniformfv': {
2982 'type': 'Custom',
2983 'data_transfer_methods': ['shm'],
2984 'result': ['SizedResult<GLfloat>'],
2986 'GetUniformiv': {
2987 'type': 'Custom',
2988 'data_transfer_methods': ['shm'],
2989 'result': ['SizedResult<GLint>'],
2991 'GetUniformuiv': {
2992 'type': 'Custom',
2993 'data_transfer_methods': ['shm'],
2994 'result': ['SizedResult<GLuint>'],
2995 'unsafe': True,
2997 'GetUniformIndices': {
2998 'type': 'Custom',
2999 'data_transfer_methods': ['shm'],
3000 'result': ['SizedResult<GLuint>'],
3001 'cmd_args': 'GLidProgram program, uint32_t names_bucket_id, '
3002 'GLuint* indices',
3003 'unsafe': True,
3005 'GetUniformLocation': {
3006 'type': 'Custom',
3007 'data_transfer_methods': ['shm'],
3008 'cmd_args':
3009 'GLidProgram program, uint32_t name_bucket_id, GLint* location',
3010 'result': ['GLint'],
3011 'error_return': -1, # http://www.opengl.org/sdk/docs/man/xhtml/glGetUniformLocation.xml
3013 'GetVertexAttribfv': {
3014 'type': 'GETn',
3015 'result': ['SizedResult<GLfloat>'],
3016 'impl_decl': False,
3017 'decoder_func': 'DoGetVertexAttribfv',
3018 'expectation': False,
3019 'client_test': False,
3021 'GetVertexAttribiv': {
3022 'type': 'GETn',
3023 'result': ['SizedResult<GLint>'],
3024 'impl_decl': False,
3025 'decoder_func': 'DoGetVertexAttribiv',
3026 'expectation': False,
3027 'client_test': False,
3029 'GetVertexAttribIiv': {
3030 'type': 'GETn',
3031 'result': ['SizedResult<GLint>'],
3032 'impl_decl': False,
3033 'decoder_func': 'DoGetVertexAttribIiv',
3034 'expectation': False,
3035 'client_test': False,
3036 'unsafe': True,
3038 'GetVertexAttribIuiv': {
3039 'type': 'GETn',
3040 'result': ['SizedResult<GLuint>'],
3041 'impl_decl': False,
3042 'decoder_func': 'DoGetVertexAttribIuiv',
3043 'expectation': False,
3044 'client_test': False,
3045 'unsafe': True,
3047 'GetVertexAttribPointerv': {
3048 'type': 'Custom',
3049 'data_transfer_methods': ['shm'],
3050 'result': ['SizedResult<GLuint>'],
3051 'client_test': False,
3053 'InvalidateFramebuffer': {
3054 'type': 'PUTn',
3055 'count': 1,
3056 'client_test': False,
3057 'unit_test': False,
3058 'unsafe': True,
3060 'InvalidateSubFramebuffer': {
3061 'type': 'PUTn',
3062 'count': 1,
3063 'client_test': False,
3064 'unit_test': False,
3065 'unsafe': True,
3067 'IsBuffer': {
3068 'type': 'Is',
3069 'decoder_func': 'DoIsBuffer',
3070 'expectation': False,
3072 'IsEnabled': {
3073 'type': 'Is',
3074 'decoder_func': 'DoIsEnabled',
3075 'client_test': False,
3076 'impl_func': False,
3077 'expectation': False,
3079 'IsFramebuffer': {
3080 'type': 'Is',
3081 'decoder_func': 'DoIsFramebuffer',
3082 'expectation': False,
3084 'IsProgram': {
3085 'type': 'Is',
3086 'decoder_func': 'DoIsProgram',
3087 'expectation': False,
3089 'IsRenderbuffer': {
3090 'type': 'Is',
3091 'decoder_func': 'DoIsRenderbuffer',
3092 'expectation': False,
3094 'IsShader': {
3095 'type': 'Is',
3096 'decoder_func': 'DoIsShader',
3097 'expectation': False,
3099 'IsSampler': {
3100 'type': 'Is',
3101 'id_mapping': [ 'Sampler' ],
3102 'expectation': False,
3103 'unsafe': True,
3105 'IsSync': {
3106 'type': 'Is',
3107 'id_mapping': [ 'Sync' ],
3108 'cmd_args': 'GLuint sync',
3109 'expectation': False,
3110 'unsafe': True,
3112 'IsTexture': {
3113 'type': 'Is',
3114 'decoder_func': 'DoIsTexture',
3115 'expectation': False,
3117 'IsTransformFeedback': {
3118 'type': 'Is',
3119 'id_mapping': [ 'TransformFeedback' ],
3120 'expectation': False,
3121 'unsafe': True,
3123 'LinkProgram': {
3124 'decoder_func': 'DoLinkProgram',
3125 'impl_func': False,
3126 'trace_level': 1,
3128 'MapBufferCHROMIUM': {
3129 'gen_cmd': False,
3130 'extension': "CHROMIUM_pixel_transfer_buffer_object",
3131 'chromium': True,
3132 'client_test': False,
3133 'trace_level': 1,
3135 'MapBufferSubDataCHROMIUM': {
3136 'gen_cmd': False,
3137 'extension': True,
3138 'chromium': True,
3139 'client_test': False,
3140 'pepper_interface': 'ChromiumMapSub',
3141 'trace_level': 1,
3143 'MapTexSubImage2DCHROMIUM': {
3144 'gen_cmd': False,
3145 'extension': "CHROMIUM_sub_image",
3146 'chromium': True,
3147 'client_test': False,
3148 'pepper_interface': 'ChromiumMapSub',
3149 'trace_level': 1,
3151 'MapBufferRange': {
3152 'type': 'Custom',
3153 'data_transfer_methods': ['shm'],
3154 'cmd_args': 'GLenumBufferTarget target, GLintptrNotNegative offset, '
3155 'GLsizeiptr size, GLbitfieldMapBufferAccess access, '
3156 'uint32_t data_shm_id, uint32_t data_shm_offset, '
3157 'uint32_t result_shm_id, uint32_t result_shm_offset',
3158 'unsafe': True,
3159 'result': ['uint32_t'],
3160 'trace_level': 1,
3162 'PauseTransformFeedback': {
3163 'unsafe': True,
3165 'PixelStorei': {'type': 'Manual'},
3166 'PostSubBufferCHROMIUM': {
3167 'type': 'Custom',
3168 'impl_func': False,
3169 'unit_test': False,
3170 'client_test': False,
3171 'extension': True,
3172 'chromium': True,
3174 'ProduceTextureCHROMIUM': {
3175 'decoder_func': 'DoProduceTextureCHROMIUM',
3176 'impl_func': False,
3177 'type': 'PUT',
3178 'count': 64, # GL_MAILBOX_SIZE_CHROMIUM
3179 'unit_test': False,
3180 'client_test': False,
3181 'extension': "CHROMIUM_texture_mailbox",
3182 'chromium': True,
3183 'trace_level': 1,
3185 'ProduceTextureDirectCHROMIUM': {
3186 'decoder_func': 'DoProduceTextureDirectCHROMIUM',
3187 'impl_func': False,
3188 'type': 'PUT',
3189 'count': 64, # GL_MAILBOX_SIZE_CHROMIUM
3190 'unit_test': False,
3191 'client_test': False,
3192 'extension': "CHROMIUM_texture_mailbox",
3193 'chromium': True,
3194 'trace_level': 1,
3196 'RenderbufferStorage': {
3197 'decoder_func': 'DoRenderbufferStorage',
3198 'gl_test_func': 'glRenderbufferStorageEXT',
3199 'expectation': False,
3200 'trace_level': 1,
3202 'RenderbufferStorageMultisampleCHROMIUM': {
3203 'cmd_comment':
3204 '// GL_CHROMIUM_framebuffer_multisample\n',
3205 'decoder_func': 'DoRenderbufferStorageMultisampleCHROMIUM',
3206 'gl_test_func': 'glRenderbufferStorageMultisampleCHROMIUM',
3207 'expectation': False,
3208 'unit_test': False,
3209 'extension_flag': 'chromium_framebuffer_multisample',
3210 'pepper_interface': 'FramebufferMultisample',
3211 'pepper_name': 'RenderbufferStorageMultisampleEXT',
3212 'trace_level': 1,
3214 'RenderbufferStorageMultisampleEXT': {
3215 'cmd_comment':
3216 '// GL_EXT_multisampled_render_to_texture\n',
3217 'decoder_func': 'DoRenderbufferStorageMultisampleEXT',
3218 'gl_test_func': 'glRenderbufferStorageMultisampleEXT',
3219 'expectation': False,
3220 'unit_test': False,
3221 'extension_flag': 'multisampled_render_to_texture',
3222 'trace_level': 1,
3224 'ReadBuffer': {
3225 'unsafe': True,
3226 'trace_level': 1,
3228 'ReadPixels': {
3229 'cmd_comment':
3230 '// ReadPixels has the result separated from the pixel buffer so that\n'
3231 '// it is easier to specify the result going to some specific place\n'
3232 '// that exactly fits the rectangle of pixels.\n',
3233 'type': 'Custom',
3234 'data_transfer_methods': ['shm'],
3235 'impl_func': False,
3236 'client_test': False,
3237 'cmd_args':
3238 'GLint x, GLint y, GLsizei width, GLsizei height, '
3239 'GLenumReadPixelFormat format, GLenumReadPixelType type, '
3240 'uint32_t pixels_shm_id, uint32_t pixels_shm_offset, '
3241 'uint32_t result_shm_id, uint32_t result_shm_offset, '
3242 'GLboolean async',
3243 'result': ['uint32_t'],
3244 'defer_reads': True,
3245 'trace_level': 1,
3247 'ReleaseShaderCompiler': {
3248 'decoder_func': 'DoReleaseShaderCompiler',
3249 'unit_test': False,
3251 'ResumeTransformFeedback': {
3252 'unsafe': True,
3254 'SamplerParameterf': {
3255 'valid_args': {
3256 '2': 'GL_NEAREST'
3258 'id_mapping': [ 'Sampler' ],
3259 'unsafe': True,
3261 'SamplerParameterfv': {
3262 'type': 'PUT',
3263 'data_value': 'GL_NEAREST',
3264 'count': 1,
3265 'gl_test_func': 'glSamplerParameterf',
3266 'decoder_func': 'DoSamplerParameterfv',
3267 'first_element_only': True,
3268 'id_mapping': [ 'Sampler' ],
3269 'unsafe': True,
3271 'SamplerParameteri': {
3272 'valid_args': {
3273 '2': 'GL_NEAREST'
3275 'id_mapping': [ 'Sampler' ],
3276 'unsafe': True,
3278 'SamplerParameteriv': {
3279 'type': 'PUT',
3280 'data_value': 'GL_NEAREST',
3281 'count': 1,
3282 'gl_test_func': 'glSamplerParameteri',
3283 'decoder_func': 'DoSamplerParameteriv',
3284 'first_element_only': True,
3285 'unsafe': True,
3287 'ShaderBinary': {
3288 'type': 'Custom',
3289 'client_test': False,
3291 'ShaderSource': {
3292 'type': 'PUTSTR',
3293 'decoder_func': 'DoShaderSource',
3294 'expectation': False,
3295 'data_transfer_methods': ['bucket'],
3296 'cmd_args':
3297 'GLuint shader, const char** str',
3298 'pepper_args':
3299 'GLuint shader, GLsizei count, const char** str, const GLint* length',
3301 'StencilMask': {
3302 'type': 'StateSetFrontBack',
3303 'state': 'StencilMask',
3304 'no_gl': True,
3305 'expectation': False,
3307 'StencilMaskSeparate': {
3308 'type': 'StateSetFrontBackSeparate',
3309 'state': 'StencilMask',
3310 'no_gl': True,
3311 'expectation': False,
3313 'SwapBuffers': {
3314 'impl_func': False,
3315 'decoder_func': 'DoSwapBuffers',
3316 'unit_test': False,
3317 'client_test': False,
3318 'extension': True,
3319 'trace_level': 1,
3321 'SwapInterval': {
3322 'impl_func': False,
3323 'decoder_func': 'DoSwapInterval',
3324 'unit_test': False,
3325 'client_test': False,
3326 'extension': True,
3327 'trace_level': 1,
3329 'TexImage2D': {
3330 'type': 'Manual',
3331 'data_transfer_methods': ['shm'],
3332 'client_test': False,
3333 'trace_level': 2,
3335 'TexImage3D': {
3336 'type': 'Manual',
3337 'data_transfer_methods': ['shm'],
3338 'client_test': False,
3339 'unsafe': True,
3340 'trace_level': 2,
3342 'TexParameterf': {
3343 'decoder_func': 'DoTexParameterf',
3344 'valid_args': {
3345 '2': 'GL_NEAREST'
3348 'TexParameteri': {
3349 'decoder_func': 'DoTexParameteri',
3350 'valid_args': {
3351 '2': 'GL_NEAREST'
3354 'TexParameterfv': {
3355 'type': 'PUT',
3356 'data_value': 'GL_NEAREST',
3357 'count': 1,
3358 'decoder_func': 'DoTexParameterfv',
3359 'gl_test_func': 'glTexParameterf',
3360 'first_element_only': True,
3362 'TexParameteriv': {
3363 'type': 'PUT',
3364 'data_value': 'GL_NEAREST',
3365 'count': 1,
3366 'decoder_func': 'DoTexParameteriv',
3367 'gl_test_func': 'glTexParameteri',
3368 'first_element_only': True,
3370 'TexStorage3D': {
3371 'unsafe': True,
3372 'trace_level': 2,
3374 'TexSubImage2D': {
3375 'type': 'Manual',
3376 'data_transfer_methods': ['shm'],
3377 'client_test': False,
3378 'trace_level': 2,
3379 'cmd_args': 'GLenumTextureTarget target, GLint level, '
3380 'GLint xoffset, GLint yoffset, '
3381 'GLsizei width, GLsizei height, '
3382 'GLenumTextureFormat format, GLenumPixelType type, '
3383 'const void* pixels, GLboolean internal'
3385 'TexSubImage3D': {
3386 'type': 'Manual',
3387 'data_transfer_methods': ['shm'],
3388 'client_test': False,
3389 'trace_level': 2,
3390 'cmd_args': 'GLenumTextureTarget target, GLint level, '
3391 'GLint xoffset, GLint yoffset, GLint zoffset, '
3392 'GLsizei width, GLsizei height, GLsizei depth, '
3393 'GLenumTextureFormat format, GLenumPixelType type, '
3394 'const void* pixels, GLboolean internal',
3395 'unsafe': True,
3397 'TransformFeedbackVaryings': {
3398 'type': 'PUTSTR',
3399 'data_transfer_methods': ['bucket'],
3400 'decoder_func': 'DoTransformFeedbackVaryings',
3401 'cmd_args':
3402 'GLuint program, const char** varyings, GLenum buffermode',
3403 'unsafe': True,
3405 'Uniform1f': {'type': 'PUTXn', 'count': 1},
3406 'Uniform1fv': {
3407 'type': 'PUTn',
3408 'count': 1,
3409 'decoder_func': 'DoUniform1fv',
3411 'Uniform1i': {'decoder_func': 'DoUniform1i', 'unit_test': False},
3412 'Uniform1iv': {
3413 'type': 'PUTn',
3414 'count': 1,
3415 'decoder_func': 'DoUniform1iv',
3416 'unit_test': False,
3418 'Uniform1ui': {
3419 'type': 'PUTXn',
3420 'count': 1,
3421 'unsafe': True,
3423 'Uniform1uiv': {
3424 'type': 'PUTn',
3425 'count': 1,
3426 'unsafe': True,
3428 'Uniform2i': {'type': 'PUTXn', 'count': 2},
3429 'Uniform2f': {'type': 'PUTXn', 'count': 2},
3430 'Uniform2fv': {
3431 'type': 'PUTn',
3432 'count': 2,
3433 'decoder_func': 'DoUniform2fv',
3435 'Uniform2iv': {
3436 'type': 'PUTn',
3437 'count': 2,
3438 'decoder_func': 'DoUniform2iv',
3440 'Uniform2ui': {
3441 'type': 'PUTXn',
3442 'count': 2,
3443 'unsafe': True,
3445 'Uniform2uiv': {
3446 'type': 'PUTn',
3447 'count': 2,
3448 'unsafe': True,
3450 'Uniform3i': {'type': 'PUTXn', 'count': 3},
3451 'Uniform3f': {'type': 'PUTXn', 'count': 3},
3452 'Uniform3fv': {
3453 'type': 'PUTn',
3454 'count': 3,
3455 'decoder_func': 'DoUniform3fv',
3457 'Uniform3iv': {
3458 'type': 'PUTn',
3459 'count': 3,
3460 'decoder_func': 'DoUniform3iv',
3462 'Uniform3ui': {
3463 'type': 'PUTXn',
3464 'count': 3,
3465 'unsafe': True,
3467 'Uniform3uiv': {
3468 'type': 'PUTn',
3469 'count': 3,
3470 'unsafe': True,
3472 'Uniform4i': {'type': 'PUTXn', 'count': 4},
3473 'Uniform4f': {'type': 'PUTXn', 'count': 4},
3474 'Uniform4fv': {
3475 'type': 'PUTn',
3476 'count': 4,
3477 'decoder_func': 'DoUniform4fv',
3479 'Uniform4iv': {
3480 'type': 'PUTn',
3481 'count': 4,
3482 'decoder_func': 'DoUniform4iv',
3484 'Uniform4ui': {
3485 'type': 'PUTXn',
3486 'count': 4,
3487 'unsafe': True,
3489 'Uniform4uiv': {
3490 'type': 'PUTn',
3491 'count': 4,
3492 'unsafe': True,
3494 'UniformMatrix2fv': {
3495 'type': 'PUTn',
3496 'count': 4,
3497 'decoder_func': 'DoUniformMatrix2fv',
3499 'UniformMatrix2x3fv': {
3500 'type': 'PUTn',
3501 'count': 6,
3502 'unsafe': True,
3504 'UniformMatrix2x4fv': {
3505 'type': 'PUTn',
3506 'count': 8,
3507 'unsafe': True,
3509 'UniformMatrix3fv': {
3510 'type': 'PUTn',
3511 'count': 9,
3512 'decoder_func': 'DoUniformMatrix3fv',
3514 'UniformMatrix3x2fv': {
3515 'type': 'PUTn',
3516 'count': 6,
3517 'unsafe': True,
3519 'UniformMatrix3x4fv': {
3520 'type': 'PUTn',
3521 'count': 12,
3522 'unsafe': True,
3524 'UniformMatrix4fv': {
3525 'type': 'PUTn',
3526 'count': 16,
3527 'decoder_func': 'DoUniformMatrix4fv',
3529 'UniformMatrix4x2fv': {
3530 'type': 'PUTn',
3531 'count': 8,
3532 'unsafe': True,
3534 'UniformMatrix4x3fv': {
3535 'type': 'PUTn',
3536 'count': 12,
3537 'unsafe': True,
3539 'UniformBlockBinding': {
3540 'type': 'Custom',
3541 'impl_func': False,
3542 'unsafe': True,
3544 'UnmapBufferCHROMIUM': {
3545 'gen_cmd': False,
3546 'extension': "CHROMIUM_pixel_transfer_buffer_object",
3547 'chromium': True,
3548 'client_test': False,
3549 'trace_level': 1,
3551 'UnmapBufferSubDataCHROMIUM': {
3552 'gen_cmd': False,
3553 'extension': True,
3554 'chromium': True,
3555 'client_test': False,
3556 'pepper_interface': 'ChromiumMapSub',
3557 'trace_level': 1,
3559 'UnmapBuffer': {
3560 'type': 'Custom',
3561 'unsafe': True,
3562 'trace_level': 1,
3564 'UnmapTexSubImage2DCHROMIUM': {
3565 'gen_cmd': False,
3566 'extension': "CHROMIUM_sub_image",
3567 'chromium': True,
3568 'client_test': False,
3569 'pepper_interface': 'ChromiumMapSub',
3570 'trace_level': 1,
3572 'UseProgram': {
3573 'type': 'Bind',
3574 'decoder_func': 'DoUseProgram',
3576 'ValidateProgram': {'decoder_func': 'DoValidateProgram'},
3577 'VertexAttrib1f': {'decoder_func': 'DoVertexAttrib1f'},
3578 'VertexAttrib1fv': {
3579 'type': 'PUT',
3580 'count': 1,
3581 'decoder_func': 'DoVertexAttrib1fv',
3583 'VertexAttrib2f': {'decoder_func': 'DoVertexAttrib2f'},
3584 'VertexAttrib2fv': {
3585 'type': 'PUT',
3586 'count': 2,
3587 'decoder_func': 'DoVertexAttrib2fv',
3589 'VertexAttrib3f': {'decoder_func': 'DoVertexAttrib3f'},
3590 'VertexAttrib3fv': {
3591 'type': 'PUT',
3592 'count': 3,
3593 'decoder_func': 'DoVertexAttrib3fv',
3595 'VertexAttrib4f': {'decoder_func': 'DoVertexAttrib4f'},
3596 'VertexAttrib4fv': {
3597 'type': 'PUT',
3598 'count': 4,
3599 'decoder_func': 'DoVertexAttrib4fv',
3601 'VertexAttribI4i': {
3602 'unsafe': True,
3603 'decoder_func': 'DoVertexAttribI4i',
3605 'VertexAttribI4iv': {
3606 'type': 'PUT',
3607 'count': 4,
3608 'unsafe': True,
3609 'decoder_func': 'DoVertexAttribI4iv',
3611 'VertexAttribI4ui': {
3612 'unsafe': True,
3613 'decoder_func': 'DoVertexAttribI4ui',
3615 'VertexAttribI4uiv': {
3616 'type': 'PUT',
3617 'count': 4,
3618 'unsafe': True,
3619 'decoder_func': 'DoVertexAttribI4uiv',
3621 'VertexAttribIPointer': {
3622 'type': 'Manual',
3623 'cmd_args': 'GLuint indx, GLintVertexAttribSize size, '
3624 'GLenumVertexAttribIType type, GLsizei stride, '
3625 'GLuint offset',
3626 'client_test': False,
3627 'unsafe': True,
3629 'VertexAttribPointer': {
3630 'type': 'Manual',
3631 'cmd_args': 'GLuint indx, GLintVertexAttribSize size, '
3632 'GLenumVertexAttribType type, GLboolean normalized, '
3633 'GLsizei stride, GLuint offset',
3634 'client_test': False,
3636 'WaitSync': {
3637 'type': 'Custom',
3638 'cmd_args': 'GLuint sync, GLbitfieldSyncFlushFlags flags, '
3639 'GLuint timeout_0, GLuint timeout_1',
3640 'impl_func': False,
3641 'client_test': False,
3642 'unsafe': True,
3643 'trace_level': 1,
3645 'Scissor': {
3646 'type': 'StateSet',
3647 'state': 'Scissor',
3649 'Viewport': {
3650 'decoder_func': 'DoViewport',
3652 'ResizeCHROMIUM': {
3653 'type': 'Custom',
3654 'impl_func': False,
3655 'unit_test': False,
3656 'extension': True,
3657 'chromium': True,
3658 'trace_level': 1,
3660 'GetRequestableExtensionsCHROMIUM': {
3661 'type': 'Custom',
3662 'impl_func': False,
3663 'cmd_args': 'uint32_t bucket_id',
3664 'extension': True,
3665 'chromium': True,
3667 'RequestExtensionCHROMIUM': {
3668 'type': 'Custom',
3669 'impl_func': False,
3670 'client_test': False,
3671 'cmd_args': 'uint32_t bucket_id',
3672 'extension': True,
3673 'chromium': True,
3675 'RateLimitOffscreenContextCHROMIUM': {
3676 'gen_cmd': False,
3677 'extension': True,
3678 'chromium': True,
3679 'client_test': False,
3681 'CreateStreamTextureCHROMIUM': {
3682 'type': 'HandWritten',
3683 'impl_func': False,
3684 'gen_cmd': False,
3685 'extension': True,
3686 'chromium': True,
3687 'trace_level': 1,
3689 'TexImageIOSurface2DCHROMIUM': {
3690 'decoder_func': 'DoTexImageIOSurface2DCHROMIUM',
3691 'unit_test': False,
3692 'extension': True,
3693 'chromium': True,
3694 'trace_level': 1,
3696 'CopyTextureCHROMIUM': {
3697 'decoder_func': 'DoCopyTextureCHROMIUM',
3698 'unit_test': False,
3699 'extension': "CHROMIUM_copy_texture",
3700 'chromium': True,
3701 'trace_level': 2,
3703 'CopySubTextureCHROMIUM': {
3704 'decoder_func': 'DoCopySubTextureCHROMIUM',
3705 'unit_test': False,
3706 'extension': "CHROMIUM_copy_texture",
3707 'chromium': True,
3708 'trace_level': 2,
3710 'CompressedCopyTextureCHROMIUM': {
3711 'decoder_func': 'DoCompressedCopyTextureCHROMIUM',
3712 'unit_test': False,
3713 'extension': True,
3714 'chromium': True,
3716 'TexStorage2DEXT': {
3717 'unit_test': False,
3718 'extension': True,
3719 'decoder_func': 'DoTexStorage2DEXT',
3720 'trace_level': 2,
3722 'DrawArraysInstancedANGLE': {
3723 'type': 'Manual',
3724 'cmd_args': 'GLenumDrawMode mode, GLint first, GLsizei count, '
3725 'GLsizei primcount',
3726 'extension': True,
3727 'unit_test': False,
3728 'pepper_interface': 'InstancedArrays',
3729 'defer_draws': True,
3730 'trace_level': 2,
3732 'DrawBuffersEXT': {
3733 'type': 'PUTn',
3734 'decoder_func': 'DoDrawBuffersEXT',
3735 'count': 1,
3736 'client_test': False,
3737 'unit_test': False,
3738 # could use 'extension_flag': 'ext_draw_buffers' but currently expected to
3739 # work without.
3740 'extension': True,
3741 'pepper_interface': 'DrawBuffers',
3742 'trace_level': 2,
3744 'DrawElementsInstancedANGLE': {
3745 'type': 'Manual',
3746 'cmd_args': 'GLenumDrawMode mode, GLsizei count, '
3747 'GLenumIndexType type, GLuint index_offset, GLsizei primcount',
3748 'extension': True,
3749 'unit_test': False,
3750 'client_test': False,
3751 'pepper_interface': 'InstancedArrays',
3752 'defer_draws': True,
3753 'trace_level': 2,
3755 'VertexAttribDivisorANGLE': {
3756 'type': 'Manual',
3757 'cmd_args': 'GLuint index, GLuint divisor',
3758 'extension': True,
3759 'unit_test': False,
3760 'pepper_interface': 'InstancedArrays',
3762 'GenQueriesEXT': {
3763 'type': 'GENn',
3764 'gl_test_func': 'glGenQueriesARB',
3765 'resource_type': 'Query',
3766 'resource_types': 'Queries',
3767 'unit_test': False,
3768 'pepper_interface': 'Query',
3769 'not_shared': 'True',
3770 'extension': "occlusion_query_EXT",
3772 'DeleteQueriesEXT': {
3773 'type': 'DELn',
3774 'gl_test_func': 'glDeleteQueriesARB',
3775 'resource_type': 'Query',
3776 'resource_types': 'Queries',
3777 'unit_test': False,
3778 'pepper_interface': 'Query',
3779 'extension': "occlusion_query_EXT",
3781 'IsQueryEXT': {
3782 'gen_cmd': False,
3783 'client_test': False,
3784 'pepper_interface': 'Query',
3785 'extension': "occlusion_query_EXT",
3787 'BeginQueryEXT': {
3788 'type': 'Manual',
3789 'cmd_args': 'GLenumQueryTarget target, GLidQuery id, void* sync_data',
3790 'data_transfer_methods': ['shm'],
3791 'gl_test_func': 'glBeginQuery',
3792 'pepper_interface': 'Query',
3793 'extension': "occlusion_query_EXT",
3795 'BeginTransformFeedback': {
3796 'unsafe': True,
3798 'EndQueryEXT': {
3799 'type': 'Manual',
3800 'cmd_args': 'GLenumQueryTarget target, GLuint submit_count',
3801 'gl_test_func': 'glEndnQuery',
3802 'client_test': False,
3803 'pepper_interface': 'Query',
3804 'extension': "occlusion_query_EXT",
3806 'EndTransformFeedback': {
3807 'unsafe': True,
3809 'FlushDriverCachesCHROMIUM': {
3810 'decoder_func': 'DoFlushDriverCachesCHROMIUM',
3811 'unit_test': False,
3812 'extension': True,
3813 'chromium': True,
3814 'trace_level': 1,
3816 'GetQueryivEXT': {
3817 'gen_cmd': False,
3818 'client_test': False,
3819 'gl_test_func': 'glGetQueryiv',
3820 'pepper_interface': 'Query',
3821 'extension': "occlusion_query_EXT",
3823 'QueryCounterEXT' : {
3824 'type': 'Manual',
3825 'cmd_args': 'GLidQuery id, GLenumQueryTarget target, '
3826 'void* sync_data, GLuint submit_count',
3827 'data_transfer_methods': ['shm'],
3828 'gl_test_func': 'glQueryCounter',
3829 'extension': "disjoint_timer_query_EXT",
3831 'GetQueryObjectuivEXT': {
3832 'gen_cmd': False,
3833 'client_test': False,
3834 'gl_test_func': 'glGetQueryObjectuiv',
3835 'pepper_interface': 'Query',
3836 'extension': "occlusion_query_EXT",
3838 'GetQueryObjectui64vEXT': {
3839 'gen_cmd': False,
3840 'client_test': False,
3841 'gl_test_func': 'glGetQueryObjectui64v',
3842 'extension': "disjoint_timer_query_EXT",
3844 'BindUniformLocationCHROMIUM': {
3845 'type': 'GLchar',
3846 'extension': True,
3847 'data_transfer_methods': ['bucket'],
3848 'needs_size': True,
3849 'gl_test_func': 'DoBindUniformLocationCHROMIUM',
3851 'InsertEventMarkerEXT': {
3852 'type': 'GLcharN',
3853 'decoder_func': 'DoInsertEventMarkerEXT',
3854 'expectation': False,
3855 'extension': True,
3857 'PushGroupMarkerEXT': {
3858 'type': 'GLcharN',
3859 'decoder_func': 'DoPushGroupMarkerEXT',
3860 'expectation': False,
3861 'extension': True,
3863 'PopGroupMarkerEXT': {
3864 'decoder_func': 'DoPopGroupMarkerEXT',
3865 'expectation': False,
3866 'extension': True,
3867 'impl_func': False,
3870 'GenVertexArraysOES': {
3871 'type': 'GENn',
3872 'extension': True,
3873 'gl_test_func': 'glGenVertexArraysOES',
3874 'resource_type': 'VertexArray',
3875 'resource_types': 'VertexArrays',
3876 'unit_test': False,
3877 'pepper_interface': 'VertexArrayObject',
3879 'BindVertexArrayOES': {
3880 'type': 'Bind',
3881 'extension': True,
3882 'gl_test_func': 'glBindVertexArrayOES',
3883 'decoder_func': 'DoBindVertexArrayOES',
3884 'gen_func': 'GenVertexArraysOES',
3885 'unit_test': False,
3886 'client_test': False,
3887 'pepper_interface': 'VertexArrayObject',
3889 'DeleteVertexArraysOES': {
3890 'type': 'DELn',
3891 'extension': True,
3892 'gl_test_func': 'glDeleteVertexArraysOES',
3893 'resource_type': 'VertexArray',
3894 'resource_types': 'VertexArrays',
3895 'unit_test': False,
3896 'pepper_interface': 'VertexArrayObject',
3898 'IsVertexArrayOES': {
3899 'type': 'Is',
3900 'extension': True,
3901 'gl_test_func': 'glIsVertexArrayOES',
3902 'decoder_func': 'DoIsVertexArrayOES',
3903 'expectation': False,
3904 'unit_test': False,
3905 'pepper_interface': 'VertexArrayObject',
3907 'BindTexImage2DCHROMIUM': {
3908 'decoder_func': 'DoBindTexImage2DCHROMIUM',
3909 'unit_test': False,
3910 'extension': "CHROMIUM_image",
3911 'chromium': True,
3913 'ReleaseTexImage2DCHROMIUM': {
3914 'decoder_func': 'DoReleaseTexImage2DCHROMIUM',
3915 'unit_test': False,
3916 'extension': "CHROMIUM_image",
3917 'chromium': True,
3919 'ShallowFinishCHROMIUM': {
3920 'impl_func': False,
3921 'gen_cmd': False,
3922 'extension': True,
3923 'chromium': True,
3924 'client_test': False,
3926 'ShallowFlushCHROMIUM': {
3927 'impl_func': False,
3928 'gen_cmd': False,
3929 'extension': "CHROMIUM_miscellaneous",
3930 'chromium': True,
3931 'client_test': False,
3933 'OrderingBarrierCHROMIUM': {
3934 'impl_func': False,
3935 'gen_cmd': False,
3936 'extension': True,
3937 'chromium': True,
3938 'client_test': False,
3940 'TraceBeginCHROMIUM': {
3941 'type': 'Custom',
3942 'impl_func': False,
3943 'client_test': False,
3944 'cmd_args': 'GLuint category_bucket_id, GLuint name_bucket_id',
3945 'extension': True,
3946 'chromium': True,
3948 'TraceEndCHROMIUM': {
3949 'impl_func': False,
3950 'client_test': False,
3951 'decoder_func': 'DoTraceEndCHROMIUM',
3952 'unit_test': False,
3953 'extension': True,
3954 'chromium': True,
3956 'AsyncTexImage2DCHROMIUM': {
3957 'type': 'Manual',
3958 'data_transfer_methods': ['shm'],
3959 'client_test': False,
3960 'cmd_args': 'GLenumTextureTarget target, GLint level, '
3961 'GLintTextureInternalFormat internalformat, '
3962 'GLsizei width, GLsizei height, '
3963 'GLintTextureBorder border, '
3964 'GLenumTextureFormat format, GLenumPixelType type, '
3965 'const void* pixels, '
3966 'uint32_t async_upload_token, '
3967 'void* sync_data',
3968 'extension': True,
3969 'chromium': True,
3970 'trace_level': 2,
3972 'AsyncTexSubImage2DCHROMIUM': {
3973 'type': 'Manual',
3974 'data_transfer_methods': ['shm'],
3975 'client_test': False,
3976 'cmd_args': 'GLenumTextureTarget target, GLint level, '
3977 'GLint xoffset, GLint yoffset, '
3978 'GLsizei width, GLsizei height, '
3979 'GLenumTextureFormat format, GLenumPixelType type, '
3980 'const void* data, '
3981 'uint32_t async_upload_token, '
3982 'void* sync_data',
3983 'extension': True,
3984 'chromium': True,
3985 'trace_level': 2,
3987 'WaitAsyncTexImage2DCHROMIUM': {
3988 'type': 'Manual',
3989 'client_test': False,
3990 'extension': True,
3991 'chromium': True,
3992 'trace_level': 1,
3994 'WaitAllAsyncTexImage2DCHROMIUM': {
3995 'type': 'Manual',
3996 'client_test': False,
3997 'extension': True,
3998 'chromium': True,
3999 'trace_level': 1,
4001 'DiscardFramebufferEXT': {
4002 'type': 'PUTn',
4003 'count': 1,
4004 'decoder_func': 'DoDiscardFramebufferEXT',
4005 'unit_test': False,
4006 'client_test': False,
4007 'extension_flag': 'ext_discard_framebuffer',
4008 'trace_level': 2,
4010 'LoseContextCHROMIUM': {
4011 'decoder_func': 'DoLoseContextCHROMIUM',
4012 'unit_test': False,
4013 'extension': True,
4014 'chromium': True,
4015 'trace_level': 1,
4017 'InsertSyncPointCHROMIUM': {
4018 'type': 'HandWritten',
4019 'impl_func': False,
4020 'extension': "CHROMIUM_sync_point",
4021 'chromium': True,
4022 'trace_level': 1,
4024 'WaitSyncPointCHROMIUM': {
4025 'type': 'Custom',
4026 'impl_func': True,
4027 'extension': "CHROMIUM_sync_point",
4028 'chromium': True,
4029 'trace_level': 1,
4031 'DiscardBackbufferCHROMIUM': {
4032 'type': 'Custom',
4033 'impl_func': True,
4034 'extension': True,
4035 'chromium': True,
4036 'trace_level': 2,
4038 'ScheduleOverlayPlaneCHROMIUM': {
4039 'type': 'Custom',
4040 'impl_func': True,
4041 'unit_test': False,
4042 'client_test': False,
4043 'extension': True,
4044 'chromium': True,
4046 'MatrixLoadfCHROMIUM': {
4047 'type': 'PUT',
4048 'count': 16,
4049 'data_type': 'GLfloat',
4050 'decoder_func': 'DoMatrixLoadfCHROMIUM',
4051 'gl_test_func': 'glMatrixLoadfEXT',
4052 'chromium': True,
4053 'extension': True,
4054 'extension_flag': 'chromium_path_rendering',
4056 'MatrixLoadIdentityCHROMIUM': {
4057 'decoder_func': 'DoMatrixLoadIdentityCHROMIUM',
4058 'gl_test_func': 'glMatrixLoadIdentityEXT',
4059 'chromium': True,
4060 'extension': True,
4061 'extension_flag': 'chromium_path_rendering',
4063 'GenPathsCHROMIUM': {
4064 'type': 'Custom',
4065 'cmd_args': 'GLuint first_client_id, GLsizei range',
4066 'chromium': True,
4067 'extension': True,
4068 'extension_flag': 'chromium_path_rendering',
4070 'DeletePathsCHROMIUM': {
4071 'type': 'Custom',
4072 'cmd_args': 'GLuint first_client_id, GLsizei range',
4073 'impl_func': False,
4074 'unit_test': False,
4075 'chromium': True,
4076 'extension': True,
4077 'extension_flag': 'chromium_path_rendering',
4079 'IsPathCHROMIUM': {
4080 'type': 'Is',
4081 'decoder_func': 'DoIsPathCHROMIUM',
4082 'gl_test_func': 'glIsPathNV',
4083 'chromium': True,
4084 'extension': True,
4085 'extension_flag': 'chromium_path_rendering',
4087 'PathCommandsCHROMIUM': {
4088 'type': 'Manual',
4089 'immediate': False,
4090 'chromium': True,
4091 'extension': True,
4092 'extension_flag': 'chromium_path_rendering',
4094 'PathParameterfCHROMIUM': {
4095 'type': 'Custom',
4096 'chromium': True,
4097 'extension': True,
4098 'extension_flag': 'chromium_path_rendering',
4100 'PathParameteriCHROMIUM': {
4101 'type': 'Custom',
4102 'chromium': True,
4103 'extension': True,
4104 'extension_flag': 'chromium_path_rendering',
4106 'PathStencilFuncCHROMIUM': {
4107 'type': 'StateSet',
4108 'state': 'PathStencilFuncCHROMIUM',
4109 'decoder_func': 'glPathStencilFuncNV',
4110 'chromium': True,
4111 'extension': True,
4112 'extension_flag': 'chromium_path_rendering',
4114 'StencilFillPathCHROMIUM': {
4115 'type': 'Custom',
4116 'chromium': True,
4117 'extension': True,
4118 'extension_flag': 'chromium_path_rendering',
4120 'StencilStrokePathCHROMIUM': {
4121 'type': 'Custom',
4122 'chromium': True,
4123 'extension': True,
4124 'extension_flag': 'chromium_path_rendering',
4126 'CoverFillPathCHROMIUM': {
4127 'type': 'Custom',
4128 'chromium': True,
4129 'extension': True,
4130 'extension_flag': 'chromium_path_rendering',
4132 'CoverStrokePathCHROMIUM': {
4133 'type': 'Custom',
4134 'chromium': True,
4135 'extension': True,
4136 'extension_flag': 'chromium_path_rendering',
4138 'StencilThenCoverFillPathCHROMIUM': {
4139 'type': 'Custom',
4140 'chromium': True,
4141 'extension': True,
4142 'extension_flag': 'chromium_path_rendering',
4144 'StencilThenCoverStrokePathCHROMIUM': {
4145 'type': 'Custom',
4146 'chromium': True,
4147 'extension': True,
4148 'extension_flag': 'chromium_path_rendering',
4154 def Grouper(n, iterable, fillvalue=None):
4155 """Collect data into fixed-length chunks or blocks"""
4156 args = [iter(iterable)] * n
4157 return itertools.izip_longest(fillvalue=fillvalue, *args)
4160 def SplitWords(input_string):
4161 """Split by '_' if found, otherwise split at uppercase/numeric chars.
4163 Will split "some_TEXT" into ["some", "TEXT"], "CamelCase" into ["Camel",
4164 "Case"], and "Vector3" into ["Vector", "3"].
4166 if input_string.find('_') > -1:
4167 # 'some_TEXT_' -> 'some TEXT'
4168 return input_string.replace('_', ' ').strip().split()
4169 else:
4170 if re.search('[A-Z]', input_string) and re.search('[a-z]', input_string):
4171 # mixed case.
4172 # look for capitalization to cut input_strings
4173 # 'SomeText' -> 'Some Text'
4174 input_string = re.sub('([A-Z])', r' \1', input_string).strip()
4175 # 'Vector3' -> 'Vector 3'
4176 input_string = re.sub('([^0-9])([0-9])', r'\1 \2', input_string)
4177 return input_string.split()
4179 def ToUnderscore(input_string):
4180 """converts CamelCase to camel_case."""
4181 words = SplitWords(input_string)
4182 return '_'.join([word.lower() for word in words])
4184 def CachedStateName(item):
4185 if item.get('cached', False):
4186 return 'cached_' + item['name']
4187 return item['name']
4189 def ToGLExtensionString(extension_flag):
4190 """Returns GL-type extension string of a extension flag."""
4191 if extension_flag == "oes_compressed_etc1_rgb8_texture":
4192 return "OES_compressed_ETC1_RGB8_texture" # Fixup inconsitency with rgb8,
4193 # unfortunate.
4194 uppercase_words = [ 'img', 'ext', 'arb', 'chromium', 'oes', 'amd', 'bgra8888',
4195 'egl', 'atc', 'etc1', 'angle']
4196 parts = extension_flag.split('_')
4197 return "_".join(
4198 [part.upper() if part in uppercase_words else part for part in parts])
4200 def ToCamelCase(input_string):
4201 """converts ABC_underscore_case to ABCUnderscoreCase."""
4202 return ''.join(w[0].upper() + w[1:] for w in input_string.split('_'))
4204 def GetGLGetTypeConversion(result_type, value_type, value):
4205 """Makes a gl compatible type conversion string for accessing state variables.
4207 Useful when accessing state variables through glGetXXX calls.
4208 glGet documetation (for example, the manual pages):
4209 [...] If glGetIntegerv is called, [...] most floating-point values are
4210 rounded to the nearest integer value. [...]
4212 Args:
4213 result_type: the gl type to be obtained
4214 value_type: the GL type of the state variable
4215 value: the name of the state variable
4217 Returns:
4218 String that converts the state variable to desired GL type according to GL
4219 rules.
4222 if result_type == 'GLint':
4223 if value_type == 'GLfloat':
4224 return 'static_cast<GLint>(round(%s))' % value
4225 return 'static_cast<%s>(%s)' % (result_type, value)
4227 class CWriter(object):
4228 """Writes to a file formatting it for Google's style guidelines."""
4230 def __init__(self, filename):
4231 self.filename = filename
4232 self.content = []
4234 def Write(self, string):
4235 """Writes a string to a file spliting if it's > 80 characters."""
4236 lines = string.splitlines()
4237 num_lines = len(lines)
4238 for ii in range(0, num_lines):
4239 self.content.append(lines[ii])
4240 if ii < (num_lines - 1) or string[-1] == '\n':
4241 self.content.append('\n')
4243 def Close(self):
4244 """Close the file."""
4245 content = "".join(self.content)
4246 write_file = True
4247 if os.path.exists(self.filename):
4248 old_file = open(self.filename, "rb");
4249 old_content = old_file.read()
4250 old_file.close();
4251 if content == old_content:
4252 write_file = False
4253 if write_file:
4254 file = open(self.filename, "wb")
4255 file.write(content)
4256 file.close()
4259 class CHeaderWriter(CWriter):
4260 """Writes a C Header file."""
4262 _non_alnum_re = re.compile(r'[^a-zA-Z0-9]')
4264 def __init__(self, filename, file_comment = None):
4265 CWriter.__init__(self, filename)
4267 base = os.path.abspath(filename)
4268 while os.path.basename(base) != 'src':
4269 new_base = os.path.dirname(base)
4270 assert new_base != base # Prevent infinite loop.
4271 base = new_base
4273 hpath = os.path.relpath(filename, base)
4274 self.guard = self._non_alnum_re.sub('_', hpath).upper() + '_'
4276 self.Write(_LICENSE)
4277 self.Write(_DO_NOT_EDIT_WARNING)
4278 if not file_comment == None:
4279 self.Write(file_comment)
4280 self.Write("#ifndef %s\n" % self.guard)
4281 self.Write("#define %s\n\n" % self.guard)
4283 def Close(self):
4284 self.Write("#endif // %s\n\n" % self.guard)
4285 CWriter.Close(self)
4287 class TypeHandler(object):
4288 """This class emits code for a particular type of function."""
4290 _remove_expected_call_re = re.compile(r' EXPECT_CALL.*?;\n', re.S)
4292 def __init__(self):
4293 pass
4295 def InitFunction(self, func):
4296 """Add or adjust anything type specific for this function."""
4297 if func.GetInfo('needs_size') and not func.name.endswith('Bucket'):
4298 func.AddCmdArg(DataSizeArgument('data_size'))
4300 def NeedsDataTransferFunction(self, func):
4301 """Overriden from TypeHandler."""
4302 return func.num_pointer_args >= 1
4304 def WriteStruct(self, func, file):
4305 """Writes a structure that matches the arguments to a function."""
4306 comment = func.GetInfo('cmd_comment')
4307 if not comment == None:
4308 file.Write(comment)
4309 file.Write("struct %s {\n" % func.name)
4310 file.Write(" typedef %s ValueType;\n" % func.name)
4311 file.Write(" static const CommandId kCmdId = k%s;\n" % func.name)
4312 func.WriteCmdArgFlag(file)
4313 func.WriteCmdFlag(file)
4314 file.Write("\n")
4315 result = func.GetInfo('result')
4316 if not result == None:
4317 if len(result) == 1:
4318 file.Write(" typedef %s Result;\n\n" % result[0])
4319 else:
4320 file.Write(" struct Result {\n")
4321 for line in result:
4322 file.Write(" %s;\n" % line)
4323 file.Write(" };\n\n")
4325 func.WriteCmdComputeSize(file)
4326 func.WriteCmdSetHeader(file)
4327 func.WriteCmdInit(file)
4328 func.WriteCmdSet(file)
4330 file.Write(" gpu::CommandHeader header;\n")
4331 args = func.GetCmdArgs()
4332 for arg in args:
4333 file.Write(" %s %s;\n" % (arg.cmd_type, arg.name))
4335 consts = func.GetCmdConstants()
4336 for const in consts:
4337 file.Write(" static const %s %s = %s;\n" %
4338 (const.cmd_type, const.name, const.GetConstantValue()))
4340 file.Write("};\n")
4341 file.Write("\n")
4343 size = len(args) * _SIZE_OF_UINT32 + _SIZE_OF_COMMAND_HEADER
4344 file.Write("static_assert(sizeof(%s) == %d,\n" % (func.name, size))
4345 file.Write(" \"size of %s should be %d\");\n" %
4346 (func.name, size))
4347 file.Write("static_assert(offsetof(%s, header) == 0,\n" % func.name)
4348 file.Write(" \"offset of %s header should be 0\");\n" %
4349 func.name)
4350 offset = _SIZE_OF_COMMAND_HEADER
4351 for arg in args:
4352 file.Write("static_assert(offsetof(%s, %s) == %d,\n" %
4353 (func.name, arg.name, offset))
4354 file.Write(" \"offset of %s %s should be %d\");\n" %
4355 (func.name, arg.name, offset))
4356 offset += _SIZE_OF_UINT32
4357 if not result == None and len(result) > 1:
4358 offset = 0;
4359 for line in result:
4360 parts = line.split()
4361 name = parts[-1]
4362 check = """
4363 static_assert(offsetof(%(cmd_name)s::Result, %(field_name)s) == %(offset)d,
4364 "offset of %(cmd_name)s Result %(field_name)s should be "
4365 "%(offset)d");
4367 file.Write((check.strip() + "\n") % {
4368 'cmd_name': func.name,
4369 'field_name': name,
4370 'offset': offset,
4372 offset += _SIZE_OF_UINT32
4373 file.Write("\n")
4375 def WriteHandlerImplementation(self, func, file):
4376 """Writes the handler implementation for this command."""
4377 if func.IsUnsafe() and func.GetInfo('id_mapping'):
4378 code_no_gen = """ if (!group_->Get%(type)sServiceId(
4379 %(var)s, &%(service_var)s)) {
4380 LOCAL_SET_GL_ERROR(GL_INVALID_OPERATION, "%(func)s", "invalid %(var)s id");
4381 return error::kNoError;
4384 code_gen = """ if (!group_->Get%(type)sServiceId(
4385 %(var)s, &%(service_var)s)) {
4386 if (!group_->bind_generates_resource()) {
4387 LOCAL_SET_GL_ERROR(
4388 GL_INVALID_OPERATION, "%(func)s", "invalid %(var)s id");
4389 return error::kNoError;
4391 GLuint client_id = %(var)s;
4392 gl%(gen_func)s(1, &%(service_var)s);
4393 Create%(type)s(client_id, %(service_var)s);
4396 gen_func = func.GetInfo('gen_func')
4397 for id_type in func.GetInfo('id_mapping'):
4398 service_var = id_type.lower()
4399 if id_type == 'Sync':
4400 service_var = "service_%s" % service_var
4401 file.Write(" GLsync %s = 0;\n" % service_var)
4402 if gen_func and id_type in gen_func:
4403 file.Write(code_gen % { 'type': id_type,
4404 'var': id_type.lower(),
4405 'service_var': service_var,
4406 'func': func.GetGLFunctionName(),
4407 'gen_func': gen_func })
4408 else:
4409 file.Write(code_no_gen % { 'type': id_type,
4410 'var': id_type.lower(),
4411 'service_var': service_var,
4412 'func': func.GetGLFunctionName() })
4413 args = []
4414 for arg in func.GetOriginalArgs():
4415 if arg.type == "GLsync":
4416 args.append("service_%s" % arg.name)
4417 elif arg.name.endswith("size") and arg.type == "GLsizei":
4418 args.append("num_%s" % func.GetLastOriginalArg().name)
4419 elif arg.name == "length":
4420 args.append("nullptr")
4421 else:
4422 args.append(arg.name)
4423 file.Write(" %s(%s);\n" %
4424 (func.GetGLFunctionName(), ", ".join(args)))
4426 def WriteCmdSizeTest(self, func, file):
4427 """Writes the size test for a command."""
4428 file.Write(" EXPECT_EQ(sizeof(cmd), cmd.header.size * 4u);\n")
4430 def WriteFormatTest(self, func, file):
4431 """Writes a format test for a command."""
4432 file.Write("TEST_F(GLES2FormatTest, %s) {\n" % func.name)
4433 file.Write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
4434 (func.name, func.name))
4435 file.Write(" void* next_cmd = cmd.Set(\n")
4436 file.Write(" &cmd")
4437 args = func.GetCmdArgs()
4438 for value, arg in enumerate(args):
4439 file.Write(",\n static_cast<%s>(%d)" % (arg.type, value + 11))
4440 file.Write(");\n")
4441 file.Write(" EXPECT_EQ(static_cast<uint32_t>(cmds::%s::kCmdId),\n" %
4442 func.name)
4443 file.Write(" cmd.header.command);\n")
4444 func.type_handler.WriteCmdSizeTest(func, file)
4445 for value, arg in enumerate(args):
4446 file.Write(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);\n" %
4447 (arg.type, value + 11, arg.name))
4448 file.Write(" CheckBytesWrittenMatchesExpectedSize(\n")
4449 file.Write(" next_cmd, sizeof(cmd));\n")
4450 file.Write("}\n")
4451 file.Write("\n")
4453 def WriteImmediateFormatTest(self, func, file):
4454 """Writes a format test for an immediate version of a command."""
4455 pass
4457 def WriteBucketFormatTest(self, func, file):
4458 """Writes a format test for a bucket version of a command."""
4459 pass
4461 def WriteGetDataSizeCode(self, func, file):
4462 """Writes the code to set data_size used in validation"""
4463 pass
4465 def WriteImmediateCmdSizeTest(self, func, file):
4466 """Writes a size test for an immediate version of a command."""
4467 file.Write(" // TODO(gman): Compute correct size.\n")
4468 file.Write(" EXPECT_EQ(sizeof(cmd), cmd.header.size * 4u);\n")
4470 def __WriteIdMapping(self, func, file):
4471 """Writes client side / service side ID mapping."""
4472 if not func.IsUnsafe() or not func.GetInfo('id_mapping'):
4473 return
4474 for id_type in func.GetInfo('id_mapping'):
4475 file.Write(" group_->Get%sServiceId(%s, &%s);\n" %
4476 (id_type, id_type.lower(), id_type.lower()))
4478 def WriteImmediateHandlerImplementation (self, func, file):
4479 """Writes the handler impl for the immediate version of a command."""
4480 self.__WriteIdMapping(func, file)
4481 file.Write(" %s(%s);\n" %
4482 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
4484 def WriteBucketHandlerImplementation (self, func, file):
4485 """Writes the handler impl for the bucket version of a command."""
4486 self.__WriteIdMapping(func, file)
4487 file.Write(" %s(%s);\n" %
4488 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
4490 def WriteServiceHandlerFunctionHeader(self, func, file):
4491 """Writes function header for service implementation handlers."""
4492 file.Write("""error::Error GLES2DecoderImpl::Handle%(name)s(
4493 uint32_t immediate_data_size, const void* cmd_data) {
4494 """ % {'name': func.name})
4495 if func.IsUnsafe():
4496 file.Write("""if (!unsafe_es3_apis_enabled())
4497 return error::kUnknownCommand;
4498 """)
4499 file.Write("""const gles2::cmds::%(name)s& c =
4500 *static_cast<const gles2::cmds::%(name)s*>(cmd_data);
4501 (void)c;
4502 """ % {'name': func.name})
4504 def WriteServiceImplementation(self, func, file):
4505 """Writes the service implementation for a command."""
4506 self.WriteServiceHandlerFunctionHeader(func, file)
4507 self.WriteHandlerExtensionCheck(func, file)
4508 self.WriteHandlerDeferReadWrite(func, file);
4509 if len(func.GetOriginalArgs()) > 0:
4510 last_arg = func.GetLastOriginalArg()
4511 all_but_last_arg = func.GetOriginalArgs()[:-1]
4512 for arg in all_but_last_arg:
4513 arg.WriteGetCode(file)
4514 self.WriteGetDataSizeCode(func, file)
4515 last_arg.WriteGetCode(file)
4516 func.WriteHandlerValidation(file)
4517 func.WriteHandlerImplementation(file)
4518 file.Write(" return error::kNoError;\n")
4519 file.Write("}\n")
4520 file.Write("\n")
4522 def WriteImmediateServiceImplementation(self, func, file):
4523 """Writes the service implementation for an immediate version of command."""
4524 self.WriteServiceHandlerFunctionHeader(func, file)
4525 self.WriteHandlerExtensionCheck(func, file)
4526 self.WriteHandlerDeferReadWrite(func, file);
4527 for arg in func.GetOriginalArgs():
4528 if arg.IsPointer():
4529 self.WriteGetDataSizeCode(func, file)
4530 arg.WriteGetCode(file)
4531 func.WriteHandlerValidation(file)
4532 func.WriteHandlerImplementation(file)
4533 file.Write(" return error::kNoError;\n")
4534 file.Write("}\n")
4535 file.Write("\n")
4537 def WriteBucketServiceImplementation(self, func, file):
4538 """Writes the service implementation for a bucket version of command."""
4539 self.WriteServiceHandlerFunctionHeader(func, file)
4540 self.WriteHandlerExtensionCheck(func, file)
4541 self.WriteHandlerDeferReadWrite(func, file);
4542 for arg in func.GetCmdArgs():
4543 arg.WriteGetCode(file)
4544 func.WriteHandlerValidation(file)
4545 func.WriteHandlerImplementation(file)
4546 file.Write(" return error::kNoError;\n")
4547 file.Write("}\n")
4548 file.Write("\n")
4550 def WriteHandlerExtensionCheck(self, func, file):
4551 if func.GetInfo('extension_flag'):
4552 file.Write(" if (!features().%s) {\n" % func.GetInfo('extension_flag'))
4553 file.Write(" LOCAL_SET_GL_ERROR(GL_INVALID_OPERATION, \"gl%s\","
4554 " \"function not available\");\n" % func.original_name)
4555 file.Write(" return error::kNoError;")
4556 file.Write(" }\n\n")
4558 def WriteHandlerDeferReadWrite(self, func, file):
4559 """Writes the code to handle deferring reads or writes."""
4560 defer_draws = func.GetInfo('defer_draws')
4561 defer_reads = func.GetInfo('defer_reads')
4562 if defer_draws or defer_reads:
4563 file.Write(" error::Error error;\n")
4564 if defer_draws:
4565 file.Write(" error = WillAccessBoundFramebufferForDraw();\n")
4566 file.Write(" if (error != error::kNoError)\n")
4567 file.Write(" return error;\n")
4568 if defer_reads:
4569 file.Write(" error = WillAccessBoundFramebufferForRead();\n")
4570 file.Write(" if (error != error::kNoError)\n")
4571 file.Write(" return error;\n")
4573 def WriteValidUnitTest(self, func, file, test, *extras):
4574 """Writes a valid unit test for the service implementation."""
4575 if func.GetInfo('expectation') == False:
4576 test = self._remove_expected_call_re.sub('', test)
4577 name = func.name
4578 arg_strings = [
4579 arg.GetValidArg(func) \
4580 for arg in func.GetOriginalArgs() if not arg.IsConstant()
4582 gl_arg_strings = [
4583 arg.GetValidGLArg(func) \
4584 for arg in func.GetOriginalArgs()
4586 gl_func_name = func.GetGLTestFunctionName()
4587 vars = {
4588 'name':name,
4589 'gl_func_name': gl_func_name,
4590 'args': ", ".join(arg_strings),
4591 'gl_args': ", ".join(gl_arg_strings),
4593 for extra in extras:
4594 vars.update(extra)
4595 old_test = ""
4596 while (old_test != test):
4597 old_test = test
4598 test = test % vars
4599 file.Write(test % vars)
4601 def WriteInvalidUnitTest(self, func, file, test, *extras):
4602 """Writes an invalid unit test for the service implementation."""
4603 if func.IsUnsafe():
4604 return
4605 for invalid_arg_index, invalid_arg in enumerate(func.GetOriginalArgs()):
4606 # Service implementation does not test constants, as they are not part of
4607 # the call in the service side.
4608 if invalid_arg.IsConstant():
4609 continue
4611 num_invalid_values = invalid_arg.GetNumInvalidValues(func)
4612 for value_index in range(0, num_invalid_values):
4613 arg_strings = []
4614 parse_result = "kNoError"
4615 gl_error = None
4616 for arg in func.GetOriginalArgs():
4617 if arg.IsConstant():
4618 continue
4619 if invalid_arg is arg:
4620 (arg_string, parse_result, gl_error) = arg.GetInvalidArg(
4621 value_index)
4622 else:
4623 arg_string = arg.GetValidArg(func)
4624 arg_strings.append(arg_string)
4625 gl_arg_strings = []
4626 for arg in func.GetOriginalArgs():
4627 gl_arg_strings.append("_")
4628 gl_func_name = func.GetGLTestFunctionName()
4629 gl_error_test = ''
4630 if not gl_error == None:
4631 gl_error_test = '\n EXPECT_EQ(%s, GetGLError());' % gl_error
4633 vars = {
4634 'name': func.name,
4635 'arg_index': invalid_arg_index,
4636 'value_index': value_index,
4637 'gl_func_name': gl_func_name,
4638 'args': ", ".join(arg_strings),
4639 'all_but_last_args': ", ".join(arg_strings[:-1]),
4640 'gl_args': ", ".join(gl_arg_strings),
4641 'parse_result': parse_result,
4642 'gl_error_test': gl_error_test,
4644 for extra in extras:
4645 vars.update(extra)
4646 file.Write(test % vars)
4648 def WriteServiceUnitTest(self, func, file, *extras):
4649 """Writes the service unit test for a command."""
4651 if func.name == 'Enable':
4652 valid_test = """
4653 TEST_P(%(test_name)s, %(name)sValidArgs) {
4654 SetupExpectationsForEnableDisable(%(gl_args)s, true);
4655 SpecializedSetup<cmds::%(name)s, 0>(true);
4656 cmds::%(name)s cmd;
4657 cmd.Init(%(args)s);"""
4658 elif func.name == 'Disable':
4659 valid_test = """
4660 TEST_P(%(test_name)s, %(name)sValidArgs) {
4661 SetupExpectationsForEnableDisable(%(gl_args)s, false);
4662 SpecializedSetup<cmds::%(name)s, 0>(true);
4663 cmds::%(name)s cmd;
4664 cmd.Init(%(args)s);"""
4665 else:
4666 valid_test = """
4667 TEST_P(%(test_name)s, %(name)sValidArgs) {
4668 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
4669 SpecializedSetup<cmds::%(name)s, 0>(true);
4670 cmds::%(name)s cmd;
4671 cmd.Init(%(args)s);"""
4672 if func.IsUnsafe():
4673 valid_test += """
4674 decoder_->set_unsafe_es3_apis_enabled(true);
4675 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4676 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4677 decoder_->set_unsafe_es3_apis_enabled(false);
4678 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));
4681 else:
4682 valid_test += """
4683 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4684 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4687 self.WriteValidUnitTest(func, file, valid_test, *extras)
4689 if not func.IsUnsafe():
4690 invalid_test = """
4691 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
4692 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
4693 SpecializedSetup<cmds::%(name)s, 0>(false);
4694 cmds::%(name)s cmd;
4695 cmd.Init(%(args)s);
4696 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
4699 self.WriteInvalidUnitTest(func, file, invalid_test, *extras)
4701 def WriteImmediateServiceUnitTest(self, func, file, *extras):
4702 """Writes the service unit test for an immediate command."""
4703 file.Write("// TODO(gman): %s\n" % func.name)
4705 def WriteImmediateValidationCode(self, func, file):
4706 """Writes the validation code for an immediate version of a command."""
4707 pass
4709 def WriteBucketServiceUnitTest(self, func, file, *extras):
4710 """Writes the service unit test for a bucket command."""
4711 file.Write("// TODO(gman): %s\n" % func.name)
4713 def WriteBucketValidationCode(self, func, file):
4714 """Writes the validation code for a bucket version of a command."""
4715 file.Write("// TODO(gman): %s\n" % func.name)
4717 def WriteGLES2ImplementationDeclaration(self, func, file):
4718 """Writes the GLES2 Implemention declaration."""
4719 impl_decl = func.GetInfo('impl_decl')
4720 if impl_decl == None or impl_decl == True:
4721 file.Write("%s %s(%s) override;\n" %
4722 (func.return_type, func.original_name,
4723 func.MakeTypedOriginalArgString("")))
4724 file.Write("\n")
4726 def WriteGLES2CLibImplementation(self, func, file):
4727 file.Write("%s GLES2%s(%s) {\n" %
4728 (func.return_type, func.name,
4729 func.MakeTypedOriginalArgString("")))
4730 result_string = "return "
4731 if func.return_type == "void":
4732 result_string = ""
4733 file.Write(" %sgles2::GetGLContext()->%s(%s);\n" %
4734 (result_string, func.original_name,
4735 func.MakeOriginalArgString("")))
4736 file.Write("}\n")
4738 def WriteGLES2Header(self, func, file):
4739 """Writes a re-write macro for GLES"""
4740 file.Write("#define gl%s GLES2_GET_FUN(%s)\n" %(func.name, func.name))
4742 def WriteClientGLCallLog(self, func, file):
4743 """Writes a logging macro for the client side code."""
4744 comma = ""
4745 if len(func.GetOriginalArgs()):
4746 comma = " << "
4747 file.Write(
4748 ' GPU_CLIENT_LOG("[" << GetLogPrefix() << "] gl%s("%s%s << ")");\n' %
4749 (func.original_name, comma, func.MakeLogArgString()))
4751 def WriteClientGLReturnLog(self, func, file):
4752 """Writes the return value logging code."""
4753 if func.return_type != "void":
4754 file.Write(' GPU_CLIENT_LOG("return:" << result)\n')
4756 def WriteGLES2ImplementationHeader(self, func, file):
4757 """Writes the GLES2 Implemention."""
4758 self.WriteGLES2ImplementationDeclaration(func, file)
4760 def WriteGLES2TraceImplementationHeader(self, func, file):
4761 """Writes the GLES2 Trace Implemention header."""
4762 file.Write("%s %s(%s) override;\n" %
4763 (func.return_type, func.original_name,
4764 func.MakeTypedOriginalArgString("")))
4766 def WriteGLES2TraceImplementation(self, func, file):
4767 """Writes the GLES2 Trace Implemention."""
4768 file.Write("%s GLES2TraceImplementation::%s(%s) {\n" %
4769 (func.return_type, func.original_name,
4770 func.MakeTypedOriginalArgString("")))
4771 result_string = "return "
4772 if func.return_type == "void":
4773 result_string = ""
4774 file.Write(' TRACE_EVENT_BINARY_EFFICIENT0("gpu", "GLES2Trace::%s");\n' %
4775 func.name)
4776 file.Write(" %sgl_->%s(%s);\n" %
4777 (result_string, func.name, func.MakeOriginalArgString("")))
4778 file.Write("}\n")
4779 file.Write("\n")
4781 def WriteGLES2Implementation(self, func, file):
4782 """Writes the GLES2 Implemention."""
4783 impl_func = func.GetInfo('impl_func')
4784 impl_decl = func.GetInfo('impl_decl')
4785 gen_cmd = func.GetInfo('gen_cmd')
4786 if (func.can_auto_generate and
4787 (impl_func == None or impl_func == True) and
4788 (impl_decl == None or impl_decl == True) and
4789 (gen_cmd == None or gen_cmd == True)):
4790 file.Write("%s GLES2Implementation::%s(%s) {\n" %
4791 (func.return_type, func.original_name,
4792 func.MakeTypedOriginalArgString("")))
4793 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
4794 self.WriteClientGLCallLog(func, file)
4795 func.WriteDestinationInitalizationValidation(file)
4796 for arg in func.GetOriginalArgs():
4797 arg.WriteClientSideValidationCode(file, func)
4798 file.Write(" helper_->%s(%s);\n" %
4799 (func.name, func.MakeHelperArgString("")))
4800 file.Write(" CheckGLError();\n")
4801 self.WriteClientGLReturnLog(func, file)
4802 file.Write("}\n")
4803 file.Write("\n")
4805 def WriteGLES2InterfaceHeader(self, func, file):
4806 """Writes the GLES2 Interface."""
4807 file.Write("virtual %s %s(%s) = 0;\n" %
4808 (func.return_type, func.original_name,
4809 func.MakeTypedOriginalArgString("")))
4811 def WriteMojoGLES2ImplHeader(self, func, file):
4812 """Writes the Mojo GLES2 implementation header."""
4813 file.Write("%s %s(%s) override;\n" %
4814 (func.return_type, func.original_name,
4815 func.MakeTypedOriginalArgString("")))
4817 def WriteMojoGLES2Impl(self, func, file):
4818 """Writes the Mojo GLES2 implementation."""
4819 file.Write("%s MojoGLES2Impl::%s(%s) {\n" %
4820 (func.return_type, func.original_name,
4821 func.MakeTypedOriginalArgString("")))
4822 extensions = ["CHROMIUM_sync_point", "CHROMIUM_texture_mailbox",
4823 "CHROMIUM_sub_image", "CHROMIUM_miscellaneous",
4824 "occlusion_query_EXT", "CHROMIUM_image",
4825 "CHROMIUM_copy_texture",
4826 "CHROMIUM_pixel_transfer_buffer_object"]
4827 if func.IsCoreGLFunction() or func.GetInfo("extension") in extensions:
4828 file.Write("MojoGLES2MakeCurrent(context_);");
4829 func_return = "gl" + func.original_name + "(" + \
4830 func.MakeOriginalArgString("") + ");"
4831 if func.return_type == "void":
4832 file.Write(func_return);
4833 else:
4834 file.Write("return " + func_return);
4835 else:
4836 file.Write("NOTREACHED() << \"Unimplemented %s.\";\n" %
4837 func.original_name);
4838 if func.return_type != "void":
4839 file.Write("return 0;")
4840 file.Write("}")
4842 def WriteGLES2InterfaceStub(self, func, file):
4843 """Writes the GLES2 Interface stub declaration."""
4844 file.Write("%s %s(%s) override;\n" %
4845 (func.return_type, func.original_name,
4846 func.MakeTypedOriginalArgString("")))
4848 def WriteGLES2InterfaceStubImpl(self, func, file):
4849 """Writes the GLES2 Interface stub declaration."""
4850 args = func.GetOriginalArgs()
4851 arg_string = ", ".join(
4852 ["%s /* %s */" % (arg.type, arg.name) for arg in args])
4853 file.Write("%s GLES2InterfaceStub::%s(%s) {\n" %
4854 (func.return_type, func.original_name, arg_string))
4855 if func.return_type != "void":
4856 file.Write(" return 0;\n")
4857 file.Write("}\n")
4859 def WriteGLES2ImplementationUnitTest(self, func, file):
4860 """Writes the GLES2 Implemention unit test."""
4861 client_test = func.GetInfo('client_test')
4862 if (func.can_auto_generate and
4863 (client_test == None or client_test == True)):
4864 code = """
4865 TEST_F(GLES2ImplementationTest, %(name)s) {
4866 struct Cmds {
4867 cmds::%(name)s cmd;
4869 Cmds expected;
4870 expected.cmd.Init(%(cmd_args)s);
4872 gl_->%(name)s(%(args)s);
4873 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
4876 cmd_arg_strings = [
4877 arg.GetValidClientSideCmdArg(func) for arg in func.GetCmdArgs()
4880 gl_arg_strings = [
4881 arg.GetValidClientSideArg(func) for arg in func.GetOriginalArgs()
4884 file.Write(code % {
4885 'name': func.name,
4886 'args': ", ".join(gl_arg_strings),
4887 'cmd_args': ", ".join(cmd_arg_strings),
4890 # Test constants for invalid values, as they are not tested by the
4891 # service.
4892 constants = [arg for arg in func.GetOriginalArgs() if arg.IsConstant()]
4893 if constants:
4894 code = """
4895 TEST_F(GLES2ImplementationTest, %(name)sInvalidConstantArg%(invalid_index)d) {
4896 gl_->%(name)s(%(args)s);
4897 EXPECT_TRUE(NoCommandsWritten());
4898 EXPECT_EQ(%(gl_error)s, CheckError());
4901 for invalid_arg in constants:
4902 gl_arg_strings = []
4903 invalid = invalid_arg.GetInvalidArg(func)
4904 for arg in func.GetOriginalArgs():
4905 if arg is invalid_arg:
4906 gl_arg_strings.append(invalid[0])
4907 else:
4908 gl_arg_strings.append(arg.GetValidClientSideArg(func))
4910 file.Write(code % {
4911 'name': func.name,
4912 'invalid_index': func.GetOriginalArgs().index(invalid_arg),
4913 'args': ", ".join(gl_arg_strings),
4914 'gl_error': invalid[2],
4916 else:
4917 if client_test != False:
4918 file.Write("// TODO(zmo): Implement unit test for %s\n" % func.name)
4920 def WriteDestinationInitalizationValidation(self, func, file):
4921 """Writes the client side destintion initialization validation."""
4922 for arg in func.GetOriginalArgs():
4923 arg.WriteDestinationInitalizationValidation(file, func)
4925 def WriteTraceEvent(self, func, file):
4926 file.Write(' TRACE_EVENT0("gpu", "GLES2Implementation::%s");\n' %
4927 func.original_name)
4929 def WriteImmediateCmdComputeSize(self, func, file):
4930 """Writes the size computation code for the immediate version of a cmd."""
4931 file.Write(" static uint32_t ComputeSize(uint32_t size_in_bytes) {\n")
4932 file.Write(" return static_cast<uint32_t>(\n")
4933 file.Write(" sizeof(ValueType) + // NOLINT\n")
4934 file.Write(" RoundSizeToMultipleOfEntries(size_in_bytes));\n")
4935 file.Write(" }\n")
4936 file.Write("\n")
4938 def WriteImmediateCmdSetHeader(self, func, file):
4939 """Writes the SetHeader function for the immediate version of a cmd."""
4940 file.Write(" void SetHeader(uint32_t size_in_bytes) {\n")
4941 file.Write(" header.SetCmdByTotalSize<ValueType>(size_in_bytes);\n")
4942 file.Write(" }\n")
4943 file.Write("\n")
4945 def WriteImmediateCmdInit(self, func, file):
4946 """Writes the Init function for the immediate version of a command."""
4947 raise NotImplementedError(func.name)
4949 def WriteImmediateCmdSet(self, func, file):
4950 """Writes the Set function for the immediate version of a command."""
4951 raise NotImplementedError(func.name)
4953 def WriteCmdHelper(self, func, file):
4954 """Writes the cmd helper definition for a cmd."""
4955 code = """ void %(name)s(%(typed_args)s) {
4956 gles2::cmds::%(name)s* c = GetCmdSpace<gles2::cmds::%(name)s>();
4957 if (c) {
4958 c->Init(%(args)s);
4963 file.Write(code % {
4964 "name": func.name,
4965 "typed_args": func.MakeTypedCmdArgString(""),
4966 "args": func.MakeCmdArgString(""),
4969 def WriteImmediateCmdHelper(self, func, file):
4970 """Writes the cmd helper definition for the immediate version of a cmd."""
4971 code = """ void %(name)s(%(typed_args)s) {
4972 const uint32_t s = 0; // TODO(gman): compute correct size
4973 gles2::cmds::%(name)s* c =
4974 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(s);
4975 if (c) {
4976 c->Init(%(args)s);
4981 file.Write(code % {
4982 "name": func.name,
4983 "typed_args": func.MakeTypedCmdArgString(""),
4984 "args": func.MakeCmdArgString(""),
4988 class StateSetHandler(TypeHandler):
4989 """Handler for commands that simply set state."""
4991 def __init__(self):
4992 TypeHandler.__init__(self)
4994 def WriteHandlerImplementation(self, func, file):
4995 """Overrriden from TypeHandler."""
4996 state_name = func.GetInfo('state')
4997 state = _STATES[state_name]
4998 states = state['states']
4999 args = func.GetOriginalArgs()
5000 for ndx,item in enumerate(states):
5001 code = []
5002 if 'range_checks' in item:
5003 for range_check in item['range_checks']:
5004 code.append("%s %s" % (args[ndx].name, range_check['check']))
5005 if 'nan_check' in item:
5006 # Drivers might generate an INVALID_VALUE error when a value is set
5007 # to NaN. This is allowed behavior under GLES 3.0 section 2.1.1 or
5008 # OpenGL 4.5 section 2.3.4.1 - providing NaN allows undefined results.
5009 # Make this behavior consistent within Chromium, and avoid leaking GL
5010 # errors by generating the error in the command buffer instead of
5011 # letting the GL driver generate it.
5012 code.append("std::isnan(%s)" % args[ndx].name)
5013 if len(code):
5014 file.Write(" if (%s) {\n" % " ||\n ".join(code))
5015 file.Write(
5016 ' LOCAL_SET_GL_ERROR(GL_INVALID_VALUE,'
5017 ' "%s", "%s out of range");\n' %
5018 (func.name, args[ndx].name))
5019 file.Write(" return error::kNoError;\n")
5020 file.Write(" }\n")
5021 code = []
5022 for ndx,item in enumerate(states):
5023 code.append("state_.%s != %s" % (item['name'], args[ndx].name))
5024 file.Write(" if (%s) {\n" % " ||\n ".join(code))
5025 for ndx,item in enumerate(states):
5026 file.Write(" state_.%s = %s;\n" % (item['name'], args[ndx].name))
5027 if 'state_flag' in state:
5028 file.Write(" %s = true;\n" % state['state_flag'])
5029 if not func.GetInfo("no_gl"):
5030 for ndx,item in enumerate(states):
5031 if item.get('cached', False):
5032 file.Write(" state_.%s = %s;\n" %
5033 (CachedStateName(item), args[ndx].name))
5034 file.Write(" %s(%s);\n" %
5035 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
5036 file.Write(" }\n")
5038 def WriteServiceUnitTest(self, func, file, *extras):
5039 """Overrriden from TypeHandler."""
5040 TypeHandler.WriteServiceUnitTest(self, func, file, *extras)
5041 state_name = func.GetInfo('state')
5042 state = _STATES[state_name]
5043 states = state['states']
5044 for ndx,item in enumerate(states):
5045 if 'range_checks' in item:
5046 for check_ndx, range_check in enumerate(item['range_checks']):
5047 valid_test = """
5048 TEST_P(%(test_name)s, %(name)sInvalidValue%(ndx)d_%(check_ndx)d) {
5049 SpecializedSetup<cmds::%(name)s, 0>(false);
5050 cmds::%(name)s cmd;
5051 cmd.Init(%(args)s);
5052 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5053 EXPECT_EQ(GL_INVALID_VALUE, GetGLError());
5056 name = func.name
5057 arg_strings = [
5058 arg.GetValidArg(func) \
5059 for arg in func.GetOriginalArgs() if not arg.IsConstant()
5062 arg_strings[ndx] = range_check['test_value']
5063 vars = {
5064 'name': name,
5065 'ndx': ndx,
5066 'check_ndx': check_ndx,
5067 'args': ", ".join(arg_strings),
5069 for extra in extras:
5070 vars.update(extra)
5071 file.Write(valid_test % vars)
5072 if 'nan_check' in item:
5073 valid_test = """
5074 TEST_P(%(test_name)s, %(name)sNaNValue%(ndx)d) {
5075 SpecializedSetup<cmds::%(name)s, 0>(false);
5076 cmds::%(name)s cmd;
5077 cmd.Init(%(args)s);
5078 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5079 EXPECT_EQ(GL_INVALID_VALUE, GetGLError());
5082 name = func.name
5083 arg_strings = [
5084 arg.GetValidArg(func) \
5085 for arg in func.GetOriginalArgs() if not arg.IsConstant()
5088 arg_strings[ndx] = 'nanf("")'
5089 vars = {
5090 'name': name,
5091 'ndx': ndx,
5092 'args': ", ".join(arg_strings),
5094 for extra in extras:
5095 vars.update(extra)
5096 file.Write(valid_test % vars)
5099 class StateSetRGBAlphaHandler(TypeHandler):
5100 """Handler for commands that simply set state that have rgb/alpha."""
5102 def __init__(self):
5103 TypeHandler.__init__(self)
5105 def WriteHandlerImplementation(self, func, file):
5106 """Overrriden from TypeHandler."""
5107 state_name = func.GetInfo('state')
5108 state = _STATES[state_name]
5109 states = state['states']
5110 args = func.GetOriginalArgs()
5111 num_args = len(args)
5112 code = []
5113 for ndx,item in enumerate(states):
5114 code.append("state_.%s != %s" % (item['name'], args[ndx % num_args].name))
5115 file.Write(" if (%s) {\n" % " ||\n ".join(code))
5116 for ndx, item in enumerate(states):
5117 file.Write(" state_.%s = %s;\n" %
5118 (item['name'], args[ndx % num_args].name))
5119 if 'state_flag' in state:
5120 file.Write(" %s = true;\n" % state['state_flag'])
5121 if not func.GetInfo("no_gl"):
5122 file.Write(" %s(%s);\n" %
5123 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
5124 file.Write(" }\n")
5127 class StateSetFrontBackSeparateHandler(TypeHandler):
5128 """Handler for commands that simply set state that have front/back."""
5130 def __init__(self):
5131 TypeHandler.__init__(self)
5133 def WriteHandlerImplementation(self, func, file):
5134 """Overrriden from TypeHandler."""
5135 state_name = func.GetInfo('state')
5136 state = _STATES[state_name]
5137 states = state['states']
5138 args = func.GetOriginalArgs()
5139 face = args[0].name
5140 num_args = len(args)
5141 file.Write(" bool changed = false;\n")
5142 for group_ndx, group in enumerate(Grouper(num_args - 1, states)):
5143 file.Write(" if (%s == %s || %s == GL_FRONT_AND_BACK) {\n" %
5144 (face, ('GL_FRONT', 'GL_BACK')[group_ndx], face))
5145 code = []
5146 for ndx, item in enumerate(group):
5147 code.append("state_.%s != %s" % (item['name'], args[ndx + 1].name))
5148 file.Write(" changed |= %s;\n" % " ||\n ".join(code))
5149 file.Write(" }\n")
5150 file.Write(" if (changed) {\n")
5151 for group_ndx, group in enumerate(Grouper(num_args - 1, states)):
5152 file.Write(" if (%s == %s || %s == GL_FRONT_AND_BACK) {\n" %
5153 (face, ('GL_FRONT', 'GL_BACK')[group_ndx], face))
5154 for ndx, item in enumerate(group):
5155 file.Write(" state_.%s = %s;\n" %
5156 (item['name'], args[ndx + 1].name))
5157 file.Write(" }\n")
5158 if 'state_flag' in state:
5159 file.Write(" %s = true;\n" % state['state_flag'])
5160 if not func.GetInfo("no_gl"):
5161 file.Write(" %s(%s);\n" %
5162 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
5163 file.Write(" }\n")
5166 class StateSetFrontBackHandler(TypeHandler):
5167 """Handler for commands that simply set state that set both front/back."""
5169 def __init__(self):
5170 TypeHandler.__init__(self)
5172 def WriteHandlerImplementation(self, func, file):
5173 """Overrriden from TypeHandler."""
5174 state_name = func.GetInfo('state')
5175 state = _STATES[state_name]
5176 states = state['states']
5177 args = func.GetOriginalArgs()
5178 num_args = len(args)
5179 code = []
5180 for group_ndx, group in enumerate(Grouper(num_args, states)):
5181 for ndx, item in enumerate(group):
5182 code.append("state_.%s != %s" % (item['name'], args[ndx].name))
5183 file.Write(" if (%s) {\n" % " ||\n ".join(code))
5184 for group_ndx, group in enumerate(Grouper(num_args, states)):
5185 for ndx, item in enumerate(group):
5186 file.Write(" state_.%s = %s;\n" % (item['name'], args[ndx].name))
5187 if 'state_flag' in state:
5188 file.Write(" %s = true;\n" % state['state_flag'])
5189 if not func.GetInfo("no_gl"):
5190 file.Write(" %s(%s);\n" %
5191 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
5192 file.Write(" }\n")
5195 class StateSetNamedParameter(TypeHandler):
5196 """Handler for commands that set a state chosen with an enum parameter."""
5198 def __init__(self):
5199 TypeHandler.__init__(self)
5201 def WriteHandlerImplementation(self, func, file):
5202 """Overridden from TypeHandler."""
5203 state_name = func.GetInfo('state')
5204 state = _STATES[state_name]
5205 states = state['states']
5206 args = func.GetOriginalArgs()
5207 num_args = len(args)
5208 assert num_args == 2
5209 file.Write(" switch (%s) {\n" % args[0].name)
5210 for state in states:
5211 file.Write(" case %s:\n" % state['enum'])
5212 file.Write(" if (state_.%s != %s) {\n" %
5213 (state['name'], args[1].name))
5214 file.Write(" state_.%s = %s;\n" % (state['name'], args[1].name))
5215 if not func.GetInfo("no_gl"):
5216 file.Write(" %s(%s);\n" %
5217 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
5218 file.Write(" }\n")
5219 file.Write(" break;\n")
5220 file.Write(" default:\n")
5221 file.Write(" NOTREACHED();\n")
5222 file.Write(" }\n")
5225 class CustomHandler(TypeHandler):
5226 """Handler for commands that are auto-generated but require minor tweaks."""
5228 def __init__(self):
5229 TypeHandler.__init__(self)
5231 def WriteServiceImplementation(self, func, file):
5232 """Overrriden from TypeHandler."""
5233 pass
5235 def WriteImmediateServiceImplementation(self, func, file):
5236 """Overrriden from TypeHandler."""
5237 pass
5239 def WriteBucketServiceImplementation(self, func, file):
5240 """Overrriden from TypeHandler."""
5241 pass
5243 def WriteServiceUnitTest(self, func, file, *extras):
5244 """Overrriden from TypeHandler."""
5245 file.Write("// TODO(gman): %s\n\n" % func.name)
5247 def WriteImmediateServiceUnitTest(self, func, file, *extras):
5248 """Overrriden from TypeHandler."""
5249 file.Write("// TODO(gman): %s\n\n" % func.name)
5251 def WriteImmediateCmdGetTotalSize(self, func, file):
5252 """Overrriden from TypeHandler."""
5253 file.Write(
5254 " uint32_t total_size = 0; // TODO(gman): get correct size.\n")
5256 def WriteImmediateCmdInit(self, func, file):
5257 """Overrriden from TypeHandler."""
5258 file.Write(" void Init(%s) {\n" % func.MakeTypedCmdArgString("_"))
5259 self.WriteImmediateCmdGetTotalSize(func, file)
5260 file.Write(" SetHeader(total_size);\n")
5261 args = func.GetCmdArgs()
5262 for arg in args:
5263 file.Write(" %s = _%s;\n" % (arg.name, arg.name))
5264 file.Write(" }\n")
5265 file.Write("\n")
5267 def WriteImmediateCmdSet(self, func, file):
5268 """Overrriden from TypeHandler."""
5269 copy_args = func.MakeCmdArgString("_", False)
5270 file.Write(" void* Set(void* cmd%s) {\n" %
5271 func.MakeTypedCmdArgString("_", True))
5272 self.WriteImmediateCmdGetTotalSize(func, file)
5273 file.Write(" static_cast<ValueType*>(cmd)->Init(%s);\n" % copy_args)
5274 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
5275 "cmd, total_size);\n")
5276 file.Write(" }\n")
5277 file.Write("\n")
5280 class TodoHandler(CustomHandler):
5281 """Handle for commands that are not yet implemented."""
5283 def NeedsDataTransferFunction(self, func):
5284 """Overriden from TypeHandler."""
5285 return False
5287 def WriteImmediateFormatTest(self, func, file):
5288 """Overrriden from TypeHandler."""
5289 pass
5291 def WriteGLES2ImplementationUnitTest(self, func, file):
5292 """Overrriden from TypeHandler."""
5293 pass
5295 def WriteGLES2Implementation(self, func, file):
5296 """Overrriden from TypeHandler."""
5297 file.Write("%s GLES2Implementation::%s(%s) {\n" %
5298 (func.return_type, func.original_name,
5299 func.MakeTypedOriginalArgString("")))
5300 file.Write(" // TODO: for now this is a no-op\n")
5301 file.Write(
5302 " SetGLError("
5303 "GL_INVALID_OPERATION, \"gl%s\", \"not implemented\");\n" %
5304 func.name)
5305 if func.return_type != "void":
5306 file.Write(" return 0;\n")
5307 file.Write("}\n")
5308 file.Write("\n")
5310 def WriteServiceImplementation(self, func, file):
5311 """Overrriden from TypeHandler."""
5312 self.WriteServiceHandlerFunctionHeader(func, file)
5313 file.Write(" // TODO: for now this is a no-op\n")
5314 file.Write(
5315 " LOCAL_SET_GL_ERROR("
5316 "GL_INVALID_OPERATION, \"gl%s\", \"not implemented\");\n" %
5317 func.name)
5318 file.Write(" return error::kNoError;\n")
5319 file.Write("}\n")
5320 file.Write("\n")
5323 class HandWrittenHandler(CustomHandler):
5324 """Handler for comands where everything must be written by hand."""
5326 def InitFunction(self, func):
5327 """Add or adjust anything type specific for this function."""
5328 CustomHandler.InitFunction(self, func)
5329 func.can_auto_generate = False
5331 def NeedsDataTransferFunction(self, func):
5332 """Overriden from TypeHandler."""
5333 # If specified explicitly, force the data transfer method.
5334 if func.GetInfo('data_transfer_methods'):
5335 return True
5336 return False
5338 def WriteStruct(self, func, file):
5339 """Overrriden from TypeHandler."""
5340 pass
5342 def WriteDocs(self, func, file):
5343 """Overrriden from TypeHandler."""
5344 pass
5346 def WriteServiceUnitTest(self, func, file, *extras):
5347 """Overrriden from TypeHandler."""
5348 file.Write("// TODO(gman): %s\n\n" % func.name)
5350 def WriteImmediateServiceUnitTest(self, func, file, *extras):
5351 """Overrriden from TypeHandler."""
5352 file.Write("// TODO(gman): %s\n\n" % func.name)
5354 def WriteBucketServiceUnitTest(self, func, file, *extras):
5355 """Overrriden from TypeHandler."""
5356 file.Write("// TODO(gman): %s\n\n" % func.name)
5358 def WriteServiceImplementation(self, func, file):
5359 """Overrriden from TypeHandler."""
5360 pass
5362 def WriteImmediateServiceImplementation(self, func, file):
5363 """Overrriden from TypeHandler."""
5364 pass
5366 def WriteBucketServiceImplementation(self, func, file):
5367 """Overrriden from TypeHandler."""
5368 pass
5370 def WriteImmediateCmdHelper(self, func, file):
5371 """Overrriden from TypeHandler."""
5372 pass
5374 def WriteCmdHelper(self, func, file):
5375 """Overrriden from TypeHandler."""
5376 pass
5378 def WriteFormatTest(self, func, file):
5379 """Overrriden from TypeHandler."""
5380 file.Write("// TODO(gman): Write test for %s\n" % func.name)
5382 def WriteImmediateFormatTest(self, func, file):
5383 """Overrriden from TypeHandler."""
5384 file.Write("// TODO(gman): Write test for %s\n" % func.name)
5386 def WriteBucketFormatTest(self, func, file):
5387 """Overrriden from TypeHandler."""
5388 file.Write("// TODO(gman): Write test for %s\n" % func.name)
5392 class ManualHandler(CustomHandler):
5393 """Handler for commands who's handlers must be written by hand."""
5395 def __init__(self):
5396 CustomHandler.__init__(self)
5398 def InitFunction(self, func):
5399 """Overrriden from TypeHandler."""
5400 if (func.name == 'CompressedTexImage2DBucket' or
5401 func.name == 'CompressedTexImage3DBucket'):
5402 func.cmd_args = func.cmd_args[:-1]
5403 func.AddCmdArg(Argument('bucket_id', 'GLuint'))
5404 else:
5405 CustomHandler.InitFunction(self, func)
5407 def WriteServiceImplementation(self, func, file):
5408 """Overrriden from TypeHandler."""
5409 pass
5411 def WriteBucketServiceImplementation(self, func, file):
5412 """Overrriden from TypeHandler."""
5413 pass
5415 def WriteServiceUnitTest(self, func, file, *extras):
5416 """Overrriden from TypeHandler."""
5417 file.Write("// TODO(gman): %s\n\n" % func.name)
5419 def WriteImmediateServiceUnitTest(self, func, file, *extras):
5420 """Overrriden from TypeHandler."""
5421 file.Write("// TODO(gman): %s\n\n" % func.name)
5423 def WriteImmediateServiceImplementation(self, func, file):
5424 """Overrriden from TypeHandler."""
5425 pass
5427 def WriteImmediateFormatTest(self, func, file):
5428 """Overrriden from TypeHandler."""
5429 file.Write("// TODO(gman): Implement test for %s\n" % func.name)
5431 def WriteGLES2Implementation(self, func, file):
5432 """Overrriden from TypeHandler."""
5433 if func.GetInfo('impl_func'):
5434 super(ManualHandler, self).WriteGLES2Implementation(func, file)
5436 def WriteGLES2ImplementationHeader(self, func, file):
5437 """Overrriden from TypeHandler."""
5438 file.Write("%s %s(%s) override;\n" %
5439 (func.return_type, func.original_name,
5440 func.MakeTypedOriginalArgString("")))
5441 file.Write("\n")
5443 def WriteImmediateCmdGetTotalSize(self, func, file):
5444 """Overrriden from TypeHandler."""
5445 # TODO(gman): Move this data to _FUNCTION_INFO?
5446 CustomHandler.WriteImmediateCmdGetTotalSize(self, func, file)
5449 class DataHandler(TypeHandler):
5450 """Handler for glBufferData, glBufferSubData, glTexImage*D, glTexSubImage*D,
5451 glCompressedTexImage*D, glCompressedTexImageSub*D."""
5452 def __init__(self):
5453 TypeHandler.__init__(self)
5455 def InitFunction(self, func):
5456 """Overrriden from TypeHandler."""
5457 if (func.name == 'CompressedTexSubImage2DBucket' or
5458 func.name == 'CompressedTexSubImage3DBucket'):
5459 func.cmd_args = func.cmd_args[:-1]
5460 func.AddCmdArg(Argument('bucket_id', 'GLuint'))
5462 def WriteGetDataSizeCode(self, func, file):
5463 """Overrriden from TypeHandler."""
5464 # TODO(gman): Move this data to _FUNCTION_INFO?
5465 name = func.name
5466 if name.endswith("Immediate"):
5467 name = name[0:-9]
5468 if name == 'BufferData' or name == 'BufferSubData':
5469 file.Write(" uint32_t data_size = size;\n")
5470 elif (name == 'CompressedTexImage2D' or
5471 name == 'CompressedTexSubImage2D' or
5472 name == 'CompressedTexImage3D' or
5473 name == 'CompressedTexSubImage3D'):
5474 file.Write(" uint32_t data_size = imageSize;\n")
5475 elif (name == 'CompressedTexSubImage2DBucket' or
5476 name == 'CompressedTexSubImage3DBucket'):
5477 file.Write(" Bucket* bucket = GetBucket(c.bucket_id);\n")
5478 file.Write(" uint32_t data_size = bucket->size();\n")
5479 file.Write(" GLsizei imageSize = data_size;\n")
5480 elif name == 'TexImage2D' or name == 'TexSubImage2D':
5481 code = """ uint32_t data_size;
5482 if (!GLES2Util::ComputeImageDataSize(
5483 width, height, format, type, unpack_alignment_, &data_size)) {
5484 return error::kOutOfBounds;
5487 file.Write(code)
5488 else:
5489 file.Write(
5490 "// uint32_t data_size = 0; // TODO(gman): get correct size!\n")
5492 def WriteImmediateCmdGetTotalSize(self, func, file):
5493 """Overrriden from TypeHandler."""
5494 pass
5496 def WriteImmediateCmdSizeTest(self, func, file):
5497 """Overrriden from TypeHandler."""
5498 file.Write(" EXPECT_EQ(sizeof(cmd), total_size);\n")
5500 def WriteImmediateCmdInit(self, func, file):
5501 """Overrriden from TypeHandler."""
5502 file.Write(" void Init(%s) {\n" % func.MakeTypedCmdArgString("_"))
5503 self.WriteImmediateCmdGetTotalSize(func, file)
5504 file.Write(" SetHeader(total_size);\n")
5505 args = func.GetCmdArgs()
5506 for arg in args:
5507 file.Write(" %s = _%s;\n" % (arg.name, arg.name))
5508 file.Write(" }\n")
5509 file.Write("\n")
5511 def WriteImmediateCmdSet(self, func, file):
5512 """Overrriden from TypeHandler."""
5513 copy_args = func.MakeCmdArgString("_", False)
5514 file.Write(" void* Set(void* cmd%s) {\n" %
5515 func.MakeTypedCmdArgString("_", True))
5516 self.WriteImmediateCmdGetTotalSize(func, file)
5517 file.Write(" static_cast<ValueType*>(cmd)->Init(%s);\n" % copy_args)
5518 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
5519 "cmd, total_size);\n")
5520 file.Write(" }\n")
5521 file.Write("\n")
5523 def WriteImmediateFormatTest(self, func, file):
5524 """Overrriden from TypeHandler."""
5525 # TODO(gman): Remove this exception.
5526 file.Write("// TODO(gman): Implement test for %s\n" % func.name)
5527 return
5529 def WriteServiceUnitTest(self, func, file, *extras):
5530 """Overrriden from TypeHandler."""
5531 file.Write("// TODO(gman): %s\n\n" % func.name)
5533 def WriteImmediateServiceUnitTest(self, func, file, *extras):
5534 """Overrriden from TypeHandler."""
5535 file.Write("// TODO(gman): %s\n\n" % func.name)
5537 def WriteBucketServiceImplementation(self, func, file):
5538 """Overrriden from TypeHandler."""
5539 if ((not func.name == 'CompressedTexSubImage2DBucket') and
5540 (not func.name == 'CompressedTexSubImage3DBucket')):
5541 TypeHandler.WriteBucketServiceImplemenation(self, func, file)
5544 class BindHandler(TypeHandler):
5545 """Handler for glBind___ type functions."""
5547 def __init__(self):
5548 TypeHandler.__init__(self)
5550 def WriteServiceUnitTest(self, func, file, *extras):
5551 """Overrriden from TypeHandler."""
5553 if len(func.GetOriginalArgs()) == 1:
5554 valid_test = """
5555 TEST_P(%(test_name)s, %(name)sValidArgs) {
5556 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
5557 SpecializedSetup<cmds::%(name)s, 0>(true);
5558 cmds::%(name)s cmd;
5559 cmd.Init(%(args)s);"""
5560 if func.IsUnsafe():
5561 valid_test += """
5562 decoder_->set_unsafe_es3_apis_enabled(true);
5563 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5564 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5565 decoder_->set_unsafe_es3_apis_enabled(false);
5566 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));
5569 else:
5570 valid_test += """
5571 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5572 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5575 if func.GetInfo("gen_func"):
5576 valid_test += """
5577 TEST_P(%(test_name)s, %(name)sValidArgsNewId) {
5578 EXPECT_CALL(*gl_, %(gl_func_name)s(kNewServiceId));
5579 EXPECT_CALL(*gl_, %(gl_gen_func_name)s(1, _))
5580 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
5581 SpecializedSetup<cmds::%(name)s, 0>(true);
5582 cmds::%(name)s cmd;
5583 cmd.Init(kNewClientId);
5584 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5585 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5586 EXPECT_TRUE(Get%(resource_type)s(kNewClientId) != NULL);
5589 self.WriteValidUnitTest(func, file, valid_test, {
5590 'resource_type': func.GetOriginalArgs()[0].resource_type,
5591 'gl_gen_func_name': func.GetInfo("gen_func"),
5592 }, *extras)
5593 else:
5594 valid_test = """
5595 TEST_P(%(test_name)s, %(name)sValidArgs) {
5596 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
5597 SpecializedSetup<cmds::%(name)s, 0>(true);
5598 cmds::%(name)s cmd;
5599 cmd.Init(%(args)s);"""
5600 if func.IsUnsafe():
5601 valid_test += """
5602 decoder_->set_unsafe_es3_apis_enabled(true);
5603 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5604 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5605 decoder_->set_unsafe_es3_apis_enabled(false);
5606 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));
5609 else:
5610 valid_test += """
5611 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5612 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5615 if func.GetInfo("gen_func"):
5616 valid_test += """
5617 TEST_P(%(test_name)s, %(name)sValidArgsNewId) {
5618 EXPECT_CALL(*gl_,
5619 %(gl_func_name)s(%(gl_args_with_new_id)s));
5620 EXPECT_CALL(*gl_, %(gl_gen_func_name)s(1, _))
5621 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
5622 SpecializedSetup<cmds::%(name)s, 0>(true);
5623 cmds::%(name)s cmd;
5624 cmd.Init(%(args_with_new_id)s);"""
5625 if func.IsUnsafe():
5626 valid_test += """
5627 decoder_->set_unsafe_es3_apis_enabled(true);
5628 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5629 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5630 EXPECT_TRUE(Get%(resource_type)s(kNewClientId) != NULL);
5631 decoder_->set_unsafe_es3_apis_enabled(false);
5632 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));
5635 else:
5636 valid_test += """
5637 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5638 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5639 EXPECT_TRUE(Get%(resource_type)s(kNewClientId) != NULL);
5643 gl_args_with_new_id = []
5644 args_with_new_id = []
5645 for arg in func.GetOriginalArgs():
5646 if hasattr(arg, 'resource_type'):
5647 gl_args_with_new_id.append('kNewServiceId')
5648 args_with_new_id.append('kNewClientId')
5649 else:
5650 gl_args_with_new_id.append(arg.GetValidGLArg(func))
5651 args_with_new_id.append(arg.GetValidArg(func))
5652 self.WriteValidUnitTest(func, file, valid_test, {
5653 'args_with_new_id': ", ".join(args_with_new_id),
5654 'gl_args_with_new_id': ", ".join(gl_args_with_new_id),
5655 'resource_type': func.GetResourceIdArg().resource_type,
5656 'gl_gen_func_name': func.GetInfo("gen_func"),
5657 }, *extras)
5659 invalid_test = """
5660 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
5661 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
5662 SpecializedSetup<cmds::%(name)s, 0>(false);
5663 cmds::%(name)s cmd;
5664 cmd.Init(%(args)s);
5665 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
5668 self.WriteInvalidUnitTest(func, file, invalid_test, *extras)
5670 def WriteGLES2Implementation(self, func, file):
5671 """Writes the GLES2 Implemention."""
5673 impl_func = func.GetInfo('impl_func')
5674 impl_decl = func.GetInfo('impl_decl')
5676 if (func.can_auto_generate and
5677 (impl_func == None or impl_func == True) and
5678 (impl_decl == None or impl_decl == True)):
5680 file.Write("%s GLES2Implementation::%s(%s) {\n" %
5681 (func.return_type, func.original_name,
5682 func.MakeTypedOriginalArgString("")))
5683 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
5684 func.WriteDestinationInitalizationValidation(file)
5685 self.WriteClientGLCallLog(func, file)
5686 for arg in func.GetOriginalArgs():
5687 arg.WriteClientSideValidationCode(file, func)
5689 code = """ if (Is%(type)sReservedId(%(id)s)) {
5690 SetGLError(GL_INVALID_OPERATION, "%(name)s\", \"%(id)s reserved id");
5691 return;
5693 %(name)sHelper(%(arg_string)s);
5694 CheckGLError();
5698 name_arg = func.GetResourceIdArg()
5699 file.Write(code % {
5700 'name': func.name,
5701 'arg_string': func.MakeOriginalArgString(""),
5702 'id': name_arg.name,
5703 'type': name_arg.resource_type,
5704 'lc_type': name_arg.resource_type.lower(),
5707 def WriteGLES2ImplementationUnitTest(self, func, file):
5708 """Overrriden from TypeHandler."""
5709 client_test = func.GetInfo('client_test')
5710 if client_test == False:
5711 return
5712 code = """
5713 TEST_F(GLES2ImplementationTest, %(name)s) {
5714 struct Cmds {
5715 cmds::%(name)s cmd;
5717 Cmds expected;
5718 expected.cmd.Init(%(cmd_args)s);
5720 gl_->%(name)s(%(args)s);
5721 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));"""
5722 if not func.IsUnsafe():
5723 code += """
5724 ClearCommands();
5725 gl_->%(name)s(%(args)s);
5726 EXPECT_TRUE(NoCommandsWritten());"""
5727 code += """
5730 cmd_arg_strings = [
5731 arg.GetValidClientSideCmdArg(func) for arg in func.GetCmdArgs()
5733 gl_arg_strings = [
5734 arg.GetValidClientSideArg(func) for arg in func.GetOriginalArgs()
5737 file.Write(code % {
5738 'name': func.name,
5739 'args': ", ".join(gl_arg_strings),
5740 'cmd_args': ", ".join(cmd_arg_strings),
5744 class GENnHandler(TypeHandler):
5745 """Handler for glGen___ type functions."""
5747 def __init__(self):
5748 TypeHandler.__init__(self)
5750 def InitFunction(self, func):
5751 """Overrriden from TypeHandler."""
5752 pass
5754 def WriteGetDataSizeCode(self, func, file):
5755 """Overrriden from TypeHandler."""
5756 code = """ uint32_t data_size;
5757 if (!SafeMultiplyUint32(n, sizeof(GLuint), &data_size)) {
5758 return error::kOutOfBounds;
5761 file.Write(code)
5763 def WriteHandlerImplementation (self, func, file):
5764 """Overrriden from TypeHandler."""
5765 file.Write(" if (!%sHelper(n, %s)) {\n"
5766 " return error::kInvalidArguments;\n"
5767 " }\n" %
5768 (func.name, func.GetLastOriginalArg().name))
5770 def WriteImmediateHandlerImplementation(self, func, file):
5771 """Overrriden from TypeHandler."""
5772 if func.IsUnsafe():
5773 file.Write(""" for (GLsizei ii = 0; ii < n; ++ii) {
5774 if (group_->Get%(resource_name)sServiceId(%(last_arg_name)s[ii], NULL)) {
5775 return error::kInvalidArguments;
5778 scoped_ptr<GLuint[]> service_ids(new GLuint[n]);
5779 gl%(func_name)s(n, service_ids.get());
5780 for (GLsizei ii = 0; ii < n; ++ii) {
5781 group_->Add%(resource_name)sId(%(last_arg_name)s[ii], service_ids[ii]);
5783 """ % { 'func_name': func.original_name,
5784 'last_arg_name': func.GetLastOriginalArg().name,
5785 'resource_name': func.GetInfo('resource_type') })
5786 else:
5787 file.Write(" if (!%sHelper(n, %s)) {\n"
5788 " return error::kInvalidArguments;\n"
5789 " }\n" %
5790 (func.original_name, func.GetLastOriginalArg().name))
5792 def WriteGLES2Implementation(self, func, file):
5793 """Overrriden from TypeHandler."""
5794 log_code = (""" GPU_CLIENT_LOG_CODE_BLOCK({
5795 for (GLsizei i = 0; i < n; ++i) {
5796 GPU_CLIENT_LOG(" " << i << ": " << %s[i]);
5798 });""" % func.GetOriginalArgs()[1].name)
5799 args = {
5800 'log_code': log_code,
5801 'return_type': func.return_type,
5802 'name': func.original_name,
5803 'typed_args': func.MakeTypedOriginalArgString(""),
5804 'args': func.MakeOriginalArgString(""),
5805 'resource_types': func.GetInfo('resource_types'),
5806 'count_name': func.GetOriginalArgs()[0].name,
5808 file.Write(
5809 "%(return_type)s GLES2Implementation::%(name)s(%(typed_args)s) {\n" %
5810 args)
5811 func.WriteDestinationInitalizationValidation(file)
5812 self.WriteClientGLCallLog(func, file)
5813 for arg in func.GetOriginalArgs():
5814 arg.WriteClientSideValidationCode(file, func)
5815 not_shared = func.GetInfo('not_shared')
5816 if not_shared:
5817 alloc_code = (
5819 """ IdAllocator* id_allocator = GetIdAllocator(id_namespaces::k%s);
5820 for (GLsizei ii = 0; ii < n; ++ii)
5821 %s[ii] = id_allocator->AllocateID();""" %
5822 (func.GetInfo('resource_types'), func.GetOriginalArgs()[1].name))
5823 else:
5824 alloc_code = (""" GetIdHandler(id_namespaces::k%(resource_types)s)->
5825 MakeIds(this, 0, %(args)s);""" % args)
5826 args['alloc_code'] = alloc_code
5828 code = """ GPU_CLIENT_SINGLE_THREAD_CHECK();
5829 %(alloc_code)s
5830 %(name)sHelper(%(args)s);
5831 helper_->%(name)sImmediate(%(args)s);
5832 if (share_group_->bind_generates_resource())
5833 helper_->CommandBufferHelper::Flush();
5834 %(log_code)s
5835 CheckGLError();
5839 file.Write(code % args)
5841 def WriteGLES2ImplementationUnitTest(self, func, file):
5842 """Overrriden from TypeHandler."""
5843 code = """
5844 TEST_F(GLES2ImplementationTest, %(name)s) {
5845 GLuint ids[2] = { 0, };
5846 struct Cmds {
5847 cmds::%(name)sImmediate gen;
5848 GLuint data[2];
5850 Cmds expected;
5851 expected.gen.Init(arraysize(ids), &ids[0]);
5852 expected.data[0] = k%(types)sStartId;
5853 expected.data[1] = k%(types)sStartId + 1;
5854 gl_->%(name)s(arraysize(ids), &ids[0]);
5855 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
5856 EXPECT_EQ(k%(types)sStartId, ids[0]);
5857 EXPECT_EQ(k%(types)sStartId + 1, ids[1]);
5860 file.Write(code % {
5861 'name': func.name,
5862 'types': func.GetInfo('resource_types'),
5865 def WriteServiceUnitTest(self, func, file, *extras):
5866 """Overrriden from TypeHandler."""
5867 valid_test = """
5868 TEST_P(%(test_name)s, %(name)sValidArgs) {
5869 EXPECT_CALL(*gl_, %(gl_func_name)s(1, _))
5870 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
5871 GetSharedMemoryAs<GLuint*>()[0] = kNewClientId;
5872 SpecializedSetup<cmds::%(name)s, 0>(true);
5873 cmds::%(name)s cmd;
5874 cmd.Init(%(args)s);
5875 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5876 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
5877 if func.IsUnsafe():
5878 valid_test += """
5879 GLuint service_id;
5880 EXPECT_TRUE(Get%(resource_name)sServiceId(kNewClientId, &service_id));
5881 EXPECT_EQ(kNewServiceId, service_id)
5884 else:
5885 valid_test += """
5886 EXPECT_TRUE(Get%(resource_name)s(kNewClientId, &service_id) != NULL);
5889 self.WriteValidUnitTest(func, file, valid_test, {
5890 'resource_name': func.GetInfo('resource_type'),
5891 }, *extras)
5892 invalid_test = """
5893 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
5894 EXPECT_CALL(*gl_, %(gl_func_name)s(_, _)).Times(0);
5895 GetSharedMemoryAs<GLuint*>()[0] = client_%(resource_name)s_id_;
5896 SpecializedSetup<cmds::%(name)s, 0>(false);
5897 cmds::%(name)s cmd;
5898 cmd.Init(%(args)s);
5899 EXPECT_EQ(error::kInvalidArguments, ExecuteCmd(cmd));
5902 self.WriteValidUnitTest(func, file, invalid_test, {
5903 'resource_name': func.GetInfo('resource_type').lower(),
5904 }, *extras)
5906 def WriteImmediateServiceUnitTest(self, func, file, *extras):
5907 """Overrriden from TypeHandler."""
5908 valid_test = """
5909 TEST_P(%(test_name)s, %(name)sValidArgs) {
5910 EXPECT_CALL(*gl_, %(gl_func_name)s(1, _))
5911 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
5912 cmds::%(name)s* cmd = GetImmediateAs<cmds::%(name)s>();
5913 GLuint temp = kNewClientId;
5914 SpecializedSetup<cmds::%(name)s, 0>(true);"""
5915 if func.IsUnsafe():
5916 valid_test += """
5917 decoder_->set_unsafe_es3_apis_enabled(true);"""
5918 valid_test += """
5919 cmd->Init(1, &temp);
5920 EXPECT_EQ(error::kNoError,
5921 ExecuteImmediateCmd(*cmd, sizeof(temp)));
5922 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
5923 if func.IsUnsafe():
5924 valid_test += """
5925 GLuint service_id;
5926 EXPECT_TRUE(Get%(resource_name)sServiceId(kNewClientId, &service_id));
5927 EXPECT_EQ(kNewServiceId, service_id);
5928 decoder_->set_unsafe_es3_apis_enabled(false);
5929 EXPECT_EQ(error::kUnknownCommand,
5930 ExecuteImmediateCmd(*cmd, sizeof(temp)));
5933 else:
5934 valid_test += """
5935 EXPECT_TRUE(Get%(resource_name)s(kNewClientId) != NULL);
5938 self.WriteValidUnitTest(func, file, valid_test, {
5939 'resource_name': func.GetInfo('resource_type'),
5940 }, *extras)
5941 invalid_test = """
5942 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
5943 EXPECT_CALL(*gl_, %(gl_func_name)s(_, _)).Times(0);
5944 cmds::%(name)s* cmd = GetImmediateAs<cmds::%(name)s>();
5945 SpecializedSetup<cmds::%(name)s, 0>(false);
5946 cmd->Init(1, &client_%(resource_name)s_id_);"""
5947 if func.IsUnsafe():
5948 invalid_test += """
5949 decoder_->set_unsafe_es3_apis_enabled(true);
5950 EXPECT_EQ(error::kInvalidArguments,
5951 ExecuteImmediateCmd(*cmd, sizeof(&client_%(resource_name)s_id_)));
5952 decoder_->set_unsafe_es3_apis_enabled(false);
5955 else:
5956 invalid_test += """
5957 EXPECT_EQ(error::kInvalidArguments,
5958 ExecuteImmediateCmd(*cmd, sizeof(&client_%(resource_name)s_id_)));
5961 self.WriteValidUnitTest(func, file, invalid_test, {
5962 'resource_name': func.GetInfo('resource_type').lower(),
5963 }, *extras)
5965 def WriteImmediateCmdComputeSize(self, func, file):
5966 """Overrriden from TypeHandler."""
5967 file.Write(" static uint32_t ComputeDataSize(GLsizei n) {\n")
5968 file.Write(
5969 " return static_cast<uint32_t>(sizeof(GLuint) * n); // NOLINT\n")
5970 file.Write(" }\n")
5971 file.Write("\n")
5972 file.Write(" static uint32_t ComputeSize(GLsizei n) {\n")
5973 file.Write(" return static_cast<uint32_t>(\n")
5974 file.Write(" sizeof(ValueType) + ComputeDataSize(n)); // NOLINT\n")
5975 file.Write(" }\n")
5976 file.Write("\n")
5978 def WriteImmediateCmdSetHeader(self, func, file):
5979 """Overrriden from TypeHandler."""
5980 file.Write(" void SetHeader(GLsizei n) {\n")
5981 file.Write(" header.SetCmdByTotalSize<ValueType>(ComputeSize(n));\n")
5982 file.Write(" }\n")
5983 file.Write("\n")
5985 def WriteImmediateCmdInit(self, func, file):
5986 """Overrriden from TypeHandler."""
5987 last_arg = func.GetLastOriginalArg()
5988 file.Write(" void Init(%s, %s _%s) {\n" %
5989 (func.MakeTypedCmdArgString("_"),
5990 last_arg.type, last_arg.name))
5991 file.Write(" SetHeader(_n);\n")
5992 args = func.GetCmdArgs()
5993 for arg in args:
5994 file.Write(" %s = _%s;\n" % (arg.name, arg.name))
5995 file.Write(" memcpy(ImmediateDataAddress(this),\n")
5996 file.Write(" _%s, ComputeDataSize(_n));\n" % last_arg.name)
5997 file.Write(" }\n")
5998 file.Write("\n")
6000 def WriteImmediateCmdSet(self, func, file):
6001 """Overrriden from TypeHandler."""
6002 last_arg = func.GetLastOriginalArg()
6003 copy_args = func.MakeCmdArgString("_", False)
6004 file.Write(" void* Set(void* cmd%s, %s _%s) {\n" %
6005 (func.MakeTypedCmdArgString("_", True),
6006 last_arg.type, last_arg.name))
6007 file.Write(" static_cast<ValueType*>(cmd)->Init(%s, _%s);\n" %
6008 (copy_args, last_arg.name))
6009 file.Write(" const uint32_t size = ComputeSize(_n);\n")
6010 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
6011 "cmd, size);\n")
6012 file.Write(" }\n")
6013 file.Write("\n")
6015 def WriteImmediateCmdHelper(self, func, file):
6016 """Overrriden from TypeHandler."""
6017 code = """ void %(name)s(%(typed_args)s) {
6018 const uint32_t size = gles2::cmds::%(name)s::ComputeSize(n);
6019 gles2::cmds::%(name)s* c =
6020 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
6021 if (c) {
6022 c->Init(%(args)s);
6027 file.Write(code % {
6028 "name": func.name,
6029 "typed_args": func.MakeTypedOriginalArgString(""),
6030 "args": func.MakeOriginalArgString(""),
6033 def WriteImmediateFormatTest(self, func, file):
6034 """Overrriden from TypeHandler."""
6035 file.Write("TEST_F(GLES2FormatTest, %s) {\n" % func.name)
6036 file.Write(" static GLuint ids[] = { 12, 23, 34, };\n")
6037 file.Write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
6038 (func.name, func.name))
6039 file.Write(" void* next_cmd = cmd.Set(\n")
6040 file.Write(" &cmd, static_cast<GLsizei>(arraysize(ids)), ids);\n")
6041 file.Write(" EXPECT_EQ(static_cast<uint32_t>(cmds::%s::kCmdId),\n" %
6042 func.name)
6043 file.Write(" cmd.header.command);\n")
6044 file.Write(" EXPECT_EQ(sizeof(cmd) +\n")
6045 file.Write(" RoundSizeToMultipleOfEntries(cmd.n * 4u),\n")
6046 file.Write(" cmd.header.size * 4u);\n")
6047 file.Write(" EXPECT_EQ(static_cast<GLsizei>(arraysize(ids)), cmd.n);\n");
6048 file.Write(" CheckBytesWrittenMatchesExpectedSize(\n")
6049 file.Write(" next_cmd, sizeof(cmd) +\n")
6050 file.Write(" RoundSizeToMultipleOfEntries(arraysize(ids) * 4u));\n")
6051 file.Write(" // TODO(gman): Check that ids were inserted;\n")
6052 file.Write("}\n")
6053 file.Write("\n")
6056 class CreateHandler(TypeHandler):
6057 """Handler for glCreate___ type functions."""
6059 def __init__(self):
6060 TypeHandler.__init__(self)
6062 def InitFunction(self, func):
6063 """Overrriden from TypeHandler."""
6064 func.AddCmdArg(Argument("client_id", 'uint32_t'))
6066 def __GetResourceType(self, func):
6067 if func.return_type == "GLsync":
6068 return "Sync"
6069 else:
6070 return func.name[6:] # Create*
6072 def WriteServiceUnitTest(self, func, file, *extras):
6073 """Overrriden from TypeHandler."""
6074 valid_test = """
6075 TEST_P(%(test_name)s, %(name)sValidArgs) {
6076 %(id_type_cast)sEXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s))
6077 .WillOnce(Return(%(const_service_id)s));
6078 SpecializedSetup<cmds::%(name)s, 0>(true);
6079 cmds::%(name)s cmd;
6080 cmd.Init(%(args)s%(comma)skNewClientId);"""
6081 if func.IsUnsafe():
6082 valid_test += """
6083 decoder_->set_unsafe_es3_apis_enabled(true);"""
6084 valid_test += """
6085 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
6086 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
6087 if func.IsUnsafe():
6088 valid_test += """
6089 %(return_type)s service_id = 0;
6090 EXPECT_TRUE(Get%(resource_type)sServiceId(kNewClientId, &service_id));
6091 EXPECT_EQ(%(const_service_id)s, service_id);
6092 decoder_->set_unsafe_es3_apis_enabled(false);
6093 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));
6096 else:
6097 valid_test += """
6098 EXPECT_TRUE(Get%(resource_type)s(kNewClientId));
6101 comma = ""
6102 cmd_arg_count = 0
6103 for arg in func.GetOriginalArgs():
6104 if not arg.IsConstant():
6105 cmd_arg_count += 1
6106 if cmd_arg_count:
6107 comma = ", "
6108 if func.return_type == 'GLsync':
6109 id_type_cast = ("const GLsync kNewServiceIdGLuint = reinterpret_cast"
6110 "<GLsync>(kNewServiceId);\n ")
6111 const_service_id = "kNewServiceIdGLuint"
6112 else:
6113 id_type_cast = ""
6114 const_service_id = "kNewServiceId"
6115 self.WriteValidUnitTest(func, file, valid_test, {
6116 'comma': comma,
6117 'resource_type': self.__GetResourceType(func),
6118 'return_type': func.return_type,
6119 'id_type_cast': id_type_cast,
6120 'const_service_id': const_service_id,
6121 }, *extras)
6122 invalid_test = """
6123 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
6124 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
6125 SpecializedSetup<cmds::%(name)s, 0>(false);
6126 cmds::%(name)s cmd;
6127 cmd.Init(%(args)s%(comma)skNewClientId);
6128 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));%(gl_error_test)s
6131 self.WriteInvalidUnitTest(func, file, invalid_test, {
6132 'comma': comma,
6133 }, *extras)
6135 def WriteHandlerImplementation (self, func, file):
6136 """Overrriden from TypeHandler."""
6137 if func.IsUnsafe():
6138 code = """ uint32_t client_id = c.client_id;
6139 %(return_type)s service_id = 0;
6140 if (group_->Get%(resource_name)sServiceId(client_id, &service_id)) {
6141 return error::kInvalidArguments;
6143 service_id = %(gl_func_name)s(%(gl_args)s);
6144 if (service_id) {
6145 group_->Add%(resource_name)sId(client_id, service_id);
6148 else:
6149 code = """ uint32_t client_id = c.client_id;
6150 if (Get%(resource_name)s(client_id)) {
6151 return error::kInvalidArguments;
6153 %(return_type)s service_id = %(gl_func_name)s(%(gl_args)s);
6154 if (service_id) {
6155 Create%(resource_name)s(client_id, service_id%(gl_args_with_comma)s);
6158 file.Write(code % {
6159 'resource_name': self.__GetResourceType(func),
6160 'return_type': func.return_type,
6161 'gl_func_name': func.GetGLFunctionName(),
6162 'gl_args': func.MakeOriginalArgString(""),
6163 'gl_args_with_comma': func.MakeOriginalArgString("", True) })
6165 def WriteGLES2Implementation(self, func, file):
6166 """Overrriden from TypeHandler."""
6167 file.Write("%s GLES2Implementation::%s(%s) {\n" %
6168 (func.return_type, func.original_name,
6169 func.MakeTypedOriginalArgString("")))
6170 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
6171 func.WriteDestinationInitalizationValidation(file)
6172 self.WriteClientGLCallLog(func, file)
6173 for arg in func.GetOriginalArgs():
6174 arg.WriteClientSideValidationCode(file, func)
6175 file.Write(" GLuint client_id;\n")
6176 if func.return_type == "GLsync":
6177 file.Write(
6178 " GetIdHandler(id_namespaces::kSyncs)->\n")
6179 else:
6180 file.Write(
6181 " GetIdHandler(id_namespaces::kProgramsAndShaders)->\n")
6182 file.Write(" MakeIds(this, 0, 1, &client_id);\n")
6183 file.Write(" helper_->%s(%s);\n" %
6184 (func.name, func.MakeCmdArgString("")))
6185 file.Write(' GPU_CLIENT_LOG("returned " << client_id);\n')
6186 file.Write(" CheckGLError();\n")
6187 if func.return_type == "GLsync":
6188 file.Write(" return reinterpret_cast<GLsync>(client_id);\n")
6189 else:
6190 file.Write(" return client_id;\n")
6191 file.Write("}\n")
6192 file.Write("\n")
6195 class DeleteHandler(TypeHandler):
6196 """Handler for glDelete___ single resource type functions."""
6198 def __init__(self):
6199 TypeHandler.__init__(self)
6201 def WriteServiceImplementation(self, func, file):
6202 """Overrriden from TypeHandler."""
6203 if func.IsUnsafe():
6204 TypeHandler.WriteServiceImplementation(self, func, file)
6205 # HandleDeleteShader and HandleDeleteProgram are manually written.
6206 pass
6208 def WriteGLES2Implementation(self, func, file):
6209 """Overrriden from TypeHandler."""
6210 file.Write("%s GLES2Implementation::%s(%s) {\n" %
6211 (func.return_type, func.original_name,
6212 func.MakeTypedOriginalArgString("")))
6213 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
6214 func.WriteDestinationInitalizationValidation(file)
6215 self.WriteClientGLCallLog(func, file)
6216 for arg in func.GetOriginalArgs():
6217 arg.WriteClientSideValidationCode(file, func)
6218 file.Write(
6219 " GPU_CLIENT_DCHECK(%s != 0);\n" % func.GetOriginalArgs()[-1].name)
6220 file.Write(" %sHelper(%s);\n" %
6221 (func.original_name, func.GetOriginalArgs()[-1].name))
6222 file.Write(" CheckGLError();\n")
6223 file.Write("}\n")
6224 file.Write("\n")
6226 def WriteHandlerImplementation (self, func, file):
6227 """Overrriden from TypeHandler."""
6228 assert len(func.GetOriginalArgs()) == 1
6229 arg = func.GetOriginalArgs()[0]
6230 if func.IsUnsafe():
6231 file.Write(""" %(arg_type)s service_id = 0;
6232 if (group_->Get%(resource_type)sServiceId(%(arg_name)s, &service_id)) {
6233 glDelete%(resource_type)s(service_id);
6234 group_->Remove%(resource_type)sId(%(arg_name)s);
6235 } else {
6236 LOCAL_SET_GL_ERROR(
6237 GL_INVALID_VALUE, "gl%(func_name)s", "unknown %(arg_name)s");
6239 """ % { 'resource_type': func.GetInfo('resource_type'),
6240 'arg_name': arg.name,
6241 'arg_type': arg.type,
6242 'func_name': func.original_name })
6243 else:
6244 file.Write(" %sHelper(%s);\n" % (func.original_name, arg.name))
6246 class DELnHandler(TypeHandler):
6247 """Handler for glDelete___ type functions."""
6249 def __init__(self):
6250 TypeHandler.__init__(self)
6252 def WriteGetDataSizeCode(self, func, file):
6253 """Overrriden from TypeHandler."""
6254 code = """ uint32_t data_size;
6255 if (!SafeMultiplyUint32(n, sizeof(GLuint), &data_size)) {
6256 return error::kOutOfBounds;
6259 file.Write(code)
6261 def WriteGLES2ImplementationUnitTest(self, func, file):
6262 """Overrriden from TypeHandler."""
6263 code = """
6264 TEST_F(GLES2ImplementationTest, %(name)s) {
6265 GLuint ids[2] = { k%(types)sStartId, k%(types)sStartId + 1 };
6266 struct Cmds {
6267 cmds::%(name)sImmediate del;
6268 GLuint data[2];
6270 Cmds expected;
6271 expected.del.Init(arraysize(ids), &ids[0]);
6272 expected.data[0] = k%(types)sStartId;
6273 expected.data[1] = k%(types)sStartId + 1;
6274 gl_->%(name)s(arraysize(ids), &ids[0]);
6275 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
6278 file.Write(code % {
6279 'name': func.name,
6280 'types': func.GetInfo('resource_types'),
6283 def WriteServiceUnitTest(self, func, file, *extras):
6284 """Overrriden from TypeHandler."""
6285 valid_test = """
6286 TEST_P(%(test_name)s, %(name)sValidArgs) {
6287 EXPECT_CALL(
6288 *gl_,
6289 %(gl_func_name)s(1, Pointee(kService%(upper_resource_name)sId)))
6290 .Times(1);
6291 GetSharedMemoryAs<GLuint*>()[0] = client_%(resource_name)s_id_;
6292 SpecializedSetup<cmds::%(name)s, 0>(true);
6293 cmds::%(name)s cmd;
6294 cmd.Init(%(args)s);
6295 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
6296 EXPECT_EQ(GL_NO_ERROR, GetGLError());
6297 EXPECT_TRUE(
6298 Get%(upper_resource_name)s(client_%(resource_name)s_id_) == NULL);
6301 self.WriteValidUnitTest(func, file, valid_test, {
6302 'resource_name': func.GetInfo('resource_type').lower(),
6303 'upper_resource_name': func.GetInfo('resource_type'),
6304 }, *extras)
6305 invalid_test = """
6306 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
6307 GetSharedMemoryAs<GLuint*>()[0] = kInvalidClientId;
6308 SpecializedSetup<cmds::%(name)s, 0>(false);
6309 cmds::%(name)s cmd;
6310 cmd.Init(%(args)s);
6311 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
6314 self.WriteValidUnitTest(func, file, invalid_test, *extras)
6316 def WriteImmediateServiceUnitTest(self, func, file, *extras):
6317 """Overrriden from TypeHandler."""
6318 valid_test = """
6319 TEST_P(%(test_name)s, %(name)sValidArgs) {
6320 EXPECT_CALL(
6321 *gl_,
6322 %(gl_func_name)s(1, Pointee(kService%(upper_resource_name)sId)))
6323 .Times(1);
6324 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
6325 SpecializedSetup<cmds::%(name)s, 0>(true);
6326 cmd.Init(1, &client_%(resource_name)s_id_);"""
6327 if func.IsUnsafe():
6328 valid_test += """
6329 decoder_->set_unsafe_es3_apis_enabled(true);"""
6330 valid_test += """
6331 EXPECT_EQ(error::kNoError,
6332 ExecuteImmediateCmd(cmd, sizeof(client_%(resource_name)s_id_)));
6333 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
6334 if func.IsUnsafe():
6335 valid_test += """
6336 EXPECT_FALSE(Get%(upper_resource_name)sServiceId(
6337 client_%(resource_name)s_id_, NULL));
6338 decoder_->set_unsafe_es3_apis_enabled(false);
6339 EXPECT_EQ(error::kUnknownCommand,
6340 ExecuteImmediateCmd(cmd, sizeof(client_%(resource_name)s_id_)));
6343 else:
6344 valid_test += """
6345 EXPECT_TRUE(
6346 Get%(upper_resource_name)s(client_%(resource_name)s_id_) == NULL);
6349 self.WriteValidUnitTest(func, file, valid_test, {
6350 'resource_name': func.GetInfo('resource_type').lower(),
6351 'upper_resource_name': func.GetInfo('resource_type'),
6352 }, *extras)
6353 invalid_test = """
6354 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
6355 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
6356 SpecializedSetup<cmds::%(name)s, 0>(false);
6357 GLuint temp = kInvalidClientId;
6358 cmd.Init(1, &temp);"""
6359 if func.IsUnsafe():
6360 invalid_test += """
6361 decoder_->set_unsafe_es3_apis_enabled(true);
6362 EXPECT_EQ(error::kNoError,
6363 ExecuteImmediateCmd(cmd, sizeof(temp)));
6364 decoder_->set_unsafe_es3_apis_enabled(false);
6365 EXPECT_EQ(error::kUnknownCommand,
6366 ExecuteImmediateCmd(cmd, sizeof(temp)));
6369 else:
6370 invalid_test += """
6371 EXPECT_EQ(error::kNoError,
6372 ExecuteImmediateCmd(cmd, sizeof(temp)));
6375 self.WriteValidUnitTest(func, file, invalid_test, *extras)
6377 def WriteHandlerImplementation (self, func, file):
6378 """Overrriden from TypeHandler."""
6379 file.Write(" %sHelper(n, %s);\n" %
6380 (func.name, func.GetLastOriginalArg().name))
6382 def WriteImmediateHandlerImplementation (self, func, file):
6383 """Overrriden from TypeHandler."""
6384 if func.IsUnsafe():
6385 file.Write(""" for (GLsizei ii = 0; ii < n; ++ii) {
6386 GLuint service_id = 0;
6387 if (group_->Get%(resource_type)sServiceId(
6388 %(last_arg_name)s[ii], &service_id)) {
6389 glDelete%(resource_type)ss(1, &service_id);
6390 group_->Remove%(resource_type)sId(%(last_arg_name)s[ii]);
6393 """ % { 'resource_type': func.GetInfo('resource_type'),
6394 'last_arg_name': func.GetLastOriginalArg().name })
6395 else:
6396 file.Write(" %sHelper(n, %s);\n" %
6397 (func.original_name, func.GetLastOriginalArg().name))
6399 def WriteGLES2Implementation(self, func, file):
6400 """Overrriden from TypeHandler."""
6401 impl_decl = func.GetInfo('impl_decl')
6402 if impl_decl == None or impl_decl == True:
6403 args = {
6404 'return_type': func.return_type,
6405 'name': func.original_name,
6406 'typed_args': func.MakeTypedOriginalArgString(""),
6407 'args': func.MakeOriginalArgString(""),
6408 'resource_type': func.GetInfo('resource_type').lower(),
6409 'count_name': func.GetOriginalArgs()[0].name,
6411 file.Write(
6412 "%(return_type)s GLES2Implementation::%(name)s(%(typed_args)s) {\n" %
6413 args)
6414 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
6415 func.WriteDestinationInitalizationValidation(file)
6416 self.WriteClientGLCallLog(func, file)
6417 file.Write(""" GPU_CLIENT_LOG_CODE_BLOCK({
6418 for (GLsizei i = 0; i < n; ++i) {
6419 GPU_CLIENT_LOG(" " << i << ": " << %s[i]);
6422 """ % func.GetOriginalArgs()[1].name)
6423 file.Write(""" GPU_CLIENT_DCHECK_CODE_BLOCK({
6424 for (GLsizei i = 0; i < n; ++i) {
6425 DCHECK(%s[i] != 0);
6428 """ % func.GetOriginalArgs()[1].name)
6429 for arg in func.GetOriginalArgs():
6430 arg.WriteClientSideValidationCode(file, func)
6431 code = """ %(name)sHelper(%(args)s);
6432 CheckGLError();
6436 file.Write(code % args)
6438 def WriteImmediateCmdComputeSize(self, func, file):
6439 """Overrriden from TypeHandler."""
6440 file.Write(" static uint32_t ComputeDataSize(GLsizei n) {\n")
6441 file.Write(
6442 " return static_cast<uint32_t>(sizeof(GLuint) * n); // NOLINT\n")
6443 file.Write(" }\n")
6444 file.Write("\n")
6445 file.Write(" static uint32_t ComputeSize(GLsizei n) {\n")
6446 file.Write(" return static_cast<uint32_t>(\n")
6447 file.Write(" sizeof(ValueType) + ComputeDataSize(n)); // NOLINT\n")
6448 file.Write(" }\n")
6449 file.Write("\n")
6451 def WriteImmediateCmdSetHeader(self, func, file):
6452 """Overrriden from TypeHandler."""
6453 file.Write(" void SetHeader(GLsizei n) {\n")
6454 file.Write(" header.SetCmdByTotalSize<ValueType>(ComputeSize(n));\n")
6455 file.Write(" }\n")
6456 file.Write("\n")
6458 def WriteImmediateCmdInit(self, func, file):
6459 """Overrriden from TypeHandler."""
6460 last_arg = func.GetLastOriginalArg()
6461 file.Write(" void Init(%s, %s _%s) {\n" %
6462 (func.MakeTypedCmdArgString("_"),
6463 last_arg.type, last_arg.name))
6464 file.Write(" SetHeader(_n);\n")
6465 args = func.GetCmdArgs()
6466 for arg in args:
6467 file.Write(" %s = _%s;\n" % (arg.name, arg.name))
6468 file.Write(" memcpy(ImmediateDataAddress(this),\n")
6469 file.Write(" _%s, ComputeDataSize(_n));\n" % last_arg.name)
6470 file.Write(" }\n")
6471 file.Write("\n")
6473 def WriteImmediateCmdSet(self, func, file):
6474 """Overrriden from TypeHandler."""
6475 last_arg = func.GetLastOriginalArg()
6476 copy_args = func.MakeCmdArgString("_", False)
6477 file.Write(" void* Set(void* cmd%s, %s _%s) {\n" %
6478 (func.MakeTypedCmdArgString("_", True),
6479 last_arg.type, last_arg.name))
6480 file.Write(" static_cast<ValueType*>(cmd)->Init(%s, _%s);\n" %
6481 (copy_args, last_arg.name))
6482 file.Write(" const uint32_t size = ComputeSize(_n);\n")
6483 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
6484 "cmd, size);\n")
6485 file.Write(" }\n")
6486 file.Write("\n")
6488 def WriteImmediateCmdHelper(self, func, file):
6489 """Overrriden from TypeHandler."""
6490 code = """ void %(name)s(%(typed_args)s) {
6491 const uint32_t size = gles2::cmds::%(name)s::ComputeSize(n);
6492 gles2::cmds::%(name)s* c =
6493 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
6494 if (c) {
6495 c->Init(%(args)s);
6500 file.Write(code % {
6501 "name": func.name,
6502 "typed_args": func.MakeTypedOriginalArgString(""),
6503 "args": func.MakeOriginalArgString(""),
6506 def WriteImmediateFormatTest(self, func, file):
6507 """Overrriden from TypeHandler."""
6508 file.Write("TEST_F(GLES2FormatTest, %s) {\n" % func.name)
6509 file.Write(" static GLuint ids[] = { 12, 23, 34, };\n")
6510 file.Write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
6511 (func.name, func.name))
6512 file.Write(" void* next_cmd = cmd.Set(\n")
6513 file.Write(" &cmd, static_cast<GLsizei>(arraysize(ids)), ids);\n")
6514 file.Write(" EXPECT_EQ(static_cast<uint32_t>(cmds::%s::kCmdId),\n" %
6515 func.name)
6516 file.Write(" cmd.header.command);\n")
6517 file.Write(" EXPECT_EQ(sizeof(cmd) +\n")
6518 file.Write(" RoundSizeToMultipleOfEntries(cmd.n * 4u),\n")
6519 file.Write(" cmd.header.size * 4u);\n")
6520 file.Write(" EXPECT_EQ(static_cast<GLsizei>(arraysize(ids)), cmd.n);\n");
6521 file.Write(" CheckBytesWrittenMatchesExpectedSize(\n")
6522 file.Write(" next_cmd, sizeof(cmd) +\n")
6523 file.Write(" RoundSizeToMultipleOfEntries(arraysize(ids) * 4u));\n")
6524 file.Write(" // TODO(gman): Check that ids were inserted;\n")
6525 file.Write("}\n")
6526 file.Write("\n")
6529 class GETnHandler(TypeHandler):
6530 """Handler for GETn for glGetBooleanv, glGetFloatv, ... type functions."""
6532 def __init__(self):
6533 TypeHandler.__init__(self)
6535 def NeedsDataTransferFunction(self, func):
6536 """Overriden from TypeHandler."""
6537 return False
6539 def WriteServiceImplementation(self, func, file):
6540 """Overrriden from TypeHandler."""
6541 self.WriteServiceHandlerFunctionHeader(func, file)
6542 last_arg = func.GetLastOriginalArg()
6543 # All except shm_id and shm_offset.
6544 all_but_last_args = func.GetCmdArgs()[:-2]
6545 for arg in all_but_last_args:
6546 arg.WriteGetCode(file)
6548 code = """ typedef cmds::%(func_name)s::Result Result;
6549 GLsizei num_values = 0;
6550 GetNumValuesReturnedForGLGet(pname, &num_values);
6551 Result* result = GetSharedMemoryAs<Result*>(
6552 c.%(last_arg_name)s_shm_id, c.%(last_arg_name)s_shm_offset,
6553 Result::ComputeSize(num_values));
6554 %(last_arg_type)s %(last_arg_name)s = result ? result->GetData() : NULL;
6556 file.Write(code % {
6557 'last_arg_type': last_arg.type,
6558 'last_arg_name': last_arg.name,
6559 'func_name': func.name,
6561 func.WriteHandlerValidation(file)
6562 code = """ // Check that the client initialized the result.
6563 if (result->size != 0) {
6564 return error::kInvalidArguments;
6567 shadowed = func.GetInfo('shadowed')
6568 if not shadowed:
6569 file.Write(' LOCAL_COPY_REAL_GL_ERRORS_TO_WRAPPER("%s");\n' % func.name)
6570 file.Write(code)
6571 func.WriteHandlerImplementation(file)
6572 if shadowed:
6573 code = """ result->SetNumResults(num_values);
6574 return error::kNoError;
6577 else:
6578 code = """ GLenum error = LOCAL_PEEK_GL_ERROR("%(func_name)s");
6579 if (error == GL_NO_ERROR) {
6580 result->SetNumResults(num_values);
6582 return error::kNoError;
6586 file.Write(code % {'func_name': func.name})
6588 def WriteGLES2Implementation(self, func, file):
6589 """Overrriden from TypeHandler."""
6590 impl_decl = func.GetInfo('impl_decl')
6591 if impl_decl == None or impl_decl == True:
6592 file.Write("%s GLES2Implementation::%s(%s) {\n" %
6593 (func.return_type, func.original_name,
6594 func.MakeTypedOriginalArgString("")))
6595 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
6596 func.WriteDestinationInitalizationValidation(file)
6597 self.WriteClientGLCallLog(func, file)
6598 for arg in func.GetOriginalArgs():
6599 arg.WriteClientSideValidationCode(file, func)
6600 all_but_last_args = func.GetOriginalArgs()[:-1]
6601 args = []
6602 has_length_arg = False
6603 for arg in all_but_last_args:
6604 if arg.type == 'GLsync':
6605 args.append('ToGLuint(%s)' % arg.name)
6606 elif arg.name.endswith('size') and arg.type == 'GLsizei':
6607 continue
6608 elif arg.name == 'length':
6609 has_length_arg = True
6610 continue
6611 else:
6612 args.append(arg.name)
6613 arg_string = ", ".join(args)
6614 all_arg_string = (
6615 ", ".join([
6616 "%s" % arg.name
6617 for arg in func.GetOriginalArgs() if not arg.IsConstant()]))
6618 self.WriteTraceEvent(func, file)
6619 code = """ if (%(func_name)sHelper(%(all_arg_string)s)) {
6620 return;
6622 typedef cmds::%(func_name)s::Result Result;
6623 Result* result = GetResultAs<Result*>();
6624 if (!result) {
6625 return;
6627 result->SetNumResults(0);
6628 helper_->%(func_name)s(%(arg_string)s,
6629 GetResultShmId(), GetResultShmOffset());
6630 WaitForCmd();
6631 result->CopyResult(%(last_arg_name)s);
6632 GPU_CLIENT_LOG_CODE_BLOCK({
6633 for (int32_t i = 0; i < result->GetNumResults(); ++i) {
6634 GPU_CLIENT_LOG(" " << i << ": " << result->GetData()[i]);
6636 });"""
6637 if has_length_arg:
6638 code += """
6639 if (length) {
6640 *length = result->GetNumResults();
6641 }"""
6642 code += """
6643 CheckGLError();
6646 file.Write(code % {
6647 'func_name': func.name,
6648 'arg_string': arg_string,
6649 'all_arg_string': all_arg_string,
6650 'last_arg_name': func.GetLastOriginalArg().name,
6653 def WriteGLES2ImplementationUnitTest(self, func, file):
6654 """Writes the GLES2 Implemention unit test."""
6655 code = """
6656 TEST_F(GLES2ImplementationTest, %(name)s) {
6657 struct Cmds {
6658 cmds::%(name)s cmd;
6660 typedef cmds::%(name)s::Result::Type ResultType;
6661 ResultType result = 0;
6662 Cmds expected;
6663 ExpectedMemoryInfo result1 = GetExpectedResultMemory(
6664 sizeof(uint32_t) + sizeof(ResultType));
6665 expected.cmd.Init(%(cmd_args)s, result1.id, result1.offset);
6666 EXPECT_CALL(*command_buffer(), OnFlush())
6667 .WillOnce(SetMemory(result1.ptr, SizedResultHelper<ResultType>(1)))
6668 .RetiresOnSaturation();
6669 gl_->%(name)s(%(args)s, &result);
6670 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
6671 EXPECT_EQ(static_cast<ResultType>(1), result);
6674 first_cmd_arg = func.GetCmdArgs()[0].GetValidNonCachedClientSideCmdArg(func)
6675 if not first_cmd_arg:
6676 return
6678 first_gl_arg = func.GetOriginalArgs()[0].GetValidNonCachedClientSideArg(
6679 func)
6681 cmd_arg_strings = [first_cmd_arg]
6682 for arg in func.GetCmdArgs()[1:-2]:
6683 cmd_arg_strings.append(arg.GetValidClientSideCmdArg(func))
6684 gl_arg_strings = [first_gl_arg]
6685 for arg in func.GetOriginalArgs()[1:-1]:
6686 gl_arg_strings.append(arg.GetValidClientSideArg(func))
6688 file.Write(code % {
6689 'name': func.name,
6690 'args': ", ".join(gl_arg_strings),
6691 'cmd_args': ", ".join(cmd_arg_strings),
6694 def WriteServiceUnitTest(self, func, file, *extras):
6695 """Overrriden from TypeHandler."""
6696 valid_test = """
6697 TEST_P(%(test_name)s, %(name)sValidArgs) {
6698 EXPECT_CALL(*gl_, GetError())
6699 .WillOnce(Return(GL_NO_ERROR))
6700 .WillOnce(Return(GL_NO_ERROR))
6701 .RetiresOnSaturation();
6702 SpecializedSetup<cmds::%(name)s, 0>(true);
6703 typedef cmds::%(name)s::Result Result;
6704 Result* result = static_cast<Result*>(shared_memory_address_);
6705 EXPECT_CALL(*gl_, %(gl_func_name)s(%(local_gl_args)s));
6706 result->size = 0;
6707 cmds::%(name)s cmd;
6708 cmd.Init(%(cmd_args)s);"""
6709 if func.IsUnsafe():
6710 valid_test += """
6711 decoder_->set_unsafe_es3_apis_enabled(true);"""
6712 valid_test += """
6713 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
6714 EXPECT_EQ(decoder_->GetGLES2Util()->GLGetNumValuesReturned(
6715 %(valid_pname)s),
6716 result->GetNumResults());
6717 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
6718 if func.IsUnsafe():
6719 valid_test += """
6720 decoder_->set_unsafe_es3_apis_enabled(false);
6721 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));"""
6722 valid_test += """
6725 gl_arg_strings = []
6726 cmd_arg_strings = []
6727 valid_pname = ''
6728 for arg in func.GetOriginalArgs()[:-1]:
6729 if arg.name == 'length':
6730 gl_arg_value = 'nullptr'
6731 elif arg.name.endswith('size'):
6732 gl_arg_value = ("decoder_->GetGLES2Util()->GLGetNumValuesReturned(%s)" %
6733 valid_pname)
6734 elif arg.type == 'GLsync':
6735 gl_arg_value = 'reinterpret_cast<GLsync>(kServiceSyncId)'
6736 else:
6737 gl_arg_value = arg.GetValidGLArg(func)
6738 gl_arg_strings.append(gl_arg_value)
6739 if arg.name == 'pname':
6740 valid_pname = gl_arg_value
6741 if arg.name.endswith('size') or arg.name == 'length':
6742 continue
6743 if arg.type == 'GLsync':
6744 arg_value = 'client_sync_id_'
6745 else:
6746 arg_value = arg.GetValidArg(func)
6747 cmd_arg_strings.append(arg_value)
6748 if func.GetInfo('gl_test_func') == 'glGetIntegerv':
6749 gl_arg_strings.append("_")
6750 else:
6751 gl_arg_strings.append("result->GetData()")
6752 cmd_arg_strings.append("shared_memory_id_")
6753 cmd_arg_strings.append("shared_memory_offset_")
6755 self.WriteValidUnitTest(func, file, valid_test, {
6756 'local_gl_args': ", ".join(gl_arg_strings),
6757 'cmd_args': ", ".join(cmd_arg_strings),
6758 'valid_pname': valid_pname,
6759 }, *extras)
6761 if not func.IsUnsafe():
6762 invalid_test = """
6763 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
6764 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
6765 SpecializedSetup<cmds::%(name)s, 0>(false);
6766 cmds::%(name)s::Result* result =
6767 static_cast<cmds::%(name)s::Result*>(shared_memory_address_);
6768 result->size = 0;
6769 cmds::%(name)s cmd;
6770 cmd.Init(%(args)s);
6771 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));
6772 EXPECT_EQ(0u, result->size);%(gl_error_test)s
6775 self.WriteInvalidUnitTest(func, file, invalid_test, *extras)
6777 class ArrayArgTypeHandler(TypeHandler):
6778 """Base class for type handlers that handle args that are arrays"""
6780 def __init__(self):
6781 TypeHandler.__init__(self)
6783 def GetArrayType(self, func):
6784 """Returns the type of the element in the element array being PUT to."""
6785 for arg in func.GetOriginalArgs():
6786 if arg.IsPointer():
6787 element_type = arg.GetPointedType()
6788 return element_type
6790 # Special case: array type handler is used for a function that is forwarded
6791 # to the actual array type implementation
6792 element_type = func.GetOriginalArgs()[-1].type
6793 assert all(arg.type == element_type \
6794 for arg in func.GetOriginalArgs()[-self.GetArrayCount(func):])
6795 return element_type
6797 def GetArrayCount(self, func):
6798 """Returns the count of the elements in the array being PUT to."""
6799 return func.GetInfo('count')
6801 class PUTHandler(ArrayArgTypeHandler):
6802 """Handler for glTexParameter_v, glVertexAttrib_v functions."""
6804 def __init__(self):
6805 ArrayArgTypeHandler.__init__(self)
6807 def WriteServiceUnitTest(self, func, file, *extras):
6808 """Writes the service unit test for a command."""
6809 expected_call = "EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));"
6810 if func.GetInfo("first_element_only"):
6811 gl_arg_strings = [
6812 arg.GetValidGLArg(func) for arg in func.GetOriginalArgs()
6814 gl_arg_strings[-1] = "*" + gl_arg_strings[-1]
6815 expected_call = ("EXPECT_CALL(*gl_, %%(gl_func_name)s(%s));" %
6816 ", ".join(gl_arg_strings))
6817 valid_test = """
6818 TEST_P(%(test_name)s, %(name)sValidArgs) {
6819 SpecializedSetup<cmds::%(name)s, 0>(true);
6820 cmds::%(name)s cmd;
6821 cmd.Init(%(args)s);
6822 GetSharedMemoryAs<%(data_type)s*>()[0] = %(data_value)s;
6823 %(expected_call)s
6824 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
6825 EXPECT_EQ(GL_NO_ERROR, GetGLError());
6828 extra = {
6829 'data_type': self.GetArrayType(func),
6830 'data_value': func.GetInfo('data_value') or '0',
6831 'expected_call': expected_call,
6833 self.WriteValidUnitTest(func, file, valid_test, extra, *extras)
6835 invalid_test = """
6836 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
6837 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
6838 SpecializedSetup<cmds::%(name)s, 0>(false);
6839 cmds::%(name)s cmd;
6840 cmd.Init(%(args)s);
6841 GetSharedMemoryAs<%(data_type)s*>()[0] = %(data_value)s;
6842 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
6845 self.WriteInvalidUnitTest(func, file, invalid_test, extra, *extras)
6847 def WriteImmediateServiceUnitTest(self, func, file, *extras):
6848 """Writes the service unit test for a command."""
6849 valid_test = """
6850 TEST_P(%(test_name)s, %(name)sValidArgs) {
6851 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
6852 SpecializedSetup<cmds::%(name)s, 0>(true);
6853 %(data_type)s temp[%(data_count)s] = { %(data_value)s, };
6854 cmd.Init(%(gl_args)s, &temp[0]);
6855 EXPECT_CALL(
6856 *gl_,
6857 %(gl_func_name)s(%(gl_args)s, %(data_ref)sreinterpret_cast<
6858 %(data_type)s*>(ImmediateDataAddress(&cmd))));"""
6859 if func.IsUnsafe():
6860 valid_test += """
6861 decoder_->set_unsafe_es3_apis_enabled(true);"""
6862 valid_test += """
6863 EXPECT_EQ(error::kNoError,
6864 ExecuteImmediateCmd(cmd, sizeof(temp)));
6865 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
6866 if func.IsUnsafe():
6867 valid_test += """
6868 decoder_->set_unsafe_es3_apis_enabled(false);
6869 EXPECT_EQ(error::kUnknownCommand,
6870 ExecuteImmediateCmd(cmd, sizeof(temp)));"""
6871 valid_test += """
6874 gl_arg_strings = [
6875 arg.GetValidGLArg(func) for arg in func.GetOriginalArgs()[0:-1]
6877 gl_any_strings = ["_"] * len(gl_arg_strings)
6879 extra = {
6880 'data_ref': ("*" if func.GetInfo('first_element_only') else ""),
6881 'data_type': self.GetArrayType(func),
6882 'data_count': self.GetArrayCount(func),
6883 'data_value': func.GetInfo('data_value') or '0',
6884 'gl_args': ", ".join(gl_arg_strings),
6885 'gl_any_args': ", ".join(gl_any_strings),
6887 self.WriteValidUnitTest(func, file, valid_test, extra, *extras)
6889 invalid_test = """
6890 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
6891 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();"""
6892 if func.IsUnsafe():
6893 invalid_test += """
6894 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_any_args)s, _)).Times(1);
6896 else:
6897 invalid_test += """
6898 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_any_args)s, _)).Times(0);
6900 invalid_test += """
6901 SpecializedSetup<cmds::%(name)s, 0>(false);
6902 %(data_type)s temp[%(data_count)s] = { %(data_value)s, };
6903 cmd.Init(%(all_but_last_args)s, &temp[0]);"""
6904 if func.IsUnsafe():
6905 invalid_test += """
6906 decoder_->set_unsafe_es3_apis_enabled(true);
6907 EXPECT_EQ(error::%(parse_result)s,
6908 ExecuteImmediateCmd(cmd, sizeof(temp)));
6909 decoder_->set_unsafe_es3_apis_enabled(false);
6912 else:
6913 invalid_test += """
6914 EXPECT_EQ(error::%(parse_result)s,
6915 ExecuteImmediateCmd(cmd, sizeof(temp)));
6916 %(gl_error_test)s
6919 self.WriteInvalidUnitTest(func, file, invalid_test, extra, *extras)
6921 def WriteGetDataSizeCode(self, func, file):
6922 """Overrriden from TypeHandler."""
6923 code = """ uint32_t data_size;
6924 if (!ComputeDataSize(1, sizeof(%s), %d, &data_size)) {
6925 return error::kOutOfBounds;
6928 file.Write(code % (self.GetArrayType(func), self.GetArrayCount(func)))
6929 if func.IsImmediate():
6930 file.Write(" if (data_size > immediate_data_size) {\n")
6931 file.Write(" return error::kOutOfBounds;\n")
6932 file.Write(" }\n")
6934 def __NeedsToCalcDataCount(self, func):
6935 use_count_func = func.GetInfo('use_count_func')
6936 return use_count_func != None and use_count_func != False
6938 def WriteGLES2Implementation(self, func, file):
6939 """Overrriden from TypeHandler."""
6940 impl_func = func.GetInfo('impl_func')
6941 if (impl_func != None and impl_func != True):
6942 return;
6943 file.Write("%s GLES2Implementation::%s(%s) {\n" %
6944 (func.return_type, func.original_name,
6945 func.MakeTypedOriginalArgString("")))
6946 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
6947 func.WriteDestinationInitalizationValidation(file)
6948 self.WriteClientGLCallLog(func, file)
6950 if self.__NeedsToCalcDataCount(func):
6951 file.Write(" size_t count = GLES2Util::Calc%sDataCount(%s);\n" %
6952 (func.name, func.GetOriginalArgs()[0].name))
6953 file.Write(" DCHECK_LE(count, %du);\n" % self.GetArrayCount(func))
6954 else:
6955 file.Write(" size_t count = %d;" % self.GetArrayCount(func))
6956 file.Write(" for (size_t ii = 0; ii < count; ++ii)\n")
6957 file.Write(' GPU_CLIENT_LOG("value[" << ii << "]: " << %s[ii]);\n' %
6958 func.GetLastOriginalArg().name)
6959 for arg in func.GetOriginalArgs():
6960 arg.WriteClientSideValidationCode(file, func)
6961 file.Write(" helper_->%sImmediate(%s);\n" %
6962 (func.name, func.MakeOriginalArgString("")))
6963 file.Write(" CheckGLError();\n")
6964 file.Write("}\n")
6965 file.Write("\n")
6967 def WriteGLES2ImplementationUnitTest(self, func, file):
6968 """Writes the GLES2 Implemention unit test."""
6969 client_test = func.GetInfo('client_test')
6970 if (client_test != None and client_test != True):
6971 return;
6972 code = """
6973 TEST_F(GLES2ImplementationTest, %(name)s) {
6974 %(type)s data[%(count)d] = {0};
6975 struct Cmds {
6976 cmds::%(name)sImmediate cmd;
6977 %(type)s data[%(count)d];
6980 for (int jj = 0; jj < %(count)d; ++jj) {
6981 data[jj] = static_cast<%(type)s>(jj);
6983 Cmds expected;
6984 expected.cmd.Init(%(cmd_args)s, &data[0]);
6985 gl_->%(name)s(%(args)s, &data[0]);
6986 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
6989 cmd_arg_strings = [
6990 arg.GetValidClientSideCmdArg(func) for arg in func.GetCmdArgs()[0:-2]
6992 gl_arg_strings = [
6993 arg.GetValidClientSideArg(func) for arg in func.GetOriginalArgs()[0:-1]
6996 file.Write(code % {
6997 'name': func.name,
6998 'type': self.GetArrayType(func),
6999 'count': self.GetArrayCount(func),
7000 'args': ", ".join(gl_arg_strings),
7001 'cmd_args': ", ".join(cmd_arg_strings),
7004 def WriteImmediateCmdComputeSize(self, func, file):
7005 """Overrriden from TypeHandler."""
7006 file.Write(" static uint32_t ComputeDataSize() {\n")
7007 file.Write(" return static_cast<uint32_t>(\n")
7008 file.Write(" sizeof(%s) * %d);\n" %
7009 (self.GetArrayType(func), self.GetArrayCount(func)))
7010 file.Write(" }\n")
7011 file.Write("\n")
7012 if self.__NeedsToCalcDataCount(func):
7013 file.Write(" static uint32_t ComputeEffectiveDataSize(%s %s) {\n" %
7014 (func.GetOriginalArgs()[0].type,
7015 func.GetOriginalArgs()[0].name))
7016 file.Write(" return static_cast<uint32_t>(\n")
7017 file.Write(" sizeof(%s) * GLES2Util::Calc%sDataCount(%s));\n" %
7018 (self.GetArrayType(func), func.original_name,
7019 func.GetOriginalArgs()[0].name))
7020 file.Write(" }\n")
7021 file.Write("\n")
7022 file.Write(" static uint32_t ComputeSize() {\n")
7023 file.Write(" return static_cast<uint32_t>(\n")
7024 file.Write(
7025 " sizeof(ValueType) + ComputeDataSize());\n")
7026 file.Write(" }\n")
7027 file.Write("\n")
7029 def WriteImmediateCmdSetHeader(self, func, file):
7030 """Overrriden from TypeHandler."""
7031 file.Write(" void SetHeader() {\n")
7032 file.Write(
7033 " header.SetCmdByTotalSize<ValueType>(ComputeSize());\n")
7034 file.Write(" }\n")
7035 file.Write("\n")
7037 def WriteImmediateCmdInit(self, func, file):
7038 """Overrriden from TypeHandler."""
7039 last_arg = func.GetLastOriginalArg()
7040 file.Write(" void Init(%s, %s _%s) {\n" %
7041 (func.MakeTypedCmdArgString("_"),
7042 last_arg.type, last_arg.name))
7043 file.Write(" SetHeader();\n")
7044 args = func.GetCmdArgs()
7045 for arg in args:
7046 file.Write(" %s = _%s;\n" % (arg.name, arg.name))
7047 file.Write(" memcpy(ImmediateDataAddress(this),\n")
7048 if self.__NeedsToCalcDataCount(func):
7049 file.Write(" _%s, ComputeEffectiveDataSize(%s));" %
7050 (last_arg.name, func.GetOriginalArgs()[0].name))
7051 file.Write("""
7052 DCHECK_GE(ComputeDataSize(), ComputeEffectiveDataSize(%(arg)s));
7053 char* pointer = reinterpret_cast<char*>(ImmediateDataAddress(this)) +
7054 ComputeEffectiveDataSize(%(arg)s);
7055 memset(pointer, 0, ComputeDataSize() - ComputeEffectiveDataSize(%(arg)s));
7056 """ % { 'arg': func.GetOriginalArgs()[0].name, })
7057 else:
7058 file.Write(" _%s, ComputeDataSize());\n" % last_arg.name)
7059 file.Write(" }\n")
7060 file.Write("\n")
7062 def WriteImmediateCmdSet(self, func, file):
7063 """Overrriden from TypeHandler."""
7064 last_arg = func.GetLastOriginalArg()
7065 copy_args = func.MakeCmdArgString("_", False)
7066 file.Write(" void* Set(void* cmd%s, %s _%s) {\n" %
7067 (func.MakeTypedCmdArgString("_", True),
7068 last_arg.type, last_arg.name))
7069 file.Write(" static_cast<ValueType*>(cmd)->Init(%s, _%s);\n" %
7070 (copy_args, last_arg.name))
7071 file.Write(" const uint32_t size = ComputeSize();\n")
7072 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
7073 "cmd, size);\n")
7074 file.Write(" }\n")
7075 file.Write("\n")
7077 def WriteImmediateCmdHelper(self, func, file):
7078 """Overrriden from TypeHandler."""
7079 code = """ void %(name)s(%(typed_args)s) {
7080 const uint32_t size = gles2::cmds::%(name)s::ComputeSize();
7081 gles2::cmds::%(name)s* c =
7082 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
7083 if (c) {
7084 c->Init(%(args)s);
7089 file.Write(code % {
7090 "name": func.name,
7091 "typed_args": func.MakeTypedOriginalArgString(""),
7092 "args": func.MakeOriginalArgString(""),
7095 def WriteImmediateFormatTest(self, func, file):
7096 """Overrriden from TypeHandler."""
7097 file.Write("TEST_F(GLES2FormatTest, %s) {\n" % func.name)
7098 file.Write(" const int kSomeBaseValueToTestWith = 51;\n")
7099 file.Write(" static %s data[] = {\n" % self.GetArrayType(func))
7100 for v in range(0, self.GetArrayCount(func)):
7101 file.Write(" static_cast<%s>(kSomeBaseValueToTestWith + %d),\n" %
7102 (self.GetArrayType(func), v))
7103 file.Write(" };\n")
7104 file.Write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
7105 (func.name, func.name))
7106 file.Write(" void* next_cmd = cmd.Set(\n")
7107 file.Write(" &cmd")
7108 args = func.GetCmdArgs()
7109 for value, arg in enumerate(args):
7110 file.Write(",\n static_cast<%s>(%d)" % (arg.type, value + 11))
7111 file.Write(",\n data);\n")
7112 args = func.GetCmdArgs()
7113 file.Write(" EXPECT_EQ(static_cast<uint32_t>(cmds::%s::kCmdId),\n"
7114 % func.name)
7115 file.Write(" cmd.header.command);\n")
7116 file.Write(" EXPECT_EQ(sizeof(cmd) +\n")
7117 file.Write(" RoundSizeToMultipleOfEntries(sizeof(data)),\n")
7118 file.Write(" cmd.header.size * 4u);\n")
7119 for value, arg in enumerate(args):
7120 file.Write(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);\n" %
7121 (arg.type, value + 11, arg.name))
7122 file.Write(" CheckBytesWrittenMatchesExpectedSize(\n")
7123 file.Write(" next_cmd, sizeof(cmd) +\n")
7124 file.Write(" RoundSizeToMultipleOfEntries(sizeof(data)));\n")
7125 file.Write(" // TODO(gman): Check that data was inserted;\n")
7126 file.Write("}\n")
7127 file.Write("\n")
7130 class PUTnHandler(ArrayArgTypeHandler):
7131 """Handler for PUTn 'glUniform__v' type functions."""
7133 def __init__(self):
7134 ArrayArgTypeHandler.__init__(self)
7136 def WriteServiceUnitTest(self, func, file, *extras):
7137 """Overridden from TypeHandler."""
7138 ArrayArgTypeHandler.WriteServiceUnitTest(self, func, file, *extras)
7140 valid_test = """
7141 TEST_P(%(test_name)s, %(name)sValidArgsCountTooLarge) {
7142 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
7143 SpecializedSetup<cmds::%(name)s, 0>(true);
7144 cmds::%(name)s cmd;
7145 cmd.Init(%(args)s);
7146 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
7147 EXPECT_EQ(GL_NO_ERROR, GetGLError());
7150 gl_arg_strings = []
7151 arg_strings = []
7152 for count, arg in enumerate(func.GetOriginalArgs()):
7153 # hardcoded to match unit tests.
7154 if count == 0:
7155 # the location of the second element of the 2nd uniform.
7156 # defined in GLES2DecoderBase::SetupShaderForUniform
7157 gl_arg_strings.append("3")
7158 arg_strings.append("ProgramManager::MakeFakeLocation(1, 1)")
7159 elif count == 1:
7160 # the number of elements that gl will be called with.
7161 gl_arg_strings.append("3")
7162 # the number of elements requested in the command.
7163 arg_strings.append("5")
7164 else:
7165 gl_arg_strings.append(arg.GetValidGLArg(func))
7166 if not arg.IsConstant():
7167 arg_strings.append(arg.GetValidArg(func))
7168 extra = {
7169 'gl_args': ", ".join(gl_arg_strings),
7170 'args': ", ".join(arg_strings),
7172 self.WriteValidUnitTest(func, file, valid_test, extra, *extras)
7174 def WriteImmediateServiceUnitTest(self, func, file, *extras):
7175 """Overridden from TypeHandler."""
7176 valid_test = """
7177 TEST_P(%(test_name)s, %(name)sValidArgs) {
7178 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
7179 EXPECT_CALL(
7180 *gl_,
7181 %(gl_func_name)s(%(gl_args)s,
7182 reinterpret_cast<%(data_type)s*>(ImmediateDataAddress(&cmd))));
7183 SpecializedSetup<cmds::%(name)s, 0>(true);
7184 %(data_type)s temp[%(data_count)s * 2] = { 0, };
7185 cmd.Init(%(args)s, &temp[0]);"""
7186 if func.IsUnsafe():
7187 valid_test += """
7188 decoder_->set_unsafe_es3_apis_enabled(true);"""
7189 valid_test += """
7190 EXPECT_EQ(error::kNoError,
7191 ExecuteImmediateCmd(cmd, sizeof(temp)));
7192 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
7193 if func.IsUnsafe():
7194 valid_test += """
7195 decoder_->set_unsafe_es3_apis_enabled(false);
7196 EXPECT_EQ(error::kUnknownCommand,
7197 ExecuteImmediateCmd(cmd, sizeof(temp)));"""
7198 valid_test += """
7201 gl_arg_strings = []
7202 gl_any_strings = []
7203 arg_strings = []
7204 for arg in func.GetOriginalArgs()[0:-1]:
7205 gl_arg_strings.append(arg.GetValidGLArg(func))
7206 gl_any_strings.append("_")
7207 if not arg.IsConstant():
7208 arg_strings.append(arg.GetValidArg(func))
7209 extra = {
7210 'data_type': self.GetArrayType(func),
7211 'data_count': self.GetArrayCount(func),
7212 'args': ", ".join(arg_strings),
7213 'gl_args': ", ".join(gl_arg_strings),
7214 'gl_any_args': ", ".join(gl_any_strings),
7216 self.WriteValidUnitTest(func, file, valid_test, extra, *extras)
7218 invalid_test = """
7219 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
7220 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
7221 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_any_args)s, _)).Times(0);
7222 SpecializedSetup<cmds::%(name)s, 0>(false);
7223 %(data_type)s temp[%(data_count)s * 2] = { 0, };
7224 cmd.Init(%(all_but_last_args)s, &temp[0]);
7225 EXPECT_EQ(error::%(parse_result)s,
7226 ExecuteImmediateCmd(cmd, sizeof(temp)));%(gl_error_test)s
7229 self.WriteInvalidUnitTest(func, file, invalid_test, extra, *extras)
7231 def WriteGetDataSizeCode(self, func, file):
7232 """Overrriden from TypeHandler."""
7233 code = """ uint32_t data_size;
7234 if (!ComputeDataSize(count, sizeof(%s), %d, &data_size)) {
7235 return error::kOutOfBounds;
7238 file.Write(code % (self.GetArrayType(func), self.GetArrayCount(func)))
7239 if func.IsImmediate():
7240 file.Write(" if (data_size > immediate_data_size) {\n")
7241 file.Write(" return error::kOutOfBounds;\n")
7242 file.Write(" }\n")
7244 def WriteGLES2Implementation(self, func, file):
7245 """Overrriden from TypeHandler."""
7246 file.Write("%s GLES2Implementation::%s(%s) {\n" %
7247 (func.return_type, func.original_name,
7248 func.MakeTypedOriginalArgString("")))
7249 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
7250 func.WriteDestinationInitalizationValidation(file)
7251 self.WriteClientGLCallLog(func, file)
7252 last_pointer_name = func.GetLastOriginalPointerArg().name
7253 file.Write(""" GPU_CLIENT_LOG_CODE_BLOCK({
7254 for (GLsizei i = 0; i < count; ++i) {
7255 """)
7256 values_str = ' << ", " << '.join(
7257 ["%s[%d + i * %d]" % (
7258 last_pointer_name, ndx, self.GetArrayCount(func)) for ndx in range(
7259 0, self.GetArrayCount(func))])
7260 file.Write(' GPU_CLIENT_LOG(" " << i << ": " << %s);\n' % values_str)
7261 file.Write(" }\n });\n")
7262 for arg in func.GetOriginalArgs():
7263 arg.WriteClientSideValidationCode(file, func)
7264 file.Write(" helper_->%sImmediate(%s);\n" %
7265 (func.name, func.MakeInitString("")))
7266 file.Write(" CheckGLError();\n")
7267 file.Write("}\n")
7268 file.Write("\n")
7270 def WriteGLES2ImplementationUnitTest(self, func, file):
7271 """Writes the GLES2 Implemention unit test."""
7272 code = """
7273 TEST_F(GLES2ImplementationTest, %(name)s) {
7274 %(type)s data[%(count_param)d][%(count)d] = {{0}};
7275 struct Cmds {
7276 cmds::%(name)sImmediate cmd;
7277 %(type)s data[%(count_param)d][%(count)d];
7280 Cmds expected;
7281 for (int ii = 0; ii < %(count_param)d; ++ii) {
7282 for (int jj = 0; jj < %(count)d; ++jj) {
7283 data[ii][jj] = static_cast<%(type)s>(ii * %(count)d + jj);
7286 expected.cmd.Init(%(cmd_args)s);
7287 gl_->%(name)s(%(args)s);
7288 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
7291 cmd_arg_strings = []
7292 for arg in func.GetCmdArgs():
7293 if arg.name.endswith("_shm_id"):
7294 cmd_arg_strings.append("&data[0][0]")
7295 elif arg.name.endswith("_shm_offset"):
7296 continue
7297 else:
7298 cmd_arg_strings.append(arg.GetValidClientSideCmdArg(func))
7299 gl_arg_strings = []
7300 count_param = 0
7301 for arg in func.GetOriginalArgs():
7302 if arg.IsPointer():
7303 valid_value = "&data[0][0]"
7304 else:
7305 valid_value = arg.GetValidClientSideArg(func)
7306 gl_arg_strings.append(valid_value)
7307 if arg.name == "count":
7308 count_param = int(valid_value)
7309 file.Write(code % {
7310 'name': func.name,
7311 'type': self.GetArrayType(func),
7312 'count': self.GetArrayCount(func),
7313 'args': ", ".join(gl_arg_strings),
7314 'cmd_args': ", ".join(cmd_arg_strings),
7315 'count_param': count_param,
7318 # Test constants for invalid values, as they are not tested by the
7319 # service.
7320 constants = [
7321 arg for arg in func.GetOriginalArgs()[0:-1] if arg.IsConstant()
7323 if not constants:
7324 return
7326 code = """
7327 TEST_F(GLES2ImplementationTest, %(name)sInvalidConstantArg%(invalid_index)d) {
7328 %(type)s data[%(count_param)d][%(count)d] = {{0}};
7329 for (int ii = 0; ii < %(count_param)d; ++ii) {
7330 for (int jj = 0; jj < %(count)d; ++jj) {
7331 data[ii][jj] = static_cast<%(type)s>(ii * %(count)d + jj);
7334 gl_->%(name)s(%(args)s);
7335 EXPECT_TRUE(NoCommandsWritten());
7336 EXPECT_EQ(%(gl_error)s, CheckError());
7339 for invalid_arg in constants:
7340 gl_arg_strings = []
7341 invalid = invalid_arg.GetInvalidArg(func)
7342 for arg in func.GetOriginalArgs():
7343 if arg is invalid_arg:
7344 gl_arg_strings.append(invalid[0])
7345 elif arg.IsPointer():
7346 gl_arg_strings.append("&data[0][0]")
7347 else:
7348 valid_value = arg.GetValidClientSideArg(func)
7349 gl_arg_strings.append(valid_value)
7350 if arg.name == "count":
7351 count_param = int(valid_value)
7353 file.Write(code % {
7354 'name': func.name,
7355 'invalid_index': func.GetOriginalArgs().index(invalid_arg),
7356 'type': self.GetArrayType(func),
7357 'count': self.GetArrayCount(func),
7358 'args': ", ".join(gl_arg_strings),
7359 'gl_error': invalid[2],
7360 'count_param': count_param,
7364 def WriteImmediateCmdComputeSize(self, func, file):
7365 """Overrriden from TypeHandler."""
7366 file.Write(" static uint32_t ComputeDataSize(GLsizei count) {\n")
7367 file.Write(" return static_cast<uint32_t>(\n")
7368 file.Write(" sizeof(%s) * %d * count); // NOLINT\n" %
7369 (self.GetArrayType(func), self.GetArrayCount(func)))
7370 file.Write(" }\n")
7371 file.Write("\n")
7372 file.Write(" static uint32_t ComputeSize(GLsizei count) {\n")
7373 file.Write(" return static_cast<uint32_t>(\n")
7374 file.Write(
7375 " sizeof(ValueType) + ComputeDataSize(count)); // NOLINT\n")
7376 file.Write(" }\n")
7377 file.Write("\n")
7379 def WriteImmediateCmdSetHeader(self, func, file):
7380 """Overrriden from TypeHandler."""
7381 file.Write(" void SetHeader(GLsizei count) {\n")
7382 file.Write(
7383 " header.SetCmdByTotalSize<ValueType>(ComputeSize(count));\n")
7384 file.Write(" }\n")
7385 file.Write("\n")
7387 def WriteImmediateCmdInit(self, func, file):
7388 """Overrriden from TypeHandler."""
7389 file.Write(" void Init(%s) {\n" %
7390 func.MakeTypedInitString("_"))
7391 file.Write(" SetHeader(_count);\n")
7392 args = func.GetCmdArgs()
7393 for arg in args:
7394 file.Write(" %s = _%s;\n" % (arg.name, arg.name))
7395 file.Write(" memcpy(ImmediateDataAddress(this),\n")
7396 pointer_arg = func.GetLastOriginalPointerArg()
7397 file.Write(" _%s, ComputeDataSize(_count));\n" % pointer_arg.name)
7398 file.Write(" }\n")
7399 file.Write("\n")
7401 def WriteImmediateCmdSet(self, func, file):
7402 """Overrriden from TypeHandler."""
7403 file.Write(" void* Set(void* cmd%s) {\n" %
7404 func.MakeTypedInitString("_", True))
7405 file.Write(" static_cast<ValueType*>(cmd)->Init(%s);\n" %
7406 func.MakeInitString("_"))
7407 file.Write(" const uint32_t size = ComputeSize(_count);\n")
7408 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
7409 "cmd, size);\n")
7410 file.Write(" }\n")
7411 file.Write("\n")
7413 def WriteImmediateCmdHelper(self, func, file):
7414 """Overrriden from TypeHandler."""
7415 code = """ void %(name)s(%(typed_args)s) {
7416 const uint32_t size = gles2::cmds::%(name)s::ComputeSize(count);
7417 gles2::cmds::%(name)s* c =
7418 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
7419 if (c) {
7420 c->Init(%(args)s);
7425 file.Write(code % {
7426 "name": func.name,
7427 "typed_args": func.MakeTypedInitString(""),
7428 "args": func.MakeInitString("")
7431 def WriteImmediateFormatTest(self, func, file):
7432 """Overrriden from TypeHandler."""
7433 args = func.GetOriginalArgs()
7434 count_param = 0
7435 for arg in args:
7436 if arg.name == "count":
7437 count_param = int(arg.GetValidClientSideCmdArg(func))
7438 file.Write("TEST_F(GLES2FormatTest, %s) {\n" % func.name)
7439 file.Write(" const int kSomeBaseValueToTestWith = 51;\n")
7440 file.Write(" static %s data[] = {\n" % self.GetArrayType(func))
7441 for v in range(0, self.GetArrayCount(func) * count_param):
7442 file.Write(" static_cast<%s>(kSomeBaseValueToTestWith + %d),\n" %
7443 (self.GetArrayType(func), v))
7444 file.Write(" };\n")
7445 file.Write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
7446 (func.name, func.name))
7447 file.Write(" const GLsizei kNumElements = %d;\n" % count_param)
7448 file.Write(" const size_t kExpectedCmdSize =\n")
7449 file.Write(" sizeof(cmd) + kNumElements * sizeof(%s) * %d;\n" %
7450 (self.GetArrayType(func), self.GetArrayCount(func)))
7451 file.Write(" void* next_cmd = cmd.Set(\n")
7452 file.Write(" &cmd")
7453 for value, arg in enumerate(args):
7454 if arg.IsPointer():
7455 file.Write(",\n data")
7456 elif arg.IsConstant():
7457 continue
7458 else:
7459 file.Write(",\n static_cast<%s>(%d)" % (arg.type, value + 1))
7460 file.Write(");\n")
7461 file.Write(" EXPECT_EQ(static_cast<uint32_t>(cmds::%s::kCmdId),\n" %
7462 func.name)
7463 file.Write(" cmd.header.command);\n")
7464 file.Write(" EXPECT_EQ(kExpectedCmdSize, cmd.header.size * 4u);\n")
7465 for value, arg in enumerate(args):
7466 if arg.IsPointer() or arg.IsConstant():
7467 continue
7468 file.Write(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);\n" %
7469 (arg.type, value + 1, arg.name))
7470 file.Write(" CheckBytesWrittenMatchesExpectedSize(\n")
7471 file.Write(" next_cmd, sizeof(cmd) +\n")
7472 file.Write(" RoundSizeToMultipleOfEntries(sizeof(data)));\n")
7473 file.Write(" // TODO(gman): Check that data was inserted;\n")
7474 file.Write("}\n")
7475 file.Write("\n")
7477 class PUTSTRHandler(ArrayArgTypeHandler):
7478 """Handler for functions that pass a string array."""
7480 def __init__(self):
7481 ArrayArgTypeHandler.__init__(self)
7483 def __GetDataArg(self, func):
7484 """Return the argument that points to the 2D char arrays"""
7485 for arg in func.GetOriginalArgs():
7486 if arg.IsPointer2D():
7487 return arg
7488 return None
7490 def __GetLengthArg(self, func):
7491 """Return the argument that holds length for each char array"""
7492 for arg in func.GetOriginalArgs():
7493 if arg.IsPointer() and not arg.IsPointer2D():
7494 return arg
7495 return None
7497 def WriteGLES2Implementation(self, func, file):
7498 """Overrriden from TypeHandler."""
7499 file.Write("%s GLES2Implementation::%s(%s) {\n" %
7500 (func.return_type, func.original_name,
7501 func.MakeTypedOriginalArgString("")))
7502 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
7503 func.WriteDestinationInitalizationValidation(file)
7504 self.WriteClientGLCallLog(func, file)
7505 data_arg = self.__GetDataArg(func)
7506 length_arg = self.__GetLengthArg(func)
7507 log_code_block = """ GPU_CLIENT_LOG_CODE_BLOCK({
7508 for (GLsizei ii = 0; ii < count; ++ii) {
7509 if (%(data)s[ii]) {"""
7510 if length_arg == None:
7511 log_code_block += """
7512 GPU_CLIENT_LOG(" " << ii << ": ---\\n" << %(data)s[ii] << "\\n---");"""
7513 else:
7514 log_code_block += """
7515 if (%(length)s && %(length)s[ii] >= 0) {
7516 const std::string my_str(%(data)s[ii], %(length)s[ii]);
7517 GPU_CLIENT_LOG(" " << ii << ": ---\\n" << my_str << "\\n---");
7518 } else {
7519 GPU_CLIENT_LOG(" " << ii << ": ---\\n" << %(data)s[ii] << "\\n---");
7520 }"""
7521 log_code_block += """
7522 } else {
7523 GPU_CLIENT_LOG(" " << ii << ": NULL");
7528 file.Write(log_code_block % {
7529 'data': data_arg.name,
7530 'length': length_arg.name if not length_arg == None else ''
7532 for arg in func.GetOriginalArgs():
7533 arg.WriteClientSideValidationCode(file, func)
7535 bucket_args = []
7536 for arg in func.GetOriginalArgs():
7537 if arg.name == 'count' or arg == self.__GetLengthArg(func):
7538 continue
7539 if arg == self.__GetDataArg(func):
7540 bucket_args.append('kResultBucketId')
7541 else:
7542 bucket_args.append(arg.name)
7543 code_block = """
7544 if (!PackStringsToBucket(count, %(data)s, %(length)s, "gl%(func_name)s")) {
7545 return;
7547 helper_->%(func_name)sBucket(%(bucket_args)s);
7548 helper_->SetBucketSize(kResultBucketId, 0);
7549 CheckGLError();
7553 file.Write(code_block % {
7554 'data': data_arg.name,
7555 'length': length_arg.name if not length_arg == None else 'NULL',
7556 'func_name': func.name,
7557 'bucket_args': ', '.join(bucket_args),
7560 def WriteGLES2ImplementationUnitTest(self, func, file):
7561 """Overrriden from TypeHandler."""
7562 code = """
7563 TEST_F(GLES2ImplementationTest, %(name)s) {
7564 const uint32 kBucketId = GLES2Implementation::kResultBucketId;
7565 const char* kString1 = "happy";
7566 const char* kString2 = "ending";
7567 const size_t kString1Size = ::strlen(kString1) + 1;
7568 const size_t kString2Size = ::strlen(kString2) + 1;
7569 const size_t kHeaderSize = sizeof(GLint) * 3;
7570 const size_t kSourceSize = kHeaderSize + kString1Size + kString2Size;
7571 const size_t kPaddedHeaderSize =
7572 transfer_buffer_->RoundToAlignment(kHeaderSize);
7573 const size_t kPaddedString1Size =
7574 transfer_buffer_->RoundToAlignment(kString1Size);
7575 const size_t kPaddedString2Size =
7576 transfer_buffer_->RoundToAlignment(kString2Size);
7577 struct Cmds {
7578 cmd::SetBucketSize set_bucket_size;
7579 cmd::SetBucketData set_bucket_header;
7580 cmd::SetToken set_token1;
7581 cmd::SetBucketData set_bucket_data1;
7582 cmd::SetToken set_token2;
7583 cmd::SetBucketData set_bucket_data2;
7584 cmd::SetToken set_token3;
7585 cmds::%(name)sBucket cmd_bucket;
7586 cmd::SetBucketSize clear_bucket_size;
7589 ExpectedMemoryInfo mem0 = GetExpectedMemory(kPaddedHeaderSize);
7590 ExpectedMemoryInfo mem1 = GetExpectedMemory(kPaddedString1Size);
7591 ExpectedMemoryInfo mem2 = GetExpectedMemory(kPaddedString2Size);
7593 Cmds expected;
7594 expected.set_bucket_size.Init(kBucketId, kSourceSize);
7595 expected.set_bucket_header.Init(
7596 kBucketId, 0, kHeaderSize, mem0.id, mem0.offset);
7597 expected.set_token1.Init(GetNextToken());
7598 expected.set_bucket_data1.Init(
7599 kBucketId, kHeaderSize, kString1Size, mem1.id, mem1.offset);
7600 expected.set_token2.Init(GetNextToken());
7601 expected.set_bucket_data2.Init(
7602 kBucketId, kHeaderSize + kString1Size, kString2Size, mem2.id,
7603 mem2.offset);
7604 expected.set_token3.Init(GetNextToken());
7605 expected.cmd_bucket.Init(%(bucket_args)s);
7606 expected.clear_bucket_size.Init(kBucketId, 0);
7607 const char* kStrings[] = { kString1, kString2 };
7608 gl_->%(name)s(%(gl_args)s);
7609 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
7612 gl_args = []
7613 bucket_args = []
7614 for arg in func.GetOriginalArgs():
7615 if arg == self.__GetDataArg(func):
7616 gl_args.append('kStrings')
7617 bucket_args.append('kBucketId')
7618 elif arg == self.__GetLengthArg(func):
7619 gl_args.append('NULL')
7620 elif arg.name == 'count':
7621 gl_args.append('2')
7622 else:
7623 gl_args.append(arg.GetValidClientSideArg(func))
7624 bucket_args.append(arg.GetValidClientSideArg(func))
7625 file.Write(code % {
7626 'name': func.name,
7627 'gl_args': ", ".join(gl_args),
7628 'bucket_args': ", ".join(bucket_args),
7631 if self.__GetLengthArg(func) == None:
7632 return
7633 code = """
7634 TEST_F(GLES2ImplementationTest, %(name)sWithLength) {
7635 const uint32 kBucketId = GLES2Implementation::kResultBucketId;
7636 const char* kString = "foobar******";
7637 const size_t kStringSize = 6; // We only need "foobar".
7638 const size_t kHeaderSize = sizeof(GLint) * 2;
7639 const size_t kSourceSize = kHeaderSize + kStringSize + 1;
7640 const size_t kPaddedHeaderSize =
7641 transfer_buffer_->RoundToAlignment(kHeaderSize);
7642 const size_t kPaddedStringSize =
7643 transfer_buffer_->RoundToAlignment(kStringSize + 1);
7644 struct Cmds {
7645 cmd::SetBucketSize set_bucket_size;
7646 cmd::SetBucketData set_bucket_header;
7647 cmd::SetToken set_token1;
7648 cmd::SetBucketData set_bucket_data;
7649 cmd::SetToken set_token2;
7650 cmds::ShaderSourceBucket shader_source_bucket;
7651 cmd::SetBucketSize clear_bucket_size;
7654 ExpectedMemoryInfo mem0 = GetExpectedMemory(kPaddedHeaderSize);
7655 ExpectedMemoryInfo mem1 = GetExpectedMemory(kPaddedStringSize);
7657 Cmds expected;
7658 expected.set_bucket_size.Init(kBucketId, kSourceSize);
7659 expected.set_bucket_header.Init(
7660 kBucketId, 0, kHeaderSize, mem0.id, mem0.offset);
7661 expected.set_token1.Init(GetNextToken());
7662 expected.set_bucket_data.Init(
7663 kBucketId, kHeaderSize, kStringSize + 1, mem1.id, mem1.offset);
7664 expected.set_token2.Init(GetNextToken());
7665 expected.shader_source_bucket.Init(%(bucket_args)s);
7666 expected.clear_bucket_size.Init(kBucketId, 0);
7667 const char* kStrings[] = { kString };
7668 const GLint kLength[] = { kStringSize };
7669 gl_->%(name)s(%(gl_args)s);
7670 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
7673 gl_args = []
7674 for arg in func.GetOriginalArgs():
7675 if arg == self.__GetDataArg(func):
7676 gl_args.append('kStrings')
7677 elif arg == self.__GetLengthArg(func):
7678 gl_args.append('kLength')
7679 elif arg.name == 'count':
7680 gl_args.append('1')
7681 else:
7682 gl_args.append(arg.GetValidClientSideArg(func))
7683 file.Write(code % {
7684 'name': func.name,
7685 'gl_args': ", ".join(gl_args),
7686 'bucket_args': ", ".join(bucket_args),
7689 def WriteBucketServiceUnitTest(self, func, file, *extras):
7690 """Overrriden from TypeHandler."""
7691 cmd_args = []
7692 cmd_args_with_invalid_id = []
7693 gl_args = []
7694 for index, arg in enumerate(func.GetOriginalArgs()):
7695 if arg == self.__GetLengthArg(func):
7696 gl_args.append('_')
7697 elif arg.name == 'count':
7698 gl_args.append('1')
7699 elif arg == self.__GetDataArg(func):
7700 cmd_args.append('kBucketId')
7701 cmd_args_with_invalid_id.append('kBucketId')
7702 gl_args.append('_')
7703 elif index == 0: # Resource ID arg
7704 cmd_args.append(arg.GetValidArg(func))
7705 cmd_args_with_invalid_id.append('kInvalidClientId')
7706 gl_args.append(arg.GetValidGLArg(func))
7707 else:
7708 cmd_args.append(arg.GetValidArg(func))
7709 cmd_args_with_invalid_id.append(arg.GetValidArg(func))
7710 gl_args.append(arg.GetValidGLArg(func))
7712 test = """
7713 TEST_P(%(test_name)s, %(name)sValidArgs) {
7714 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
7715 const uint32 kBucketId = 123;
7716 const char kSource0[] = "hello";
7717 const char* kSource[] = { kSource0 };
7718 const char kValidStrEnd = 0;
7719 SetBucketAsCStrings(kBucketId, 1, kSource, 1, kValidStrEnd);
7720 cmds::%(name)s cmd;
7721 cmd.Init(%(cmd_args)s);
7722 decoder_->set_unsafe_es3_apis_enabled(true);
7723 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));"""
7724 if func.IsUnsafe():
7725 test += """
7726 decoder_->set_unsafe_es3_apis_enabled(false);
7727 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));
7729 test += """
7732 self.WriteValidUnitTest(func, file, test, {
7733 'cmd_args': ", ".join(cmd_args),
7734 'gl_args': ", ".join(gl_args),
7735 }, *extras)
7737 test = """
7738 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
7739 const uint32 kBucketId = 123;
7740 const char kSource0[] = "hello";
7741 const char* kSource[] = { kSource0 };
7742 const char kValidStrEnd = 0;
7743 decoder_->set_unsafe_es3_apis_enabled(true);
7744 cmds::%(name)s cmd;
7745 // Test no bucket.
7746 cmd.Init(%(cmd_args)s);
7747 EXPECT_NE(error::kNoError, ExecuteCmd(cmd));
7748 // Test invalid client.
7749 SetBucketAsCStrings(kBucketId, 1, kSource, 1, kValidStrEnd);
7750 cmd.Init(%(cmd_args_with_invalid_id)s);
7751 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
7752 EXPECT_EQ(GL_INVALID_VALUE, GetGLError());
7755 self.WriteValidUnitTest(func, file, test, {
7756 'cmd_args': ", ".join(cmd_args),
7757 'cmd_args_with_invalid_id': ", ".join(cmd_args_with_invalid_id),
7758 }, *extras)
7760 test = """
7761 TEST_P(%(test_name)s, %(name)sInvalidHeader) {
7762 const uint32 kBucketId = 123;
7763 const char kSource0[] = "hello";
7764 const char* kSource[] = { kSource0 };
7765 const char kValidStrEnd = 0;
7766 const GLsizei kCount = static_cast<GLsizei>(arraysize(kSource));
7767 const GLsizei kTests[] = {
7768 kCount + 1,
7770 std::numeric_limits<GLsizei>::max(),
7773 decoder_->set_unsafe_es3_apis_enabled(true);
7774 for (size_t ii = 0; ii < arraysize(kTests); ++ii) {
7775 SetBucketAsCStrings(kBucketId, 1, kSource, kTests[ii], kValidStrEnd);
7776 cmds::%(name)s cmd;
7777 cmd.Init(%(cmd_args)s);
7778 EXPECT_EQ(error::kInvalidArguments, ExecuteCmd(cmd));
7782 self.WriteValidUnitTest(func, file, test, {
7783 'cmd_args': ", ".join(cmd_args),
7784 }, *extras)
7786 test = """
7787 TEST_P(%(test_name)s, %(name)sInvalidStringEnding) {
7788 const uint32 kBucketId = 123;
7789 const char kSource0[] = "hello";
7790 const char* kSource[] = { kSource0 };
7791 const char kInvalidStrEnd = '*';
7792 SetBucketAsCStrings(kBucketId, 1, kSource, 1, kInvalidStrEnd);
7793 cmds::%(name)s cmd;
7794 cmd.Init(%(cmd_args)s);
7795 decoder_->set_unsafe_es3_apis_enabled(true);
7796 EXPECT_EQ(error::kInvalidArguments, ExecuteCmd(cmd));
7799 self.WriteValidUnitTest(func, file, test, {
7800 'cmd_args': ", ".join(cmd_args),
7801 }, *extras)
7804 class PUTXnHandler(ArrayArgTypeHandler):
7805 """Handler for glUniform?f functions."""
7806 def __init__(self):
7807 ArrayArgTypeHandler.__init__(self)
7809 def WriteHandlerImplementation(self, func, file):
7810 """Overrriden from TypeHandler."""
7811 code = """ %(type)s temp[%(count)s] = { %(values)s};"""
7812 if func.IsUnsafe():
7813 code += """
7814 gl%(name)sv(%(location)s, 1, &temp[0]);
7816 else:
7817 code += """
7818 Do%(name)sv(%(location)s, 1, &temp[0]);
7820 values = ""
7821 args = func.GetOriginalArgs()
7822 count = int(self.GetArrayCount(func))
7823 num_args = len(args)
7824 for ii in range(count):
7825 values += "%s, " % args[len(args) - count + ii].name
7827 file.Write(code % {
7828 'name': func.name,
7829 'count': self.GetArrayCount(func),
7830 'type': self.GetArrayType(func),
7831 'location': args[0].name,
7832 'args': func.MakeOriginalArgString(""),
7833 'values': values,
7836 def WriteServiceUnitTest(self, func, file, *extras):
7837 """Overrriden from TypeHandler."""
7838 valid_test = """
7839 TEST_P(%(test_name)s, %(name)sValidArgs) {
7840 EXPECT_CALL(*gl_, %(name)sv(%(local_args)s));
7841 SpecializedSetup<cmds::%(name)s, 0>(true);
7842 cmds::%(name)s cmd;
7843 cmd.Init(%(args)s);"""
7844 if func.IsUnsafe():
7845 valid_test += """
7846 decoder_->set_unsafe_es3_apis_enabled(true);"""
7847 valid_test += """
7848 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
7849 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
7850 if func.IsUnsafe():
7851 valid_test += """
7852 decoder_->set_unsafe_es3_apis_enabled(false);
7853 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));"""
7854 valid_test += """
7857 args = func.GetOriginalArgs()
7858 local_args = "%s, 1, _" % args[0].GetValidGLArg(func)
7859 self.WriteValidUnitTest(func, file, valid_test, {
7860 'name': func.name,
7861 'count': self.GetArrayCount(func),
7862 'local_args': local_args,
7863 }, *extras)
7865 invalid_test = """
7866 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
7867 EXPECT_CALL(*gl_, %(name)sv(_, _, _).Times(0);
7868 SpecializedSetup<cmds::%(name)s, 0>(false);
7869 cmds::%(name)s cmd;
7870 cmd.Init(%(args)s);
7871 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
7874 self.WriteInvalidUnitTest(func, file, invalid_test, {
7875 'name': func.GetInfo('name'),
7876 'count': self.GetArrayCount(func),
7880 class GLcharHandler(CustomHandler):
7881 """Handler for functions that pass a single string ."""
7883 def __init__(self):
7884 CustomHandler.__init__(self)
7886 def WriteImmediateCmdComputeSize(self, func, file):
7887 """Overrriden from TypeHandler."""
7888 file.Write(" static uint32_t ComputeSize(uint32_t data_size) {\n")
7889 file.Write(" return static_cast<uint32_t>(\n")
7890 file.Write(" sizeof(ValueType) + data_size); // NOLINT\n")
7891 file.Write(" }\n")
7893 def WriteImmediateCmdSetHeader(self, func, file):
7894 """Overrriden from TypeHandler."""
7895 code = """
7896 void SetHeader(uint32_t data_size) {
7897 header.SetCmdBySize<ValueType>(data_size);
7900 file.Write(code)
7902 def WriteImmediateCmdInit(self, func, file):
7903 """Overrriden from TypeHandler."""
7904 last_arg = func.GetLastOriginalArg()
7905 args = func.GetCmdArgs()
7906 set_code = []
7907 for arg in args:
7908 set_code.append(" %s = _%s;" % (arg.name, arg.name))
7909 code = """
7910 void Init(%(typed_args)s, uint32_t _data_size) {
7911 SetHeader(_data_size);
7912 %(set_code)s
7913 memcpy(ImmediateDataAddress(this), _%(last_arg)s, _data_size);
7917 file.Write(code % {
7918 "typed_args": func.MakeTypedArgString("_"),
7919 "set_code": "\n".join(set_code),
7920 "last_arg": last_arg.name
7923 def WriteImmediateCmdSet(self, func, file):
7924 """Overrriden from TypeHandler."""
7925 last_arg = func.GetLastOriginalArg()
7926 file.Write(" void* Set(void* cmd%s, uint32_t _data_size) {\n" %
7927 func.MakeTypedCmdArgString("_", True))
7928 file.Write(" static_cast<ValueType*>(cmd)->Init(%s, _data_size);\n" %
7929 func.MakeCmdArgString("_"))
7930 file.Write(" return NextImmediateCmdAddress<ValueType>("
7931 "cmd, _data_size);\n")
7932 file.Write(" }\n")
7933 file.Write("\n")
7935 def WriteImmediateCmdHelper(self, func, file):
7936 """Overrriden from TypeHandler."""
7937 code = """ void %(name)s(%(typed_args)s) {
7938 const uint32_t data_size = strlen(name);
7939 gles2::cmds::%(name)s* c =
7940 GetImmediateCmdSpace<gles2::cmds::%(name)s>(data_size);
7941 if (c) {
7942 c->Init(%(args)s, data_size);
7947 file.Write(code % {
7948 "name": func.name,
7949 "typed_args": func.MakeTypedOriginalArgString(""),
7950 "args": func.MakeOriginalArgString(""),
7954 def WriteImmediateFormatTest(self, func, file):
7955 """Overrriden from TypeHandler."""
7956 init_code = []
7957 check_code = []
7958 all_but_last_arg = func.GetCmdArgs()[:-1]
7959 for value, arg in enumerate(all_but_last_arg):
7960 init_code.append(" static_cast<%s>(%d)," % (arg.type, value + 11))
7961 for value, arg in enumerate(all_but_last_arg):
7962 check_code.append(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);" %
7963 (arg.type, value + 11, arg.name))
7964 code = """
7965 TEST_F(GLES2FormatTest, %(func_name)s) {
7966 cmds::%(func_name)s& cmd = *GetBufferAs<cmds::%(func_name)s>();
7967 static const char* const test_str = \"test string\";
7968 void* next_cmd = cmd.Set(
7969 &cmd,
7970 %(init_code)s
7971 test_str,
7972 strlen(test_str));
7973 EXPECT_EQ(static_cast<uint32_t>(cmds::%(func_name)s::kCmdId),
7974 cmd.header.command);
7975 EXPECT_EQ(sizeof(cmd) +
7976 RoundSizeToMultipleOfEntries(strlen(test_str)),
7977 cmd.header.size * 4u);
7978 EXPECT_EQ(static_cast<char*>(next_cmd),
7979 reinterpret_cast<char*>(&cmd) + sizeof(cmd) +
7980 RoundSizeToMultipleOfEntries(strlen(test_str)));
7981 %(check_code)s
7982 EXPECT_EQ(static_cast<uint32_t>(strlen(test_str)), cmd.data_size);
7983 EXPECT_EQ(0, memcmp(test_str, ImmediateDataAddress(&cmd), strlen(test_str)));
7984 CheckBytesWritten(
7985 next_cmd,
7986 sizeof(cmd) + RoundSizeToMultipleOfEntries(strlen(test_str)),
7987 sizeof(cmd) + strlen(test_str));
7991 file.Write(code % {
7992 'func_name': func.name,
7993 'init_code': "\n".join(init_code),
7994 'check_code': "\n".join(check_code),
7998 class GLcharNHandler(CustomHandler):
7999 """Handler for functions that pass a single string with an optional len."""
8001 def __init__(self):
8002 CustomHandler.__init__(self)
8004 def InitFunction(self, func):
8005 """Overrriden from TypeHandler."""
8006 func.cmd_args = []
8007 func.AddCmdArg(Argument('bucket_id', 'GLuint'))
8009 def NeedsDataTransferFunction(self, func):
8010 """Overriden from TypeHandler."""
8011 return False
8013 def AddBucketFunction(self, generator, func):
8014 """Overrriden from TypeHandler."""
8015 pass
8017 def WriteServiceImplementation(self, func, file):
8018 """Overrriden from TypeHandler."""
8019 self.WriteServiceHandlerFunctionHeader(func, file)
8020 file.Write("""
8021 GLuint bucket_id = static_cast<GLuint>(c.%(bucket_id)s);
8022 Bucket* bucket = GetBucket(bucket_id);
8023 if (!bucket || bucket->size() == 0) {
8024 return error::kInvalidArguments;
8026 std::string str;
8027 if (!bucket->GetAsString(&str)) {
8028 return error::kInvalidArguments;
8030 %(gl_func_name)s(0, str.c_str());
8031 return error::kNoError;
8034 """ % {
8035 'name': func.name,
8036 'gl_func_name': func.GetGLFunctionName(),
8037 'bucket_id': func.cmd_args[0].name,
8041 class IsHandler(TypeHandler):
8042 """Handler for glIs____ type and glGetError functions."""
8044 def __init__(self):
8045 TypeHandler.__init__(self)
8047 def InitFunction(self, func):
8048 """Overrriden from TypeHandler."""
8049 func.AddCmdArg(Argument("result_shm_id", 'uint32_t'))
8050 func.AddCmdArg(Argument("result_shm_offset", 'uint32_t'))
8051 if func.GetInfo('result') == None:
8052 func.AddInfo('result', ['uint32_t'])
8054 def WriteServiceUnitTest(self, func, file, *extras):
8055 """Overrriden from TypeHandler."""
8056 valid_test = """
8057 TEST_P(%(test_name)s, %(name)sValidArgs) {
8058 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
8059 SpecializedSetup<cmds::%(name)s, 0>(true);
8060 cmds::%(name)s cmd;
8061 cmd.Init(%(args)s%(comma)sshared_memory_id_, shared_memory_offset_);"""
8062 if func.IsUnsafe():
8063 valid_test += """
8064 decoder_->set_unsafe_es3_apis_enabled(true);"""
8065 valid_test += """
8066 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
8067 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
8068 if func.IsUnsafe():
8069 valid_test += """
8070 decoder_->set_unsafe_es3_apis_enabled(false);
8071 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));"""
8072 valid_test += """
8075 comma = ""
8076 if len(func.GetOriginalArgs()):
8077 comma =", "
8078 self.WriteValidUnitTest(func, file, valid_test, {
8079 'comma': comma,
8080 }, *extras)
8082 invalid_test = """
8083 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
8084 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
8085 SpecializedSetup<cmds::%(name)s, 0>(false);
8086 cmds::%(name)s cmd;
8087 cmd.Init(%(args)s%(comma)sshared_memory_id_, shared_memory_offset_);
8088 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
8091 self.WriteInvalidUnitTest(func, file, invalid_test, {
8092 'comma': comma,
8093 }, *extras)
8095 invalid_test = """
8096 TEST_P(%(test_name)s, %(name)sInvalidArgsBadSharedMemoryId) {
8097 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
8098 SpecializedSetup<cmds::%(name)s, 0>(false);"""
8099 if func.IsUnsafe():
8100 invalid_test += """
8101 decoder_->set_unsafe_es3_apis_enabled(true);"""
8102 invalid_test += """
8103 cmds::%(name)s cmd;
8104 cmd.Init(%(args)s%(comma)skInvalidSharedMemoryId, shared_memory_offset_);
8105 EXPECT_EQ(error::kOutOfBounds, ExecuteCmd(cmd));
8106 cmd.Init(%(args)s%(comma)sshared_memory_id_, kInvalidSharedMemoryOffset);
8107 EXPECT_EQ(error::kOutOfBounds, ExecuteCmd(cmd));"""
8108 if func.IsUnsafe():
8109 invalid_test += """
8110 decoder_->set_unsafe_es3_apis_enabled(true);"""
8111 invalid_test += """
8114 self.WriteValidUnitTest(func, file, invalid_test, {
8115 'comma': comma,
8116 }, *extras)
8118 def WriteServiceImplementation(self, func, file):
8119 """Overrriden from TypeHandler."""
8120 self.WriteServiceHandlerFunctionHeader(func, file)
8121 self.WriteHandlerExtensionCheck(func, file)
8122 args = func.GetOriginalArgs()
8123 for arg in args:
8124 arg.WriteGetCode(file)
8126 code = """ typedef cmds::%(func_name)s::Result Result;
8127 Result* result_dst = GetSharedMemoryAs<Result*>(
8128 c.result_shm_id, c.result_shm_offset, sizeof(*result_dst));
8129 if (!result_dst) {
8130 return error::kOutOfBounds;
8133 file.Write(code % {'func_name': func.name})
8134 func.WriteHandlerValidation(file)
8135 if func.IsUnsafe():
8136 assert func.GetInfo('id_mapping')
8137 assert len(func.GetInfo('id_mapping')) == 1
8138 assert len(args) == 1
8139 id_type = func.GetInfo('id_mapping')[0]
8140 file.Write(" %s service_%s = 0;\n" % (args[0].type, id_type.lower()))
8141 file.Write(" *result_dst = group_->Get%sServiceId(%s, &service_%s);\n" %
8142 (id_type, id_type.lower(), id_type.lower()))
8143 else:
8144 file.Write(" *result_dst = %s(%s);\n" %
8145 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
8146 file.Write(" return error::kNoError;\n")
8147 file.Write("}\n")
8148 file.Write("\n")
8150 def WriteGLES2Implementation(self, func, file):
8151 """Overrriden from TypeHandler."""
8152 impl_func = func.GetInfo('impl_func')
8153 if impl_func == None or impl_func == True:
8154 error_value = func.GetInfo("error_value") or "GL_FALSE"
8155 file.Write("%s GLES2Implementation::%s(%s) {\n" %
8156 (func.return_type, func.original_name,
8157 func.MakeTypedOriginalArgString("")))
8158 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
8159 self.WriteTraceEvent(func, file)
8160 func.WriteDestinationInitalizationValidation(file)
8161 self.WriteClientGLCallLog(func, file)
8162 file.Write(" typedef cmds::%s::Result Result;\n" % func.name)
8163 file.Write(" Result* result = GetResultAs<Result*>();\n")
8164 file.Write(" if (!result) {\n")
8165 file.Write(" return %s;\n" % error_value)
8166 file.Write(" }\n")
8167 file.Write(" *result = 0;\n")
8168 assert len(func.GetOriginalArgs()) == 1
8169 id_arg = func.GetOriginalArgs()[0]
8170 if id_arg.type == 'GLsync':
8171 arg_string = "ToGLuint(%s)" % func.MakeOriginalArgString("")
8172 else:
8173 arg_string = func.MakeOriginalArgString("")
8174 file.Write(
8175 " helper_->%s(%s, GetResultShmId(), GetResultShmOffset());\n" %
8176 (func.name, arg_string))
8177 file.Write(" WaitForCmd();\n")
8178 file.Write(" %s result_value = *result" % func.return_type)
8179 if func.return_type == "GLboolean":
8180 file.Write(" != 0")
8181 file.Write(';\n GPU_CLIENT_LOG("returned " << result_value);\n')
8182 file.Write(" CheckGLError();\n")
8183 file.Write(" return result_value;\n")
8184 file.Write("}\n")
8185 file.Write("\n")
8187 def WriteGLES2ImplementationUnitTest(self, func, file):
8188 """Overrriden from TypeHandler."""
8189 client_test = func.GetInfo('client_test')
8190 if client_test == None or client_test == True:
8191 code = """
8192 TEST_F(GLES2ImplementationTest, %(name)s) {
8193 struct Cmds {
8194 cmds::%(name)s cmd;
8197 Cmds expected;
8198 ExpectedMemoryInfo result1 =
8199 GetExpectedResultMemory(sizeof(cmds::%(name)s::Result));
8200 expected.cmd.Init(%(cmd_id_value)s, result1.id, result1.offset);
8202 EXPECT_CALL(*command_buffer(), OnFlush())
8203 .WillOnce(SetMemory(result1.ptr, uint32_t(GL_TRUE)))
8204 .RetiresOnSaturation();
8206 GLboolean result = gl_->%(name)s(%(gl_id_value)s);
8207 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
8208 EXPECT_TRUE(result);
8211 args = func.GetOriginalArgs()
8212 assert len(args) == 1
8213 file.Write(code % {
8214 'name': func.name,
8215 'cmd_id_value': args[0].GetValidClientSideCmdArg(func),
8216 'gl_id_value': args[0].GetValidClientSideArg(func) })
8219 class STRnHandler(TypeHandler):
8220 """Handler for GetProgramInfoLog, GetShaderInfoLog, GetShaderSource, and
8221 GetTranslatedShaderSourceANGLE."""
8223 def __init__(self):
8224 TypeHandler.__init__(self)
8226 def InitFunction(self, func):
8227 """Overrriden from TypeHandler."""
8228 # remove all but the first cmd args.
8229 cmd_args = func.GetCmdArgs()
8230 func.ClearCmdArgs()
8231 func.AddCmdArg(cmd_args[0])
8232 # add on a bucket id.
8233 func.AddCmdArg(Argument('bucket_id', 'uint32_t'))
8235 def WriteGLES2Implementation(self, func, file):
8236 """Overrriden from TypeHandler."""
8237 code_1 = """%(return_type)s GLES2Implementation::%(func_name)s(%(args)s) {
8238 GPU_CLIENT_SINGLE_THREAD_CHECK();
8240 code_2 = """ GPU_CLIENT_LOG("[" << GetLogPrefix()
8241 << "] gl%(func_name)s" << "("
8242 << %(arg0)s << ", "
8243 << %(arg1)s << ", "
8244 << static_cast<void*>(%(arg2)s) << ", "
8245 << static_cast<void*>(%(arg3)s) << ")");
8246 helper_->SetBucketSize(kResultBucketId, 0);
8247 helper_->%(func_name)s(%(id_name)s, kResultBucketId);
8248 std::string str;
8249 GLsizei max_size = 0;
8250 if (GetBucketAsString(kResultBucketId, &str)) {
8251 if (bufsize > 0) {
8252 max_size =
8253 std::min(static_cast<size_t>(%(bufsize_name)s) - 1, str.size());
8254 memcpy(%(dest_name)s, str.c_str(), max_size);
8255 %(dest_name)s[max_size] = '\\0';
8256 GPU_CLIENT_LOG("------\\n" << %(dest_name)s << "\\n------");
8259 if (%(length_name)s != NULL) {
8260 *%(length_name)s = max_size;
8262 CheckGLError();
8265 args = func.GetOriginalArgs()
8266 str_args = {
8267 'return_type': func.return_type,
8268 'func_name': func.original_name,
8269 'args': func.MakeTypedOriginalArgString(""),
8270 'id_name': args[0].name,
8271 'bufsize_name': args[1].name,
8272 'length_name': args[2].name,
8273 'dest_name': args[3].name,
8274 'arg0': args[0].name,
8275 'arg1': args[1].name,
8276 'arg2': args[2].name,
8277 'arg3': args[3].name,
8279 file.Write(code_1 % str_args)
8280 func.WriteDestinationInitalizationValidation(file)
8281 file.Write(code_2 % str_args)
8283 def WriteServiceUnitTest(self, func, file, *extras):
8284 """Overrriden from TypeHandler."""
8285 valid_test = """
8286 TEST_P(%(test_name)s, %(name)sValidArgs) {
8287 const char* kInfo = "hello";
8288 const uint32_t kBucketId = 123;
8289 SpecializedSetup<cmds::%(name)s, 0>(true);
8290 %(expect_len_code)s
8291 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s))
8292 .WillOnce(DoAll(SetArgumentPointee<2>(strlen(kInfo)),
8293 SetArrayArgument<3>(kInfo, kInfo + strlen(kInfo) + 1)));
8294 cmds::%(name)s cmd;
8295 cmd.Init(%(args)s);
8296 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
8297 CommonDecoder::Bucket* bucket = decoder_->GetBucket(kBucketId);
8298 ASSERT_TRUE(bucket != NULL);
8299 EXPECT_EQ(strlen(kInfo) + 1, bucket->size());
8300 EXPECT_EQ(0, memcmp(bucket->GetData(0, bucket->size()), kInfo,
8301 bucket->size()));
8302 EXPECT_EQ(GL_NO_ERROR, GetGLError());
8305 args = func.GetOriginalArgs()
8306 id_name = args[0].GetValidGLArg(func)
8307 get_len_func = func.GetInfo('get_len_func')
8308 get_len_enum = func.GetInfo('get_len_enum')
8309 sub = {
8310 'id_name': id_name,
8311 'get_len_func': get_len_func,
8312 'get_len_enum': get_len_enum,
8313 'gl_args': '%s, strlen(kInfo) + 1, _, _' %
8314 args[0].GetValidGLArg(func),
8315 'args': '%s, kBucketId' % args[0].GetValidArg(func),
8316 'expect_len_code': '',
8318 if get_len_func and get_len_func[0:2] == 'gl':
8319 sub['expect_len_code'] = (
8320 " EXPECT_CALL(*gl_, %s(%s, %s, _))\n"
8321 " .WillOnce(SetArgumentPointee<2>(strlen(kInfo) + 1));") % (
8322 get_len_func[2:], id_name, get_len_enum)
8323 self.WriteValidUnitTest(func, file, valid_test, sub, *extras)
8325 invalid_test = """
8326 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
8327 const uint32_t kBucketId = 123;
8328 EXPECT_CALL(*gl_, %(gl_func_name)s(_, _, _, _))
8329 .Times(0);
8330 cmds::%(name)s cmd;
8331 cmd.Init(kInvalidClientId, kBucketId);
8332 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
8333 EXPECT_EQ(GL_INVALID_VALUE, GetGLError());
8336 self.WriteValidUnitTest(func, file, invalid_test, *extras)
8338 def WriteServiceImplementation(self, func, file):
8339 """Overrriden from TypeHandler."""
8340 pass
8342 class NamedType(object):
8343 """A class that represents a type of an argument in a client function.
8345 A type of an argument that is to be passed through in the command buffer
8346 command. Currently used only for the arguments that are specificly named in
8347 the 'cmd_buffer_functions.txt' file, mostly enums.
8350 def __init__(self, info):
8351 assert not 'is_complete' in info or info['is_complete'] == True
8352 self.info = info
8353 self.valid = info['valid']
8354 if 'invalid' in info:
8355 self.invalid = info['invalid']
8356 else:
8357 self.invalid = []
8358 if 'valid_es3' in info:
8359 self.valid_es3 = info['valid_es3']
8360 else:
8361 self.valid_es3 = []
8362 if 'deprecated_es3' in info:
8363 self.deprecated_es3 = info['deprecated_es3']
8364 else:
8365 self.deprecated_es3 = []
8367 def GetType(self):
8368 return self.info['type']
8370 def GetInvalidValues(self):
8371 return self.invalid
8373 def GetValidValues(self):
8374 return self.valid
8376 def GetValidValuesES3(self):
8377 return self.valid_es3
8379 def GetDeprecatedValuesES3(self):
8380 return self.deprecated_es3
8382 def IsConstant(self):
8383 if not 'is_complete' in self.info:
8384 return False
8386 return len(self.GetValidValues()) == 1
8388 def GetConstantValue(self):
8389 return self.GetValidValues()[0]
8391 class Argument(object):
8392 """A class that represents a function argument."""
8394 cmd_type_map_ = {
8395 'GLenum': 'uint32_t',
8396 'GLint': 'int32_t',
8397 'GLintptr': 'int32_t',
8398 'GLsizei': 'int32_t',
8399 'GLsizeiptr': 'int32_t',
8400 'GLfloat': 'float',
8401 'GLclampf': 'float',
8403 need_validation_ = ['GLsizei*', 'GLboolean*', 'GLenum*', 'GLint*']
8405 def __init__(self, name, type):
8406 self.name = name
8407 self.optional = type.endswith("Optional*")
8408 if self.optional:
8409 type = type[:-9] + "*"
8410 self.type = type
8412 if type in self.cmd_type_map_:
8413 self.cmd_type = self.cmd_type_map_[type]
8414 else:
8415 self.cmd_type = 'uint32_t'
8417 def IsPointer(self):
8418 """Returns true if argument is a pointer."""
8419 return False
8421 def IsPointer2D(self):
8422 """Returns true if argument is a 2D pointer."""
8423 return False
8425 def IsConstant(self):
8426 """Returns true if the argument has only one valid value."""
8427 return False
8429 def AddCmdArgs(self, args):
8430 """Adds command arguments for this argument to the given list."""
8431 if not self.IsConstant():
8432 return args.append(self)
8434 def AddInitArgs(self, args):
8435 """Adds init arguments for this argument to the given list."""
8436 if not self.IsConstant():
8437 return args.append(self)
8439 def GetValidArg(self, func):
8440 """Gets a valid value for this argument."""
8441 valid_arg = func.GetValidArg(self)
8442 if valid_arg != None:
8443 return valid_arg
8445 index = func.GetOriginalArgs().index(self)
8446 return str(index + 1)
8448 def GetValidClientSideArg(self, func):
8449 """Gets a valid value for this argument."""
8450 valid_arg = func.GetValidArg(self)
8451 if valid_arg != None:
8452 return valid_arg
8454 if self.IsPointer():
8455 return 'nullptr'
8456 index = func.GetOriginalArgs().index(self)
8457 if self.type == 'GLsync':
8458 return ("reinterpret_cast<GLsync>(%d)" % (index + 1))
8459 return str(index + 1)
8461 def GetValidClientSideCmdArg(self, func):
8462 """Gets a valid value for this argument."""
8463 valid_arg = func.GetValidArg(self)
8464 if valid_arg != None:
8465 return valid_arg
8466 try:
8467 index = func.GetOriginalArgs().index(self)
8468 return str(index + 1)
8469 except ValueError:
8470 pass
8471 index = func.GetCmdArgs().index(self)
8472 return str(index + 1)
8474 def GetValidGLArg(self, func):
8475 """Gets a valid GL value for this argument."""
8476 value = self.GetValidArg(func)
8477 if self.type == 'GLsync':
8478 return ("reinterpret_cast<GLsync>(%s)" % value)
8479 return value
8481 def GetValidNonCachedClientSideArg(self, func):
8482 """Returns a valid value for this argument in a GL call.
8483 Using the value will produce a command buffer service invocation.
8484 Returns None if there is no such value."""
8485 value = '123'
8486 if self.type == 'GLsync':
8487 return ("reinterpret_cast<GLsync>(%s)" % value)
8488 return value
8490 def GetValidNonCachedClientSideCmdArg(self, func):
8491 """Returns a valid value for this argument in a command buffer command.
8492 Calling the GL function with the value returned by
8493 GetValidNonCachedClientSideArg will result in a command buffer command
8494 that contains the value returned by this function. """
8495 return '123'
8497 def GetNumInvalidValues(self, func):
8498 """returns the number of invalid values to be tested."""
8499 return 0
8501 def GetInvalidArg(self, index):
8502 """returns an invalid value and expected parse result by index."""
8503 return ("---ERROR0---", "---ERROR2---", None)
8505 def GetLogArg(self):
8506 """Get argument appropriate for LOG macro."""
8507 if self.type == 'GLboolean':
8508 return 'GLES2Util::GetStringBool(%s)' % self.name
8509 if self.type == 'GLenum':
8510 return 'GLES2Util::GetStringEnum(%s)' % self.name
8511 return self.name
8513 def WriteGetCode(self, file):
8514 """Writes the code to get an argument from a command structure."""
8515 if self.type == 'GLsync':
8516 my_type = 'GLuint'
8517 else:
8518 my_type = self.type
8519 file.Write(" %s %s = static_cast<%s>(c.%s);\n" %
8520 (my_type, self.name, my_type, self.name))
8522 def WriteValidationCode(self, file, func):
8523 """Writes the validation code for an argument."""
8524 pass
8526 def WriteClientSideValidationCode(self, file, func):
8527 """Writes the validation code for an argument."""
8528 pass
8530 def WriteDestinationInitalizationValidation(self, file, func):
8531 """Writes the client side destintion initialization validation."""
8532 pass
8534 def WriteDestinationInitalizationValidatationIfNeeded(self, file, func):
8535 """Writes the client side destintion initialization validation if needed."""
8536 parts = self.type.split(" ")
8537 if len(parts) > 1:
8538 return
8539 if parts[0] in self.need_validation_:
8540 file.Write(
8541 " GPU_CLIENT_VALIDATE_DESTINATION_%sINITALIZATION(%s, %s);\n" %
8542 ("OPTIONAL_" if self.optional else "", self.type[:-1], self.name))
8545 def WriteGetAddress(self, file):
8546 """Writes the code to get the address this argument refers to."""
8547 pass
8549 def GetImmediateVersion(self):
8550 """Gets the immediate version of this argument."""
8551 return self
8553 def GetBucketVersion(self):
8554 """Gets the bucket version of this argument."""
8555 return self
8558 class BoolArgument(Argument):
8559 """class for GLboolean"""
8561 def __init__(self, name, type):
8562 Argument.__init__(self, name, 'GLboolean')
8564 def GetValidArg(self, func):
8565 """Gets a valid value for this argument."""
8566 return 'true'
8568 def GetValidClientSideArg(self, func):
8569 """Gets a valid value for this argument."""
8570 return 'true'
8572 def GetValidClientSideCmdArg(self, func):
8573 """Gets a valid value for this argument."""
8574 return 'true'
8576 def GetValidGLArg(self, func):
8577 """Gets a valid GL value for this argument."""
8578 return 'true'
8581 class UniformLocationArgument(Argument):
8582 """class for uniform locations."""
8584 def __init__(self, name):
8585 Argument.__init__(self, name, "GLint")
8587 def WriteGetCode(self, file):
8588 """Writes the code to get an argument from a command structure."""
8589 code = """ %s %s = static_cast<%s>(c.%s);
8591 file.Write(code % (self.type, self.name, self.type, self.name))
8593 class DataSizeArgument(Argument):
8594 """class for data_size which Bucket commands do not need."""
8596 def __init__(self, name):
8597 Argument.__init__(self, name, "uint32_t")
8599 def GetBucketVersion(self):
8600 return None
8603 class SizeArgument(Argument):
8604 """class for GLsizei and GLsizeiptr."""
8606 def __init__(self, name, type):
8607 Argument.__init__(self, name, type)
8609 def GetNumInvalidValues(self, func):
8610 """overridden from Argument."""
8611 if func.IsImmediate():
8612 return 0
8613 return 1
8615 def GetInvalidArg(self, index):
8616 """overridden from Argument."""
8617 return ("-1", "kNoError", "GL_INVALID_VALUE")
8619 def WriteValidationCode(self, file, func):
8620 """overridden from Argument."""
8621 if func.IsUnsafe():
8622 return
8623 code = """ if (%(var_name)s < 0) {
8624 LOCAL_SET_GL_ERROR(GL_INVALID_VALUE, "gl%(func_name)s", "%(var_name)s < 0");
8625 return error::kNoError;
8628 file.Write(code % {
8629 "var_name": self.name,
8630 "func_name": func.original_name,
8633 def WriteClientSideValidationCode(self, file, func):
8634 """overridden from Argument."""
8635 code = """ if (%(var_name)s < 0) {
8636 SetGLError(GL_INVALID_VALUE, "gl%(func_name)s", "%(var_name)s < 0");
8637 return;
8640 file.Write(code % {
8641 "var_name": self.name,
8642 "func_name": func.original_name,
8646 class SizeNotNegativeArgument(SizeArgument):
8647 """class for GLsizeiNotNegative. It's NEVER allowed to be negative"""
8649 def __init__(self, name, type, gl_type):
8650 SizeArgument.__init__(self, name, gl_type)
8652 def GetInvalidArg(self, index):
8653 """overridden from SizeArgument."""
8654 return ("-1", "kOutOfBounds", "GL_NO_ERROR")
8656 def WriteValidationCode(self, file, func):
8657 """overridden from SizeArgument."""
8658 pass
8661 class EnumBaseArgument(Argument):
8662 """Base class for EnumArgument, IntArgument, BitfieldArgument, and
8663 ValidatedBoolArgument."""
8665 def __init__(self, name, gl_type, type, gl_error):
8666 Argument.__init__(self, name, gl_type)
8668 self.local_type = type
8669 self.gl_error = gl_error
8670 name = type[len(gl_type):]
8671 self.type_name = name
8672 self.named_type = NamedType(_NAMED_TYPE_INFO[name])
8674 def IsConstant(self):
8675 return self.named_type.IsConstant()
8677 def GetConstantValue(self):
8678 return self.named_type.GetConstantValue()
8680 def WriteValidationCode(self, file, func):
8681 if func.IsUnsafe():
8682 return
8683 if self.named_type.IsConstant():
8684 return
8685 file.Write(" if (!validators_->%s.IsValid(%s)) {\n" %
8686 (ToUnderscore(self.type_name), self.name))
8687 if self.gl_error == "GL_INVALID_ENUM":
8688 file.Write(
8689 " LOCAL_SET_GL_ERROR_INVALID_ENUM(\"gl%s\", %s, \"%s\");\n" %
8690 (func.original_name, self.name, self.name))
8691 else:
8692 file.Write(
8693 " LOCAL_SET_GL_ERROR(%s, \"gl%s\", \"%s %s\");\n" %
8694 (self.gl_error, func.original_name, self.name, self.gl_error))
8695 file.Write(" return error::kNoError;\n")
8696 file.Write(" }\n")
8698 def WriteClientSideValidationCode(self, file, func):
8699 if not self.named_type.IsConstant():
8700 return
8701 file.Write(" if (%s != %s) {" % (self.name,
8702 self.GetConstantValue()))
8703 file.Write(
8704 " SetGLError(%s, \"gl%s\", \"%s %s\");\n" %
8705 (self.gl_error, func.original_name, self.name, self.gl_error))
8706 if func.return_type == "void":
8707 file.Write(" return;\n")
8708 else:
8709 file.Write(" return %s;\n" % func.GetErrorReturnString())
8710 file.Write(" }\n")
8712 def GetValidArg(self, func):
8713 valid_arg = func.GetValidArg(self)
8714 if valid_arg != None:
8715 return valid_arg
8716 valid = self.named_type.GetValidValues()
8717 if valid:
8718 num_valid = len(valid)
8719 return valid[0]
8721 index = func.GetOriginalArgs().index(self)
8722 return str(index + 1)
8724 def GetValidClientSideArg(self, func):
8725 """Gets a valid value for this argument."""
8726 return self.GetValidArg(func)
8728 def GetValidClientSideCmdArg(self, func):
8729 """Gets a valid value for this argument."""
8730 valid_arg = func.GetValidArg(self)
8731 if valid_arg != None:
8732 return valid_arg
8734 valid = self.named_type.GetValidValues()
8735 if valid:
8736 num_valid = len(valid)
8737 return valid[0]
8739 try:
8740 index = func.GetOriginalArgs().index(self)
8741 return str(index + 1)
8742 except ValueError:
8743 pass
8744 index = func.GetCmdArgs().index(self)
8745 return str(index + 1)
8747 def GetValidGLArg(self, func):
8748 """Gets a valid value for this argument."""
8749 return self.GetValidArg(func)
8751 def GetNumInvalidValues(self, func):
8752 """returns the number of invalid values to be tested."""
8753 return len(self.named_type.GetInvalidValues())
8755 def GetInvalidArg(self, index):
8756 """returns an invalid value by index."""
8757 invalid = self.named_type.GetInvalidValues()
8758 if invalid:
8759 num_invalid = len(invalid)
8760 if index >= num_invalid:
8761 index = num_invalid - 1
8762 return (invalid[index], "kNoError", self.gl_error)
8763 return ("---ERROR1---", "kNoError", self.gl_error)
8766 class EnumArgument(EnumBaseArgument):
8767 """A class that represents a GLenum argument"""
8769 def __init__(self, name, type):
8770 EnumBaseArgument.__init__(self, name, "GLenum", type, "GL_INVALID_ENUM")
8772 def GetLogArg(self):
8773 """Overridden from Argument."""
8774 return ("GLES2Util::GetString%s(%s)" %
8775 (self.type_name, self.name))
8778 class IntArgument(EnumBaseArgument):
8779 """A class for a GLint argument that can only accept specific values.
8781 For example glTexImage2D takes a GLint for its internalformat
8782 argument instead of a GLenum.
8785 def __init__(self, name, type):
8786 EnumBaseArgument.__init__(self, name, "GLint", type, "GL_INVALID_VALUE")
8789 class ValidatedBoolArgument(EnumBaseArgument):
8790 """A class for a GLboolean argument that can only accept specific values.
8792 For example glUniformMatrix takes a GLboolean for it's transpose but it
8793 must be false.
8796 def __init__(self, name, type):
8797 EnumBaseArgument.__init__(self, name, "GLboolean", type, "GL_INVALID_VALUE")
8799 def GetLogArg(self):
8800 """Overridden from Argument."""
8801 return 'GLES2Util::GetStringBool(%s)' % self.name
8804 class BitFieldArgument(EnumBaseArgument):
8805 """A class for a GLbitfield argument that can only accept specific values.
8807 For example glFenceSync takes a GLbitfield for its flags argument bit it
8808 must be 0.
8811 def __init__(self, name, type):
8812 EnumBaseArgument.__init__(self, name, "GLbitfield", type,
8813 "GL_INVALID_VALUE")
8816 class ImmediatePointerArgument(Argument):
8817 """A class that represents an immediate argument to a function.
8819 An immediate argument is one where the data follows the command.
8822 def __init__(self, name, type):
8823 Argument.__init__(self, name, type)
8825 def IsPointer(self):
8826 return True
8828 def GetPointedType(self):
8829 match = re.match('(const\s+)?(?P<element_type>[\w]+)\s*\*', self.type)
8830 assert match
8831 return match.groupdict()['element_type']
8833 def AddCmdArgs(self, args):
8834 """Overridden from Argument."""
8835 pass
8837 def WriteGetCode(self, file):
8838 """Overridden from Argument."""
8839 file.Write(
8840 " %s %s = GetImmediateDataAs<%s>(\n" %
8841 (self.type, self.name, self.type))
8842 file.Write(" c, data_size, immediate_data_size);\n")
8844 def WriteValidationCode(self, file, func):
8845 """Overridden from Argument."""
8846 if self.optional:
8847 return
8848 file.Write(" if (%s == NULL) {\n" % self.name)
8849 file.Write(" return error::kOutOfBounds;\n")
8850 file.Write(" }\n")
8852 def GetImmediateVersion(self):
8853 """Overridden from Argument."""
8854 return None
8856 def WriteDestinationInitalizationValidation(self, file, func):
8857 """Overridden from Argument."""
8858 self.WriteDestinationInitalizationValidatationIfNeeded(file, func)
8860 def GetLogArg(self):
8861 """Overridden from Argument."""
8862 return "static_cast<const void*>(%s)" % self.name
8865 class PointerArgument(Argument):
8866 """A class that represents a pointer argument to a function."""
8868 def __init__(self, name, type):
8869 Argument.__init__(self, name, type)
8871 def IsPointer(self):
8872 """Overridden from Argument."""
8873 return True
8875 def IsPointer2D(self):
8876 """Overridden from Argument."""
8877 return self.type.count('*') == 2
8879 def GetPointedType(self):
8880 match = re.match('(const\s+)?(?P<element_type>[\w]+)\s*\*', self.type)
8881 assert match
8882 return match.groupdict()['element_type']
8884 def GetValidArg(self, func):
8885 """Overridden from Argument."""
8886 return "shared_memory_id_, shared_memory_offset_"
8888 def GetValidGLArg(self, func):
8889 """Overridden from Argument."""
8890 return "reinterpret_cast<%s>(shared_memory_address_)" % self.type
8892 def GetNumInvalidValues(self, func):
8893 """Overridden from Argument."""
8894 return 2
8896 def GetInvalidArg(self, index):
8897 """Overridden from Argument."""
8898 if index == 0:
8899 return ("kInvalidSharedMemoryId, 0", "kOutOfBounds", None)
8900 else:
8901 return ("shared_memory_id_, kInvalidSharedMemoryOffset",
8902 "kOutOfBounds", None)
8904 def GetLogArg(self):
8905 """Overridden from Argument."""
8906 return "static_cast<const void*>(%s)" % self.name
8908 def AddCmdArgs(self, args):
8909 """Overridden from Argument."""
8910 args.append(Argument("%s_shm_id" % self.name, 'uint32_t'))
8911 args.append(Argument("%s_shm_offset" % self.name, 'uint32_t'))
8913 def WriteGetCode(self, file):
8914 """Overridden from Argument."""
8915 file.Write(
8916 " %s %s = GetSharedMemoryAs<%s>(\n" %
8917 (self.type, self.name, self.type))
8918 file.Write(
8919 " c.%s_shm_id, c.%s_shm_offset, data_size);\n" %
8920 (self.name, self.name))
8922 def WriteGetAddress(self, file):
8923 """Overridden from Argument."""
8924 file.Write(
8925 " %s %s = GetSharedMemoryAs<%s>(\n" %
8926 (self.type, self.name, self.type))
8927 file.Write(
8928 " %s_shm_id, %s_shm_offset, %s_size);\n" %
8929 (self.name, self.name, self.name))
8931 def WriteValidationCode(self, file, func):
8932 """Overridden from Argument."""
8933 if self.optional:
8934 return
8935 file.Write(" if (%s == NULL) {\n" % self.name)
8936 file.Write(" return error::kOutOfBounds;\n")
8937 file.Write(" }\n")
8939 def GetImmediateVersion(self):
8940 """Overridden from Argument."""
8941 return ImmediatePointerArgument(self.name, self.type)
8943 def GetBucketVersion(self):
8944 """Overridden from Argument."""
8945 if self.type.find('char') >= 0:
8946 if self.IsPointer2D():
8947 return InputStringArrayBucketArgument(self.name, self.type)
8948 return InputStringBucketArgument(self.name, self.type)
8949 return BucketPointerArgument(self.name, self.type)
8951 def WriteDestinationInitalizationValidation(self, file, func):
8952 """Overridden from Argument."""
8953 self.WriteDestinationInitalizationValidatationIfNeeded(file, func)
8956 class BucketPointerArgument(PointerArgument):
8957 """A class that represents an bucket argument to a function."""
8959 def __init__(self, name, type):
8960 Argument.__init__(self, name, type)
8962 def AddCmdArgs(self, args):
8963 """Overridden from Argument."""
8964 pass
8966 def WriteGetCode(self, file):
8967 """Overridden from Argument."""
8968 file.Write(
8969 " %s %s = bucket->GetData(0, data_size);\n" %
8970 (self.type, self.name))
8972 def WriteValidationCode(self, file, func):
8973 """Overridden from Argument."""
8974 pass
8976 def GetImmediateVersion(self):
8977 """Overridden from Argument."""
8978 return None
8980 def WriteDestinationInitalizationValidation(self, file, func):
8981 """Overridden from Argument."""
8982 self.WriteDestinationInitalizationValidatationIfNeeded(file, func)
8984 def GetLogArg(self):
8985 """Overridden from Argument."""
8986 return "static_cast<const void*>(%s)" % self.name
8989 class InputStringBucketArgument(Argument):
8990 """A string input argument where the string is passed in a bucket."""
8992 def __init__(self, name, type):
8993 Argument.__init__(self, name + "_bucket_id", "uint32_t")
8995 def IsPointer(self):
8996 """Overridden from Argument."""
8997 return True
8999 def IsPointer2D(self):
9000 """Overridden from Argument."""
9001 return False
9004 class InputStringArrayBucketArgument(Argument):
9005 """A string array input argument where the strings are passed in a bucket."""
9007 def __init__(self, name, type):
9008 Argument.__init__(self, name + "_bucket_id", "uint32_t")
9009 self._original_name = name
9011 def WriteGetCode(self, file):
9012 """Overridden from Argument."""
9013 code = """
9014 Bucket* bucket = GetBucket(c.%(name)s);
9015 if (!bucket) {
9016 return error::kInvalidArguments;
9018 GLsizei count = 0;
9019 std::vector<char*> strs;
9020 std::vector<GLint> len;
9021 if (!bucket->GetAsStrings(&count, &strs, &len)) {
9022 return error::kInvalidArguments;
9024 const char** %(original_name)s =
9025 strs.size() > 0 ? const_cast<const char**>(&strs[0]) : NULL;
9026 const GLint* length =
9027 len.size() > 0 ? const_cast<const GLint*>(&len[0]) : NULL;
9028 (void)length;
9030 file.Write(code % {
9031 'name': self.name,
9032 'original_name': self._original_name,
9035 def GetValidArg(self, func):
9036 return "kNameBucketId"
9038 def GetValidGLArg(self, func):
9039 return "_"
9041 def IsPointer(self):
9042 """Overridden from Argument."""
9043 return True
9045 def IsPointer2D(self):
9046 """Overridden from Argument."""
9047 return True
9050 class ResourceIdArgument(Argument):
9051 """A class that represents a resource id argument to a function."""
9053 def __init__(self, name, type):
9054 match = re.match("(GLid\w+)", type)
9055 self.resource_type = match.group(1)[4:]
9056 if self.resource_type == "Sync":
9057 type = type.replace(match.group(1), "GLsync")
9058 else:
9059 type = type.replace(match.group(1), "GLuint")
9060 Argument.__init__(self, name, type)
9062 def WriteGetCode(self, file):
9063 """Overridden from Argument."""
9064 if self.type == "GLsync":
9065 my_type = "GLuint"
9066 else:
9067 my_type = self.type
9068 file.Write(" %s %s = c.%s;\n" % (my_type, self.name, self.name))
9070 def GetValidArg(self, func):
9071 return "client_%s_id_" % self.resource_type.lower()
9073 def GetValidGLArg(self, func):
9074 if self.resource_type == "Sync":
9075 return "reinterpret_cast<GLsync>(kService%sId)" % self.resource_type
9076 return "kService%sId" % self.resource_type
9079 class ResourceIdBindArgument(Argument):
9080 """Represents a resource id argument to a bind function."""
9082 def __init__(self, name, type):
9083 match = re.match("(GLidBind\w+)", type)
9084 self.resource_type = match.group(1)[8:]
9085 type = type.replace(match.group(1), "GLuint")
9086 Argument.__init__(self, name, type)
9088 def WriteGetCode(self, file):
9089 """Overridden from Argument."""
9090 code = """ %(type)s %(name)s = c.%(name)s;
9092 file.Write(code % {'type': self.type, 'name': self.name})
9094 def GetValidArg(self, func):
9095 return "client_%s_id_" % self.resource_type.lower()
9097 def GetValidGLArg(self, func):
9098 return "kService%sId" % self.resource_type
9101 class ResourceIdZeroArgument(Argument):
9102 """Represents a resource id argument to a function that can be zero."""
9104 def __init__(self, name, type):
9105 match = re.match("(GLidZero\w+)", type)
9106 self.resource_type = match.group(1)[8:]
9107 type = type.replace(match.group(1), "GLuint")
9108 Argument.__init__(self, name, type)
9110 def WriteGetCode(self, file):
9111 """Overridden from Argument."""
9112 file.Write(" %s %s = c.%s;\n" % (self.type, self.name, self.name))
9114 def GetValidArg(self, func):
9115 return "client_%s_id_" % self.resource_type.lower()
9117 def GetValidGLArg(self, func):
9118 return "kService%sId" % self.resource_type
9120 def GetNumInvalidValues(self, func):
9121 """returns the number of invalid values to be tested."""
9122 return 1
9124 def GetInvalidArg(self, index):
9125 """returns an invalid value by index."""
9126 return ("kInvalidClientId", "kNoError", "GL_INVALID_VALUE")
9129 class Function(object):
9130 """A class that represents a function."""
9132 type_handlers = {
9133 '': TypeHandler(),
9134 'Bind': BindHandler(),
9135 'Create': CreateHandler(),
9136 'Custom': CustomHandler(),
9137 'Data': DataHandler(),
9138 'Delete': DeleteHandler(),
9139 'DELn': DELnHandler(),
9140 'GENn': GENnHandler(),
9141 'GETn': GETnHandler(),
9142 'GLchar': GLcharHandler(),
9143 'GLcharN': GLcharNHandler(),
9144 'HandWritten': HandWrittenHandler(),
9145 'Is': IsHandler(),
9146 'Manual': ManualHandler(),
9147 'PUT': PUTHandler(),
9148 'PUTn': PUTnHandler(),
9149 'PUTSTR': PUTSTRHandler(),
9150 'PUTXn': PUTXnHandler(),
9151 'StateSet': StateSetHandler(),
9152 'StateSetRGBAlpha': StateSetRGBAlphaHandler(),
9153 'StateSetFrontBack': StateSetFrontBackHandler(),
9154 'StateSetFrontBackSeparate': StateSetFrontBackSeparateHandler(),
9155 'StateSetNamedParameter': StateSetNamedParameter(),
9156 'STRn': STRnHandler(),
9157 'Todo': TodoHandler(),
9160 def __init__(self, name, info):
9161 self.name = name
9162 self.original_name = info['original_name']
9164 self.original_args = self.ParseArgs(info['original_args'])
9166 if 'cmd_args' in info:
9167 self.args_for_cmds = self.ParseArgs(info['cmd_args'])
9168 else:
9169 self.args_for_cmds = self.original_args[:]
9171 self.return_type = info['return_type']
9172 if self.return_type != 'void':
9173 self.return_arg = CreateArg(info['return_type'] + " result")
9174 else:
9175 self.return_arg = None
9177 self.num_pointer_args = sum(
9178 [1 for arg in self.args_for_cmds if arg.IsPointer()])
9179 if self.num_pointer_args > 0:
9180 for arg in reversed(self.original_args):
9181 if arg.IsPointer():
9182 self.last_original_pointer_arg = arg
9183 break
9184 else:
9185 self.last_original_pointer_arg = None
9186 self.info = info
9187 self.type_handler = self.type_handlers[info['type']]
9188 self.can_auto_generate = (self.num_pointer_args == 0 and
9189 info['return_type'] == "void")
9190 self.InitFunction()
9192 def ParseArgs(self, arg_string):
9193 """Parses a function arg string."""
9194 args = []
9195 parts = arg_string.split(',')
9196 for arg_string in parts:
9197 arg = CreateArg(arg_string)
9198 if arg:
9199 args.append(arg)
9200 return args
9202 def IsType(self, type_name):
9203 """Returns true if function is a certain type."""
9204 return self.info['type'] == type_name
9206 def InitFunction(self):
9207 """Creates command args and calls the init function for the type handler.
9209 Creates argument lists for command buffer commands, eg. self.cmd_args and
9210 self.init_args.
9211 Calls the type function initialization.
9212 Override to create different kind of command buffer command argument lists.
9214 self.cmd_args = []
9215 for arg in self.args_for_cmds:
9216 arg.AddCmdArgs(self.cmd_args)
9218 self.init_args = []
9219 for arg in self.args_for_cmds:
9220 arg.AddInitArgs(self.init_args)
9222 if self.return_arg:
9223 self.init_args.append(self.return_arg)
9225 self.type_handler.InitFunction(self)
9227 def IsImmediate(self):
9228 """Returns whether the function is immediate data function or not."""
9229 return False
9231 def IsUnsafe(self):
9232 """Returns whether the function has service side validation or not."""
9233 return self.GetInfo('unsafe', False)
9235 def GetInfo(self, name, default = None):
9236 """Returns a value from the function info for this function."""
9237 if name in self.info:
9238 return self.info[name]
9239 return default
9241 def GetValidArg(self, arg):
9242 """Gets a valid argument value for the parameter arg from the function info
9243 if one exists."""
9244 try:
9245 index = self.GetOriginalArgs().index(arg)
9246 except ValueError:
9247 return None
9249 valid_args = self.GetInfo('valid_args')
9250 if valid_args and str(index) in valid_args:
9251 return valid_args[str(index)]
9252 return None
9254 def AddInfo(self, name, value):
9255 """Adds an info."""
9256 self.info[name] = value
9258 def IsExtension(self):
9259 return self.GetInfo('extension') or self.GetInfo('extension_flag')
9261 def IsCoreGLFunction(self):
9262 return (not self.IsExtension() and
9263 not self.GetInfo('pepper_interface') and
9264 not self.IsUnsafe())
9266 def InPepperInterface(self, interface):
9267 ext = self.GetInfo('pepper_interface')
9268 if not interface.GetName():
9269 return self.IsCoreGLFunction()
9270 return ext == interface.GetName()
9272 def InAnyPepperExtension(self):
9273 return self.IsCoreGLFunction() or self.GetInfo('pepper_interface')
9275 def GetErrorReturnString(self):
9276 if self.GetInfo("error_return"):
9277 return self.GetInfo("error_return")
9278 elif self.return_type == "GLboolean":
9279 return "GL_FALSE"
9280 elif "*" in self.return_type:
9281 return "NULL"
9282 return "0"
9284 def GetGLFunctionName(self):
9285 """Gets the function to call to execute GL for this command."""
9286 if self.GetInfo('decoder_func'):
9287 return self.GetInfo('decoder_func')
9288 return "gl%s" % self.original_name
9290 def GetGLTestFunctionName(self):
9291 gl_func_name = self.GetInfo('gl_test_func')
9292 if gl_func_name == None:
9293 gl_func_name = self.GetGLFunctionName()
9294 if gl_func_name.startswith("gl"):
9295 gl_func_name = gl_func_name[2:]
9296 else:
9297 gl_func_name = self.original_name
9298 return gl_func_name
9300 def GetDataTransferMethods(self):
9301 return self.GetInfo('data_transfer_methods',
9302 ['immediate' if self.num_pointer_args == 1 else 'shm'])
9304 def AddCmdArg(self, arg):
9305 """Adds a cmd argument to this function."""
9306 self.cmd_args.append(arg)
9308 def GetCmdArgs(self):
9309 """Gets the command args for this function."""
9310 return self.cmd_args
9312 def ClearCmdArgs(self):
9313 """Clears the command args for this function."""
9314 self.cmd_args = []
9316 def GetCmdConstants(self):
9317 """Gets the constants for this function."""
9318 return [arg for arg in self.args_for_cmds if arg.IsConstant()]
9320 def GetInitArgs(self):
9321 """Gets the init args for this function."""
9322 return self.init_args
9324 def GetOriginalArgs(self):
9325 """Gets the original arguments to this function."""
9326 return self.original_args
9328 def GetLastOriginalArg(self):
9329 """Gets the last original argument to this function."""
9330 return self.original_args[len(self.original_args) - 1]
9332 def GetLastOriginalPointerArg(self):
9333 return self.last_original_pointer_arg
9335 def GetResourceIdArg(self):
9336 for arg in self.original_args:
9337 if hasattr(arg, 'resource_type'):
9338 return arg
9339 return None
9341 def _MaybePrependComma(self, arg_string, add_comma):
9342 """Adds a comma if arg_string is not empty and add_comma is true."""
9343 comma = ""
9344 if add_comma and len(arg_string):
9345 comma = ", "
9346 return "%s%s" % (comma, arg_string)
9348 def MakeTypedOriginalArgString(self, prefix, add_comma = False):
9349 """Gets a list of arguments as they are in GL."""
9350 args = self.GetOriginalArgs()
9351 arg_string = ", ".join(
9352 ["%s %s%s" % (arg.type, prefix, arg.name) for arg in args])
9353 return self._MaybePrependComma(arg_string, add_comma)
9355 def MakeOriginalArgString(self, prefix, add_comma = False, separator = ", "):
9356 """Gets the list of arguments as they are in GL."""
9357 args = self.GetOriginalArgs()
9358 arg_string = separator.join(
9359 ["%s%s" % (prefix, arg.name) for arg in args])
9360 return self._MaybePrependComma(arg_string, add_comma)
9362 def MakeTypedHelperArgString(self, prefix, add_comma = False):
9363 """Gets a list of typed GL arguments after removing unneeded arguments."""
9364 args = self.GetOriginalArgs()
9365 arg_string = ", ".join(
9366 ["%s %s%s" % (
9367 arg.type,
9368 prefix,
9369 arg.name,
9370 ) for arg in args if not arg.IsConstant()])
9371 return self._MaybePrependComma(arg_string, add_comma)
9373 def MakeHelperArgString(self, prefix, add_comma = False, separator = ", "):
9374 """Gets a list of GL arguments after removing unneeded arguments."""
9375 args = self.GetOriginalArgs()
9376 arg_string = separator.join(
9377 ["%s%s" % (prefix, arg.name)
9378 for arg in args if not arg.IsConstant()])
9379 return self._MaybePrependComma(arg_string, add_comma)
9381 def MakeTypedPepperArgString(self, prefix):
9382 """Gets a list of arguments as they need to be for Pepper."""
9383 if self.GetInfo("pepper_args"):
9384 return self.GetInfo("pepper_args")
9385 else:
9386 return self.MakeTypedOriginalArgString(prefix, False)
9388 def MapCTypeToPepperIdlType(self, ctype, is_for_return_type=False):
9389 """Converts a C type name to the corresponding Pepper IDL type."""
9390 idltype = {
9391 'char*': '[out] str_t',
9392 'const GLchar* const*': '[out] cstr_t',
9393 'const char*': 'cstr_t',
9394 'const void*': 'mem_t',
9395 'void*': '[out] mem_t',
9396 'void**': '[out] mem_ptr_t',
9397 }.get(ctype, ctype)
9398 # We use "GLxxx_ptr_t" for "GLxxx*".
9399 matched = re.match(r'(const )?(GL\w+)\*$', ctype)
9400 if matched:
9401 idltype = matched.group(2) + '_ptr_t'
9402 if not matched.group(1):
9403 idltype = '[out] ' + idltype
9404 # If an in/out specifier is not specified yet, prepend [in].
9405 if idltype[0] != '[':
9406 idltype = '[in] ' + idltype
9407 # Strip the in/out specifier for a return type.
9408 if is_for_return_type:
9409 idltype = re.sub(r'\[\w+\] ', '', idltype)
9410 return idltype
9412 def MakeTypedPepperIdlArgStrings(self):
9413 """Gets a list of arguments as they need to be for Pepper IDL."""
9414 args = self.GetOriginalArgs()
9415 return ["%s %s" % (self.MapCTypeToPepperIdlType(arg.type), arg.name)
9416 for arg in args]
9418 def GetPepperName(self):
9419 if self.GetInfo("pepper_name"):
9420 return self.GetInfo("pepper_name")
9421 return self.name
9423 def MakeTypedCmdArgString(self, prefix, add_comma = False):
9424 """Gets a typed list of arguments as they need to be for command buffers."""
9425 args = self.GetCmdArgs()
9426 arg_string = ", ".join(
9427 ["%s %s%s" % (arg.type, prefix, arg.name) for arg in args])
9428 return self._MaybePrependComma(arg_string, add_comma)
9430 def MakeCmdArgString(self, prefix, add_comma = False):
9431 """Gets the list of arguments as they need to be for command buffers."""
9432 args = self.GetCmdArgs()
9433 arg_string = ", ".join(
9434 ["%s%s" % (prefix, arg.name) for arg in args])
9435 return self._MaybePrependComma(arg_string, add_comma)
9437 def MakeTypedInitString(self, prefix, add_comma = False):
9438 """Gets a typed list of arguments as they need to be for cmd Init/Set."""
9439 args = self.GetInitArgs()
9440 arg_string = ", ".join(
9441 ["%s %s%s" % (arg.type, prefix, arg.name) for arg in args])
9442 return self._MaybePrependComma(arg_string, add_comma)
9444 def MakeInitString(self, prefix, add_comma = False):
9445 """Gets the list of arguments as they need to be for cmd Init/Set."""
9446 args = self.GetInitArgs()
9447 arg_string = ", ".join(
9448 ["%s%s" % (prefix, arg.name) for arg in args])
9449 return self._MaybePrependComma(arg_string, add_comma)
9451 def MakeLogArgString(self):
9452 """Makes a string of the arguments for the LOG macros"""
9453 args = self.GetOriginalArgs()
9454 return ' << ", " << '.join([arg.GetLogArg() for arg in args])
9456 def WriteCommandDescription(self, file):
9457 """Writes a description of the command."""
9458 file.Write("//! Command that corresponds to gl%s.\n" % self.original_name)
9460 def WriteHandlerValidation(self, file):
9461 """Writes validation code for the function."""
9462 for arg in self.GetOriginalArgs():
9463 arg.WriteValidationCode(file, self)
9464 self.WriteValidationCode(file)
9466 def WriteHandlerImplementation(self, file):
9467 """Writes the handler implementation for this command."""
9468 self.type_handler.WriteHandlerImplementation(self, file)
9470 def WriteValidationCode(self, file):
9471 """Writes the validation code for a command."""
9472 pass
9474 def WriteCmdFlag(self, file):
9475 """Writes the cmd cmd_flags constant."""
9476 flags = []
9477 # By default trace only at the highest level 3.
9478 trace_level = int(self.GetInfo('trace_level', default = 3))
9479 if trace_level not in xrange(0, 4):
9480 raise KeyError("Unhandled trace_level: %d" % trace_level)
9482 flags.append('CMD_FLAG_SET_TRACE_LEVEL(%d)' % trace_level)
9484 if len(flags) > 0:
9485 cmd_flags = ' | '.join(flags)
9486 else:
9487 cmd_flags = 0
9489 file.Write(" static const uint8 cmd_flags = %s;\n" % cmd_flags)
9492 def WriteCmdArgFlag(self, file):
9493 """Writes the cmd kArgFlags constant."""
9494 file.Write(" static const cmd::ArgFlags kArgFlags = cmd::kFixed;\n")
9496 def WriteCmdComputeSize(self, file):
9497 """Writes the ComputeSize function for the command."""
9498 file.Write(" static uint32_t ComputeSize() {\n")
9499 file.Write(
9500 " return static_cast<uint32_t>(sizeof(ValueType)); // NOLINT\n")
9501 file.Write(" }\n")
9502 file.Write("\n")
9504 def WriteCmdSetHeader(self, file):
9505 """Writes the cmd's SetHeader function."""
9506 file.Write(" void SetHeader() {\n")
9507 file.Write(" header.SetCmd<ValueType>();\n")
9508 file.Write(" }\n")
9509 file.Write("\n")
9511 def WriteCmdInit(self, file):
9512 """Writes the cmd's Init function."""
9513 file.Write(" void Init(%s) {\n" % self.MakeTypedCmdArgString("_"))
9514 file.Write(" SetHeader();\n")
9515 args = self.GetCmdArgs()
9516 for arg in args:
9517 file.Write(" %s = _%s;\n" % (arg.name, arg.name))
9518 file.Write(" }\n")
9519 file.Write("\n")
9521 def WriteCmdSet(self, file):
9522 """Writes the cmd's Set function."""
9523 copy_args = self.MakeCmdArgString("_", False)
9524 file.Write(" void* Set(void* cmd%s) {\n" %
9525 self.MakeTypedCmdArgString("_", True))
9526 file.Write(" static_cast<ValueType*>(cmd)->Init(%s);\n" % copy_args)
9527 file.Write(" return NextCmdAddress<ValueType>(cmd);\n")
9528 file.Write(" }\n")
9529 file.Write("\n")
9531 def WriteStruct(self, file):
9532 self.type_handler.WriteStruct(self, file)
9534 def WriteDocs(self, file):
9535 self.type_handler.WriteDocs(self, file)
9537 def WriteCmdHelper(self, file):
9538 """Writes the cmd's helper."""
9539 self.type_handler.WriteCmdHelper(self, file)
9541 def WriteServiceImplementation(self, file):
9542 """Writes the service implementation for a command."""
9543 self.type_handler.WriteServiceImplementation(self, file)
9545 def WriteServiceUnitTest(self, file, *extras):
9546 """Writes the service implementation for a command."""
9547 self.type_handler.WriteServiceUnitTest(self, file, *extras)
9549 def WriteGLES2CLibImplementation(self, file):
9550 """Writes the GLES2 C Lib Implemention."""
9551 self.type_handler.WriteGLES2CLibImplementation(self, file)
9553 def WriteGLES2InterfaceHeader(self, file):
9554 """Writes the GLES2 Interface declaration."""
9555 self.type_handler.WriteGLES2InterfaceHeader(self, file)
9557 def WriteMojoGLES2ImplHeader(self, file):
9558 """Writes the Mojo GLES2 implementation header declaration."""
9559 self.type_handler.WriteMojoGLES2ImplHeader(self, file)
9561 def WriteMojoGLES2Impl(self, file):
9562 """Writes the Mojo GLES2 implementation declaration."""
9563 self.type_handler.WriteMojoGLES2Impl(self, file)
9565 def WriteGLES2InterfaceStub(self, file):
9566 """Writes the GLES2 Interface Stub declaration."""
9567 self.type_handler.WriteGLES2InterfaceStub(self, file)
9569 def WriteGLES2InterfaceStubImpl(self, file):
9570 """Writes the GLES2 Interface Stub declaration."""
9571 self.type_handler.WriteGLES2InterfaceStubImpl(self, file)
9573 def WriteGLES2ImplementationHeader(self, file):
9574 """Writes the GLES2 Implemention declaration."""
9575 self.type_handler.WriteGLES2ImplementationHeader(self, file)
9577 def WriteGLES2Implementation(self, file):
9578 """Writes the GLES2 Implemention definition."""
9579 self.type_handler.WriteGLES2Implementation(self, file)
9581 def WriteGLES2TraceImplementationHeader(self, file):
9582 """Writes the GLES2 Trace Implemention declaration."""
9583 self.type_handler.WriteGLES2TraceImplementationHeader(self, file)
9585 def WriteGLES2TraceImplementation(self, file):
9586 """Writes the GLES2 Trace Implemention definition."""
9587 self.type_handler.WriteGLES2TraceImplementation(self, file)
9589 def WriteGLES2Header(self, file):
9590 """Writes the GLES2 Implemention unit test."""
9591 self.type_handler.WriteGLES2Header(self, file)
9593 def WriteGLES2ImplementationUnitTest(self, file):
9594 """Writes the GLES2 Implemention unit test."""
9595 self.type_handler.WriteGLES2ImplementationUnitTest(self, file)
9597 def WriteDestinationInitalizationValidation(self, file):
9598 """Writes the client side destintion initialization validation."""
9599 self.type_handler.WriteDestinationInitalizationValidation(self, file)
9601 def WriteFormatTest(self, file):
9602 """Writes the cmd's format test."""
9603 self.type_handler.WriteFormatTest(self, file)
9606 class PepperInterface(object):
9607 """A class that represents a function."""
9609 def __init__(self, info):
9610 self.name = info["name"]
9611 self.dev = info["dev"]
9613 def GetName(self):
9614 return self.name
9616 def GetInterfaceName(self):
9617 upperint = ""
9618 dev = ""
9619 if self.name:
9620 upperint = "_" + self.name.upper()
9621 if self.dev:
9622 dev = "_DEV"
9623 return "PPB_OPENGLES2%s%s_INTERFACE" % (upperint, dev)
9625 def GetInterfaceString(self):
9626 dev = ""
9627 if self.dev:
9628 dev = "(Dev)"
9629 return "PPB_OpenGLES2%s%s" % (self.name, dev)
9631 def GetStructName(self):
9632 dev = ""
9633 if self.dev:
9634 dev = "_Dev"
9635 return "PPB_OpenGLES2%s%s" % (self.name, dev)
9638 class ImmediateFunction(Function):
9639 """A class that represnets an immediate function command."""
9641 def __init__(self, func):
9642 Function.__init__(
9643 self,
9644 "%sImmediate" % func.name,
9645 func.info)
9647 def InitFunction(self):
9648 # Override args in original_args and args_for_cmds with immediate versions
9649 # of the args.
9651 new_original_args = []
9652 for arg in self.original_args:
9653 new_arg = arg.GetImmediateVersion()
9654 if new_arg:
9655 new_original_args.append(new_arg)
9656 self.original_args = new_original_args
9658 new_args_for_cmds = []
9659 for arg in self.args_for_cmds:
9660 new_arg = arg.GetImmediateVersion()
9661 if new_arg:
9662 new_args_for_cmds.append(new_arg)
9664 self.args_for_cmds = new_args_for_cmds
9666 Function.InitFunction(self)
9668 def IsImmediate(self):
9669 return True
9671 def WriteCommandDescription(self, file):
9672 """Overridden from Function"""
9673 file.Write("//! Immediate version of command that corresponds to gl%s.\n" %
9674 self.original_name)
9676 def WriteServiceImplementation(self, file):
9677 """Overridden from Function"""
9678 self.type_handler.WriteImmediateServiceImplementation(self, file)
9680 def WriteHandlerImplementation(self, file):
9681 """Overridden from Function"""
9682 self.type_handler.WriteImmediateHandlerImplementation(self, file)
9684 def WriteServiceUnitTest(self, file, *extras):
9685 """Writes the service implementation for a command."""
9686 self.type_handler.WriteImmediateServiceUnitTest(self, file, *extras)
9688 def WriteValidationCode(self, file):
9689 """Overridden from Function"""
9690 self.type_handler.WriteImmediateValidationCode(self, file)
9692 def WriteCmdArgFlag(self, file):
9693 """Overridden from Function"""
9694 file.Write(" static const cmd::ArgFlags kArgFlags = cmd::kAtLeastN;\n")
9696 def WriteCmdComputeSize(self, file):
9697 """Overridden from Function"""
9698 self.type_handler.WriteImmediateCmdComputeSize(self, file)
9700 def WriteCmdSetHeader(self, file):
9701 """Overridden from Function"""
9702 self.type_handler.WriteImmediateCmdSetHeader(self, file)
9704 def WriteCmdInit(self, file):
9705 """Overridden from Function"""
9706 self.type_handler.WriteImmediateCmdInit(self, file)
9708 def WriteCmdSet(self, file):
9709 """Overridden from Function"""
9710 self.type_handler.WriteImmediateCmdSet(self, file)
9712 def WriteCmdHelper(self, file):
9713 """Overridden from Function"""
9714 self.type_handler.WriteImmediateCmdHelper(self, file)
9716 def WriteFormatTest(self, file):
9717 """Overridden from Function"""
9718 self.type_handler.WriteImmediateFormatTest(self, file)
9721 class BucketFunction(Function):
9722 """A class that represnets a bucket version of a function command."""
9724 def __init__(self, func):
9725 Function.__init__(
9726 self,
9727 "%sBucket" % func.name,
9728 func.info)
9730 def InitFunction(self):
9731 # Override args in original_args and args_for_cmds with bucket versions
9732 # of the args.
9734 new_original_args = []
9735 for arg in self.original_args:
9736 new_arg = arg.GetBucketVersion()
9737 if new_arg:
9738 new_original_args.append(new_arg)
9739 self.original_args = new_original_args
9741 new_args_for_cmds = []
9742 for arg in self.args_for_cmds:
9743 new_arg = arg.GetBucketVersion()
9744 if new_arg:
9745 new_args_for_cmds.append(new_arg)
9747 self.args_for_cmds = new_args_for_cmds
9749 Function.InitFunction(self)
9751 def WriteCommandDescription(self, file):
9752 """Overridden from Function"""
9753 file.Write("//! Bucket version of command that corresponds to gl%s.\n" %
9754 self.original_name)
9756 def WriteServiceImplementation(self, file):
9757 """Overridden from Function"""
9758 self.type_handler.WriteBucketServiceImplementation(self, file)
9760 def WriteHandlerImplementation(self, file):
9761 """Overridden from Function"""
9762 self.type_handler.WriteBucketHandlerImplementation(self, file)
9764 def WriteServiceUnitTest(self, file, *extras):
9765 """Overridden from Function"""
9766 self.type_handler.WriteBucketServiceUnitTest(self, file, *extras)
9768 def MakeOriginalArgString(self, prefix, add_comma = False, separator = ", "):
9769 """Overridden from Function"""
9770 args = self.GetOriginalArgs()
9771 arg_string = separator.join(
9772 ["%s%s" % (prefix, arg.name[0:-10] if arg.name.endswith("_bucket_id")
9773 else arg.name) for arg in args])
9774 return super(BucketFunction, self)._MaybePrependComma(arg_string, add_comma)
9777 def CreateArg(arg_string):
9778 """Creates an Argument."""
9779 arg_parts = arg_string.split()
9780 if len(arg_parts) == 1 and arg_parts[0] == 'void':
9781 return None
9782 # Is this a pointer argument?
9783 elif arg_string.find('*') >= 0:
9784 return PointerArgument(
9785 arg_parts[-1],
9786 " ".join(arg_parts[0:-1]))
9787 # Is this a resource argument? Must come after pointer check.
9788 elif arg_parts[0].startswith('GLidBind'):
9789 return ResourceIdBindArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
9790 elif arg_parts[0].startswith('GLidZero'):
9791 return ResourceIdZeroArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
9792 elif arg_parts[0].startswith('GLid'):
9793 return ResourceIdArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
9794 elif arg_parts[0].startswith('GLenum') and len(arg_parts[0]) > 6:
9795 return EnumArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
9796 elif arg_parts[0].startswith('GLbitfield') and len(arg_parts[0]) > 10:
9797 return BitFieldArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
9798 elif arg_parts[0].startswith('GLboolean') and len(arg_parts[0]) > 9:
9799 return ValidatedBoolArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
9800 elif arg_parts[0].startswith('GLboolean'):
9801 return BoolArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
9802 elif arg_parts[0].startswith('GLintUniformLocation'):
9803 return UniformLocationArgument(arg_parts[-1])
9804 elif (arg_parts[0].startswith('GLint') and len(arg_parts[0]) > 5 and
9805 not arg_parts[0].startswith('GLintptr')):
9806 return IntArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
9807 elif (arg_parts[0].startswith('GLsizeiNotNegative') or
9808 arg_parts[0].startswith('GLintptrNotNegative')):
9809 return SizeNotNegativeArgument(arg_parts[-1],
9810 " ".join(arg_parts[0:-1]),
9811 arg_parts[0][0:-11])
9812 elif arg_parts[0].startswith('GLsize'):
9813 return SizeArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
9814 else:
9815 return Argument(arg_parts[-1], " ".join(arg_parts[0:-1]))
9818 class GLGenerator(object):
9819 """A class to generate GL command buffers."""
9821 _function_re = re.compile(r'GL_APICALL(.*?)GL_APIENTRY (.*?) \((.*?)\);')
9823 def __init__(self, verbose):
9824 self.original_functions = []
9825 self.functions = []
9826 self.verbose = verbose
9827 self.errors = 0
9828 self.pepper_interfaces = []
9829 self.interface_info = {}
9830 self.generated_cpp_filenames = []
9832 for interface in _PEPPER_INTERFACES:
9833 interface = PepperInterface(interface)
9834 self.pepper_interfaces.append(interface)
9835 self.interface_info[interface.GetName()] = interface
9837 def AddFunction(self, func):
9838 """Adds a function."""
9839 self.functions.append(func)
9841 def GetFunctionInfo(self, name):
9842 """Gets a type info for the given function name."""
9843 if name in _FUNCTION_INFO:
9844 func_info = _FUNCTION_INFO[name].copy()
9845 else:
9846 func_info = {}
9848 if not 'type' in func_info:
9849 func_info['type'] = ''
9851 return func_info
9853 def Log(self, msg):
9854 """Prints something if verbose is true."""
9855 if self.verbose:
9856 print msg
9858 def Error(self, msg):
9859 """Prints an error."""
9860 print "Error: %s" % msg
9861 self.errors += 1
9863 def WriteLicense(self, file):
9864 """Writes the license."""
9865 file.Write(_LICENSE)
9867 def WriteNamespaceOpen(self, file):
9868 """Writes the code for the namespace."""
9869 file.Write("namespace gpu {\n")
9870 file.Write("namespace gles2 {\n")
9871 file.Write("\n")
9873 def WriteNamespaceClose(self, file):
9874 """Writes the code to close the namespace."""
9875 file.Write("} // namespace gles2\n")
9876 file.Write("} // namespace gpu\n")
9877 file.Write("\n")
9879 def ParseGLH(self, filename):
9880 """Parses the cmd_buffer_functions.txt file and extracts the functions"""
9881 f = open(filename, "r")
9882 functions = f.read()
9883 f.close()
9884 for line in functions.splitlines():
9885 match = self._function_re.match(line)
9886 if match:
9887 func_name = match.group(2)[2:]
9888 func_info = self.GetFunctionInfo(func_name)
9889 if func_info['type'] == 'Noop':
9890 continue
9892 parsed_func_info = {
9893 'original_name': func_name,
9894 'original_args': match.group(3),
9895 'return_type': match.group(1).strip(),
9898 for k in parsed_func_info.keys():
9899 if not k in func_info:
9900 func_info[k] = parsed_func_info[k]
9902 f = Function(func_name, func_info)
9903 self.original_functions.append(f)
9905 #for arg in f.GetOriginalArgs():
9906 # if not isinstance(arg, EnumArgument) and arg.type == 'GLenum':
9907 # self.Log("%s uses bare GLenum %s." % (func_name, arg.name))
9909 gen_cmd = f.GetInfo('gen_cmd')
9910 if gen_cmd == True or gen_cmd == None:
9911 if f.type_handler.NeedsDataTransferFunction(f):
9912 methods = f.GetDataTransferMethods()
9913 if 'immediate' in methods:
9914 self.AddFunction(ImmediateFunction(f))
9915 if 'bucket' in methods:
9916 self.AddFunction(BucketFunction(f))
9917 if 'shm' in methods:
9918 self.AddFunction(f)
9919 else:
9920 self.AddFunction(f)
9922 self.Log("Auto Generated Functions : %d" %
9923 len([f for f in self.functions if f.can_auto_generate or
9924 (not f.IsType('') and not f.IsType('Custom') and
9925 not f.IsType('Todo'))]))
9927 funcs = [f for f in self.functions if not f.can_auto_generate and
9928 (f.IsType('') or f.IsType('Custom') or f.IsType('Todo'))]
9929 self.Log("Non Auto Generated Functions: %d" % len(funcs))
9931 for f in funcs:
9932 self.Log(" %-10s %-20s gl%s" % (f.info['type'], f.return_type, f.name))
9934 def WriteCommandIds(self, filename):
9935 """Writes the command buffer format"""
9936 file = CHeaderWriter(filename)
9937 file.Write("#define GLES2_COMMAND_LIST(OP) \\\n")
9938 id = 256
9939 for func in self.functions:
9940 file.Write(" %-60s /* %d */ \\\n" %
9941 ("OP(%s)" % func.name, id))
9942 id += 1
9943 file.Write("\n")
9945 file.Write("enum CommandId {\n")
9946 file.Write(" kStartPoint = cmd::kLastCommonId, "
9947 "// All GLES2 commands start after this.\n")
9948 file.Write("#define GLES2_CMD_OP(name) k ## name,\n")
9949 file.Write(" GLES2_COMMAND_LIST(GLES2_CMD_OP)\n")
9950 file.Write("#undef GLES2_CMD_OP\n")
9951 file.Write(" kNumCommands\n")
9952 file.Write("};\n")
9953 file.Write("\n")
9954 file.Close()
9955 self.generated_cpp_filenames.append(file.filename)
9957 def WriteFormat(self, filename):
9958 """Writes the command buffer format"""
9959 file = CHeaderWriter(filename)
9960 # Forward declaration of a few enums used in constant argument
9961 # to avoid including GL header files.
9962 enum_defines = {
9963 'GL_SYNC_GPU_COMMANDS_COMPLETE': '0x9117',
9964 'GL_SYNC_FLUSH_COMMANDS_BIT': '0x00000001',
9966 file.Write('\n')
9967 for enum in enum_defines:
9968 file.Write("#define %s %s\n" % (enum, enum_defines[enum]))
9969 file.Write('\n')
9970 for func in self.functions:
9971 if True:
9972 #gen_cmd = func.GetInfo('gen_cmd')
9973 #if gen_cmd == True or gen_cmd == None:
9974 func.WriteStruct(file)
9975 file.Write("\n")
9976 file.Close()
9977 self.generated_cpp_filenames.append(file.filename)
9979 def WriteDocs(self, filename):
9980 """Writes the command buffer doc version of the commands"""
9981 file = CWriter(filename)
9982 for func in self.functions:
9983 if True:
9984 #gen_cmd = func.GetInfo('gen_cmd')
9985 #if gen_cmd == True or gen_cmd == None:
9986 func.WriteDocs(file)
9987 file.Write("\n")
9988 file.Close()
9989 self.generated_cpp_filenames.append(file.filename)
9991 def WriteFormatTest(self, filename):
9992 """Writes the command buffer format test."""
9993 file = CHeaderWriter(
9994 filename,
9995 "// This file contains unit tests for gles2 commmands\n"
9996 "// It is included by gles2_cmd_format_test.cc\n"
9997 "\n")
9999 for func in self.functions:
10000 if True:
10001 #gen_cmd = func.GetInfo('gen_cmd')
10002 #if gen_cmd == True or gen_cmd == None:
10003 func.WriteFormatTest(file)
10005 file.Close()
10006 self.generated_cpp_filenames.append(file.filename)
10008 def WriteCmdHelperHeader(self, filename):
10009 """Writes the gles2 command helper."""
10010 file = CHeaderWriter(filename)
10012 for func in self.functions:
10013 if True:
10014 #gen_cmd = func.GetInfo('gen_cmd')
10015 #if gen_cmd == True or gen_cmd == None:
10016 func.WriteCmdHelper(file)
10018 file.Close()
10019 self.generated_cpp_filenames.append(file.filename)
10021 def WriteServiceContextStateHeader(self, filename):
10022 """Writes the service context state header."""
10023 file = CHeaderWriter(
10024 filename,
10025 "// It is included by context_state.h\n")
10026 file.Write("struct EnableFlags {\n")
10027 file.Write(" EnableFlags();\n")
10028 for capability in _CAPABILITY_FLAGS:
10029 file.Write(" bool %s;\n" % capability['name'])
10030 file.Write(" bool cached_%s;\n" % capability['name'])
10031 file.Write("};\n\n")
10033 for state_name in sorted(_STATES.keys()):
10034 state = _STATES[state_name]
10035 for item in state['states']:
10036 if isinstance(item['default'], list):
10037 file.Write("%s %s[%d];\n" % (item['type'], item['name'],
10038 len(item['default'])))
10039 else:
10040 file.Write("%s %s;\n" % (item['type'], item['name']))
10042 if item.get('cached', False):
10043 if isinstance(item['default'], list):
10044 file.Write("%s cached_%s[%d];\n" % (item['type'], item['name'],
10045 len(item['default'])))
10046 else:
10047 file.Write("%s cached_%s;\n" % (item['type'], item['name']))
10049 file.Write("\n")
10051 file.Write("""
10052 inline void SetDeviceCapabilityState(GLenum cap, bool enable) {
10053 switch (cap) {
10054 """)
10055 for capability in _CAPABILITY_FLAGS:
10056 file.Write("""\
10057 case GL_%s:
10058 """ % capability['name'].upper())
10059 file.Write("""\
10060 if (enable_flags.cached_%(name)s == enable &&
10061 !ignore_cached_state)
10062 return;
10063 enable_flags.cached_%(name)s = enable;
10064 break;
10065 """ % capability)
10067 file.Write("""\
10068 default:
10069 NOTREACHED();
10070 return;
10072 if (enable)
10073 glEnable(cap);
10074 else
10075 glDisable(cap);
10077 """)
10079 file.Close()
10080 self.generated_cpp_filenames.append(file.filename)
10082 def WriteClientContextStateHeader(self, filename):
10083 """Writes the client context state header."""
10084 file = CHeaderWriter(
10085 filename,
10086 "// It is included by client_context_state.h\n")
10087 file.Write("struct EnableFlags {\n")
10088 file.Write(" EnableFlags();\n")
10089 for capability in _CAPABILITY_FLAGS:
10090 file.Write(" bool %s;\n" % capability['name'])
10091 file.Write("};\n\n")
10093 file.Close()
10094 self.generated_cpp_filenames.append(file.filename)
10096 def WriteContextStateGetters(self, file, class_name):
10097 """Writes the state getters."""
10098 for gl_type in ["GLint", "GLfloat"]:
10099 file.Write("""
10100 bool %s::GetStateAs%s(
10101 GLenum pname, %s* params, GLsizei* num_written) const {
10102 switch (pname) {
10103 """ % (class_name, gl_type, gl_type))
10104 for state_name in sorted(_STATES.keys()):
10105 state = _STATES[state_name]
10106 if 'enum' in state:
10107 file.Write(" case %s:\n" % state['enum'])
10108 file.Write(" *num_written = %d;\n" % len(state['states']))
10109 file.Write(" if (params) {\n")
10110 for ndx,item in enumerate(state['states']):
10111 file.Write(" params[%d] = static_cast<%s>(%s);\n" %
10112 (ndx, gl_type, item['name']))
10113 file.Write(" }\n")
10114 file.Write(" return true;\n")
10115 else:
10116 for item in state['states']:
10117 file.Write(" case %s:\n" % item['enum'])
10118 if isinstance(item['default'], list):
10119 item_len = len(item['default'])
10120 file.Write(" *num_written = %d;\n" % item_len)
10121 file.Write(" if (params) {\n")
10122 if item['type'] == gl_type:
10123 file.Write(" memcpy(params, %s, sizeof(%s) * %d);\n" %
10124 (item['name'], item['type'], item_len))
10125 else:
10126 file.Write(" for (size_t i = 0; i < %s; ++i) {\n" %
10127 item_len)
10128 file.Write(" params[i] = %s;\n" %
10129 (GetGLGetTypeConversion(gl_type, item['type'],
10130 "%s[i]" % item['name'])))
10131 file.Write(" }\n");
10132 else:
10133 file.Write(" *num_written = 1;\n")
10134 file.Write(" if (params) {\n")
10135 file.Write(" params[0] = %s;\n" %
10136 (GetGLGetTypeConversion(gl_type, item['type'],
10137 item['name'])))
10138 file.Write(" }\n")
10139 file.Write(" return true;\n")
10140 for capability in _CAPABILITY_FLAGS:
10141 file.Write(" case GL_%s:\n" % capability['name'].upper())
10142 file.Write(" *num_written = 1;\n")
10143 file.Write(" if (params) {\n")
10144 file.Write(
10145 " params[0] = static_cast<%s>(enable_flags.%s);\n" %
10146 (gl_type, capability['name']))
10147 file.Write(" }\n")
10148 file.Write(" return true;\n")
10149 file.Write(""" default:
10150 return false;
10153 """)
10155 def WriteServiceContextStateImpl(self, filename):
10156 """Writes the context state service implementation."""
10157 file = CHeaderWriter(
10158 filename,
10159 "// It is included by context_state.cc\n")
10160 code = []
10161 for capability in _CAPABILITY_FLAGS:
10162 code.append("%s(%s)" %
10163 (capability['name'],
10164 ('false', 'true')['default' in capability]))
10165 code.append("cached_%s(%s)" %
10166 (capability['name'],
10167 ('false', 'true')['default' in capability]))
10168 file.Write("ContextState::EnableFlags::EnableFlags()\n : %s {\n}\n" %
10169 ",\n ".join(code))
10170 file.Write("\n")
10172 file.Write("void ContextState::Initialize() {\n")
10173 for state_name in sorted(_STATES.keys()):
10174 state = _STATES[state_name]
10175 for item in state['states']:
10176 if isinstance(item['default'], list):
10177 for ndx, value in enumerate(item['default']):
10178 file.Write(" %s[%d] = %s;\n" % (item['name'], ndx, value))
10179 else:
10180 file.Write(" %s = %s;\n" % (item['name'], item['default']))
10181 if item.get('cached', False):
10182 if isinstance(item['default'], list):
10183 for ndx, value in enumerate(item['default']):
10184 file.Write(" cached_%s[%d] = %s;\n" % (item['name'], ndx, value))
10185 else:
10186 file.Write(" cached_%s = %s;\n" % (item['name'], item['default']))
10187 file.Write("}\n")
10189 file.Write("""
10190 void ContextState::InitCapabilities(const ContextState* prev_state) const {
10191 """)
10192 def WriteCapabilities(test_prev, es3_caps):
10193 for capability in _CAPABILITY_FLAGS:
10194 capability_name = capability['name']
10195 capability_es3 = 'es3' in capability and capability['es3'] == True
10196 if capability_es3 and not es3_caps or not capability_es3 and es3_caps:
10197 continue
10198 if test_prev:
10199 file.Write(""" if (prev_state->enable_flags.cached_%s !=
10200 enable_flags.cached_%s) {\n""" %
10201 (capability_name, capability_name))
10202 file.Write(" EnableDisable(GL_%s, enable_flags.cached_%s);\n" %
10203 (capability_name.upper(), capability_name))
10204 if test_prev:
10205 file.Write(" }")
10207 file.Write(" if (prev_state) {")
10208 WriteCapabilities(True, False)
10209 file.Write(" if (feature_info_->IsES3Capable()) {\n")
10210 WriteCapabilities(True, True)
10211 file.Write(" }\n")
10212 file.Write(" } else {")
10213 WriteCapabilities(False, False)
10214 file.Write(" if (feature_info_->IsES3Capable()) {\n")
10215 WriteCapabilities(False, True)
10216 file.Write(" }\n")
10217 file.Write(" }")
10219 file.Write("""}
10221 void ContextState::InitState(const ContextState *prev_state) const {
10222 """)
10224 def WriteStates(test_prev):
10225 # We need to sort the keys so the expectations match
10226 for state_name in sorted(_STATES.keys()):
10227 state = _STATES[state_name]
10228 if state['type'] == 'FrontBack':
10229 num_states = len(state['states'])
10230 for ndx, group in enumerate(Grouper(num_states / 2, state['states'])):
10231 if test_prev:
10232 file.Write(" if (")
10233 args = []
10234 for place, item in enumerate(group):
10235 item_name = CachedStateName(item)
10236 args.append('%s' % item_name)
10237 if test_prev:
10238 if place > 0:
10239 file.Write(' ||\n')
10240 file.Write("(%s != prev_state->%s)" % (item_name, item_name))
10241 if test_prev:
10242 file.Write(")\n")
10243 file.Write(
10244 " gl%s(%s, %s);\n" %
10245 (state['func'], ('GL_FRONT', 'GL_BACK')[ndx], ", ".join(args)))
10246 elif state['type'] == 'NamedParameter':
10247 for item in state['states']:
10248 item_name = CachedStateName(item)
10250 if 'extension_flag' in item:
10251 file.Write(" if (feature_info_->feature_flags().%s) {\n " %
10252 item['extension_flag'])
10253 if test_prev:
10254 if isinstance(item['default'], list):
10255 file.Write(" if (memcmp(prev_state->%s, %s, "
10256 "sizeof(%s) * %d)) {\n" %
10257 (item_name, item_name, item['type'],
10258 len(item['default'])))
10259 else:
10260 file.Write(" if (prev_state->%s != %s) {\n " %
10261 (item_name, item_name))
10262 if 'gl_version_flag' in item:
10263 item_name = item['gl_version_flag']
10264 inverted = ''
10265 if item_name[0] == '!':
10266 inverted = '!'
10267 item_name = item_name[1:]
10268 file.Write(" if (%sfeature_info_->gl_version_info().%s) {\n" %
10269 (inverted, item_name))
10270 file.Write(" gl%s(%s, %s);\n" %
10271 (state['func'],
10272 (item['enum_set']
10273 if 'enum_set' in item else item['enum']),
10274 item['name']))
10275 if 'gl_version_flag' in item:
10276 file.Write(" }\n")
10277 if test_prev:
10278 if 'extension_flag' in item:
10279 file.Write(" ")
10280 file.Write(" }")
10281 if 'extension_flag' in item:
10282 file.Write(" }")
10283 else:
10284 if 'extension_flag' in state:
10285 file.Write(" if (feature_info_->feature_flags().%s)\n " %
10286 state['extension_flag'])
10287 if test_prev:
10288 file.Write(" if (")
10289 args = []
10290 for place, item in enumerate(state['states']):
10291 item_name = CachedStateName(item)
10292 args.append('%s' % item_name)
10293 if test_prev:
10294 if place > 0:
10295 file.Write(' ||\n')
10296 file.Write("(%s != prev_state->%s)" %
10297 (item_name, item_name))
10298 if test_prev:
10299 file.Write(" )\n")
10300 file.Write(" gl%s(%s);\n" % (state['func'], ", ".join(args)))
10302 file.Write(" if (prev_state) {")
10303 WriteStates(True)
10304 file.Write(" } else {")
10305 WriteStates(False)
10306 file.Write(" }")
10307 file.Write("}\n")
10309 file.Write("""bool ContextState::GetEnabled(GLenum cap) const {
10310 switch (cap) {
10311 """)
10312 for capability in _CAPABILITY_FLAGS:
10313 file.Write(" case GL_%s:\n" % capability['name'].upper())
10314 file.Write(" return enable_flags.%s;\n" % capability['name'])
10315 file.Write(""" default:
10316 NOTREACHED();
10317 return false;
10320 """)
10322 self.WriteContextStateGetters(file, "ContextState")
10323 file.Close()
10324 self.generated_cpp_filenames.append(file.filename)
10326 def WriteClientContextStateImpl(self, filename):
10327 """Writes the context state client side implementation."""
10328 file = CHeaderWriter(
10329 filename,
10330 "// It is included by client_context_state.cc\n")
10331 code = []
10332 for capability in _CAPABILITY_FLAGS:
10333 code.append("%s(%s)" %
10334 (capability['name'],
10335 ('false', 'true')['default' in capability]))
10336 file.Write(
10337 "ClientContextState::EnableFlags::EnableFlags()\n : %s {\n}\n" %
10338 ",\n ".join(code))
10339 file.Write("\n")
10341 file.Write("""
10342 bool ClientContextState::SetCapabilityState(
10343 GLenum cap, bool enabled, bool* changed) {
10344 *changed = false;
10345 switch (cap) {
10346 """)
10347 for capability in _CAPABILITY_FLAGS:
10348 file.Write(" case GL_%s:\n" % capability['name'].upper())
10349 file.Write(""" if (enable_flags.%(name)s != enabled) {
10350 *changed = true;
10351 enable_flags.%(name)s = enabled;
10353 return true;
10354 """ % capability)
10355 file.Write(""" default:
10356 return false;
10359 """)
10360 file.Write("""bool ClientContextState::GetEnabled(
10361 GLenum cap, bool* enabled) const {
10362 switch (cap) {
10363 """)
10364 for capability in _CAPABILITY_FLAGS:
10365 file.Write(" case GL_%s:\n" % capability['name'].upper())
10366 file.Write(" *enabled = enable_flags.%s;\n" % capability['name'])
10367 file.Write(" return true;\n")
10368 file.Write(""" default:
10369 return false;
10372 """)
10373 file.Close()
10374 self.generated_cpp_filenames.append(file.filename)
10376 def WriteServiceImplementation(self, filename):
10377 """Writes the service decorder implementation."""
10378 file = CHeaderWriter(
10379 filename,
10380 "// It is included by gles2_cmd_decoder.cc\n")
10382 for func in self.functions:
10383 if True:
10384 #gen_cmd = func.GetInfo('gen_cmd')
10385 #if gen_cmd == True or gen_cmd == None:
10386 func.WriteServiceImplementation(file)
10388 file.Write("""
10389 bool GLES2DecoderImpl::SetCapabilityState(GLenum cap, bool enabled) {
10390 switch (cap) {
10391 """)
10392 for capability in _CAPABILITY_FLAGS:
10393 file.Write(" case GL_%s:\n" % capability['name'].upper())
10394 if 'state_flag' in capability:
10396 file.Write("""\
10397 state_.enable_flags.%(name)s = enabled;
10398 if (state_.enable_flags.cached_%(name)s != enabled
10399 || state_.ignore_cached_state) {
10400 %(state_flag)s = true;
10402 return false;
10403 """ % capability)
10404 else:
10405 file.Write("""\
10406 state_.enable_flags.%(name)s = enabled;
10407 if (state_.enable_flags.cached_%(name)s != enabled
10408 || state_.ignore_cached_state) {
10409 state_.enable_flags.cached_%(name)s = enabled;
10410 return true;
10412 return false;
10413 """ % capability)
10414 file.Write(""" default:
10415 NOTREACHED();
10416 return false;
10419 """)
10420 file.Close()
10421 self.generated_cpp_filenames.append(file.filename)
10423 def WriteServiceUnitTests(self, filename):
10424 """Writes the service decorder unit tests."""
10425 num_tests = len(self.functions)
10426 FUNCTIONS_PER_FILE = 98 # hard code this so it doesn't change.
10427 count = 0
10428 for test_num in range(0, num_tests, FUNCTIONS_PER_FILE):
10429 count += 1
10430 name = filename % count
10431 file = CHeaderWriter(
10432 name,
10433 "// It is included by gles2_cmd_decoder_unittest_%d.cc\n" % count)
10434 test_name = 'GLES2DecoderTest%d' % count
10435 end = test_num + FUNCTIONS_PER_FILE
10436 if end > num_tests:
10437 end = num_tests
10438 for idx in range(test_num, end):
10439 func = self.functions[idx]
10441 # Do any filtering of the functions here, so that the functions
10442 # will not move between the numbered files if filtering properties
10443 # are changed.
10444 if func.GetInfo('extension_flag'):
10445 continue
10447 if True:
10448 #gen_cmd = func.GetInfo('gen_cmd')
10449 #if gen_cmd == True or gen_cmd == None:
10450 if func.GetInfo('unit_test') == False:
10451 file.Write("// TODO(gman): %s\n" % func.name)
10452 else:
10453 func.WriteServiceUnitTest(file, {
10454 'test_name': test_name
10456 file.Close()
10457 self.generated_cpp_filenames.append(file.filename)
10458 file = CHeaderWriter(
10459 filename % 0,
10460 "// It is included by gles2_cmd_decoder_unittest_base.cc\n")
10461 file.Write(
10462 """void GLES2DecoderTestBase::SetupInitCapabilitiesExpectations(
10463 bool es3_capable) {""")
10464 for capability in _CAPABILITY_FLAGS:
10465 capability_es3 = 'es3' in capability and capability['es3'] == True
10466 if not capability_es3:
10467 file.Write(" ExpectEnableDisable(GL_%s, %s);\n" %
10468 (capability['name'].upper(),
10469 ('false', 'true')['default' in capability]))
10471 file.Write(" if (es3_capable) {")
10472 for capability in _CAPABILITY_FLAGS:
10473 capability_es3 = 'es3' in capability and capability['es3'] == True
10474 if capability_es3:
10475 file.Write(" ExpectEnableDisable(GL_%s, %s);\n" %
10476 (capability['name'].upper(),
10477 ('false', 'true')['default' in capability]))
10478 file.Write(""" }
10481 void GLES2DecoderTestBase::SetupInitStateExpectations() {
10482 """)
10484 # We need to sort the keys so the expectations match
10485 for state_name in sorted(_STATES.keys()):
10486 state = _STATES[state_name]
10487 if state['type'] == 'FrontBack':
10488 num_states = len(state['states'])
10489 for ndx, group in enumerate(Grouper(num_states / 2, state['states'])):
10490 args = []
10491 for item in group:
10492 if 'expected' in item:
10493 args.append(item['expected'])
10494 else:
10495 args.append(item['default'])
10496 file.Write(
10497 " EXPECT_CALL(*gl_, %s(%s, %s))\n" %
10498 (state['func'], ('GL_FRONT', 'GL_BACK')[ndx], ", ".join(args)))
10499 file.Write(" .Times(1)\n")
10500 file.Write(" .RetiresOnSaturation();\n")
10501 elif state['type'] == 'NamedParameter':
10502 for item in state['states']:
10503 if 'extension_flag' in item:
10504 file.Write(" if (group_->feature_info()->feature_flags().%s) {\n" %
10505 item['extension_flag'])
10506 file.Write(" ")
10507 expect_value = item['default']
10508 if isinstance(expect_value, list):
10509 # TODO: Currently we do not check array values.
10510 expect_value = "_"
10512 file.Write(
10513 " EXPECT_CALL(*gl_, %s(%s, %s))\n" %
10514 (state['func'],
10515 (item['enum_set']
10516 if 'enum_set' in item else item['enum']),
10517 expect_value))
10518 file.Write(" .Times(1)\n")
10519 file.Write(" .RetiresOnSaturation();\n")
10520 if 'extension_flag' in item:
10521 file.Write(" }\n")
10522 else:
10523 if 'extension_flag' in state:
10524 file.Write(" if (group_->feature_info()->feature_flags().%s) {\n" %
10525 state['extension_flag'])
10526 file.Write(" ")
10527 args = []
10528 for item in state['states']:
10529 if 'expected' in item:
10530 args.append(item['expected'])
10531 else:
10532 args.append(item['default'])
10533 # TODO: Currently we do not check array values.
10534 args = ["_" if isinstance(arg, list) else arg for arg in args]
10535 file.Write(" EXPECT_CALL(*gl_, %s(%s))\n" %
10536 (state['func'], ", ".join(args)))
10537 file.Write(" .Times(1)\n")
10538 file.Write(" .RetiresOnSaturation();\n")
10539 if 'extension_flag' in state:
10540 file.Write(" }\n")
10541 file.Write("""}
10542 """)
10543 file.Close()
10544 self.generated_cpp_filenames.append(file.filename)
10546 def WriteServiceUnitTestsForExtensions(self, filename):
10547 """Writes the service decorder unit tests for functions with extension_flag.
10549 The functions are special in that they need a specific unit test
10550 baseclass to turn on the extension.
10552 functions = [f for f in self.functions if f.GetInfo('extension_flag')]
10553 file = CHeaderWriter(
10554 filename,
10555 "// It is included by gles2_cmd_decoder_unittest_extensions.cc\n")
10556 for func in functions:
10557 if True:
10558 if func.GetInfo('unit_test') == False:
10559 file.Write("// TODO(gman): %s\n" % func.name)
10560 else:
10561 extension = ToCamelCase(
10562 ToGLExtensionString(func.GetInfo('extension_flag')))
10563 func.WriteServiceUnitTest(file, {
10564 'test_name': 'GLES2DecoderTestWith%s' % extension
10567 file.Close()
10568 self.generated_cpp_filenames.append(file.filename)
10570 def WriteGLES2Header(self, filename):
10571 """Writes the GLES2 header."""
10572 file = CHeaderWriter(
10573 filename,
10574 "// This file contains Chromium-specific GLES2 declarations.\n\n")
10576 for func in self.original_functions:
10577 func.WriteGLES2Header(file)
10579 file.Write("\n")
10580 file.Close()
10581 self.generated_cpp_filenames.append(file.filename)
10583 def WriteGLES2CLibImplementation(self, filename):
10584 """Writes the GLES2 c lib implementation."""
10585 file = CHeaderWriter(
10586 filename,
10587 "// These functions emulate GLES2 over command buffers.\n")
10589 for func in self.original_functions:
10590 func.WriteGLES2CLibImplementation(file)
10592 file.Write("""
10593 namespace gles2 {
10595 extern const NameToFunc g_gles2_function_table[] = {
10596 """)
10597 for func in self.original_functions:
10598 file.Write(
10599 ' { "gl%s", reinterpret_cast<GLES2FunctionPointer>(gl%s), },\n' %
10600 (func.name, func.name))
10601 file.Write(""" { NULL, NULL, },
10604 } // namespace gles2
10605 """)
10606 file.Close()
10607 self.generated_cpp_filenames.append(file.filename)
10609 def WriteGLES2InterfaceHeader(self, filename):
10610 """Writes the GLES2 interface header."""
10611 file = CHeaderWriter(
10612 filename,
10613 "// This file is included by gles2_interface.h to declare the\n"
10614 "// GL api functions.\n")
10615 for func in self.original_functions:
10616 func.WriteGLES2InterfaceHeader(file)
10617 file.Close()
10618 self.generated_cpp_filenames.append(file.filename)
10620 def WriteMojoGLES2ImplHeader(self, filename):
10621 """Writes the Mojo GLES2 implementation header."""
10622 file = CHeaderWriter(
10623 filename,
10624 "// This file is included by gles2_interface.h to declare the\n"
10625 "// GL api functions.\n")
10627 code = """
10628 #include "gpu/command_buffer/client/gles2_interface.h"
10629 #include "third_party/mojo/src/mojo/public/c/gles2/gles2.h"
10631 namespace mojo {
10633 class MojoGLES2Impl : public gpu::gles2::GLES2Interface {
10634 public:
10635 explicit MojoGLES2Impl(MojoGLES2Context context) {
10636 context_ = context;
10638 ~MojoGLES2Impl() override {}
10640 file.Write(code);
10641 for func in self.original_functions:
10642 func.WriteMojoGLES2ImplHeader(file)
10643 code = """
10644 private:
10645 MojoGLES2Context context_;
10648 } // namespace mojo
10650 file.Write(code);
10651 file.Close()
10652 self.generated_cpp_filenames.append(file.filename)
10654 def WriteMojoGLES2Impl(self, filename):
10655 """Writes the Mojo GLES2 implementation."""
10656 file = CWriter(filename)
10657 file.Write(_LICENSE)
10658 file.Write(_DO_NOT_EDIT_WARNING)
10660 code = """
10661 #include "mojo/gpu/mojo_gles2_impl_autogen.h"
10663 #include "base/logging.h"
10664 #include "third_party/mojo/src/mojo/public/c/gles2/chromium_copy_texture.h"
10665 #include "third_party/mojo/src/mojo/public/c/gles2/chromium_image.h"
10666 #include "third_party/mojo/src/mojo/public/c/gles2/chromium_miscellaneous.h"
10667 #include "third_party/mojo/src/mojo/public/c/gles2/chromium_pixel_transfer_buffer_object.h"
10668 #include "third_party/mojo/src/mojo/public/c/gles2/chromium_sub_image.h"
10669 #include "third_party/mojo/src/mojo/public/c/gles2/chromium_sync_point.h"
10670 #include "third_party/mojo/src/mojo/public/c/gles2/chromium_texture_mailbox.h"
10671 #include "third_party/mojo/src/mojo/public/c/gles2/gles2.h"
10672 #include "third_party/mojo/src/mojo/public/c/gles2/occlusion_query_ext.h"
10674 namespace mojo {
10677 file.Write(code);
10678 for func in self.original_functions:
10679 func.WriteMojoGLES2Impl(file)
10680 code = """
10682 } // namespace mojo
10684 file.Write(code);
10685 file.Close()
10686 self.generated_cpp_filenames.append(file.filename)
10688 def WriteGLES2InterfaceStub(self, filename):
10689 """Writes the GLES2 interface stub header."""
10690 file = CHeaderWriter(
10691 filename,
10692 "// This file is included by gles2_interface_stub.h.\n")
10693 for func in self.original_functions:
10694 func.WriteGLES2InterfaceStub(file)
10695 file.Close()
10696 self.generated_cpp_filenames.append(file.filename)
10698 def WriteGLES2InterfaceStubImpl(self, filename):
10699 """Writes the GLES2 interface header."""
10700 file = CHeaderWriter(
10701 filename,
10702 "// This file is included by gles2_interface_stub.cc.\n")
10703 for func in self.original_functions:
10704 func.WriteGLES2InterfaceStubImpl(file)
10705 file.Close()
10706 self.generated_cpp_filenames.append(file.filename)
10708 def WriteGLES2ImplementationHeader(self, filename):
10709 """Writes the GLES2 Implementation header."""
10710 file = CHeaderWriter(
10711 filename,
10712 "// This file is included by gles2_implementation.h to declare the\n"
10713 "// GL api functions.\n")
10714 for func in self.original_functions:
10715 func.WriteGLES2ImplementationHeader(file)
10716 file.Close()
10717 self.generated_cpp_filenames.append(file.filename)
10719 def WriteGLES2Implementation(self, filename):
10720 """Writes the GLES2 Implementation."""
10721 file = CHeaderWriter(
10722 filename,
10723 "// This file is included by gles2_implementation.cc to define the\n"
10724 "// GL api functions.\n")
10725 for func in self.original_functions:
10726 func.WriteGLES2Implementation(file)
10727 file.Close()
10728 self.generated_cpp_filenames.append(file.filename)
10730 def WriteGLES2TraceImplementationHeader(self, filename):
10731 """Writes the GLES2 Trace Implementation header."""
10732 file = CHeaderWriter(
10733 filename,
10734 "// This file is included by gles2_trace_implementation.h\n")
10735 for func in self.original_functions:
10736 func.WriteGLES2TraceImplementationHeader(file)
10737 file.Close()
10738 self.generated_cpp_filenames.append(file.filename)
10740 def WriteGLES2TraceImplementation(self, filename):
10741 """Writes the GLES2 Trace Implementation."""
10742 file = CHeaderWriter(
10743 filename,
10744 "// This file is included by gles2_trace_implementation.cc\n")
10745 for func in self.original_functions:
10746 func.WriteGLES2TraceImplementation(file)
10747 file.Close()
10748 self.generated_cpp_filenames.append(file.filename)
10750 def WriteGLES2ImplementationUnitTests(self, filename):
10751 """Writes the GLES2 helper header."""
10752 file = CHeaderWriter(
10753 filename,
10754 "// This file is included by gles2_implementation.h to declare the\n"
10755 "// GL api functions.\n")
10756 for func in self.original_functions:
10757 func.WriteGLES2ImplementationUnitTest(file)
10758 file.Close()
10759 self.generated_cpp_filenames.append(file.filename)
10761 def WriteServiceUtilsHeader(self, filename):
10762 """Writes the gles2 auto generated utility header."""
10763 file = CHeaderWriter(filename)
10764 for name in sorted(_NAMED_TYPE_INFO.keys()):
10765 named_type = NamedType(_NAMED_TYPE_INFO[name])
10766 if named_type.IsConstant():
10767 continue
10768 file.Write("ValueValidator<%s> %s;\n" %
10769 (named_type.GetType(), ToUnderscore(name)))
10770 file.Write("\n")
10771 file.Close()
10772 self.generated_cpp_filenames.append(file.filename)
10774 def WriteServiceUtilsImplementation(self, filename):
10775 """Writes the gles2 auto generated utility implementation."""
10776 file = CHeaderWriter(filename)
10777 names = sorted(_NAMED_TYPE_INFO.keys())
10778 for name in names:
10779 named_type = NamedType(_NAMED_TYPE_INFO[name])
10780 if named_type.IsConstant():
10781 continue
10782 if named_type.GetValidValues():
10783 file.Write("static const %s valid_%s_table[] = {\n" %
10784 (named_type.GetType(), ToUnderscore(name)))
10785 for value in named_type.GetValidValues():
10786 file.Write(" %s,\n" % value)
10787 file.Write("};\n")
10788 file.Write("\n")
10789 if named_type.GetValidValuesES3():
10790 file.Write("static const %s valid_%s_table_es3[] = {\n" %
10791 (named_type.GetType(), ToUnderscore(name)))
10792 for value in named_type.GetValidValuesES3():
10793 file.Write(" %s,\n" % value)
10794 file.Write("};\n")
10795 file.Write("\n")
10796 if named_type.GetDeprecatedValuesES3():
10797 file.Write("static const %s deprecated_%s_table_es3[] = {\n" %
10798 (named_type.GetType(), ToUnderscore(name)))
10799 for value in named_type.GetDeprecatedValuesES3():
10800 file.Write(" %s,\n" % value)
10801 file.Write("};\n")
10802 file.Write("\n")
10803 file.Write("Validators::Validators()")
10804 pre = ' : '
10805 for count, name in enumerate(names):
10806 named_type = NamedType(_NAMED_TYPE_INFO[name])
10807 if named_type.IsConstant():
10808 continue
10809 if named_type.GetValidValues():
10810 code = """%(pre)s%(name)s(
10811 valid_%(name)s_table, arraysize(valid_%(name)s_table))"""
10812 else:
10813 code = "%(pre)s%(name)s()"
10814 file.Write(code % {
10815 'name': ToUnderscore(name),
10816 'pre': pre,
10818 pre = ',\n '
10819 file.Write(" {\n");
10820 file.Write("}\n\n");
10822 file.Write("void Validators::UpdateValuesES3() {\n")
10823 for name in names:
10824 named_type = NamedType(_NAMED_TYPE_INFO[name])
10825 if named_type.GetDeprecatedValuesES3():
10826 code = """ %(name)s.RemoveValues(
10827 deprecated_%(name)s_table_es3, arraysize(deprecated_%(name)s_table_es3));
10829 file.Write(code % {
10830 'name': ToUnderscore(name),
10832 if named_type.GetValidValuesES3():
10833 code = """ %(name)s.AddValues(
10834 valid_%(name)s_table_es3, arraysize(valid_%(name)s_table_es3));
10836 file.Write(code % {
10837 'name': ToUnderscore(name),
10839 file.Write("}\n\n");
10840 file.Close()
10841 self.generated_cpp_filenames.append(file.filename)
10843 def WriteCommonUtilsHeader(self, filename):
10844 """Writes the gles2 common utility header."""
10845 file = CHeaderWriter(filename)
10846 type_infos = sorted(_NAMED_TYPE_INFO.keys())
10847 for type_info in type_infos:
10848 if _NAMED_TYPE_INFO[type_info]['type'] == 'GLenum':
10849 file.Write("static std::string GetString%s(uint32_t value);\n" %
10850 type_info)
10851 file.Write("\n")
10852 file.Close()
10853 self.generated_cpp_filenames.append(file.filename)
10855 def WriteCommonUtilsImpl(self, filename):
10856 """Writes the gles2 common utility header."""
10857 enum_re = re.compile(r'\#define\s+(GL_[a-zA-Z0-9_]+)\s+([0-9A-Fa-fx]+)')
10858 dict = {}
10859 for fname in ['third_party/khronos/GLES2/gl2.h',
10860 'third_party/khronos/GLES2/gl2ext.h',
10861 'third_party/khronos/GLES3/gl3.h',
10862 'gpu/GLES2/gl2chromium.h',
10863 'gpu/GLES2/gl2extchromium.h']:
10864 lines = open(fname).readlines()
10865 for line in lines:
10866 m = enum_re.match(line)
10867 if m:
10868 name = m.group(1)
10869 value = m.group(2)
10870 if len(value) <= 10:
10871 if not value in dict:
10872 dict[value] = name
10873 # check our own _CHROMIUM macro conflicts with khronos GL headers.
10874 elif dict[value] != name and (name.endswith('_CHROMIUM') or
10875 dict[value].endswith('_CHROMIUM')):
10876 self.Error("code collision: %s and %s have the same code %s" %
10877 (dict[value], name, value))
10879 file = CHeaderWriter(filename)
10880 file.Write("static const GLES2Util::EnumToString "
10881 "enum_to_string_table[] = {\n")
10882 for value in dict:
10883 file.Write(' { %s, "%s", },\n' % (value, dict[value]))
10884 file.Write("""};
10886 const GLES2Util::EnumToString* const GLES2Util::enum_to_string_table_ =
10887 enum_to_string_table;
10888 const size_t GLES2Util::enum_to_string_table_len_ =
10889 sizeof(enum_to_string_table) / sizeof(enum_to_string_table[0]);
10891 """)
10893 enums = sorted(_NAMED_TYPE_INFO.keys())
10894 for enum in enums:
10895 if _NAMED_TYPE_INFO[enum]['type'] == 'GLenum':
10896 file.Write("std::string GLES2Util::GetString%s(uint32_t value) {\n" %
10897 enum)
10898 valid_list = _NAMED_TYPE_INFO[enum]['valid']
10899 if 'valid_es3' in _NAMED_TYPE_INFO[enum]:
10900 valid_list = valid_list + _NAMED_TYPE_INFO[enum]['valid_es3']
10901 assert len(valid_list) == len(set(valid_list))
10902 if len(valid_list) > 0:
10903 file.Write(" static const EnumToString string_table[] = {\n")
10904 for value in valid_list:
10905 file.Write(' { %s, "%s" },\n' % (value, value))
10906 file.Write(""" };
10907 return GLES2Util::GetQualifiedEnumString(
10908 string_table, arraysize(string_table), value);
10911 """)
10912 else:
10913 file.Write(""" return GLES2Util::GetQualifiedEnumString(
10914 NULL, 0, value);
10917 """)
10918 file.Close()
10919 self.generated_cpp_filenames.append(file.filename)
10921 def WritePepperGLES2Interface(self, filename, dev):
10922 """Writes the Pepper OpenGLES interface definition."""
10923 file = CWriter(filename)
10924 file.Write(_LICENSE)
10925 file.Write(_DO_NOT_EDIT_WARNING)
10927 file.Write("label Chrome {\n")
10928 file.Write(" M39 = 1.0\n")
10929 file.Write("};\n\n")
10931 if not dev:
10932 # Declare GL types.
10933 file.Write("[version=1.0]\n")
10934 file.Write("describe {\n")
10935 for gltype in ['GLbitfield', 'GLboolean', 'GLbyte', 'GLclampf',
10936 'GLclampx', 'GLenum', 'GLfixed', 'GLfloat', 'GLint',
10937 'GLintptr', 'GLshort', 'GLsizei', 'GLsizeiptr',
10938 'GLubyte', 'GLuint', 'GLushort']:
10939 file.Write(" %s;\n" % gltype)
10940 file.Write(" %s_ptr_t;\n" % gltype)
10941 file.Write("};\n\n")
10943 # C level typedefs.
10944 file.Write("#inline c\n")
10945 file.Write("#include \"ppapi/c/pp_resource.h\"\n")
10946 if dev:
10947 file.Write("#include \"ppapi/c/ppb_opengles2.h\"\n\n")
10948 else:
10949 file.Write("\n#ifndef __gl2_h_\n")
10950 for (k, v) in _GL_TYPES.iteritems():
10951 file.Write("typedef %s %s;\n" % (v, k))
10952 file.Write("#ifdef _WIN64\n")
10953 for (k, v) in _GL_TYPES_64.iteritems():
10954 file.Write("typedef %s %s;\n" % (v, k))
10955 file.Write("#else\n")
10956 for (k, v) in _GL_TYPES_32.iteritems():
10957 file.Write("typedef %s %s;\n" % (v, k))
10958 file.Write("#endif // _WIN64\n")
10959 file.Write("#endif // __gl2_h_\n\n")
10960 file.Write("#endinl\n")
10962 for interface in self.pepper_interfaces:
10963 if interface.dev != dev:
10964 continue
10965 # Historically, we provide OpenGLES2 interfaces with struct
10966 # namespace. Not to break code which uses the interface as
10967 # "struct OpenGLES2", we put it in struct namespace.
10968 file.Write('\n[macro="%s", force_struct_namespace]\n' %
10969 interface.GetInterfaceName())
10970 file.Write("interface %s {\n" % interface.GetStructName())
10971 for func in self.original_functions:
10972 if not func.InPepperInterface(interface):
10973 continue
10975 ret_type = func.MapCTypeToPepperIdlType(func.return_type,
10976 is_for_return_type=True)
10977 func_prefix = " %s %s(" % (ret_type, func.GetPepperName())
10978 file.Write(func_prefix)
10979 file.Write("[in] PP_Resource context")
10980 for arg in func.MakeTypedPepperIdlArgStrings():
10981 file.Write(",\n" + " " * len(func_prefix) + arg)
10982 file.Write(");\n")
10983 file.Write("};\n\n")
10986 file.Close()
10988 def WritePepperGLES2Implementation(self, filename):
10989 """Writes the Pepper OpenGLES interface implementation."""
10991 file = CWriter(filename)
10992 file.Write(_LICENSE)
10993 file.Write(_DO_NOT_EDIT_WARNING)
10995 file.Write("#include \"ppapi/shared_impl/ppb_opengles2_shared.h\"\n\n")
10996 file.Write("#include \"base/logging.h\"\n")
10997 file.Write("#include \"gpu/command_buffer/client/gles2_implementation.h\"\n")
10998 file.Write("#include \"ppapi/shared_impl/ppb_graphics_3d_shared.h\"\n")
10999 file.Write("#include \"ppapi/thunk/enter.h\"\n\n")
11001 file.Write("namespace ppapi {\n\n")
11002 file.Write("namespace {\n\n")
11004 file.Write("typedef thunk::EnterResource<thunk::PPB_Graphics3D_API>"
11005 " Enter3D;\n\n")
11007 file.Write("gpu::gles2::GLES2Implementation* ToGles2Impl(Enter3D*"
11008 " enter) {\n")
11009 file.Write(" DCHECK(enter);\n")
11010 file.Write(" DCHECK(enter->succeeded());\n")
11011 file.Write(" return static_cast<PPB_Graphics3D_Shared*>(enter->object())->"
11012 "gles2_impl();\n");
11013 file.Write("}\n\n");
11015 for func in self.original_functions:
11016 if not func.InAnyPepperExtension():
11017 continue
11019 original_arg = func.MakeTypedPepperArgString("")
11020 context_arg = "PP_Resource context_id"
11021 if len(original_arg):
11022 arg = context_arg + ", " + original_arg
11023 else:
11024 arg = context_arg
11025 file.Write("%s %s(%s) {\n" %
11026 (func.return_type, func.GetPepperName(), arg))
11027 file.Write(" Enter3D enter(context_id, true);\n")
11028 file.Write(" if (enter.succeeded()) {\n")
11030 return_str = "" if func.return_type == "void" else "return "
11031 file.Write(" %sToGles2Impl(&enter)->%s(%s);\n" %
11032 (return_str, func.original_name,
11033 func.MakeOriginalArgString("")))
11034 file.Write(" }")
11035 if func.return_type == "void":
11036 file.Write("\n")
11037 else:
11038 file.Write(" else {\n")
11039 file.Write(" return %s;\n" % func.GetErrorReturnString())
11040 file.Write(" }\n")
11041 file.Write("}\n\n")
11043 file.Write("} // namespace\n")
11045 for interface in self.pepper_interfaces:
11046 file.Write("const %s* PPB_OpenGLES2_Shared::Get%sInterface() {\n" %
11047 (interface.GetStructName(), interface.GetName()))
11048 file.Write(" static const struct %s "
11049 "ppb_opengles2 = {\n" % interface.GetStructName())
11050 file.Write(" &")
11051 file.Write(",\n &".join(
11052 f.GetPepperName() for f in self.original_functions
11053 if f.InPepperInterface(interface)))
11054 file.Write("\n")
11056 file.Write(" };\n")
11057 file.Write(" return &ppb_opengles2;\n")
11058 file.Write("}\n")
11060 file.Write("} // namespace ppapi\n")
11061 file.Close()
11062 self.generated_cpp_filenames.append(file.filename)
11064 def WriteGLES2ToPPAPIBridge(self, filename):
11065 """Connects GLES2 helper library to PPB_OpenGLES2 interface"""
11067 file = CWriter(filename)
11068 file.Write(_LICENSE)
11069 file.Write(_DO_NOT_EDIT_WARNING)
11071 file.Write("#ifndef GL_GLEXT_PROTOTYPES\n")
11072 file.Write("#define GL_GLEXT_PROTOTYPES\n")
11073 file.Write("#endif\n")
11074 file.Write("#include <GLES2/gl2.h>\n")
11075 file.Write("#include <GLES2/gl2ext.h>\n")
11076 file.Write("#include \"ppapi/lib/gl/gles2/gl2ext_ppapi.h\"\n\n")
11078 for func in self.original_functions:
11079 if not func.InAnyPepperExtension():
11080 continue
11082 interface = self.interface_info[func.GetInfo('pepper_interface') or '']
11084 file.Write("%s GL_APIENTRY gl%s(%s) {\n" %
11085 (func.return_type, func.GetPepperName(),
11086 func.MakeTypedPepperArgString("")))
11087 return_str = "" if func.return_type == "void" else "return "
11088 interface_str = "glGet%sInterfacePPAPI()" % interface.GetName()
11089 original_arg = func.MakeOriginalArgString("")
11090 context_arg = "glGetCurrentContextPPAPI()"
11091 if len(original_arg):
11092 arg = context_arg + ", " + original_arg
11093 else:
11094 arg = context_arg
11095 if interface.GetName():
11096 file.Write(" const struct %s* ext = %s;\n" %
11097 (interface.GetStructName(), interface_str))
11098 file.Write(" if (ext)\n")
11099 file.Write(" %sext->%s(%s);\n" %
11100 (return_str, func.GetPepperName(), arg))
11101 if return_str:
11102 file.Write(" %s0;\n" % return_str)
11103 else:
11104 file.Write(" %s%s->%s(%s);\n" %
11105 (return_str, interface_str, func.GetPepperName(), arg))
11106 file.Write("}\n\n")
11107 file.Close()
11108 self.generated_cpp_filenames.append(file.filename)
11110 def WriteMojoGLCallVisitor(self, filename):
11111 """Provides the GL implementation for mojo"""
11112 file = CWriter(filename)
11113 file.Write(_LICENSE)
11114 file.Write(_DO_NOT_EDIT_WARNING)
11116 for func in self.original_functions:
11117 if not func.IsCoreGLFunction():
11118 continue
11119 file.Write("VISIT_GL_CALL(%s, %s, (%s), (%s))\n" %
11120 (func.name, func.return_type,
11121 func.MakeTypedOriginalArgString(""),
11122 func.MakeOriginalArgString("")))
11124 file.Close()
11125 self.generated_cpp_filenames.append(file.filename)
11127 def WriteMojoGLCallVisitorForExtension(self, filename, extension):
11128 """Provides the GL implementation for mojo for a particular extension"""
11129 file = CWriter(filename)
11130 file.Write(_LICENSE)
11131 file.Write(_DO_NOT_EDIT_WARNING)
11133 for func in self.original_functions:
11134 if func.GetInfo("extension") != extension:
11135 continue
11136 file.Write("VISIT_GL_CALL(%s, %s, (%s), (%s))\n" %
11137 (func.name, func.return_type,
11138 func.MakeTypedOriginalArgString(""),
11139 func.MakeOriginalArgString("")))
11141 file.Close()
11142 self.generated_cpp_filenames.append(file.filename)
11144 def Format(generated_files):
11145 formatter = "clang-format"
11146 if platform.system() == "Windows":
11147 formatter += ".bat"
11148 for filename in generated_files:
11149 call([formatter, "-i", "-style=chromium", filename])
11151 def main(argv):
11152 """This is the main function."""
11153 parser = OptionParser()
11154 parser.add_option(
11155 "--output-dir",
11156 help="base directory for resulting files, under chrome/src. default is "
11157 "empty. Use this if you want the result stored under gen.")
11158 parser.add_option(
11159 "-v", "--verbose", action="store_true",
11160 help="prints more output.")
11162 (options, args) = parser.parse_args(args=argv)
11164 # Add in states and capabilites to GLState
11165 gl_state_valid = _NAMED_TYPE_INFO['GLState']['valid']
11166 for state_name in sorted(_STATES.keys()):
11167 state = _STATES[state_name]
11168 if 'extension_flag' in state:
11169 continue
11170 if 'enum' in state:
11171 if not state['enum'] in gl_state_valid:
11172 gl_state_valid.append(state['enum'])
11173 else:
11174 for item in state['states']:
11175 if 'extension_flag' in item:
11176 continue
11177 if not item['enum'] in gl_state_valid:
11178 gl_state_valid.append(item['enum'])
11179 for capability in _CAPABILITY_FLAGS:
11180 valid_value = "GL_%s" % capability['name'].upper()
11181 if not valid_value in gl_state_valid:
11182 gl_state_valid.append(valid_value)
11184 # This script lives under gpu/command_buffer, cd to base directory.
11185 os.chdir(os.path.dirname(__file__) + "/../..")
11186 base_dir = os.getcwd()
11187 gen = GLGenerator(options.verbose)
11188 gen.ParseGLH("gpu/command_buffer/cmd_buffer_functions.txt")
11190 # Support generating files under gen/
11191 if options.output_dir != None:
11192 os.chdir(options.output_dir)
11194 gen.WritePepperGLES2Interface("ppapi/api/ppb_opengles2.idl", False)
11195 gen.WritePepperGLES2Interface("ppapi/api/dev/ppb_opengles2ext_dev.idl", True)
11196 gen.WriteGLES2ToPPAPIBridge("ppapi/lib/gl/gles2/gles2.c")
11197 gen.WritePepperGLES2Implementation(
11198 "ppapi/shared_impl/ppb_opengles2_shared.cc")
11199 os.chdir(base_dir)
11200 gen.WriteCommandIds("gpu/command_buffer/common/gles2_cmd_ids_autogen.h")
11201 gen.WriteFormat("gpu/command_buffer/common/gles2_cmd_format_autogen.h")
11202 gen.WriteFormatTest(
11203 "gpu/command_buffer/common/gles2_cmd_format_test_autogen.h")
11204 gen.WriteGLES2InterfaceHeader(
11205 "gpu/command_buffer/client/gles2_interface_autogen.h")
11206 gen.WriteMojoGLES2ImplHeader(
11207 "mojo/gpu/mojo_gles2_impl_autogen.h")
11208 gen.WriteMojoGLES2Impl(
11209 "mojo/gpu/mojo_gles2_impl_autogen.cc")
11210 gen.WriteGLES2InterfaceStub(
11211 "gpu/command_buffer/client/gles2_interface_stub_autogen.h")
11212 gen.WriteGLES2InterfaceStubImpl(
11213 "gpu/command_buffer/client/gles2_interface_stub_impl_autogen.h")
11214 gen.WriteGLES2ImplementationHeader(
11215 "gpu/command_buffer/client/gles2_implementation_autogen.h")
11216 gen.WriteGLES2Implementation(
11217 "gpu/command_buffer/client/gles2_implementation_impl_autogen.h")
11218 gen.WriteGLES2ImplementationUnitTests(
11219 "gpu/command_buffer/client/gles2_implementation_unittest_autogen.h")
11220 gen.WriteGLES2TraceImplementationHeader(
11221 "gpu/command_buffer/client/gles2_trace_implementation_autogen.h")
11222 gen.WriteGLES2TraceImplementation(
11223 "gpu/command_buffer/client/gles2_trace_implementation_impl_autogen.h")
11224 gen.WriteGLES2CLibImplementation(
11225 "gpu/command_buffer/client/gles2_c_lib_autogen.h")
11226 gen.WriteCmdHelperHeader(
11227 "gpu/command_buffer/client/gles2_cmd_helper_autogen.h")
11228 gen.WriteServiceImplementation(
11229 "gpu/command_buffer/service/gles2_cmd_decoder_autogen.h")
11230 gen.WriteServiceContextStateHeader(
11231 "gpu/command_buffer/service/context_state_autogen.h")
11232 gen.WriteServiceContextStateImpl(
11233 "gpu/command_buffer/service/context_state_impl_autogen.h")
11234 gen.WriteClientContextStateHeader(
11235 "gpu/command_buffer/client/client_context_state_autogen.h")
11236 gen.WriteClientContextStateImpl(
11237 "gpu/command_buffer/client/client_context_state_impl_autogen.h")
11238 gen.WriteServiceUnitTests(
11239 "gpu/command_buffer/service/gles2_cmd_decoder_unittest_%d_autogen.h")
11240 gen.WriteServiceUnitTestsForExtensions(
11241 "gpu/command_buffer/service/"
11242 "gles2_cmd_decoder_unittest_extensions_autogen.h")
11243 gen.WriteServiceUtilsHeader(
11244 "gpu/command_buffer/service/gles2_cmd_validation_autogen.h")
11245 gen.WriteServiceUtilsImplementation(
11246 "gpu/command_buffer/service/"
11247 "gles2_cmd_validation_implementation_autogen.h")
11248 gen.WriteCommonUtilsHeader(
11249 "gpu/command_buffer/common/gles2_cmd_utils_autogen.h")
11250 gen.WriteCommonUtilsImpl(
11251 "gpu/command_buffer/common/gles2_cmd_utils_implementation_autogen.h")
11252 gen.WriteGLES2Header("gpu/GLES2/gl2chromium_autogen.h")
11253 mojo_gles2_prefix = ("third_party/mojo/src/mojo/public/c/gles2/"
11254 "gles2_call_visitor")
11255 gen.WriteMojoGLCallVisitor(mojo_gles2_prefix + "_autogen.h")
11256 gen.WriteMojoGLCallVisitorForExtension(
11257 mojo_gles2_prefix + "_chromium_texture_mailbox_autogen.h",
11258 "CHROMIUM_texture_mailbox")
11259 gen.WriteMojoGLCallVisitorForExtension(
11260 mojo_gles2_prefix + "_chromium_sync_point_autogen.h",
11261 "CHROMIUM_sync_point")
11262 gen.WriteMojoGLCallVisitorForExtension(
11263 mojo_gles2_prefix + "_chromium_sub_image_autogen.h",
11264 "CHROMIUM_sub_image")
11265 gen.WriteMojoGLCallVisitorForExtension(
11266 mojo_gles2_prefix + "_chromium_miscellaneous_autogen.h",
11267 "CHROMIUM_miscellaneous")
11268 gen.WriteMojoGLCallVisitorForExtension(
11269 mojo_gles2_prefix + "_occlusion_query_ext_autogen.h",
11270 "occlusion_query_EXT")
11271 gen.WriteMojoGLCallVisitorForExtension(
11272 mojo_gles2_prefix + "_chromium_image_autogen.h",
11273 "CHROMIUM_image")
11274 gen.WriteMojoGLCallVisitorForExtension(
11275 mojo_gles2_prefix + "_chromium_copy_texture_autogen.h",
11276 "CHROMIUM_copy_texture")
11277 gen.WriteMojoGLCallVisitorForExtension(
11278 mojo_gles2_prefix + "_chromium_pixel_transfer_buffer_object_autogen.h",
11279 "CHROMIUM_pixel_transfer_buffer_object")
11281 Format(gen.generated_cpp_filenames)
11283 if gen.errors > 0:
11284 print "%d errors" % gen.errors
11285 return 1
11286 return 0
11289 if __name__ == '__main__':
11290 sys.exit(main(sys.argv[1:]))