Supervised user import: Listen for profile creation/deletion
[chromium-blink-merge.git] / gpu / command_buffer / build_gles2_cmd_buffer.py
blobcb1d0034462d7c068a7f24877c073e27ada008cc
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',
545 # Named type info object represents a named type that is used in OpenGL call
546 # arguments. Each named type defines a set of valid OpenGL call arguments. The
547 # named types are used in 'cmd_buffer_functions.txt'.
548 # type: The actual GL type of the named type.
549 # valid: The list of values that are valid for both the client and the service.
550 # valid_es3: The list of values that are valid in OpenGL ES 3, but not ES 2.
551 # invalid: Examples of invalid values for the type. At least these values
552 # should be tested to be invalid.
553 # deprecated_es3: The list of values that are valid in OpenGL ES 2, but
554 # deprecated in ES 3.
555 # is_complete: The list of valid values of type are final and will not be
556 # modified during runtime.
557 _NAMED_TYPE_INFO = {
558 'BlitFilter': {
559 'type': 'GLenum',
560 'valid': [
561 'GL_NEAREST',
562 'GL_LINEAR',
564 'invalid': [
565 'GL_LINEAR_MIPMAP_LINEAR',
568 'FrameBufferTarget': {
569 'type': 'GLenum',
570 'valid': [
571 'GL_FRAMEBUFFER',
573 'invalid': [
574 'GL_DRAW_FRAMEBUFFER' ,
575 'GL_READ_FRAMEBUFFER' ,
578 'RenderBufferTarget': {
579 'type': 'GLenum',
580 'valid': [
581 'GL_RENDERBUFFER',
583 'invalid': [
584 'GL_FRAMEBUFFER',
587 'BufferTarget': {
588 'type': 'GLenum',
589 'valid': [
590 'GL_ARRAY_BUFFER',
591 'GL_ELEMENT_ARRAY_BUFFER',
593 'valid_es3': [
594 'GL_COPY_READ_BUFFER',
595 'GL_COPY_WRITE_BUFFER',
596 'GL_PIXEL_PACK_BUFFER',
597 'GL_PIXEL_UNPACK_BUFFER',
598 'GL_TRANSFORM_FEEDBACK_BUFFER',
599 'GL_UNIFORM_BUFFER',
601 'invalid': [
602 'GL_RENDERBUFFER',
605 'IndexedBufferTarget': {
606 'type': 'GLenum',
607 'valid': [
608 'GL_TRANSFORM_FEEDBACK_BUFFER',
609 'GL_UNIFORM_BUFFER',
611 'invalid': [
612 'GL_RENDERBUFFER',
615 'MapBufferAccess': {
616 'type': 'GLenum',
617 'valid': [
618 'GL_MAP_READ_BIT',
619 'GL_MAP_WRITE_BIT',
620 'GL_MAP_INVALIDATE_RANGE_BIT',
621 'GL_MAP_INVALIDATE_BUFFER_BIT',
622 'GL_MAP_FLUSH_EXPLICIT_BIT',
623 'GL_MAP_UNSYNCHRONIZED_BIT',
625 'invalid': [
626 'GL_SYNC_FLUSH_COMMANDS_BIT',
629 'Bufferiv': {
630 'type': 'GLenum',
631 'valid': [
632 'GL_COLOR',
633 'GL_STENCIL',
635 'invalid': [
636 'GL_RENDERBUFFER',
639 'Bufferuiv': {
640 'type': 'GLenum',
641 'valid': [
642 'GL_COLOR',
644 'invalid': [
645 'GL_RENDERBUFFER',
648 'Bufferfv': {
649 'type': 'GLenum',
650 'valid': [
651 'GL_COLOR',
652 'GL_DEPTH',
654 'invalid': [
655 'GL_RENDERBUFFER',
658 'Bufferfi': {
659 'type': 'GLenum',
660 'valid': [
661 'GL_DEPTH_STENCIL',
663 'invalid': [
664 'GL_RENDERBUFFER',
667 'BufferUsage': {
668 'type': 'GLenum',
669 'valid': [
670 'GL_STREAM_DRAW',
671 'GL_STATIC_DRAW',
672 'GL_DYNAMIC_DRAW',
674 'invalid': [
675 'GL_STATIC_READ',
678 'CompressedTextureFormat': {
679 'type': 'GLenum',
680 'valid': [
682 'valid_es3': [
683 'GL_COMPRESSED_R11_EAC',
684 'GL_COMPRESSED_SIGNED_R11_EAC',
685 'GL_COMPRESSED_RG11_EAC',
686 'GL_COMPRESSED_SIGNED_RG11_EAC',
687 'GL_COMPRESSED_RGB8_ETC2',
688 'GL_COMPRESSED_SRGB8_ETC2',
689 'GL_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2',
690 'GL_COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2',
691 'GL_COMPRESSED_RGBA8_ETC2_EAC',
692 'GL_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC',
695 'GLState': {
696 'type': 'GLenum',
697 'valid': [
698 # NOTE: State an Capability entries added later.
699 'GL_ACTIVE_TEXTURE',
700 'GL_ALIASED_LINE_WIDTH_RANGE',
701 'GL_ALIASED_POINT_SIZE_RANGE',
702 'GL_ALPHA_BITS',
703 'GL_ARRAY_BUFFER_BINDING',
704 'GL_BLUE_BITS',
705 'GL_COMPRESSED_TEXTURE_FORMATS',
706 'GL_CURRENT_PROGRAM',
707 'GL_DEPTH_BITS',
708 'GL_DEPTH_RANGE',
709 'GL_ELEMENT_ARRAY_BUFFER_BINDING',
710 'GL_FRAMEBUFFER_BINDING',
711 'GL_GENERATE_MIPMAP_HINT',
712 'GL_GREEN_BITS',
713 'GL_IMPLEMENTATION_COLOR_READ_FORMAT',
714 'GL_IMPLEMENTATION_COLOR_READ_TYPE',
715 'GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS',
716 'GL_MAX_CUBE_MAP_TEXTURE_SIZE',
717 'GL_MAX_FRAGMENT_UNIFORM_VECTORS',
718 'GL_MAX_RENDERBUFFER_SIZE',
719 'GL_MAX_TEXTURE_IMAGE_UNITS',
720 'GL_MAX_TEXTURE_SIZE',
721 'GL_MAX_VARYING_VECTORS',
722 'GL_MAX_VERTEX_ATTRIBS',
723 'GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS',
724 'GL_MAX_VERTEX_UNIFORM_VECTORS',
725 'GL_MAX_VIEWPORT_DIMS',
726 'GL_NUM_COMPRESSED_TEXTURE_FORMATS',
727 'GL_NUM_SHADER_BINARY_FORMATS',
728 'GL_PACK_ALIGNMENT',
729 'GL_RED_BITS',
730 'GL_RENDERBUFFER_BINDING',
731 'GL_SAMPLE_BUFFERS',
732 'GL_SAMPLE_COVERAGE_INVERT',
733 'GL_SAMPLE_COVERAGE_VALUE',
734 'GL_SAMPLES',
735 'GL_SCISSOR_BOX',
736 'GL_SHADER_BINARY_FORMATS',
737 'GL_SHADER_COMPILER',
738 'GL_SUBPIXEL_BITS',
739 'GL_STENCIL_BITS',
740 'GL_TEXTURE_BINDING_2D',
741 'GL_TEXTURE_BINDING_CUBE_MAP',
742 'GL_UNPACK_ALIGNMENT',
743 'GL_UNPACK_FLIP_Y_CHROMIUM',
744 'GL_UNPACK_PREMULTIPLY_ALPHA_CHROMIUM',
745 'GL_UNPACK_UNPREMULTIPLY_ALPHA_CHROMIUM',
746 'GL_BIND_GENERATES_RESOURCE_CHROMIUM',
747 # we can add this because we emulate it if the driver does not support it.
748 'GL_VERTEX_ARRAY_BINDING_OES',
749 'GL_VIEWPORT',
751 'valid_es3': [
752 'GL_COPY_READ_BUFFER_BINDING',
753 'GL_COPY_WRITE_BUFFER_BINDING',
754 'GL_DRAW_BUFFER0',
755 'GL_DRAW_BUFFER1',
756 'GL_DRAW_BUFFER2',
757 'GL_DRAW_BUFFER3',
758 'GL_DRAW_BUFFER4',
759 'GL_DRAW_BUFFER5',
760 'GL_DRAW_BUFFER6',
761 'GL_DRAW_BUFFER7',
762 'GL_DRAW_BUFFER8',
763 'GL_DRAW_BUFFER9',
764 'GL_DRAW_BUFFER10',
765 'GL_DRAW_BUFFER11',
766 'GL_DRAW_BUFFER12',
767 'GL_DRAW_BUFFER13',
768 'GL_DRAW_BUFFER14',
769 'GL_DRAW_BUFFER15',
770 'GL_DRAW_FRAMEBUFFER_BINDING',
771 'GL_FRAGMENT_SHADER_DERIVATIVE_HINT',
772 'GL_MAJOR_VERSION',
773 'GL_MAX_3D_TEXTURE_SIZE',
774 'GL_MAX_ARRAY_TEXTURE_LAYERS',
775 'GL_MAX_COLOR_ATTACHMENTS',
776 'GL_MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS',
777 'GL_MAX_COMBINED_UNIFORM_BLOCKS',
778 'GL_MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS',
779 'GL_MAX_DRAW_BUFFERS',
780 'GL_MAX_ELEMENT_INDEX',
781 'GL_MAX_ELEMENTS_INDICES',
782 'GL_MAX_ELEMENTS_VERTICES',
783 'GL_MAX_FRAGMENT_INPUT_COMPONENTS',
784 'GL_MAX_FRAGMENT_UNIFORM_BLOCKS',
785 'GL_MAX_FRAGMENT_UNIFORM_COMPONENTS',
786 'GL_MAX_PROGRAM_TEXEL_OFFSET',
787 'GL_MAX_SAMPLES',
788 'GL_MAX_SERVER_WAIT_TIMEOUT',
789 'GL_MAX_TEXTURE_LOD_BIAS',
790 'GL_MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS',
791 'GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS',
792 'GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS',
793 'GL_MAX_UNIFORM_BLOCK_SIZE',
794 'GL_MAX_UNIFORM_BUFFER_BINDINGS',
795 'GL_MAX_VARYING_COMPONENTS',
796 'GL_MAX_VERTEX_OUTPUT_COMPONENTS',
797 'GL_MAX_VERTEX_UNIFORM_BLOCKS',
798 'GL_MAX_VERTEX_UNIFORM_COMPONENTS',
799 'GL_MIN_PROGRAM_TEXEL_OFFSET',
800 'GL_MINOR_VERSION',
801 'GL_NUM_EXTENSIONS',
802 'GL_NUM_PROGRAM_BINARY_FORMATS',
803 'GL_PACK_ROW_LENGTH',
804 'GL_PACK_SKIP_PIXELS',
805 'GL_PACK_SKIP_ROWS',
806 'GL_PIXEL_PACK_BUFFER_BINDING',
807 'GL_PIXEL_UNPACK_BUFFER_BINDING',
808 'GL_PROGRAM_BINARY_FORMATS',
809 'GL_READ_BUFFER',
810 'GL_READ_FRAMEBUFFER_BINDING',
811 'GL_SAMPLER_BINDING',
812 'GL_TEXTURE_BINDING_2D_ARRAY',
813 'GL_TEXTURE_BINDING_3D',
814 'GL_TRANSFORM_FEEDBACK_BINDING',
815 'GL_TRANSFORM_FEEDBACK_ACTIVE',
816 'GL_TRANSFORM_FEEDBACK_BUFFER_BINDING',
817 'GL_TRANSFORM_FEEDBACK_PAUSED',
818 'GL_TRANSFORM_FEEDBACK_BUFFER_SIZE',
819 'GL_TRANSFORM_FEEDBACK_BUFFER_START',
820 'GL_UNIFORM_BUFFER_BINDING',
821 'GL_UNIFORM_BUFFER_OFFSET_ALIGNMENT',
822 'GL_UNIFORM_BUFFER_SIZE',
823 'GL_UNIFORM_BUFFER_START',
824 'GL_UNPACK_IMAGE_HEIGHT',
825 'GL_UNPACK_ROW_LENGTH',
826 'GL_UNPACK_SKIP_IMAGES',
827 'GL_UNPACK_SKIP_PIXELS',
828 'GL_UNPACK_SKIP_ROWS',
829 # GL_VERTEX_ARRAY_BINDING is the same as GL_VERTEX_ARRAY_BINDING_OES
830 # 'GL_VERTEX_ARRAY_BINDING',
832 'invalid': [
833 'GL_FOG_HINT',
836 'IndexedGLState': {
837 'type': 'GLenum',
838 'valid': [
839 'GL_TRANSFORM_FEEDBACK_BUFFER_BINDING',
840 'GL_TRANSFORM_FEEDBACK_BUFFER_SIZE',
841 'GL_TRANSFORM_FEEDBACK_BUFFER_START',
842 'GL_UNIFORM_BUFFER_BINDING',
843 'GL_UNIFORM_BUFFER_SIZE',
844 'GL_UNIFORM_BUFFER_START',
846 'invalid': [
847 'GL_FOG_HINT',
850 'GetTexParamTarget': {
851 'type': 'GLenum',
852 'valid': [
853 'GL_TEXTURE_2D',
854 'GL_TEXTURE_CUBE_MAP',
856 'invalid': [
857 'GL_PROXY_TEXTURE_CUBE_MAP',
860 'TextureTarget': {
861 'type': 'GLenum',
862 'valid': [
863 'GL_TEXTURE_2D',
864 'GL_TEXTURE_CUBE_MAP_POSITIVE_X',
865 'GL_TEXTURE_CUBE_MAP_NEGATIVE_X',
866 'GL_TEXTURE_CUBE_MAP_POSITIVE_Y',
867 'GL_TEXTURE_CUBE_MAP_NEGATIVE_Y',
868 'GL_TEXTURE_CUBE_MAP_POSITIVE_Z',
869 'GL_TEXTURE_CUBE_MAP_NEGATIVE_Z',
871 'invalid': [
872 'GL_PROXY_TEXTURE_CUBE_MAP',
875 'Texture3DTarget': {
876 'type': 'GLenum',
877 'valid': [
878 'GL_TEXTURE_3D',
879 'GL_TEXTURE_2D_ARRAY',
881 'invalid': [
882 'GL_TEXTURE_2D',
885 'TextureBindTarget': {
886 'type': 'GLenum',
887 'valid': [
888 'GL_TEXTURE_2D',
889 'GL_TEXTURE_CUBE_MAP',
891 'valid_es3': [
892 'GL_TEXTURE_3D',
893 'GL_TEXTURE_2D_ARRAY',
895 'invalid': [
896 'GL_TEXTURE_1D',
897 'GL_TEXTURE_3D',
900 'TransformFeedbackBindTarget': {
901 'type': 'GLenum',
902 'valid': [
903 'GL_TRANSFORM_FEEDBACK',
905 'invalid': [
906 'GL_TEXTURE_2D',
909 'TransformFeedbackPrimitiveMode': {
910 'type': 'GLenum',
911 'valid': [
912 'GL_POINTS',
913 'GL_LINES',
914 'GL_TRIANGLES',
916 'invalid': [
917 'GL_LINE_LOOP',
920 'ShaderType': {
921 'type': 'GLenum',
922 'valid': [
923 'GL_VERTEX_SHADER',
924 'GL_FRAGMENT_SHADER',
926 'invalid': [
927 'GL_GEOMETRY_SHADER',
930 'FaceType': {
931 'type': 'GLenum',
932 'valid': [
933 'GL_FRONT',
934 'GL_BACK',
935 'GL_FRONT_AND_BACK',
938 'FaceMode': {
939 'type': 'GLenum',
940 'valid': [
941 'GL_CW',
942 'GL_CCW',
945 'CmpFunction': {
946 'type': 'GLenum',
947 'valid': [
948 'GL_NEVER',
949 'GL_LESS',
950 'GL_EQUAL',
951 'GL_LEQUAL',
952 'GL_GREATER',
953 'GL_NOTEQUAL',
954 'GL_GEQUAL',
955 'GL_ALWAYS',
958 'Equation': {
959 'type': 'GLenum',
960 'valid': [
961 'GL_FUNC_ADD',
962 'GL_FUNC_SUBTRACT',
963 'GL_FUNC_REVERSE_SUBTRACT',
965 'invalid': [
966 'GL_MIN',
967 'GL_MAX',
970 'SrcBlendFactor': {
971 'type': 'GLenum',
972 'valid': [
973 'GL_ZERO',
974 'GL_ONE',
975 'GL_SRC_COLOR',
976 'GL_ONE_MINUS_SRC_COLOR',
977 'GL_DST_COLOR',
978 'GL_ONE_MINUS_DST_COLOR',
979 'GL_SRC_ALPHA',
980 'GL_ONE_MINUS_SRC_ALPHA',
981 'GL_DST_ALPHA',
982 'GL_ONE_MINUS_DST_ALPHA',
983 'GL_CONSTANT_COLOR',
984 'GL_ONE_MINUS_CONSTANT_COLOR',
985 'GL_CONSTANT_ALPHA',
986 'GL_ONE_MINUS_CONSTANT_ALPHA',
987 'GL_SRC_ALPHA_SATURATE',
990 'DstBlendFactor': {
991 'type': 'GLenum',
992 'valid': [
993 'GL_ZERO',
994 'GL_ONE',
995 'GL_SRC_COLOR',
996 'GL_ONE_MINUS_SRC_COLOR',
997 'GL_DST_COLOR',
998 'GL_ONE_MINUS_DST_COLOR',
999 'GL_SRC_ALPHA',
1000 'GL_ONE_MINUS_SRC_ALPHA',
1001 'GL_DST_ALPHA',
1002 'GL_ONE_MINUS_DST_ALPHA',
1003 'GL_CONSTANT_COLOR',
1004 'GL_ONE_MINUS_CONSTANT_COLOR',
1005 'GL_CONSTANT_ALPHA',
1006 'GL_ONE_MINUS_CONSTANT_ALPHA',
1009 'Capability': {
1010 'type': 'GLenum',
1011 'valid': ["GL_%s" % cap['name'].upper() for cap in _CAPABILITY_FLAGS
1012 if 'es3' not in cap or cap['es3'] != True],
1013 'valid_es3': ["GL_%s" % cap['name'].upper() for cap in _CAPABILITY_FLAGS
1014 if 'es3' in cap and cap['es3'] == True],
1015 'invalid': [
1016 'GL_CLIP_PLANE0',
1017 'GL_POINT_SPRITE',
1020 'DrawMode': {
1021 'type': 'GLenum',
1022 'valid': [
1023 'GL_POINTS',
1024 'GL_LINE_STRIP',
1025 'GL_LINE_LOOP',
1026 'GL_LINES',
1027 'GL_TRIANGLE_STRIP',
1028 'GL_TRIANGLE_FAN',
1029 'GL_TRIANGLES',
1031 'invalid': [
1032 'GL_QUADS',
1033 'GL_POLYGON',
1036 'IndexType': {
1037 'type': 'GLenum',
1038 'valid': [
1039 'GL_UNSIGNED_BYTE',
1040 'GL_UNSIGNED_SHORT',
1042 'invalid': [
1043 'GL_UNSIGNED_INT',
1044 'GL_INT',
1047 'GetMaxIndexType': {
1048 'type': 'GLenum',
1049 'valid': [
1050 'GL_UNSIGNED_BYTE',
1051 'GL_UNSIGNED_SHORT',
1052 'GL_UNSIGNED_INT',
1054 'invalid': [
1055 'GL_INT',
1058 'Attachment': {
1059 'type': 'GLenum',
1060 'valid': [
1061 'GL_COLOR_ATTACHMENT0',
1062 'GL_DEPTH_ATTACHMENT',
1063 'GL_STENCIL_ATTACHMENT',
1066 'BackbufferAttachment': {
1067 'type': 'GLenum',
1068 'valid': [
1069 'GL_COLOR_EXT',
1070 'GL_DEPTH_EXT',
1071 'GL_STENCIL_EXT',
1074 'BufferParameter': {
1075 'type': 'GLenum',
1076 'valid': [
1077 'GL_BUFFER_SIZE',
1078 'GL_BUFFER_USAGE',
1080 'invalid': [
1081 'GL_PIXEL_PACK_BUFFER',
1084 'BufferMode': {
1085 'type': 'GLenum',
1086 'valid': [
1087 'GL_INTERLEAVED_ATTRIBS',
1088 'GL_SEPARATE_ATTRIBS',
1090 'invalid': [
1091 'GL_PIXEL_PACK_BUFFER',
1094 'FrameBufferParameter': {
1095 'type': 'GLenum',
1096 'valid': [
1097 'GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE',
1098 'GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME',
1099 'GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL',
1100 'GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE',
1103 'MatrixMode': {
1104 'type': 'GLenum',
1105 'valid': [
1106 'GL_PATH_PROJECTION_CHROMIUM',
1107 'GL_PATH_MODELVIEW_CHROMIUM',
1110 'ProgramParameter': {
1111 'type': 'GLenum',
1112 'valid': [
1113 'GL_DELETE_STATUS',
1114 'GL_LINK_STATUS',
1115 'GL_VALIDATE_STATUS',
1116 'GL_INFO_LOG_LENGTH',
1117 'GL_ATTACHED_SHADERS',
1118 'GL_ACTIVE_ATTRIBUTES',
1119 'GL_ACTIVE_ATTRIBUTE_MAX_LENGTH',
1120 'GL_ACTIVE_UNIFORMS',
1121 'GL_ACTIVE_UNIFORM_MAX_LENGTH',
1124 'QueryObjectParameter': {
1125 'type': 'GLenum',
1126 'valid': [
1127 'GL_QUERY_RESULT_EXT',
1128 'GL_QUERY_RESULT_AVAILABLE_EXT',
1131 'QueryParameter': {
1132 'type': 'GLenum',
1133 'valid': [
1134 'GL_CURRENT_QUERY_EXT',
1137 'QueryTarget': {
1138 'type': 'GLenum',
1139 'valid': [
1140 'GL_ANY_SAMPLES_PASSED_EXT',
1141 'GL_ANY_SAMPLES_PASSED_CONSERVATIVE_EXT',
1142 'GL_COMMANDS_ISSUED_CHROMIUM',
1143 'GL_LATENCY_QUERY_CHROMIUM',
1144 'GL_ASYNC_PIXEL_UNPACK_COMPLETED_CHROMIUM',
1145 'GL_ASYNC_PIXEL_PACK_COMPLETED_CHROMIUM',
1146 'GL_COMMANDS_COMPLETED_CHROMIUM',
1149 'RenderBufferParameter': {
1150 'type': 'GLenum',
1151 'valid': [
1152 'GL_RENDERBUFFER_RED_SIZE',
1153 'GL_RENDERBUFFER_GREEN_SIZE',
1154 'GL_RENDERBUFFER_BLUE_SIZE',
1155 'GL_RENDERBUFFER_ALPHA_SIZE',
1156 'GL_RENDERBUFFER_DEPTH_SIZE',
1157 'GL_RENDERBUFFER_STENCIL_SIZE',
1158 'GL_RENDERBUFFER_WIDTH',
1159 'GL_RENDERBUFFER_HEIGHT',
1160 'GL_RENDERBUFFER_INTERNAL_FORMAT',
1163 'SamplerParameter': {
1164 'type': 'GLenum',
1165 'valid': [
1166 'GL_TEXTURE_MAG_FILTER',
1167 'GL_TEXTURE_MIN_FILTER',
1168 'GL_TEXTURE_MIN_LOD',
1169 'GL_TEXTURE_MAX_LOD',
1170 'GL_TEXTURE_WRAP_S',
1171 'GL_TEXTURE_WRAP_T',
1172 'GL_TEXTURE_WRAP_R',
1173 'GL_TEXTURE_COMPARE_MODE',
1174 'GL_TEXTURE_COMPARE_FUNC',
1176 'invalid': [
1177 'GL_GENERATE_MIPMAP',
1180 'ShaderParameter': {
1181 'type': 'GLenum',
1182 'valid': [
1183 'GL_SHADER_TYPE',
1184 'GL_DELETE_STATUS',
1185 'GL_COMPILE_STATUS',
1186 'GL_INFO_LOG_LENGTH',
1187 'GL_SHADER_SOURCE_LENGTH',
1188 'GL_TRANSLATED_SHADER_SOURCE_LENGTH_ANGLE',
1191 'ShaderPrecision': {
1192 'type': 'GLenum',
1193 'valid': [
1194 'GL_LOW_FLOAT',
1195 'GL_MEDIUM_FLOAT',
1196 'GL_HIGH_FLOAT',
1197 'GL_LOW_INT',
1198 'GL_MEDIUM_INT',
1199 'GL_HIGH_INT',
1202 'StringType': {
1203 'type': 'GLenum',
1204 'valid': [
1205 'GL_VENDOR',
1206 'GL_RENDERER',
1207 'GL_VERSION',
1208 'GL_SHADING_LANGUAGE_VERSION',
1209 'GL_EXTENSIONS',
1212 'TextureParameter': {
1213 'type': 'GLenum',
1214 'valid': [
1215 'GL_TEXTURE_MAG_FILTER',
1216 'GL_TEXTURE_MIN_FILTER',
1217 'GL_TEXTURE_POOL_CHROMIUM',
1218 'GL_TEXTURE_WRAP_S',
1219 'GL_TEXTURE_WRAP_T',
1221 'invalid': [
1222 'GL_GENERATE_MIPMAP',
1225 'TexturePool': {
1226 'type': 'GLenum',
1227 'valid': [
1228 'GL_TEXTURE_POOL_MANAGED_CHROMIUM',
1229 'GL_TEXTURE_POOL_UNMANAGED_CHROMIUM',
1232 'TextureWrapMode': {
1233 'type': 'GLenum',
1234 'valid': [
1235 'GL_CLAMP_TO_EDGE',
1236 'GL_MIRRORED_REPEAT',
1237 'GL_REPEAT',
1240 'TextureMinFilterMode': {
1241 'type': 'GLenum',
1242 'valid': [
1243 'GL_NEAREST',
1244 'GL_LINEAR',
1245 'GL_NEAREST_MIPMAP_NEAREST',
1246 'GL_LINEAR_MIPMAP_NEAREST',
1247 'GL_NEAREST_MIPMAP_LINEAR',
1248 'GL_LINEAR_MIPMAP_LINEAR',
1251 'TextureMagFilterMode': {
1252 'type': 'GLenum',
1253 'valid': [
1254 'GL_NEAREST',
1255 'GL_LINEAR',
1258 'TextureUsage': {
1259 'type': 'GLenum',
1260 'valid': [
1261 'GL_NONE',
1262 'GL_FRAMEBUFFER_ATTACHMENT_ANGLE',
1265 'VertexAttribute': {
1266 'type': 'GLenum',
1267 'valid': [
1268 # some enum that the decoder actually passes through to GL needs
1269 # to be the first listed here since it's used in unit tests.
1270 'GL_VERTEX_ATTRIB_ARRAY_NORMALIZED',
1271 'GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING',
1272 'GL_VERTEX_ATTRIB_ARRAY_ENABLED',
1273 'GL_VERTEX_ATTRIB_ARRAY_SIZE',
1274 'GL_VERTEX_ATTRIB_ARRAY_STRIDE',
1275 'GL_VERTEX_ATTRIB_ARRAY_TYPE',
1276 'GL_CURRENT_VERTEX_ATTRIB',
1279 'VertexPointer': {
1280 'type': 'GLenum',
1281 'valid': [
1282 'GL_VERTEX_ATTRIB_ARRAY_POINTER',
1285 'HintTarget': {
1286 'type': 'GLenum',
1287 'valid': [
1288 'GL_GENERATE_MIPMAP_HINT',
1290 'invalid': [
1291 'GL_PERSPECTIVE_CORRECTION_HINT',
1294 'HintMode': {
1295 'type': 'GLenum',
1296 'valid': [
1297 'GL_FASTEST',
1298 'GL_NICEST',
1299 'GL_DONT_CARE',
1302 'PixelStore': {
1303 'type': 'GLenum',
1304 'valid': [
1305 'GL_PACK_ALIGNMENT',
1306 'GL_UNPACK_ALIGNMENT',
1307 'GL_UNPACK_FLIP_Y_CHROMIUM',
1308 'GL_UNPACK_PREMULTIPLY_ALPHA_CHROMIUM',
1309 'GL_UNPACK_UNPREMULTIPLY_ALPHA_CHROMIUM',
1311 'invalid': [
1312 'GL_PACK_SWAP_BYTES',
1313 'GL_UNPACK_SWAP_BYTES',
1316 'PixelStoreAlignment': {
1317 'type': 'GLint',
1318 'valid': [
1319 '1',
1320 '2',
1321 '4',
1322 '8',
1324 'invalid': [
1325 '3',
1326 '9',
1329 'ReadPixelFormat': {
1330 'type': 'GLenum',
1331 'valid': [
1332 'GL_ALPHA',
1333 'GL_RGB',
1334 'GL_RGBA',
1337 'PixelType': {
1338 'type': 'GLenum',
1339 'valid': [
1340 'GL_UNSIGNED_BYTE',
1341 'GL_UNSIGNED_SHORT_5_6_5',
1342 'GL_UNSIGNED_SHORT_4_4_4_4',
1343 'GL_UNSIGNED_SHORT_5_5_5_1',
1345 'valid_es3': [
1346 'GL_BYTE',
1347 'GL_UNSIGNED_SHORT',
1348 'GL_SHORT',
1349 'GL_UNSIGNED_INT',
1350 'GL_INT',
1351 'GL_HALF_FLOAT',
1352 'GL_FLOAT',
1353 'GL_UNSIGNED_INT_2_10_10_10_REV',
1354 'GL_UNSIGNED_INT_10F_11F_11F_REV',
1355 'GL_UNSIGNED_INT_5_9_9_9_REV',
1356 'GL_UNSIGNED_INT_24_8',
1357 'GL_FLOAT_32_UNSIGNED_INT_24_8_REV',
1359 'invalid': [
1360 'GL_UNSIGNED_BYTE_3_3_2',
1363 'ReadPixelType': {
1364 'type': 'GLenum',
1365 'valid': [
1366 'GL_UNSIGNED_BYTE',
1367 'GL_UNSIGNED_SHORT_5_6_5',
1368 'GL_UNSIGNED_SHORT_4_4_4_4',
1369 'GL_UNSIGNED_SHORT_5_5_5_1',
1371 'invalid': [
1372 'GL_SHORT',
1373 'GL_INT',
1376 'RenderBufferFormat': {
1377 'type': 'GLenum',
1378 'valid': [
1379 'GL_RGBA4',
1380 'GL_RGB565',
1381 'GL_RGB5_A1',
1382 'GL_DEPTH_COMPONENT16',
1383 'GL_STENCIL_INDEX8',
1386 'ShaderBinaryFormat': {
1387 'type': 'GLenum',
1388 'valid': [
1391 'StencilOp': {
1392 'type': 'GLenum',
1393 'valid': [
1394 'GL_KEEP',
1395 'GL_ZERO',
1396 'GL_REPLACE',
1397 'GL_INCR',
1398 'GL_INCR_WRAP',
1399 'GL_DECR',
1400 'GL_DECR_WRAP',
1401 'GL_INVERT',
1404 'TextureFormat': {
1405 'type': 'GLenum',
1406 'valid': [
1407 'GL_ALPHA',
1408 'GL_LUMINANCE',
1409 'GL_LUMINANCE_ALPHA',
1410 'GL_RGB',
1411 'GL_RGBA',
1413 'valid_es3': [
1414 'GL_RED',
1415 'GL_RED_INTEGER',
1416 'GL_RG',
1417 'GL_RG_INTEGER',
1418 'GL_RGB_INTEGER',
1419 'GL_RGBA_INTEGER',
1420 'GL_DEPTH_COMPONENT',
1421 'GL_DEPTH_STENCIL',
1423 'invalid': [
1424 'GL_BGRA',
1425 'GL_BGR',
1428 'TextureInternalFormat': {
1429 'type': 'GLenum',
1430 'valid': [
1431 'GL_ALPHA',
1432 'GL_LUMINANCE',
1433 'GL_LUMINANCE_ALPHA',
1434 'GL_RGB',
1435 'GL_RGBA',
1437 'valid_es3': [
1438 'GL_R8',
1439 'GL_R8_SNORM',
1440 'GL_R16F',
1441 'GL_R32F',
1442 'GL_R8UI',
1443 'GL_R8I',
1444 'GL_R16UI',
1445 'GL_R16I',
1446 'GL_R32UI',
1447 'GL_R32I',
1448 'GL_RG8',
1449 'GL_RG8_SNORM',
1450 'GL_RG16F',
1451 'GL_RG32F',
1452 'GL_RG8UI',
1453 'GL_RG8I',
1454 'GL_RG16UI',
1455 'GL_RG16I',
1456 'GL_RG32UI',
1457 'GL_RG32I',
1458 'GL_RGB8',
1459 'GL_SRGB8',
1460 'GL_RGB565',
1461 'GL_RGB8_SNORM',
1462 'GL_R11F_G11F_B10F',
1463 'GL_RGB9_E5',
1464 'GL_RGB16F',
1465 'GL_RGB32F',
1466 'GL_RGB8UI',
1467 'GL_RGB8I',
1468 'GL_RGB16UI',
1469 'GL_RGB16I',
1470 'GL_RGB32UI',
1471 'GL_RGB32I',
1472 'GL_RGBA8',
1473 'GL_SRGB8_ALPHA8',
1474 'GL_RGBA8_SNORM',
1475 'GL_RGB5_A1',
1476 'GL_RGBA4',
1477 'GL_RGB10_A2',
1478 'GL_RGBA16F',
1479 'GL_RGBA32F',
1480 'GL_RGBA8UI',
1481 'GL_RGBA8I',
1482 'GL_RGB10_A2UI',
1483 'GL_RGBA16UI',
1484 'GL_RGBA16I',
1485 'GL_RGBA32UI',
1486 'GL_RGBA32I',
1487 # The DEPTH/STENCIL formats are not supported in CopyTexImage2D.
1488 # We will reject them dynamically in GPU command buffer.
1489 'GL_DEPTH_COMPONENT16',
1490 'GL_DEPTH_COMPONENT24',
1491 'GL_DEPTH_COMPONENT32F',
1492 'GL_DEPTH24_STENCIL8',
1493 'GL_DEPTH32F_STENCIL8',
1495 'invalid': [
1496 'GL_BGRA',
1497 'GL_BGR',
1500 'TextureInternalFormatStorage': {
1501 'type': 'GLenum',
1502 'valid': [
1503 'GL_RGB565',
1504 'GL_RGBA4',
1505 'GL_RGB5_A1',
1506 'GL_ALPHA8_EXT',
1507 'GL_LUMINANCE8_EXT',
1508 'GL_LUMINANCE8_ALPHA8_EXT',
1509 'GL_RGB8_OES',
1510 'GL_RGBA8_OES',
1512 'valid_es3': [
1513 'GL_R8',
1514 'GL_R8_SNORM',
1515 'GL_R16F',
1516 'GL_R32F',
1517 'GL_R8UI',
1518 'GL_R8I',
1519 'GL_R16UI',
1520 'GL_R16I',
1521 'GL_R32UI',
1522 'GL_R32I',
1523 'GL_RG8',
1524 'GL_RG8_SNORM',
1525 'GL_RG16F',
1526 'GL_RG32F',
1527 'GL_RG8UI',
1528 'GL_RG8I',
1529 'GL_RG16UI',
1530 'GL_RG16I',
1531 'GL_RG32UI',
1532 'GL_RG32I',
1533 'GL_SRGB8',
1534 'GL_RGB8_SNORM',
1535 'GL_R11F_G11F_B10F',
1536 'GL_RGB9_E5',
1537 'GL_RGB16F',
1538 'GL_RGB32F',
1539 'GL_RGB8UI',
1540 'GL_RGB8I',
1541 'GL_RGB16UI',
1542 'GL_RGB16I',
1543 'GL_RGB32UI',
1544 'GL_RGB32I',
1545 'GL_SRGB8_ALPHA8',
1546 'GL_RGBA8_SNORM',
1547 'GL_RGB10_A2',
1548 'GL_RGBA16F',
1549 'GL_RGBA32F',
1550 'GL_RGBA8UI',
1551 'GL_RGBA8I',
1552 'GL_RGB10_A2UI',
1553 'GL_RGBA16UI',
1554 'GL_RGBA16I',
1555 'GL_RGBA32UI',
1556 'GL_RGBA32I',
1557 'GL_DEPTH_COMPONENT16',
1558 'GL_DEPTH_COMPONENT24',
1559 'GL_DEPTH_COMPONENT32F',
1560 'GL_DEPTH24_STENCIL8',
1561 'GL_DEPTH32F_STENCIL8',
1562 'GL_COMPRESSED_R11_EAC',
1563 'GL_COMPRESSED_SIGNED_R11_EAC',
1564 'GL_COMPRESSED_RG11_EAC',
1565 'GL_COMPRESSED_SIGNED_RG11_EAC',
1566 'GL_COMPRESSED_RGB8_ETC2',
1567 'GL_COMPRESSED_SRGB8_ETC2',
1568 'GL_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2',
1569 'GL_COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2',
1570 'GL_COMPRESSED_RGBA8_ETC2_EAC',
1571 'GL_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC',
1573 'deprecated_es3': [
1574 'GL_ALPHA8_EXT',
1575 'GL_LUMINANCE8_EXT',
1576 'GL_LUMINANCE8_ALPHA8_EXT',
1577 'GL_ALPHA16F_EXT',
1578 'GL_LUMINANCE16F_EXT',
1579 'GL_LUMINANCE_ALPHA16F_EXT',
1580 'GL_ALPHA32F_EXT',
1581 'GL_LUMINANCE32F_EXT',
1582 'GL_LUMINANCE_ALPHA32F_EXT',
1585 'ImageInternalFormat': {
1586 'type': 'GLenum',
1587 'valid': [
1588 'GL_RGB',
1589 'GL_RGB_YUV_420_CHROMIUM',
1590 'GL_RGBA',
1593 'ImageUsage': {
1594 'type': 'GLenum',
1595 'valid': [
1596 'GL_MAP_CHROMIUM',
1597 'GL_SCANOUT_CHROMIUM'
1600 'ValueBufferTarget': {
1601 'type': 'GLenum',
1602 'valid': [
1603 'GL_SUBSCRIBED_VALUES_BUFFER_CHROMIUM',
1606 'SubscriptionTarget': {
1607 'type': 'GLenum',
1608 'valid': [
1609 'GL_MOUSE_POSITION_CHROMIUM',
1612 'UniformParameter': {
1613 'type': 'GLenum',
1614 'valid': [
1615 'GL_UNIFORM_SIZE',
1616 'GL_UNIFORM_TYPE',
1617 'GL_UNIFORM_NAME_LENGTH',
1618 'GL_UNIFORM_BLOCK_INDEX',
1619 'GL_UNIFORM_OFFSET',
1620 'GL_UNIFORM_ARRAY_STRIDE',
1621 'GL_UNIFORM_MATRIX_STRIDE',
1622 'GL_UNIFORM_IS_ROW_MAJOR',
1624 'invalid': [
1625 'GL_UNIFORM_BLOCK_NAME_LENGTH',
1628 'UniformBlockParameter': {
1629 'type': 'GLenum',
1630 'valid': [
1631 'GL_UNIFORM_BLOCK_BINDING',
1632 'GL_UNIFORM_BLOCK_DATA_SIZE',
1633 'GL_UNIFORM_BLOCK_NAME_LENGTH',
1634 'GL_UNIFORM_BLOCK_ACTIVE_UNIFORMS',
1635 'GL_UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES',
1636 'GL_UNIFORM_BLOCK_REFERENCED_BY_VERTEX_SHADER',
1637 'GL_UNIFORM_BLOCK_REFERENCED_BY_FRAGMENT_SHADER',
1639 'invalid': [
1640 'GL_NEAREST',
1643 'VertexAttribType': {
1644 'type': 'GLenum',
1645 'valid': [
1646 'GL_BYTE',
1647 'GL_UNSIGNED_BYTE',
1648 'GL_SHORT',
1649 'GL_UNSIGNED_SHORT',
1650 # 'GL_FIXED', // This is not available on Desktop GL.
1651 'GL_FLOAT',
1653 'invalid': [
1654 'GL_DOUBLE',
1657 'VertexAttribIType': {
1658 'type': 'GLenum',
1659 'valid': [
1660 'GL_BYTE',
1661 'GL_UNSIGNED_BYTE',
1662 'GL_SHORT',
1663 'GL_UNSIGNED_SHORT',
1664 'GL_INT',
1665 'GL_UNSIGNED_INT',
1667 'invalid': [
1668 'GL_FLOAT',
1669 'GL_DOUBLE',
1672 'TextureBorder': {
1673 'type': 'GLint',
1674 'is_complete': True,
1675 'valid': [
1676 '0',
1678 'invalid': [
1679 '1',
1682 'VertexAttribSize': {
1683 'type': 'GLint',
1684 'valid': [
1685 '1',
1686 '2',
1687 '3',
1688 '4',
1690 'invalid': [
1691 '0',
1692 '5',
1695 'ZeroOnly': {
1696 'type': 'GLint',
1697 'is_complete': True,
1698 'valid': [
1699 '0',
1701 'invalid': [
1702 '1',
1705 'FalseOnly': {
1706 'type': 'GLboolean',
1707 'is_complete': True,
1708 'valid': [
1709 'false',
1711 'invalid': [
1712 'true',
1715 'ResetStatus': {
1716 'type': 'GLenum',
1717 'valid': [
1718 'GL_GUILTY_CONTEXT_RESET_ARB',
1719 'GL_INNOCENT_CONTEXT_RESET_ARB',
1720 'GL_UNKNOWN_CONTEXT_RESET_ARB',
1723 'SyncCondition': {
1724 'type': 'GLenum',
1725 'is_complete': True,
1726 'valid': [
1727 'GL_SYNC_GPU_COMMANDS_COMPLETE',
1729 'invalid': [
1730 '0',
1733 'SyncFlags': {
1734 'type': 'GLbitfield',
1735 'is_complete': True,
1736 'valid': [
1737 '0',
1739 'invalid': [
1740 '1',
1743 'SyncFlushFlags': {
1744 'type': 'GLbitfield',
1745 'valid': [
1746 'GL_SYNC_FLUSH_COMMANDS_BIT',
1747 '0',
1749 'invalid': [
1750 '0xFFFFFFFF',
1753 'SyncParameter': {
1754 'type': 'GLenum',
1755 'valid': [
1756 'GL_SYNC_STATUS', # This needs to be the 1st; all others are cached.
1757 'GL_OBJECT_TYPE',
1758 'GL_SYNC_CONDITION',
1759 'GL_SYNC_FLAGS',
1761 'invalid': [
1762 'GL_SYNC_FENCE',
1767 # This table specifies the different pepper interfaces that are supported for
1768 # GL commands. 'dev' is true if it's a dev interface.
1769 _PEPPER_INTERFACES = [
1770 {'name': '', 'dev': False},
1771 {'name': 'InstancedArrays', 'dev': False},
1772 {'name': 'FramebufferBlit', 'dev': False},
1773 {'name': 'FramebufferMultisample', 'dev': False},
1774 {'name': 'ChromiumEnableFeature', 'dev': False},
1775 {'name': 'ChromiumMapSub', 'dev': False},
1776 {'name': 'Query', 'dev': False},
1777 {'name': 'VertexArrayObject', 'dev': False},
1778 {'name': 'DrawBuffers', 'dev': True},
1781 # A function info object specifies the type and other special data for the
1782 # command that will be generated. A base function info object is generated by
1783 # parsing the "cmd_buffer_functions.txt", one for each function in the
1784 # file. These function info objects can be augmented and their values can be
1785 # overridden by adding an object to the table below.
1787 # Must match function names specified in "cmd_buffer_functions.txt".
1789 # cmd_comment: A comment added to the cmd format.
1790 # type: defines which handler will be used to generate code.
1791 # decoder_func: defines which function to call in the decoder to execute the
1792 # corresponding GL command. If not specified the GL command will
1793 # be called directly.
1794 # gl_test_func: GL function that is expected to be called when testing.
1795 # cmd_args: The arguments to use for the command. This overrides generating
1796 # them based on the GL function arguments.
1797 # gen_cmd: Whether or not this function geneates a command. Default = True.
1798 # data_transfer_methods: Array of methods that are used for transfering the
1799 # pointer data. Possible values: 'immediate', 'shm', 'bucket'.
1800 # The default is 'immediate' if the command has one pointer
1801 # argument, otherwise 'shm'. One command is generated for each
1802 # transfer method. Affects only commands which are not of type
1803 # 'HandWritten', 'GETn' or 'GLcharN'.
1804 # Note: the command arguments that affect this are the final args,
1805 # taking cmd_args override into consideration.
1806 # impl_func: Whether or not to generate the GLES2Implementation part of this
1807 # command.
1808 # impl_decl: Whether or not to generate the GLES2Implementation declaration
1809 # for this command.
1810 # needs_size: If True a data_size field is added to the command.
1811 # count: The number of units per element. For PUTn or PUT types.
1812 # use_count_func: If True the actual data count needs to be computed; the count
1813 # argument specifies the maximum count.
1814 # unit_test: If False no service side unit test will be generated.
1815 # client_test: If False no client side unit test will be generated.
1816 # expectation: If False the unit test will have no expected calls.
1817 # gen_func: Name of function that generates GL resource for corresponding
1818 # bind function.
1819 # states: array of states that get set by this function corresponding to
1820 # the given arguments
1821 # state_flag: name of flag that is set to true when function is called.
1822 # no_gl: no GL function is called.
1823 # valid_args: A dictionary of argument indices to args to use in unit tests
1824 # when they can not be automatically determined.
1825 # pepper_interface: The pepper interface that is used for this extension
1826 # pepper_name: The name of the function as exposed to pepper.
1827 # pepper_args: A string representing the argument list (what would appear in
1828 # C/C++ between the parentheses for the function declaration)
1829 # that the Pepper API expects for this function. Use this only if
1830 # the stable Pepper API differs from the GLES2 argument list.
1831 # invalid_test: False if no invalid test needed.
1832 # shadowed: True = the value is shadowed so no glGetXXX call will be made.
1833 # first_element_only: For PUT types, True if only the first element of an
1834 # array is used and we end up calling the single value
1835 # corresponding function. eg. TexParameteriv -> TexParameteri
1836 # extension: Function is an extension to GL and should not be exposed to
1837 # pepper unless pepper_interface is defined.
1838 # extension_flag: Function is an extension and should be enabled only when
1839 # the corresponding feature info flag is enabled. Implies
1840 # 'extension': True.
1841 # not_shared: For GENn types, True if objects can't be shared between contexts
1842 # unsafe: True = no validation is implemented on the service side and the
1843 # command is only available with --enable-unsafe-es3-apis.
1844 # id_mapping: A list of resource type names whose client side IDs need to be
1845 # mapped to service side IDs. This is only used for unsafe APIs.
1847 _FUNCTION_INFO = {
1848 'ActiveTexture': {
1849 'decoder_func': 'DoActiveTexture',
1850 'unit_test': False,
1851 'impl_func': False,
1852 'client_test': False,
1854 'AttachShader': {'decoder_func': 'DoAttachShader'},
1855 'BindAttribLocation': {
1856 'type': 'GLchar',
1857 'data_transfer_methods': ['bucket'],
1858 'needs_size': True,
1860 'BindBuffer': {
1861 'type': 'Bind',
1862 'decoder_func': 'DoBindBuffer',
1863 'gen_func': 'GenBuffersARB',
1865 'BindBufferBase': {
1866 'type': 'Bind',
1867 'id_mapping': [ 'Buffer' ],
1868 'gen_func': 'GenBuffersARB',
1869 'unsafe': True,
1871 'BindBufferRange': {
1872 'type': 'Bind',
1873 'id_mapping': [ 'Buffer' ],
1874 'gen_func': 'GenBuffersARB',
1875 'valid_args': {
1876 '3': '4',
1877 '4': '4'
1879 'unsafe': True,
1881 'BindFramebuffer': {
1882 'type': 'Bind',
1883 'decoder_func': 'DoBindFramebuffer',
1884 'gl_test_func': 'glBindFramebufferEXT',
1885 'gen_func': 'GenFramebuffersEXT',
1886 'trace_level': 1,
1888 'BindRenderbuffer': {
1889 'type': 'Bind',
1890 'decoder_func': 'DoBindRenderbuffer',
1891 'gl_test_func': 'glBindRenderbufferEXT',
1892 'gen_func': 'GenRenderbuffersEXT',
1894 'BindSampler': {
1895 'type': 'Bind',
1896 'id_mapping': [ 'Sampler' ],
1897 'unsafe': True,
1899 'BindTexture': {
1900 'type': 'Bind',
1901 'decoder_func': 'DoBindTexture',
1902 'gen_func': 'GenTextures',
1903 # TODO(gman): remove this once client side caching works.
1904 'client_test': False,
1905 'trace_level': 1,
1907 'BindTransformFeedback': {
1908 'type': 'Bind',
1909 'id_mapping': [ 'TransformFeedback' ],
1910 'unsafe': True,
1912 'BlitFramebufferCHROMIUM': {
1913 'decoder_func': 'DoBlitFramebufferCHROMIUM',
1914 'unit_test': False,
1915 'extension_flag': 'chromium_framebuffer_multisample',
1916 'pepper_interface': 'FramebufferBlit',
1917 'pepper_name': 'BlitFramebufferEXT',
1918 'defer_reads': True,
1919 'defer_draws': True,
1920 'trace_level': 1,
1922 'BufferData': {
1923 'type': 'Manual',
1924 'data_transfer_methods': ['shm'],
1925 'client_test': False,
1927 'BufferSubData': {
1928 'type': 'Data',
1929 'client_test': False,
1930 'decoder_func': 'DoBufferSubData',
1931 'data_transfer_methods': ['shm'],
1933 'CheckFramebufferStatus': {
1934 'type': 'Is',
1935 'decoder_func': 'DoCheckFramebufferStatus',
1936 'gl_test_func': 'glCheckFramebufferStatusEXT',
1937 'error_value': 'GL_FRAMEBUFFER_UNSUPPORTED',
1938 'result': ['GLenum'],
1940 'Clear': {
1941 'decoder_func': 'DoClear',
1942 'defer_draws': True,
1943 'trace_level': 1,
1945 'ClearBufferiv': {
1946 'type': 'PUT',
1947 'use_count_func': True,
1948 'count': 4,
1949 'unsafe': True,
1951 'ClearBufferuiv': {
1952 'type': 'PUT',
1953 'count': 4,
1954 'unsafe': True,
1956 'ClearBufferfv': {
1957 'type': 'PUT',
1958 'use_count_func': True,
1959 'count': 4,
1960 'unsafe': True,
1962 'ClearBufferfi': {
1963 'unsafe': True,
1965 'ClearColor': {
1966 'type': 'StateSet',
1967 'state': 'ClearColor',
1969 'ClearDepthf': {
1970 'type': 'StateSet',
1971 'state': 'ClearDepthf',
1972 'decoder_func': 'glClearDepth',
1973 'gl_test_func': 'glClearDepth',
1974 'valid_args': {
1975 '0': '0.5f'
1978 'ClientWaitSync': {
1979 'type': 'Custom',
1980 'data_transfer_methods': ['shm'],
1981 'cmd_args': 'GLuint sync, GLbitfieldSyncFlushFlags flags, '
1982 'GLuint timeout_0, GLuint timeout_1, GLenum* result',
1983 'unsafe': True,
1984 'result': ['GLenum'],
1986 'ColorMask': {
1987 'type': 'StateSet',
1988 'state': 'ColorMask',
1989 'no_gl': True,
1990 'expectation': False,
1992 'ConsumeTextureCHROMIUM': {
1993 'decoder_func': 'DoConsumeTextureCHROMIUM',
1994 'impl_func': False,
1995 'type': 'PUT',
1996 'count': 64, # GL_MAILBOX_SIZE_CHROMIUM
1997 'unit_test': False,
1998 'client_test': False,
1999 'extension': "CHROMIUM_texture_mailbox",
2000 'chromium': True,
2001 'trace_level': 1,
2003 'CopyBufferSubData': {
2004 'unsafe': True,
2006 'CreateAndConsumeTextureCHROMIUM': {
2007 'decoder_func': 'DoCreateAndConsumeTextureCHROMIUM',
2008 'impl_func': False,
2009 'type': 'HandWritten',
2010 'data_transfer_methods': ['immediate'],
2011 'unit_test': False,
2012 'client_test': False,
2013 'extension': "CHROMIUM_texture_mailbox",
2014 'chromium': True,
2016 'GenValuebuffersCHROMIUM': {
2017 'type': 'GENn',
2018 'gl_test_func': 'glGenValuebuffersCHROMIUM',
2019 'resource_type': 'Valuebuffer',
2020 'resource_types': 'Valuebuffers',
2021 'unit_test': False,
2022 'extension': True,
2023 'chromium': True,
2025 'DeleteValuebuffersCHROMIUM': {
2026 'type': 'DELn',
2027 'gl_test_func': 'glDeleteValuebuffersCHROMIUM',
2028 'resource_type': 'Valuebuffer',
2029 'resource_types': 'Valuebuffers',
2030 'unit_test': False,
2031 'extension': True,
2032 'chromium': True,
2034 'IsValuebufferCHROMIUM': {
2035 'type': 'Is',
2036 'decoder_func': 'DoIsValuebufferCHROMIUM',
2037 'expectation': False,
2038 'extension': True,
2039 'chromium': True,
2041 'BindValuebufferCHROMIUM': {
2042 'type': 'Bind',
2043 'decoder_func': 'DoBindValueBufferCHROMIUM',
2044 'gen_func': 'GenValueBuffersCHROMIUM',
2045 'unit_test': False,
2046 'extension': True,
2047 'chromium': True,
2049 'SubscribeValueCHROMIUM': {
2050 'decoder_func': 'DoSubscribeValueCHROMIUM',
2051 'unit_test': False,
2052 'extension': True,
2053 'chromium': True,
2055 'PopulateSubscribedValuesCHROMIUM': {
2056 'decoder_func': 'DoPopulateSubscribedValuesCHROMIUM',
2057 'unit_test': False,
2058 'extension': True,
2059 'chromium': True,
2061 'UniformValuebufferCHROMIUM': {
2062 'decoder_func': 'DoUniformValueBufferCHROMIUM',
2063 'unit_test': False,
2064 'extension': True,
2065 'chromium': True,
2067 'ClearStencil': {
2068 'type': 'StateSet',
2069 'state': 'ClearStencil',
2071 'EnableFeatureCHROMIUM': {
2072 'type': 'Custom',
2073 'data_transfer_methods': ['shm'],
2074 'decoder_func': 'DoEnableFeatureCHROMIUM',
2075 'expectation': False,
2076 'cmd_args': 'GLuint bucket_id, GLint* result',
2077 'result': ['GLint'],
2078 'extension': True,
2079 'chromium': True,
2080 'pepper_interface': 'ChromiumEnableFeature',
2082 'CompileShader': {'decoder_func': 'DoCompileShader', 'unit_test': False},
2083 'CompressedTexImage2D': {
2084 'type': 'Manual',
2085 'data_transfer_methods': ['bucket', 'shm'],
2087 'CompressedTexSubImage2D': {
2088 'type': 'Data',
2089 'data_transfer_methods': ['bucket', 'shm'],
2090 'decoder_func': 'DoCompressedTexSubImage2D',
2092 'CopyTexImage2D': {
2093 'decoder_func': 'DoCopyTexImage2D',
2094 'unit_test': False,
2095 'defer_reads': True,
2097 'CopyTexSubImage2D': {
2098 'decoder_func': 'DoCopyTexSubImage2D',
2099 'defer_reads': True,
2101 'CompressedTexImage3D': {
2102 'type': 'Manual',
2103 'data_transfer_methods': ['bucket', 'shm'],
2104 'unsafe': True,
2106 'CopyTexSubImage3D': {
2107 'defer_reads': True,
2108 'unsafe': True,
2110 'CreateImageCHROMIUM': {
2111 'type': 'Manual',
2112 'cmd_args':
2113 'ClientBuffer buffer, GLsizei width, GLsizei height, '
2114 'GLenum internalformat',
2115 'result': ['GLuint'],
2116 'client_test': False,
2117 'gen_cmd': False,
2118 'expectation': False,
2119 'extension': True,
2120 'chromium': True,
2122 'DestroyImageCHROMIUM': {
2123 'type': 'Manual',
2124 'client_test': False,
2125 'gen_cmd': False,
2126 'extension': True,
2127 'chromium': True,
2129 'CreateGpuMemoryBufferImageCHROMIUM': {
2130 'type': 'Manual',
2131 'cmd_args':
2132 'GLsizei width, GLsizei height, GLenum internalformat, GLenum usage',
2133 'result': ['GLuint'],
2134 'client_test': False,
2135 'gen_cmd': False,
2136 'expectation': False,
2137 'extension': True,
2138 'chromium': True,
2140 'CreateProgram': {
2141 'type': 'Create',
2142 'client_test': False,
2144 'CreateShader': {
2145 'type': 'Create',
2146 'client_test': False,
2148 'BlendColor': {
2149 'type': 'StateSet',
2150 'state': 'BlendColor',
2152 'BlendEquation': {
2153 'type': 'StateSetRGBAlpha',
2154 'state': 'BlendEquation',
2155 'valid_args': {
2156 '0': 'GL_FUNC_SUBTRACT'
2159 'BlendEquationSeparate': {
2160 'type': 'StateSet',
2161 'state': 'BlendEquation',
2162 'valid_args': {
2163 '0': 'GL_FUNC_SUBTRACT'
2166 'BlendFunc': {
2167 'type': 'StateSetRGBAlpha',
2168 'state': 'BlendFunc',
2170 'BlendFuncSeparate': {
2171 'type': 'StateSet',
2172 'state': 'BlendFunc',
2174 'BlendBarrierKHR': {
2175 'gl_test_func': 'glBlendBarrierKHR',
2176 'extension': True,
2177 'extension_flag': 'blend_equation_advanced',
2178 'client_test': False,
2180 'SampleCoverage': {'decoder_func': 'DoSampleCoverage'},
2181 'StencilFunc': {
2182 'type': 'StateSetFrontBack',
2183 'state': 'StencilFunc',
2185 'StencilFuncSeparate': {
2186 'type': 'StateSetFrontBackSeparate',
2187 'state': 'StencilFunc',
2189 'StencilOp': {
2190 'type': 'StateSetFrontBack',
2191 'state': 'StencilOp',
2192 'valid_args': {
2193 '1': 'GL_INCR'
2196 'StencilOpSeparate': {
2197 'type': 'StateSetFrontBackSeparate',
2198 'state': 'StencilOp',
2199 'valid_args': {
2200 '1': 'GL_INCR'
2203 'Hint': {
2204 'type': 'StateSetNamedParameter',
2205 'state': 'Hint',
2207 'CullFace': {'type': 'StateSet', 'state': 'CullFace'},
2208 'FrontFace': {'type': 'StateSet', 'state': 'FrontFace'},
2209 'DepthFunc': {'type': 'StateSet', 'state': 'DepthFunc'},
2210 'LineWidth': {
2211 'type': 'StateSet',
2212 'state': 'LineWidth',
2213 'valid_args': {
2214 '0': '0.5f'
2217 'PolygonOffset': {
2218 'type': 'StateSet',
2219 'state': 'PolygonOffset',
2221 'DeleteBuffers': {
2222 'type': 'DELn',
2223 'gl_test_func': 'glDeleteBuffersARB',
2224 'resource_type': 'Buffer',
2225 'resource_types': 'Buffers',
2227 'DeleteFramebuffers': {
2228 'type': 'DELn',
2229 'gl_test_func': 'glDeleteFramebuffersEXT',
2230 'resource_type': 'Framebuffer',
2231 'resource_types': 'Framebuffers',
2233 'DeleteProgram': { 'type': 'Delete' },
2234 'DeleteRenderbuffers': {
2235 'type': 'DELn',
2236 'gl_test_func': 'glDeleteRenderbuffersEXT',
2237 'resource_type': 'Renderbuffer',
2238 'resource_types': 'Renderbuffers',
2240 'DeleteSamplers': {
2241 'type': 'DELn',
2242 'resource_type': 'Sampler',
2243 'resource_types': 'Samplers',
2244 'unsafe': True,
2246 'DeleteShader': { 'type': 'Delete' },
2247 'DeleteSync': {
2248 'type': 'Delete',
2249 'cmd_args': 'GLuint sync',
2250 'resource_type': 'Sync',
2251 'unsafe': True,
2253 'DeleteTextures': {
2254 'type': 'DELn',
2255 'resource_type': 'Texture',
2256 'resource_types': 'Textures',
2258 'DeleteTransformFeedbacks': {
2259 'type': 'DELn',
2260 'resource_type': 'TransformFeedback',
2261 'resource_types': 'TransformFeedbacks',
2262 'unsafe': True,
2264 'DepthRangef': {
2265 'decoder_func': 'DoDepthRangef',
2266 'gl_test_func': 'glDepthRange',
2268 'DepthMask': {
2269 'type': 'StateSet',
2270 'state': 'DepthMask',
2271 'no_gl': True,
2272 'expectation': False,
2274 'DetachShader': {'decoder_func': 'DoDetachShader'},
2275 'Disable': {
2276 'decoder_func': 'DoDisable',
2277 'impl_func': False,
2278 'client_test': False,
2280 'DisableVertexAttribArray': {
2281 'decoder_func': 'DoDisableVertexAttribArray',
2282 'impl_decl': False,
2284 'DrawArrays': {
2285 'type': 'Manual',
2286 'cmd_args': 'GLenumDrawMode mode, GLint first, GLsizei count',
2287 'defer_draws': True,
2288 'trace_level': 2,
2290 'DrawElements': {
2291 'type': 'Manual',
2292 'cmd_args': 'GLenumDrawMode mode, GLsizei count, '
2293 'GLenumIndexType type, GLuint index_offset',
2294 'client_test': False,
2295 'defer_draws': True,
2296 'trace_level': 2,
2298 'DrawRangeElements': {
2299 'type': 'Manual',
2300 'gen_cmd': 'False',
2301 'unsafe': True,
2303 'Enable': {
2304 'decoder_func': 'DoEnable',
2305 'impl_func': False,
2306 'client_test': False,
2308 'EnableVertexAttribArray': {
2309 'decoder_func': 'DoEnableVertexAttribArray',
2310 'impl_decl': False,
2312 'FenceSync': {
2313 'type': 'Create',
2314 'client_test': False,
2315 'unsafe': True,
2317 'Finish': {
2318 'impl_func': False,
2319 'client_test': False,
2320 'decoder_func': 'DoFinish',
2321 'defer_reads': True,
2323 'Flush': {
2324 'impl_func': False,
2325 'decoder_func': 'DoFlush',
2327 'FramebufferRenderbuffer': {
2328 'decoder_func': 'DoFramebufferRenderbuffer',
2329 'gl_test_func': 'glFramebufferRenderbufferEXT',
2331 'FramebufferTexture2D': {
2332 'decoder_func': 'DoFramebufferTexture2D',
2333 'gl_test_func': 'glFramebufferTexture2DEXT',
2334 'trace_level': 1,
2336 'FramebufferTexture2DMultisampleEXT': {
2337 'decoder_func': 'DoFramebufferTexture2DMultisample',
2338 'gl_test_func': 'glFramebufferTexture2DMultisampleEXT',
2339 'expectation': False,
2340 'unit_test': False,
2341 'extension_flag': 'multisampled_render_to_texture',
2342 'trace_level': 1,
2344 'FramebufferTextureLayer': {
2345 'decoder_func': 'DoFramebufferTextureLayer',
2346 'unsafe': True,
2348 'GenerateMipmap': {
2349 'decoder_func': 'DoGenerateMipmap',
2350 'gl_test_func': 'glGenerateMipmapEXT',
2352 'GenBuffers': {
2353 'type': 'GENn',
2354 'gl_test_func': 'glGenBuffersARB',
2355 'resource_type': 'Buffer',
2356 'resource_types': 'Buffers',
2358 'GenMailboxCHROMIUM': {
2359 'type': 'HandWritten',
2360 'impl_func': False,
2361 'extension': "CHROMIUM_texture_mailbox",
2362 'chromium': True,
2364 'GenFramebuffers': {
2365 'type': 'GENn',
2366 'gl_test_func': 'glGenFramebuffersEXT',
2367 'resource_type': 'Framebuffer',
2368 'resource_types': 'Framebuffers',
2370 'GenRenderbuffers': {
2371 'type': 'GENn', 'gl_test_func': 'glGenRenderbuffersEXT',
2372 'resource_type': 'Renderbuffer',
2373 'resource_types': 'Renderbuffers',
2375 'GenSamplers': {
2376 'type': 'GENn',
2377 'gl_test_func': 'glGenSamplers',
2378 'resource_type': 'Sampler',
2379 'resource_types': 'Samplers',
2380 'unsafe': True,
2382 'GenTextures': {
2383 'type': 'GENn',
2384 'gl_test_func': 'glGenTextures',
2385 'resource_type': 'Texture',
2386 'resource_types': 'Textures',
2388 'GenTransformFeedbacks': {
2389 'type': 'GENn',
2390 'gl_test_func': 'glGenTransformFeedbacks',
2391 'resource_type': 'TransformFeedback',
2392 'resource_types': 'TransformFeedbacks',
2393 'unsafe': True,
2395 'GetActiveAttrib': {
2396 'type': 'Custom',
2397 'data_transfer_methods': ['shm'],
2398 'cmd_args':
2399 'GLidProgram program, GLuint index, uint32_t name_bucket_id, '
2400 'void* result',
2401 'result': [
2402 'int32_t success',
2403 'int32_t size',
2404 'uint32_t type',
2407 'GetActiveUniform': {
2408 'type': 'Custom',
2409 'data_transfer_methods': ['shm'],
2410 'cmd_args':
2411 'GLidProgram program, GLuint index, uint32_t name_bucket_id, '
2412 'void* result',
2413 'result': [
2414 'int32_t success',
2415 'int32_t size',
2416 'uint32_t type',
2419 'GetActiveUniformBlockiv': {
2420 'type': 'Custom',
2421 'data_transfer_methods': ['shm'],
2422 'result': ['SizedResult<GLint>'],
2423 'unsafe': True,
2425 'GetActiveUniformBlockName': {
2426 'type': 'Custom',
2427 'data_transfer_methods': ['shm'],
2428 'cmd_args':
2429 'GLidProgram program, GLuint index, uint32_t name_bucket_id, '
2430 'void* result',
2431 'result': ['int32_t'],
2432 'unsafe': True,
2434 'GetActiveUniformsiv': {
2435 'type': 'Custom',
2436 'data_transfer_methods': ['shm'],
2437 'cmd_args':
2438 'GLidProgram program, uint32_t indices_bucket_id, GLenum pname, '
2439 'GLint* params',
2440 'result': ['SizedResult<GLint>'],
2441 'unsafe': True,
2443 'GetAttachedShaders': {
2444 'type': 'Custom',
2445 'data_transfer_methods': ['shm'],
2446 'cmd_args': 'GLidProgram program, void* result, uint32_t result_size',
2447 'result': ['SizedResult<GLuint>'],
2449 'GetAttribLocation': {
2450 'type': 'Custom',
2451 'data_transfer_methods': ['shm'],
2452 'cmd_args':
2453 'GLidProgram program, uint32_t name_bucket_id, GLint* location',
2454 'result': ['GLint'],
2455 'error_return': -1,
2457 'GetFragDataLocation': {
2458 'type': 'Custom',
2459 'data_transfer_methods': ['shm'],
2460 'cmd_args':
2461 'GLidProgram program, uint32_t name_bucket_id, GLint* location',
2462 'result': ['GLint'],
2463 'error_return': -1,
2464 'unsafe': True,
2466 'GetBooleanv': {
2467 'type': 'GETn',
2468 'result': ['SizedResult<GLboolean>'],
2469 'decoder_func': 'DoGetBooleanv',
2470 'gl_test_func': 'glGetBooleanv',
2472 'GetBufferParameteriv': {
2473 'type': 'GETn',
2474 'result': ['SizedResult<GLint>'],
2475 'decoder_func': 'DoGetBufferParameteriv',
2476 'expectation': False,
2477 'shadowed': True,
2479 'GetError': {
2480 'type': 'Is',
2481 'decoder_func': 'GetErrorState()->GetGLError',
2482 'impl_func': False,
2483 'result': ['GLenum'],
2484 'client_test': False,
2486 'GetFloatv': {
2487 'type': 'GETn',
2488 'result': ['SizedResult<GLfloat>'],
2489 'decoder_func': 'DoGetFloatv',
2490 'gl_test_func': 'glGetFloatv',
2492 'GetFramebufferAttachmentParameteriv': {
2493 'type': 'GETn',
2494 'decoder_func': 'DoGetFramebufferAttachmentParameteriv',
2495 'gl_test_func': 'glGetFramebufferAttachmentParameterivEXT',
2496 'result': ['SizedResult<GLint>'],
2498 'GetInteger64v': {
2499 'type': 'GETn',
2500 'result': ['SizedResult<GLint64>'],
2501 'client_test': False,
2502 'decoder_func': 'DoGetInteger64v',
2503 'unsafe': True
2505 'GetIntegerv': {
2506 'type': 'GETn',
2507 'result': ['SizedResult<GLint>'],
2508 'decoder_func': 'DoGetIntegerv',
2509 'client_test': False,
2511 'GetInteger64i_v': {
2512 'type': 'GETn',
2513 'result': ['SizedResult<GLint64>'],
2514 'client_test': False,
2515 'unsafe': True
2517 'GetIntegeri_v': {
2518 'type': 'GETn',
2519 'result': ['SizedResult<GLint>'],
2520 'client_test': False,
2521 'unsafe': True
2523 'GetInternalformativ': {
2524 'type': 'GETn',
2525 'result': ['SizedResult<GLint>'],
2526 'unsafe': True,
2528 'GetMaxValueInBufferCHROMIUM': {
2529 'type': 'Is',
2530 'decoder_func': 'DoGetMaxValueInBufferCHROMIUM',
2531 'result': ['GLuint'],
2532 'unit_test': False,
2533 'client_test': False,
2534 'extension': True,
2535 'chromium': True,
2536 'impl_func': False,
2538 'GetProgramiv': {
2539 'type': 'GETn',
2540 'decoder_func': 'DoGetProgramiv',
2541 'result': ['SizedResult<GLint>'],
2542 'expectation': False,
2544 'GetProgramInfoCHROMIUM': {
2545 'type': 'Custom',
2546 'expectation': False,
2547 'impl_func': False,
2548 'extension': True,
2549 'chromium': True,
2550 'client_test': False,
2551 'cmd_args': 'GLidProgram program, uint32_t bucket_id',
2552 'result': [
2553 'uint32_t link_status',
2554 'uint32_t num_attribs',
2555 'uint32_t num_uniforms',
2558 'GetProgramInfoLog': {
2559 'type': 'STRn',
2560 'expectation': False,
2562 'GetRenderbufferParameteriv': {
2563 'type': 'GETn',
2564 'decoder_func': 'DoGetRenderbufferParameteriv',
2565 'gl_test_func': 'glGetRenderbufferParameterivEXT',
2566 'result': ['SizedResult<GLint>'],
2568 'GetSamplerParameterfv': {
2569 'type': 'GETn',
2570 'result': ['SizedResult<GLfloat>'],
2571 'id_mapping': [ 'Sampler' ],
2572 'unsafe': True,
2574 'GetSamplerParameteriv': {
2575 'type': 'GETn',
2576 'result': ['SizedResult<GLint>'],
2577 'id_mapping': [ 'Sampler' ],
2578 'unsafe': True,
2580 'GetShaderiv': {
2581 'type': 'GETn',
2582 'decoder_func': 'DoGetShaderiv',
2583 'result': ['SizedResult<GLint>'],
2585 'GetShaderInfoLog': {
2586 'type': 'STRn',
2587 'get_len_func': 'glGetShaderiv',
2588 'get_len_enum': 'GL_INFO_LOG_LENGTH',
2589 'unit_test': False,
2591 'GetShaderPrecisionFormat': {
2592 'type': 'Custom',
2593 'data_transfer_methods': ['shm'],
2594 'cmd_args':
2595 'GLenumShaderType shadertype, GLenumShaderPrecision precisiontype, '
2596 'void* result',
2597 'result': [
2598 'int32_t success',
2599 'int32_t min_range',
2600 'int32_t max_range',
2601 'int32_t precision',
2604 'GetShaderSource': {
2605 'type': 'STRn',
2606 'get_len_func': 'DoGetShaderiv',
2607 'get_len_enum': 'GL_SHADER_SOURCE_LENGTH',
2608 'unit_test': False,
2609 'client_test': False,
2611 'GetString': {
2612 'type': 'Custom',
2613 'client_test': False,
2614 'cmd_args': 'GLenumStringType name, uint32_t bucket_id',
2616 'GetSynciv': {
2617 'type': 'GETn',
2618 'cmd_args': 'GLuint sync, GLenumSyncParameter pname, void* values',
2619 'result': ['SizedResult<GLint>'],
2620 'id_mapping': ['Sync'],
2621 'unsafe': True,
2623 'GetTexParameterfv': {
2624 'type': 'GETn',
2625 'decoder_func': 'DoGetTexParameterfv',
2626 'result': ['SizedResult<GLfloat>']
2628 'GetTexParameteriv': {
2629 'type': 'GETn',
2630 'decoder_func': 'DoGetTexParameteriv',
2631 'result': ['SizedResult<GLint>']
2633 'GetTranslatedShaderSourceANGLE': {
2634 'type': 'STRn',
2635 'get_len_func': 'DoGetShaderiv',
2636 'get_len_enum': 'GL_TRANSLATED_SHADER_SOURCE_LENGTH_ANGLE',
2637 'unit_test': False,
2638 'extension': True,
2640 'GetUniformBlockIndex': {
2641 'type': 'Custom',
2642 'data_transfer_methods': ['shm'],
2643 'cmd_args':
2644 'GLidProgram program, uint32_t name_bucket_id, GLuint* index',
2645 'result': ['GLuint'],
2646 'error_return': 'GL_INVALID_INDEX',
2647 'unsafe': True,
2649 'GetUniformBlocksCHROMIUM': {
2650 'type': 'Custom',
2651 'expectation': False,
2652 'impl_func': False,
2653 'extension': True,
2654 'chromium': True,
2655 'client_test': False,
2656 'cmd_args': 'GLidProgram program, uint32_t bucket_id',
2657 'result': ['uint32_t'],
2658 'unsafe': True,
2660 'GetUniformsES3CHROMIUM': {
2661 'type': 'Custom',
2662 'expectation': False,
2663 'impl_func': False,
2664 'extension': True,
2665 'chromium': True,
2666 'client_test': False,
2667 'cmd_args': 'GLidProgram program, uint32_t bucket_id',
2668 'result': ['uint32_t'],
2669 'unsafe': True,
2671 'GetTransformFeedbackVarying': {
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',
2682 'unsafe': True,
2684 'GetTransformFeedbackVaryingsCHROMIUM': {
2685 'type': 'Custom',
2686 'expectation': False,
2687 'impl_func': False,
2688 'extension': True,
2689 'chromium': True,
2690 'client_test': False,
2691 'cmd_args': 'GLidProgram program, uint32_t bucket_id',
2692 'result': ['uint32_t'],
2693 'unsafe': True,
2695 'GetUniformfv': {
2696 'type': 'Custom',
2697 'data_transfer_methods': ['shm'],
2698 'result': ['SizedResult<GLfloat>'],
2700 'GetUniformiv': {
2701 'type': 'Custom',
2702 'data_transfer_methods': ['shm'],
2703 'result': ['SizedResult<GLint>'],
2705 'GetUniformIndices': {
2706 'type': 'Custom',
2707 'data_transfer_methods': ['shm'],
2708 'result': ['SizedResult<GLuint>'],
2709 'cmd_args': 'GLidProgram program, uint32_t names_bucket_id, '
2710 'GLuint* indices',
2711 'unsafe': True,
2713 'GetUniformLocation': {
2714 'type': 'Custom',
2715 'data_transfer_methods': ['shm'],
2716 'cmd_args':
2717 'GLidProgram program, uint32_t name_bucket_id, GLint* location',
2718 'result': ['GLint'],
2719 'error_return': -1, # http://www.opengl.org/sdk/docs/man/xhtml/glGetUniformLocation.xml
2721 'GetVertexAttribfv': {
2722 'type': 'GETn',
2723 'result': ['SizedResult<GLfloat>'],
2724 'impl_decl': False,
2725 'decoder_func': 'DoGetVertexAttribfv',
2726 'expectation': False,
2727 'client_test': False,
2729 'GetVertexAttribiv': {
2730 'type': 'GETn',
2731 'result': ['SizedResult<GLint>'],
2732 'impl_decl': False,
2733 'decoder_func': 'DoGetVertexAttribiv',
2734 'expectation': False,
2735 'client_test': False,
2737 'GetVertexAttribPointerv': {
2738 'type': 'Custom',
2739 'data_transfer_methods': ['shm'],
2740 'result': ['SizedResult<GLuint>'],
2741 'client_test': False,
2743 'InvalidateFramebuffer': {
2744 'type': 'PUTn',
2745 'count': 1,
2746 'client_test': False,
2747 'unit_test': False,
2748 'unsafe': True,
2750 'InvalidateSubFramebuffer': {
2751 'type': 'PUTn',
2752 'count': 1,
2753 'client_test': False,
2754 'unit_test': False,
2755 'unsafe': True,
2757 'IsBuffer': {
2758 'type': 'Is',
2759 'decoder_func': 'DoIsBuffer',
2760 'expectation': False,
2762 'IsEnabled': {
2763 'type': 'Is',
2764 'decoder_func': 'DoIsEnabled',
2765 'client_test': False,
2766 'impl_func': False,
2767 'expectation': False,
2769 'IsFramebuffer': {
2770 'type': 'Is',
2771 'decoder_func': 'DoIsFramebuffer',
2772 'expectation': False,
2774 'IsProgram': {
2775 'type': 'Is',
2776 'decoder_func': 'DoIsProgram',
2777 'expectation': False,
2779 'IsRenderbuffer': {
2780 'type': 'Is',
2781 'decoder_func': 'DoIsRenderbuffer',
2782 'expectation': False,
2784 'IsShader': {
2785 'type': 'Is',
2786 'decoder_func': 'DoIsShader',
2787 'expectation': False,
2789 'IsSampler': {
2790 'type': 'Is',
2791 'id_mapping': [ 'Sampler' ],
2792 'expectation': False,
2793 'unsafe': True,
2795 'IsSync': {
2796 'type': 'Is',
2797 'id_mapping': [ 'Sync' ],
2798 'cmd_args': 'GLuint sync',
2799 'expectation': False,
2800 'unsafe': True,
2802 'IsTexture': {
2803 'type': 'Is',
2804 'decoder_func': 'DoIsTexture',
2805 'expectation': False,
2807 'IsTransformFeedback': {
2808 'type': 'Is',
2809 'id_mapping': [ 'TransformFeedback' ],
2810 'expectation': False,
2811 'unsafe': True,
2813 'LinkProgram': {
2814 'decoder_func': 'DoLinkProgram',
2815 'impl_func': False,
2817 'MapBufferCHROMIUM': {
2818 'gen_cmd': False,
2819 'extension': True,
2820 'chromium': True,
2821 'client_test': False,
2823 'MapBufferSubDataCHROMIUM': {
2824 'gen_cmd': False,
2825 'extension': True,
2826 'chromium': True,
2827 'client_test': False,
2828 'pepper_interface': 'ChromiumMapSub',
2830 'MapTexSubImage2DCHROMIUM': {
2831 'gen_cmd': False,
2832 'extension': "CHROMIUM_sub_image",
2833 'chromium': True,
2834 'client_test': False,
2835 'pepper_interface': 'ChromiumMapSub',
2837 'MapBufferRange': {
2838 'type': 'Custom',
2839 'data_transfer_methods': ['shm'],
2840 'cmd_args': 'GLenumBufferTarget target, GLintptrNotNegative offset, '
2841 'GLsizeiptr size, GLbitfieldMapBufferAccess access, '
2842 'uint32_t data_shm_id, uint32_t data_shm_offset, '
2843 'uint32_t result_shm_id, uint32_t result_shm_offset',
2844 'unsafe': True,
2845 'result': ['uint32_t'],
2847 'PauseTransformFeedback': {
2848 'unsafe': True,
2850 'PixelStorei': {'type': 'Manual'},
2851 'PostSubBufferCHROMIUM': {
2852 'type': 'Custom',
2853 'impl_func': False,
2854 'unit_test': False,
2855 'client_test': False,
2856 'extension': True,
2857 'chromium': True,
2859 'ProduceTextureCHROMIUM': {
2860 'decoder_func': 'DoProduceTextureCHROMIUM',
2861 'impl_func': False,
2862 'type': 'PUT',
2863 'count': 64, # GL_MAILBOX_SIZE_CHROMIUM
2864 'unit_test': False,
2865 'client_test': False,
2866 'extension': "CHROMIUM_texture_mailbox",
2867 'chromium': True,
2868 'trace_level': 1,
2870 'ProduceTextureDirectCHROMIUM': {
2871 'decoder_func': 'DoProduceTextureDirectCHROMIUM',
2872 'impl_func': False,
2873 'type': 'PUT',
2874 'count': 64, # GL_MAILBOX_SIZE_CHROMIUM
2875 'unit_test': False,
2876 'client_test': False,
2877 'extension': "CHROMIUM_texture_mailbox",
2878 'chromium': True,
2879 'trace_level': 1,
2881 'RenderbufferStorage': {
2882 'decoder_func': 'DoRenderbufferStorage',
2883 'gl_test_func': 'glRenderbufferStorageEXT',
2884 'expectation': False,
2886 'RenderbufferStorageMultisampleCHROMIUM': {
2887 'cmd_comment':
2888 '// GL_CHROMIUM_framebuffer_multisample\n',
2889 'decoder_func': 'DoRenderbufferStorageMultisampleCHROMIUM',
2890 'gl_test_func': 'glRenderbufferStorageMultisampleCHROMIUM',
2891 'expectation': False,
2892 'unit_test': False,
2893 'extension_flag': 'chromium_framebuffer_multisample',
2894 'pepper_interface': 'FramebufferMultisample',
2895 'pepper_name': 'RenderbufferStorageMultisampleEXT',
2897 'RenderbufferStorageMultisampleEXT': {
2898 'cmd_comment':
2899 '// GL_EXT_multisampled_render_to_texture\n',
2900 'decoder_func': 'DoRenderbufferStorageMultisampleEXT',
2901 'gl_test_func': 'glRenderbufferStorageMultisampleEXT',
2902 'expectation': False,
2903 'unit_test': False,
2904 'extension_flag': 'multisampled_render_to_texture',
2906 'ReadBuffer': {
2907 'unsafe': True,
2909 'ReadPixels': {
2910 'cmd_comment':
2911 '// ReadPixels has the result separated from the pixel buffer so that\n'
2912 '// it is easier to specify the result going to some specific place\n'
2913 '// that exactly fits the rectangle of pixels.\n',
2914 'type': 'Custom',
2915 'data_transfer_methods': ['shm'],
2916 'impl_func': False,
2917 'client_test': False,
2918 'cmd_args':
2919 'GLint x, GLint y, GLsizei width, GLsizei height, '
2920 'GLenumReadPixelFormat format, GLenumReadPixelType type, '
2921 'uint32_t pixels_shm_id, uint32_t pixels_shm_offset, '
2922 'uint32_t result_shm_id, uint32_t result_shm_offset, '
2923 'GLboolean async',
2924 'result': ['uint32_t'],
2925 'defer_reads': True,
2927 'ReleaseShaderCompiler': {
2928 'decoder_func': 'DoReleaseShaderCompiler',
2929 'unit_test': False,
2931 'ResumeTransformFeedback': {
2932 'unsafe': True,
2934 'SamplerParameterf': {
2935 'valid_args': {
2936 '2': 'GL_NEAREST'
2938 'id_mapping': [ 'Sampler' ],
2939 'unsafe': True,
2941 'SamplerParameterfv': {
2942 'type': 'PUT',
2943 'data_value': 'GL_NEAREST',
2944 'count': 1,
2945 'gl_test_func': 'glSamplerParameterf',
2946 'decoder_func': 'DoSamplerParameterfv',
2947 'first_element_only': True,
2948 'id_mapping': [ 'Sampler' ],
2949 'unsafe': True,
2951 'SamplerParameteri': {
2952 'valid_args': {
2953 '2': 'GL_NEAREST'
2955 'id_mapping': [ 'Sampler' ],
2956 'unsafe': True,
2958 'SamplerParameteriv': {
2959 'type': 'PUT',
2960 'data_value': 'GL_NEAREST',
2961 'count': 1,
2962 'gl_test_func': 'glSamplerParameteri',
2963 'decoder_func': 'DoSamplerParameteriv',
2964 'first_element_only': True,
2965 'unsafe': True,
2967 'ShaderBinary': {
2968 'type': 'Custom',
2969 'client_test': False,
2971 'ShaderSource': {
2972 'type': 'PUTSTR',
2973 'decoder_func': 'DoShaderSource',
2974 'expectation': False,
2975 'data_transfer_methods': ['bucket'],
2976 'cmd_args':
2977 'GLuint shader, const char** str',
2978 'pepper_args':
2979 'GLuint shader, GLsizei count, const char** str, const GLint* length',
2981 'StencilMask': {
2982 'type': 'StateSetFrontBack',
2983 'state': 'StencilMask',
2984 'no_gl': True,
2985 'expectation': False,
2987 'StencilMaskSeparate': {
2988 'type': 'StateSetFrontBackSeparate',
2989 'state': 'StencilMask',
2990 'no_gl': True,
2991 'expectation': False,
2993 'SwapBuffers': {
2994 'impl_func': False,
2995 'decoder_func': 'DoSwapBuffers',
2996 'unit_test': False,
2997 'client_test': False,
2998 'extension': True,
2999 'trace_level': 1,
3001 'SwapInterval': {
3002 'impl_func': False,
3003 'decoder_func': 'DoSwapInterval',
3004 'unit_test': False,
3005 'client_test': False,
3006 'extension': True,
3007 'trace_level': 1,
3009 'TexImage2D': {
3010 'type': 'Manual',
3011 'data_transfer_methods': ['shm'],
3012 'client_test': False,
3014 'TexImage3D': {
3015 'type': 'Manual',
3016 'data_transfer_methods': ['shm'],
3017 'client_test': False,
3018 'unsafe': True,
3020 'TexParameterf': {
3021 'decoder_func': 'DoTexParameterf',
3022 'valid_args': {
3023 '2': 'GL_NEAREST'
3026 'TexParameteri': {
3027 'decoder_func': 'DoTexParameteri',
3028 'valid_args': {
3029 '2': 'GL_NEAREST'
3032 'TexParameterfv': {
3033 'type': 'PUT',
3034 'data_value': 'GL_NEAREST',
3035 'count': 1,
3036 'decoder_func': 'DoTexParameterfv',
3037 'gl_test_func': 'glTexParameterf',
3038 'first_element_only': True,
3040 'TexParameteriv': {
3041 'type': 'PUT',
3042 'data_value': 'GL_NEAREST',
3043 'count': 1,
3044 'decoder_func': 'DoTexParameteriv',
3045 'gl_test_func': 'glTexParameteri',
3046 'first_element_only': True,
3048 'TexStorage3D': {
3049 'unsafe': True,
3051 'TexSubImage2D': {
3052 'type': 'Manual',
3053 'data_transfer_methods': ['shm'],
3054 'client_test': False,
3055 'cmd_args': 'GLenumTextureTarget target, GLint level, '
3056 'GLint xoffset, GLint yoffset, '
3057 'GLsizei width, GLsizei height, '
3058 'GLenumTextureFormat format, GLenumPixelType type, '
3059 'const void* pixels, GLboolean internal'
3061 'TexSubImage3D': {
3062 'type': 'Manual',
3063 'data_transfer_methods': ['shm'],
3064 'client_test': False,
3065 'cmd_args': 'GLenumTextureTarget target, GLint level, '
3066 'GLint xoffset, GLint yoffset, GLint zoffset, '
3067 'GLsizei width, GLsizei height, GLsizei depth, '
3068 'GLenumTextureFormat format, GLenumPixelType type, '
3069 'const void* pixels, GLboolean internal',
3070 'unsafe': True,
3072 'TransformFeedbackVaryings': {
3073 'type': 'PUTSTR',
3074 'data_transfer_methods': ['bucket'],
3075 'decoder_func': 'DoTransformFeedbackVaryings',
3076 'cmd_args':
3077 'GLuint program, const char** varyings, GLenum buffermode',
3078 'unsafe': True,
3080 'Uniform1f': {'type': 'PUTXn', 'count': 1},
3081 'Uniform1fv': {
3082 'type': 'PUTn',
3083 'count': 1,
3084 'decoder_func': 'DoUniform1fv',
3086 'Uniform1i': {'decoder_func': 'DoUniform1i', 'unit_test': False},
3087 'Uniform1iv': {
3088 'type': 'PUTn',
3089 'count': 1,
3090 'decoder_func': 'DoUniform1iv',
3091 'unit_test': False,
3093 'Uniform1ui': {
3094 'type': 'PUTXn',
3095 'count': 1,
3096 'unsafe': True,
3098 'Uniform1uiv': {
3099 'type': 'PUTn',
3100 'count': 1,
3101 'unsafe': True,
3103 'Uniform2i': {'type': 'PUTXn', 'count': 2},
3104 'Uniform2f': {'type': 'PUTXn', 'count': 2},
3105 'Uniform2fv': {
3106 'type': 'PUTn',
3107 'count': 2,
3108 'decoder_func': 'DoUniform2fv',
3110 'Uniform2iv': {
3111 'type': 'PUTn',
3112 'count': 2,
3113 'decoder_func': 'DoUniform2iv',
3115 'Uniform2ui': {
3116 'type': 'PUTXn',
3117 'count': 2,
3118 'unsafe': True,
3120 'Uniform2uiv': {
3121 'type': 'PUTn',
3122 'count': 2,
3123 'unsafe': True,
3125 'Uniform3i': {'type': 'PUTXn', 'count': 3},
3126 'Uniform3f': {'type': 'PUTXn', 'count': 3},
3127 'Uniform3fv': {
3128 'type': 'PUTn',
3129 'count': 3,
3130 'decoder_func': 'DoUniform3fv',
3132 'Uniform3iv': {
3133 'type': 'PUTn',
3134 'count': 3,
3135 'decoder_func': 'DoUniform3iv',
3137 'Uniform3ui': {
3138 'type': 'PUTXn',
3139 'count': 3,
3140 'unsafe': True,
3142 'Uniform3uiv': {
3143 'type': 'PUTn',
3144 'count': 3,
3145 'unsafe': True,
3147 'Uniform4i': {'type': 'PUTXn', 'count': 4},
3148 'Uniform4f': {'type': 'PUTXn', 'count': 4},
3149 'Uniform4fv': {
3150 'type': 'PUTn',
3151 'count': 4,
3152 'decoder_func': 'DoUniform4fv',
3154 'Uniform4iv': {
3155 'type': 'PUTn',
3156 'count': 4,
3157 'decoder_func': 'DoUniform4iv',
3159 'Uniform4ui': {
3160 'type': 'PUTXn',
3161 'count': 4,
3162 'unsafe': True,
3164 'Uniform4uiv': {
3165 'type': 'PUTn',
3166 'count': 4,
3167 'unsafe': True,
3169 'UniformMatrix2fv': {
3170 'type': 'PUTn',
3171 'count': 4,
3172 'decoder_func': 'DoUniformMatrix2fv',
3174 'UniformMatrix2x3fv': {
3175 'type': 'PUTn',
3176 'count': 6,
3177 'unsafe': True,
3179 'UniformMatrix2x4fv': {
3180 'type': 'PUTn',
3181 'count': 8,
3182 'unsafe': True,
3184 'UniformMatrix3fv': {
3185 'type': 'PUTn',
3186 'count': 9,
3187 'decoder_func': 'DoUniformMatrix3fv',
3189 'UniformMatrix3x2fv': {
3190 'type': 'PUTn',
3191 'count': 6,
3192 'unsafe': True,
3194 'UniformMatrix3x4fv': {
3195 'type': 'PUTn',
3196 'count': 12,
3197 'unsafe': True,
3199 'UniformMatrix4fv': {
3200 'type': 'PUTn',
3201 'count': 16,
3202 'decoder_func': 'DoUniformMatrix4fv',
3204 'UniformMatrix4x2fv': {
3205 'type': 'PUTn',
3206 'count': 8,
3207 'unsafe': True,
3209 'UniformMatrix4x3fv': {
3210 'type': 'PUTn',
3211 'count': 12,
3212 'unsafe': True,
3214 'UniformBlockBinding': {
3215 'type': 'Custom',
3216 'impl_func': False,
3217 'unsafe': True,
3219 'UnmapBufferCHROMIUM': {
3220 'gen_cmd': False,
3221 'extension': True,
3222 'chromium': True,
3223 'client_test': False,
3225 'UnmapBufferSubDataCHROMIUM': {
3226 'gen_cmd': False,
3227 'extension': True,
3228 'chromium': True,
3229 'client_test': False,
3230 'pepper_interface': 'ChromiumMapSub',
3232 'UnmapBuffer': {
3233 'type': 'Custom',
3234 'unsafe': True,
3236 'UnmapTexSubImage2DCHROMIUM': {
3237 'gen_cmd': False,
3238 'extension': "CHROMIUM_sub_image",
3239 'chromium': True,
3240 'client_test': False,
3241 'pepper_interface': 'ChromiumMapSub',
3243 'UseProgram': {
3244 'type': 'Bind',
3245 'decoder_func': 'DoUseProgram',
3247 'ValidateProgram': {'decoder_func': 'DoValidateProgram'},
3248 'VertexAttrib1f': {'decoder_func': 'DoVertexAttrib1f'},
3249 'VertexAttrib1fv': {
3250 'type': 'PUT',
3251 'count': 1,
3252 'decoder_func': 'DoVertexAttrib1fv',
3254 'VertexAttrib2f': {'decoder_func': 'DoVertexAttrib2f'},
3255 'VertexAttrib2fv': {
3256 'type': 'PUT',
3257 'count': 2,
3258 'decoder_func': 'DoVertexAttrib2fv',
3260 'VertexAttrib3f': {'decoder_func': 'DoVertexAttrib3f'},
3261 'VertexAttrib3fv': {
3262 'type': 'PUT',
3263 'count': 3,
3264 'decoder_func': 'DoVertexAttrib3fv',
3266 'VertexAttrib4f': {'decoder_func': 'DoVertexAttrib4f'},
3267 'VertexAttrib4fv': {
3268 'type': 'PUT',
3269 'count': 4,
3270 'decoder_func': 'DoVertexAttrib4fv',
3272 'VertexAttribI4i': {
3273 'unsafe': True,
3275 'VertexAttribI4iv': {
3276 'type': 'PUT',
3277 'count': 4,
3278 'unsafe': True,
3280 'VertexAttribI4ui': {
3281 'unsafe': True,
3283 'VertexAttribI4uiv': {
3284 'type': 'PUT',
3285 'count': 4,
3286 'unsafe': True,
3288 'VertexAttribIPointer': {
3289 'type': 'Manual',
3290 'cmd_args': 'GLuint indx, GLintVertexAttribSize size, '
3291 'GLenumVertexAttribIType type, GLsizei stride, '
3292 'GLuint offset',
3293 'client_test': False,
3294 'unsafe': True,
3296 'VertexAttribPointer': {
3297 'type': 'Manual',
3298 'cmd_args': 'GLuint indx, GLintVertexAttribSize size, '
3299 'GLenumVertexAttribType type, GLboolean normalized, '
3300 'GLsizei stride, GLuint offset',
3301 'client_test': False,
3303 'WaitSync': {
3304 'type': 'Custom',
3305 'cmd_args': 'GLuint sync, GLbitfieldSyncFlushFlags flags, '
3306 'GLuint timeout_0, GLuint timeout_1',
3307 'impl_func': False,
3308 'client_test': False,
3309 'unsafe': True,
3311 'Scissor': {
3312 'type': 'StateSet',
3313 'state': 'Scissor',
3315 'Viewport': {
3316 'decoder_func': 'DoViewport',
3318 'ResizeCHROMIUM': {
3319 'type': 'Custom',
3320 'impl_func': False,
3321 'unit_test': False,
3322 'extension': True,
3323 'chromium': True,
3325 'GetRequestableExtensionsCHROMIUM': {
3326 'type': 'Custom',
3327 'impl_func': False,
3328 'cmd_args': 'uint32_t bucket_id',
3329 'extension': True,
3330 'chromium': True,
3332 'RequestExtensionCHROMIUM': {
3333 'type': 'Custom',
3334 'impl_func': False,
3335 'client_test': False,
3336 'cmd_args': 'uint32_t bucket_id',
3337 'extension': True,
3338 'chromium': True,
3340 'RateLimitOffscreenContextCHROMIUM': {
3341 'gen_cmd': False,
3342 'extension': True,
3343 'chromium': True,
3344 'client_test': False,
3346 'CreateStreamTextureCHROMIUM': {
3347 'type': 'HandWritten',
3348 'impl_func': False,
3349 'gen_cmd': False,
3350 'extension': True,
3351 'chromium': True,
3353 'TexImageIOSurface2DCHROMIUM': {
3354 'decoder_func': 'DoTexImageIOSurface2DCHROMIUM',
3355 'unit_test': False,
3356 'extension': True,
3357 'chromium': True,
3359 'CopyTextureCHROMIUM': {
3360 'decoder_func': 'DoCopyTextureCHROMIUM',
3361 'unit_test': False,
3362 'extension': True,
3363 'chromium': True,
3365 'CopySubTextureCHROMIUM': {
3366 'decoder_func': 'DoCopySubTextureCHROMIUM',
3367 'unit_test': False,
3368 'extension': True,
3369 'chromium': True,
3371 'TexStorage2DEXT': {
3372 'unit_test': False,
3373 'extension': True,
3374 'decoder_func': 'DoTexStorage2DEXT',
3376 'DrawArraysInstancedANGLE': {
3377 'type': 'Manual',
3378 'cmd_args': 'GLenumDrawMode mode, GLint first, GLsizei count, '
3379 'GLsizei primcount',
3380 'extension': True,
3381 'unit_test': False,
3382 'pepper_interface': 'InstancedArrays',
3383 'defer_draws': True,
3385 'DrawBuffersEXT': {
3386 'type': 'PUTn',
3387 'decoder_func': 'DoDrawBuffersEXT',
3388 'count': 1,
3389 'client_test': False,
3390 'unit_test': False,
3391 # could use 'extension_flag': 'ext_draw_buffers' but currently expected to
3392 # work without.
3393 'extension': True,
3394 'pepper_interface': 'DrawBuffers',
3396 'DrawElementsInstancedANGLE': {
3397 'type': 'Manual',
3398 'cmd_args': 'GLenumDrawMode mode, GLsizei count, '
3399 'GLenumIndexType type, GLuint index_offset, GLsizei primcount',
3400 'extension': True,
3401 'unit_test': False,
3402 'client_test': False,
3403 'pepper_interface': 'InstancedArrays',
3404 'defer_draws': True,
3406 'VertexAttribDivisorANGLE': {
3407 'type': 'Manual',
3408 'cmd_args': 'GLuint index, GLuint divisor',
3409 'extension': True,
3410 'unit_test': False,
3411 'pepper_interface': 'InstancedArrays',
3413 'GenQueriesEXT': {
3414 'type': 'GENn',
3415 'gl_test_func': 'glGenQueriesARB',
3416 'resource_type': 'Query',
3417 'resource_types': 'Queries',
3418 'unit_test': False,
3419 'pepper_interface': 'Query',
3420 'not_shared': 'True',
3421 'extension': "occlusion_query_EXT",
3423 'DeleteQueriesEXT': {
3424 'type': 'DELn',
3425 'gl_test_func': 'glDeleteQueriesARB',
3426 'resource_type': 'Query',
3427 'resource_types': 'Queries',
3428 'unit_test': False,
3429 'pepper_interface': 'Query',
3430 'extension': "occlusion_query_EXT",
3432 'IsQueryEXT': {
3433 'gen_cmd': False,
3434 'client_test': False,
3435 'pepper_interface': 'Query',
3436 'extension': "occlusion_query_EXT",
3438 'BeginQueryEXT': {
3439 'type': 'Manual',
3440 'cmd_args': 'GLenumQueryTarget target, GLidQuery id, void* sync_data',
3441 'data_transfer_methods': ['shm'],
3442 'gl_test_func': 'glBeginQuery',
3443 'pepper_interface': 'Query',
3444 'extension': "occlusion_query_EXT",
3446 'BeginTransformFeedback': {
3447 'unsafe': True,
3449 'EndQueryEXT': {
3450 'type': 'Manual',
3451 'cmd_args': 'GLenumQueryTarget target, GLuint submit_count',
3452 'gl_test_func': 'glEndnQuery',
3453 'client_test': False,
3454 'pepper_interface': 'Query',
3455 'extension': "occlusion_query_EXT",
3457 'EndTransformFeedback': {
3458 'unsafe': True,
3460 'GetQueryivEXT': {
3461 'gen_cmd': False,
3462 'client_test': False,
3463 'gl_test_func': 'glGetQueryiv',
3464 'pepper_interface': 'Query',
3465 'extension': "occlusion_query_EXT",
3467 'GetQueryObjectuivEXT': {
3468 'gen_cmd': False,
3469 'client_test': False,
3470 'gl_test_func': 'glGetQueryObjectuiv',
3471 'pepper_interface': 'Query',
3472 'extension': "occlusion_query_EXT",
3474 'BindUniformLocationCHROMIUM': {
3475 'type': 'GLchar',
3476 'extension': True,
3477 'data_transfer_methods': ['bucket'],
3478 'needs_size': True,
3479 'gl_test_func': 'DoBindUniformLocationCHROMIUM',
3481 'InsertEventMarkerEXT': {
3482 'type': 'GLcharN',
3483 'decoder_func': 'DoInsertEventMarkerEXT',
3484 'expectation': False,
3485 'extension': True,
3487 'PushGroupMarkerEXT': {
3488 'type': 'GLcharN',
3489 'decoder_func': 'DoPushGroupMarkerEXT',
3490 'expectation': False,
3491 'extension': True,
3493 'PopGroupMarkerEXT': {
3494 'decoder_func': 'DoPopGroupMarkerEXT',
3495 'expectation': False,
3496 'extension': True,
3497 'impl_func': False,
3500 'GenVertexArraysOES': {
3501 'type': 'GENn',
3502 'extension': True,
3503 'gl_test_func': 'glGenVertexArraysOES',
3504 'resource_type': 'VertexArray',
3505 'resource_types': 'VertexArrays',
3506 'unit_test': False,
3507 'pepper_interface': 'VertexArrayObject',
3509 'BindVertexArrayOES': {
3510 'type': 'Bind',
3511 'extension': True,
3512 'gl_test_func': 'glBindVertexArrayOES',
3513 'decoder_func': 'DoBindVertexArrayOES',
3514 'gen_func': 'GenVertexArraysOES',
3515 'unit_test': False,
3516 'client_test': False,
3517 'pepper_interface': 'VertexArrayObject',
3519 'DeleteVertexArraysOES': {
3520 'type': 'DELn',
3521 'extension': True,
3522 'gl_test_func': 'glDeleteVertexArraysOES',
3523 'resource_type': 'VertexArray',
3524 'resource_types': 'VertexArrays',
3525 'unit_test': False,
3526 'pepper_interface': 'VertexArrayObject',
3528 'IsVertexArrayOES': {
3529 'type': 'Is',
3530 'extension': True,
3531 'gl_test_func': 'glIsVertexArrayOES',
3532 'decoder_func': 'DoIsVertexArrayOES',
3533 'expectation': False,
3534 'unit_test': False,
3535 'pepper_interface': 'VertexArrayObject',
3537 'BindTexImage2DCHROMIUM': {
3538 'decoder_func': 'DoBindTexImage2DCHROMIUM',
3539 'unit_test': False,
3540 'extension': True,
3541 'chromium': True,
3543 'ReleaseTexImage2DCHROMIUM': {
3544 'decoder_func': 'DoReleaseTexImage2DCHROMIUM',
3545 'unit_test': False,
3546 'extension': True,
3547 'chromium': True,
3549 'ShallowFinishCHROMIUM': {
3550 'impl_func': False,
3551 'gen_cmd': False,
3552 'extension': True,
3553 'chromium': True,
3554 'client_test': False,
3556 'ShallowFlushCHROMIUM': {
3557 'impl_func': False,
3558 'gen_cmd': False,
3559 'extension': "CHROMIUM_miscellaneous",
3560 'chromium': True,
3561 'client_test': False,
3563 'OrderingBarrierCHROMIUM': {
3564 'impl_func': False,
3565 'gen_cmd': False,
3566 'extension': True,
3567 'chromium': True,
3568 'client_test': False,
3570 'TraceBeginCHROMIUM': {
3571 'type': 'Custom',
3572 'impl_func': False,
3573 'client_test': False,
3574 'cmd_args': 'GLuint category_bucket_id, GLuint name_bucket_id',
3575 'extension': True,
3576 'chromium': True,
3578 'TraceEndCHROMIUM': {
3579 'impl_func': False,
3580 'client_test': False,
3581 'decoder_func': 'DoTraceEndCHROMIUM',
3582 'unit_test': False,
3583 'extension': True,
3584 'chromium': True,
3586 'AsyncTexImage2DCHROMIUM': {
3587 'type': 'Manual',
3588 'data_transfer_methods': ['shm'],
3589 'client_test': False,
3590 'cmd_args': 'GLenumTextureTarget target, GLint level, '
3591 'GLintTextureInternalFormat internalformat, '
3592 'GLsizei width, GLsizei height, '
3593 'GLintTextureBorder border, '
3594 'GLenumTextureFormat format, GLenumPixelType type, '
3595 'const void* pixels, '
3596 'uint32_t async_upload_token, '
3597 'void* sync_data',
3598 'extension': True,
3599 'chromium': True,
3601 'AsyncTexSubImage2DCHROMIUM': {
3602 'type': 'Manual',
3603 'data_transfer_methods': ['shm'],
3604 'client_test': False,
3605 'cmd_args': 'GLenumTextureTarget target, GLint level, '
3606 'GLint xoffset, GLint yoffset, '
3607 'GLsizei width, GLsizei height, '
3608 'GLenumTextureFormat format, GLenumPixelType type, '
3609 'const void* data, '
3610 'uint32_t async_upload_token, '
3611 'void* sync_data',
3612 'extension': True,
3613 'chromium': True,
3615 'WaitAsyncTexImage2DCHROMIUM': {
3616 'type': 'Manual',
3617 'client_test': False,
3618 'extension': True,
3619 'chromium': True,
3621 'WaitAllAsyncTexImage2DCHROMIUM': {
3622 'type': 'Manual',
3623 'client_test': False,
3624 'extension': True,
3625 'chromium': True,
3627 'DiscardFramebufferEXT': {
3628 'type': 'PUTn',
3629 'count': 1,
3630 'decoder_func': 'DoDiscardFramebufferEXT',
3631 'unit_test': False,
3632 'client_test': False,
3633 'extension_flag': 'ext_discard_framebuffer',
3635 'LoseContextCHROMIUM': {
3636 'decoder_func': 'DoLoseContextCHROMIUM',
3637 'unit_test': False,
3638 'extension': True,
3639 'chromium': True,
3641 'InsertSyncPointCHROMIUM': {
3642 'type': 'HandWritten',
3643 'impl_func': False,
3644 'extension': "CHROMIUM_sync_point",
3645 'chromium': True,
3647 'WaitSyncPointCHROMIUM': {
3648 'type': 'Custom',
3649 'impl_func': True,
3650 'extension': "CHROMIUM_sync_point",
3651 'chromium': True,
3652 'trace_level': 1,
3654 'DiscardBackbufferCHROMIUM': {
3655 'type': 'Custom',
3656 'impl_func': True,
3657 'extension': True,
3658 'chromium': True,
3660 'ScheduleOverlayPlaneCHROMIUM': {
3661 'type': 'Custom',
3662 'impl_func': True,
3663 'unit_test': False,
3664 'client_test': False,
3665 'extension': True,
3666 'chromium': True,
3668 'MatrixLoadfCHROMIUM': {
3669 'type': 'PUT',
3670 'count': 16,
3671 'data_type': 'GLfloat',
3672 'decoder_func': 'DoMatrixLoadfCHROMIUM',
3673 'gl_test_func': 'glMatrixLoadfEXT',
3674 'chromium': True,
3675 'extension': True,
3676 'extension_flag': 'chromium_path_rendering',
3678 'MatrixLoadIdentityCHROMIUM': {
3679 'decoder_func': 'DoMatrixLoadIdentityCHROMIUM',
3680 'gl_test_func': 'glMatrixLoadIdentityEXT',
3681 'chromium': True,
3682 'extension': True,
3683 'extension_flag': 'chromium_path_rendering',
3688 def Grouper(n, iterable, fillvalue=None):
3689 """Collect data into fixed-length chunks or blocks"""
3690 args = [iter(iterable)] * n
3691 return itertools.izip_longest(fillvalue=fillvalue, *args)
3694 def SplitWords(input_string):
3695 """Transforms a input_string into a list of lower-case components.
3697 Args:
3698 input_string: the input string.
3700 Returns:
3701 a list of lower-case words.
3703 if input_string.find('_') > -1:
3704 # 'some_TEXT_' -> 'some text'
3705 return input_string.replace('_', ' ').strip().lower().split()
3706 else:
3707 if re.search('[A-Z]', input_string) and re.search('[a-z]', input_string):
3708 # mixed case.
3709 # look for capitalization to cut input_strings
3710 # 'SomeText' -> 'Some Text'
3711 input_string = re.sub('([A-Z])', r' \1', input_string).strip()
3712 # 'Vector3' -> 'Vector 3'
3713 input_string = re.sub('([^0-9])([0-9])', r'\1 \2', input_string)
3714 return input_string.lower().split()
3717 def Lower(words):
3718 """Makes a lower-case identifier from words.
3720 Args:
3721 words: a list of lower-case words.
3723 Returns:
3724 the lower-case identifier.
3726 return '_'.join(words)
3729 def ToUnderscore(input_string):
3730 """converts CamelCase to camel_case."""
3731 words = SplitWords(input_string)
3732 return Lower(words)
3734 def CachedStateName(item):
3735 if item.get('cached', False):
3736 return 'cached_' + item['name']
3737 return item['name']
3739 def ToGLExtensionString(extension_flag):
3740 """Returns GL-type extension string of a extension flag."""
3741 if extension_flag == "oes_compressed_etc1_rgb8_texture":
3742 return "OES_compressed_ETC1_RGB8_texture" # Fixup inconsitency with rgb8,
3743 # unfortunate.
3744 uppercase_words = [ 'img', 'ext', 'arb', 'chromium', 'oes', 'amd', 'bgra8888',
3745 'egl', 'atc', 'etc1', 'angle']
3746 parts = extension_flag.split('_')
3747 return "_".join(
3748 [part.upper() if part in uppercase_words else part for part in parts])
3750 def ToCamelCase(input_string):
3751 """converts ABC_underscore_case to ABCUnderscoreCase."""
3752 return ''.join(w[0].upper() + w[1:] for w in input_string.split('_'))
3754 def GetGLGetTypeConversion(result_type, value_type, value):
3755 """Makes a gl compatible type conversion string for accessing state variables.
3757 Useful when accessing state variables through glGetXXX calls.
3758 glGet documetation (for example, the manual pages):
3759 [...] If glGetIntegerv is called, [...] most floating-point values are
3760 rounded to the nearest integer value. [...]
3762 Args:
3763 result_type: the gl type to be obtained
3764 value_type: the GL type of the state variable
3765 value: the name of the state variable
3767 Returns:
3768 String that converts the state variable to desired GL type according to GL
3769 rules.
3772 if result_type == 'GLint':
3773 if value_type == 'GLfloat':
3774 return 'static_cast<GLint>(round(%s))' % value
3775 return 'static_cast<%s>(%s)' % (result_type, value)
3777 class CWriter(object):
3778 """Writes to a file formatting it for Google's style guidelines."""
3780 def __init__(self, filename):
3781 self.filename = filename
3782 self.content = []
3784 def Write(self, string):
3785 """Writes a string to a file spliting if it's > 80 characters."""
3786 lines = string.splitlines()
3787 num_lines = len(lines)
3788 for ii in range(0, num_lines):
3789 self.content.append(lines[ii])
3790 if ii < (num_lines - 1) or string[-1] == '\n':
3791 self.content.append('\n')
3793 def Close(self):
3794 """Close the file."""
3795 content = "".join(self.content)
3796 write_file = True
3797 if os.path.exists(self.filename):
3798 old_file = open(self.filename, "rb");
3799 old_content = old_file.read()
3800 old_file.close();
3801 if content == old_content:
3802 write_file = False
3803 if write_file:
3804 file = open(self.filename, "wb")
3805 file.write(content)
3806 file.close()
3809 class CHeaderWriter(CWriter):
3810 """Writes a C Header file."""
3812 _non_alnum_re = re.compile(r'[^a-zA-Z0-9]')
3814 def __init__(self, filename, file_comment = None):
3815 CWriter.__init__(self, filename)
3817 base = os.path.abspath(filename)
3818 while os.path.basename(base) != 'src':
3819 new_base = os.path.dirname(base)
3820 assert new_base != base # Prevent infinite loop.
3821 base = new_base
3823 hpath = os.path.relpath(filename, base)
3824 self.guard = self._non_alnum_re.sub('_', hpath).upper() + '_'
3826 self.Write(_LICENSE)
3827 self.Write(_DO_NOT_EDIT_WARNING)
3828 if not file_comment == None:
3829 self.Write(file_comment)
3830 self.Write("#ifndef %s\n" % self.guard)
3831 self.Write("#define %s\n\n" % self.guard)
3833 def Close(self):
3834 self.Write("#endif // %s\n\n" % self.guard)
3835 CWriter.Close(self)
3837 class TypeHandler(object):
3838 """This class emits code for a particular type of function."""
3840 _remove_expected_call_re = re.compile(r' EXPECT_CALL.*?;\n', re.S)
3842 def __init__(self):
3843 pass
3845 def InitFunction(self, func):
3846 """Add or adjust anything type specific for this function."""
3847 if func.GetInfo('needs_size') and not func.name.endswith('Bucket'):
3848 func.AddCmdArg(DataSizeArgument('data_size'))
3850 def NeedsDataTransferFunction(self, func):
3851 """Overriden from TypeHandler."""
3852 return func.num_pointer_args >= 1
3854 def WriteStruct(self, func, file):
3855 """Writes a structure that matches the arguments to a function."""
3856 comment = func.GetInfo('cmd_comment')
3857 if not comment == None:
3858 file.Write(comment)
3859 file.Write("struct %s {\n" % func.name)
3860 file.Write(" typedef %s ValueType;\n" % func.name)
3861 file.Write(" static const CommandId kCmdId = k%s;\n" % func.name)
3862 func.WriteCmdArgFlag(file)
3863 func.WriteCmdFlag(file)
3864 file.Write("\n")
3865 result = func.GetInfo('result')
3866 if not result == None:
3867 if len(result) == 1:
3868 file.Write(" typedef %s Result;\n\n" % result[0])
3869 else:
3870 file.Write(" struct Result {\n")
3871 for line in result:
3872 file.Write(" %s;\n" % line)
3873 file.Write(" };\n\n")
3875 func.WriteCmdComputeSize(file)
3876 func.WriteCmdSetHeader(file)
3877 func.WriteCmdInit(file)
3878 func.WriteCmdSet(file)
3880 file.Write(" gpu::CommandHeader header;\n")
3881 args = func.GetCmdArgs()
3882 for arg in args:
3883 file.Write(" %s %s;\n" % (arg.cmd_type, arg.name))
3885 consts = func.GetCmdConstants()
3886 for const in consts:
3887 file.Write(" static const %s %s = %s;\n" %
3888 (const.cmd_type, const.name, const.GetConstantValue()))
3890 file.Write("};\n")
3891 file.Write("\n")
3893 size = len(args) * _SIZE_OF_UINT32 + _SIZE_OF_COMMAND_HEADER
3894 file.Write("static_assert(sizeof(%s) == %d,\n" % (func.name, size))
3895 file.Write(" \"size of %s should be %d\");\n" %
3896 (func.name, size))
3897 file.Write("static_assert(offsetof(%s, header) == 0,\n" % func.name)
3898 file.Write(" \"offset of %s header should be 0\");\n" %
3899 func.name)
3900 offset = _SIZE_OF_COMMAND_HEADER
3901 for arg in args:
3902 file.Write("static_assert(offsetof(%s, %s) == %d,\n" %
3903 (func.name, arg.name, offset))
3904 file.Write(" \"offset of %s %s should be %d\");\n" %
3905 (func.name, arg.name, offset))
3906 offset += _SIZE_OF_UINT32
3907 if not result == None and len(result) > 1:
3908 offset = 0;
3909 for line in result:
3910 parts = line.split()
3911 name = parts[-1]
3912 check = """
3913 static_assert(offsetof(%(cmd_name)s::Result, %(field_name)s) == %(offset)d,
3914 "offset of %(cmd_name)s Result %(field_name)s should be "
3915 "%(offset)d");
3917 file.Write((check.strip() + "\n") % {
3918 'cmd_name': func.name,
3919 'field_name': name,
3920 'offset': offset,
3922 offset += _SIZE_OF_UINT32
3923 file.Write("\n")
3925 def WriteHandlerImplementation(self, func, file):
3926 """Writes the handler implementation for this command."""
3927 if func.IsUnsafe() and func.GetInfo('id_mapping'):
3928 code_no_gen = """ if (!group_->Get%(type)sServiceId(
3929 %(var)s, &%(service_var)s)) {
3930 LOCAL_SET_GL_ERROR(GL_INVALID_OPERATION, "%(func)s", "invalid %(var)s id");
3931 return error::kNoError;
3934 code_gen = """ if (!group_->Get%(type)sServiceId(
3935 %(var)s, &%(service_var)s)) {
3936 if (!group_->bind_generates_resource()) {
3937 LOCAL_SET_GL_ERROR(
3938 GL_INVALID_OPERATION, "%(func)s", "invalid %(var)s id");
3939 return error::kNoError;
3941 GLuint client_id = %(var)s;
3942 gl%(gen_func)s(1, &%(service_var)s);
3943 Create%(type)s(client_id, %(service_var)s);
3946 gen_func = func.GetInfo('gen_func')
3947 for id_type in func.GetInfo('id_mapping'):
3948 service_var = id_type.lower()
3949 if id_type == 'Sync':
3950 service_var = "service_%s" % service_var
3951 file.Write(" GLsync %s = 0;\n" % service_var)
3952 if gen_func and id_type in gen_func:
3953 file.Write(code_gen % { 'type': id_type,
3954 'var': id_type.lower(),
3955 'service_var': service_var,
3956 'func': func.GetGLFunctionName(),
3957 'gen_func': gen_func })
3958 else:
3959 file.Write(code_no_gen % { 'type': id_type,
3960 'var': id_type.lower(),
3961 'service_var': service_var,
3962 'func': func.GetGLFunctionName() })
3963 args = []
3964 for arg in func.GetOriginalArgs():
3965 if arg.type == "GLsync":
3966 args.append("service_%s" % arg.name)
3967 elif arg.name.endswith("size") and arg.type == "GLsizei":
3968 args.append("num_%s" % func.GetLastOriginalArg().name)
3969 elif arg.name == "length":
3970 args.append("nullptr")
3971 else:
3972 args.append(arg.name)
3973 file.Write(" %s(%s);\n" %
3974 (func.GetGLFunctionName(), ", ".join(args)))
3976 def WriteCmdSizeTest(self, func, file):
3977 """Writes the size test for a command."""
3978 file.Write(" EXPECT_EQ(sizeof(cmd), cmd.header.size * 4u);\n")
3980 def WriteFormatTest(self, func, file):
3981 """Writes a format test for a command."""
3982 file.Write("TEST_F(GLES2FormatTest, %s) {\n" % func.name)
3983 file.Write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
3984 (func.name, func.name))
3985 file.Write(" void* next_cmd = cmd.Set(\n")
3986 file.Write(" &cmd")
3987 args = func.GetCmdArgs()
3988 for value, arg in enumerate(args):
3989 file.Write(",\n static_cast<%s>(%d)" % (arg.type, value + 11))
3990 file.Write(");\n")
3991 file.Write(" EXPECT_EQ(static_cast<uint32_t>(cmds::%s::kCmdId),\n" %
3992 func.name)
3993 file.Write(" cmd.header.command);\n")
3994 func.type_handler.WriteCmdSizeTest(func, file)
3995 for value, arg in enumerate(args):
3996 file.Write(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);\n" %
3997 (arg.type, value + 11, arg.name))
3998 file.Write(" CheckBytesWrittenMatchesExpectedSize(\n")
3999 file.Write(" next_cmd, sizeof(cmd));\n")
4000 file.Write("}\n")
4001 file.Write("\n")
4003 def WriteImmediateFormatTest(self, func, file):
4004 """Writes a format test for an immediate version of a command."""
4005 pass
4007 def WriteBucketFormatTest(self, func, file):
4008 """Writes a format test for a bucket version of a command."""
4009 pass
4011 def WriteGetDataSizeCode(self, func, file):
4012 """Writes the code to set data_size used in validation"""
4013 pass
4015 def WriteImmediateCmdSizeTest(self, func, file):
4016 """Writes a size test for an immediate version of a command."""
4017 file.Write(" // TODO(gman): Compute correct size.\n")
4018 file.Write(" EXPECT_EQ(sizeof(cmd), cmd.header.size * 4u);\n")
4020 def __WriteIdMapping(self, func, file):
4021 """Writes client side / service side ID mapping."""
4022 if not func.IsUnsafe() or not func.GetInfo('id_mapping'):
4023 return
4024 for id_type in func.GetInfo('id_mapping'):
4025 file.Write(" group_->Get%sServiceId(%s, &%s);\n" %
4026 (id_type, id_type.lower(), id_type.lower()))
4028 def WriteImmediateHandlerImplementation (self, func, file):
4029 """Writes the handler impl for the immediate version of a command."""
4030 self.__WriteIdMapping(func, file)
4031 file.Write(" %s(%s);\n" %
4032 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
4034 def WriteBucketHandlerImplementation (self, func, file):
4035 """Writes the handler impl for the bucket version of a command."""
4036 self.__WriteIdMapping(func, file)
4037 file.Write(" %s(%s);\n" %
4038 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
4040 def WriteServiceHandlerFunctionHeader(self, func, file):
4041 """Writes function header for service implementation handlers."""
4042 file.Write("""error::Error GLES2DecoderImpl::Handle%(name)s(
4043 uint32_t immediate_data_size, const void* cmd_data) {
4044 """ % {'name': func.name})
4045 if func.IsUnsafe():
4046 file.Write("""if (!unsafe_es3_apis_enabled())
4047 return error::kUnknownCommand;
4048 """)
4049 file.Write("""const gles2::cmds::%(name)s& c =
4050 *static_cast<const gles2::cmds::%(name)s*>(cmd_data);
4051 (void)c;
4052 """ % {'name': func.name})
4054 def WriteServiceImplementation(self, func, file):
4055 """Writes the service implementation for a command."""
4056 self.WriteServiceHandlerFunctionHeader(func, file)
4057 self.WriteHandlerExtensionCheck(func, file)
4058 self.WriteHandlerDeferReadWrite(func, file);
4059 if len(func.GetOriginalArgs()) > 0:
4060 last_arg = func.GetLastOriginalArg()
4061 all_but_last_arg = func.GetOriginalArgs()[:-1]
4062 for arg in all_but_last_arg:
4063 arg.WriteGetCode(file)
4064 self.WriteGetDataSizeCode(func, file)
4065 last_arg.WriteGetCode(file)
4066 func.WriteHandlerValidation(file)
4067 func.WriteHandlerImplementation(file)
4068 file.Write(" return error::kNoError;\n")
4069 file.Write("}\n")
4070 file.Write("\n")
4072 def WriteImmediateServiceImplementation(self, func, file):
4073 """Writes the service implementation for an immediate version of command."""
4074 self.WriteServiceHandlerFunctionHeader(func, file)
4075 self.WriteHandlerExtensionCheck(func, file)
4076 self.WriteHandlerDeferReadWrite(func, file);
4077 for arg in func.GetOriginalArgs():
4078 if arg.IsPointer():
4079 self.WriteGetDataSizeCode(func, file)
4080 arg.WriteGetCode(file)
4081 func.WriteHandlerValidation(file)
4082 func.WriteHandlerImplementation(file)
4083 file.Write(" return error::kNoError;\n")
4084 file.Write("}\n")
4085 file.Write("\n")
4087 def WriteBucketServiceImplementation(self, func, file):
4088 """Writes the service implementation for a bucket version of command."""
4089 self.WriteServiceHandlerFunctionHeader(func, file)
4090 self.WriteHandlerExtensionCheck(func, file)
4091 self.WriteHandlerDeferReadWrite(func, file);
4092 for arg in func.GetCmdArgs():
4093 arg.WriteGetCode(file)
4094 func.WriteHandlerValidation(file)
4095 func.WriteHandlerImplementation(file)
4096 file.Write(" return error::kNoError;\n")
4097 file.Write("}\n")
4098 file.Write("\n")
4100 def WriteHandlerExtensionCheck(self, func, file):
4101 if func.GetInfo('extension_flag'):
4102 file.Write(" if (!features().%s) {\n" % func.GetInfo('extension_flag'))
4103 file.Write(" LOCAL_SET_GL_ERROR(GL_INVALID_OPERATION, \"gl%s\","
4104 " \"function not available\");\n" % func.original_name)
4105 file.Write(" return error::kNoError;")
4106 file.Write(" }\n\n")
4108 def WriteHandlerDeferReadWrite(self, func, file):
4109 """Writes the code to handle deferring reads or writes."""
4110 defer_draws = func.GetInfo('defer_draws')
4111 defer_reads = func.GetInfo('defer_reads')
4112 if defer_draws or defer_reads:
4113 file.Write(" error::Error error;\n")
4114 if defer_draws:
4115 file.Write(" error = WillAccessBoundFramebufferForDraw();\n")
4116 file.Write(" if (error != error::kNoError)\n")
4117 file.Write(" return error;\n")
4118 if defer_reads:
4119 file.Write(" error = WillAccessBoundFramebufferForRead();\n")
4120 file.Write(" if (error != error::kNoError)\n")
4121 file.Write(" return error;\n")
4123 def WriteValidUnitTest(self, func, file, test, *extras):
4124 """Writes a valid unit test for the service implementation."""
4125 if func.GetInfo('expectation') == False:
4126 test = self._remove_expected_call_re.sub('', test)
4127 name = func.name
4128 arg_strings = [
4129 arg.GetValidArg(func) \
4130 for arg in func.GetOriginalArgs() if not arg.IsConstant()
4132 gl_arg_strings = [
4133 arg.GetValidGLArg(func) \
4134 for arg in func.GetOriginalArgs()
4136 gl_func_name = func.GetGLTestFunctionName()
4137 vars = {
4138 'name':name,
4139 'gl_func_name': gl_func_name,
4140 'args': ", ".join(arg_strings),
4141 'gl_args': ", ".join(gl_arg_strings),
4143 for extra in extras:
4144 vars.update(extra)
4145 old_test = ""
4146 while (old_test != test):
4147 old_test = test
4148 test = test % vars
4149 file.Write(test % vars)
4151 def WriteInvalidUnitTest(self, func, file, test, *extras):
4152 """Writes an invalid unit test for the service implementation."""
4153 if func.IsUnsafe():
4154 return
4155 for invalid_arg_index, invalid_arg in enumerate(func.GetOriginalArgs()):
4156 # Service implementation does not test constants, as they are not part of
4157 # the call in the service side.
4158 if invalid_arg.IsConstant():
4159 continue
4161 num_invalid_values = invalid_arg.GetNumInvalidValues(func)
4162 for value_index in range(0, num_invalid_values):
4163 arg_strings = []
4164 parse_result = "kNoError"
4165 gl_error = None
4166 for arg in func.GetOriginalArgs():
4167 if arg.IsConstant():
4168 continue
4169 if invalid_arg is arg:
4170 (arg_string, parse_result, gl_error) = arg.GetInvalidArg(
4171 value_index)
4172 else:
4173 arg_string = arg.GetValidArg(func)
4174 arg_strings.append(arg_string)
4175 gl_arg_strings = []
4176 for arg in func.GetOriginalArgs():
4177 gl_arg_strings.append("_")
4178 gl_func_name = func.GetGLTestFunctionName()
4179 gl_error_test = ''
4180 if not gl_error == None:
4181 gl_error_test = '\n EXPECT_EQ(%s, GetGLError());' % gl_error
4183 vars = {
4184 'name': func.name,
4185 'arg_index': invalid_arg_index,
4186 'value_index': value_index,
4187 'gl_func_name': gl_func_name,
4188 'args': ", ".join(arg_strings),
4189 'all_but_last_args': ", ".join(arg_strings[:-1]),
4190 'gl_args': ", ".join(gl_arg_strings),
4191 'parse_result': parse_result,
4192 'gl_error_test': gl_error_test,
4194 for extra in extras:
4195 vars.update(extra)
4196 file.Write(test % vars)
4198 def WriteServiceUnitTest(self, func, file, *extras):
4199 """Writes the service unit test for a command."""
4201 if func.name == 'Enable':
4202 valid_test = """
4203 TEST_P(%(test_name)s, %(name)sValidArgs) {
4204 SetupExpectationsForEnableDisable(%(gl_args)s, true);
4205 SpecializedSetup<cmds::%(name)s, 0>(true);
4206 cmds::%(name)s cmd;
4207 cmd.Init(%(args)s);"""
4208 elif func.name == 'Disable':
4209 valid_test = """
4210 TEST_P(%(test_name)s, %(name)sValidArgs) {
4211 SetupExpectationsForEnableDisable(%(gl_args)s, false);
4212 SpecializedSetup<cmds::%(name)s, 0>(true);
4213 cmds::%(name)s cmd;
4214 cmd.Init(%(args)s);"""
4215 else:
4216 valid_test = """
4217 TEST_P(%(test_name)s, %(name)sValidArgs) {
4218 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
4219 SpecializedSetup<cmds::%(name)s, 0>(true);
4220 cmds::%(name)s cmd;
4221 cmd.Init(%(args)s);"""
4222 if func.IsUnsafe():
4223 valid_test += """
4224 decoder_->set_unsafe_es3_apis_enabled(true);
4225 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4226 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4227 decoder_->set_unsafe_es3_apis_enabled(false);
4228 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));
4231 else:
4232 valid_test += """
4233 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4234 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4237 self.WriteValidUnitTest(func, file, valid_test, *extras)
4239 if not func.IsUnsafe():
4240 invalid_test = """
4241 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
4242 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
4243 SpecializedSetup<cmds::%(name)s, 0>(false);
4244 cmds::%(name)s cmd;
4245 cmd.Init(%(args)s);
4246 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
4249 self.WriteInvalidUnitTest(func, file, invalid_test, *extras)
4251 def WriteImmediateServiceUnitTest(self, func, file, *extras):
4252 """Writes the service unit test for an immediate command."""
4253 file.Write("// TODO(gman): %s\n" % func.name)
4255 def WriteImmediateValidationCode(self, func, file):
4256 """Writes the validation code for an immediate version of a command."""
4257 pass
4259 def WriteBucketServiceUnitTest(self, func, file, *extras):
4260 """Writes the service unit test for a bucket command."""
4261 file.Write("// TODO(gman): %s\n" % func.name)
4263 def WriteBucketValidationCode(self, func, file):
4264 """Writes the validation code for a bucket version of a command."""
4265 file.Write("// TODO(gman): %s\n" % func.name)
4267 def WriteGLES2ImplementationDeclaration(self, func, file):
4268 """Writes the GLES2 Implemention declaration."""
4269 impl_decl = func.GetInfo('impl_decl')
4270 if impl_decl == None or impl_decl == True:
4271 file.Write("%s %s(%s) override;\n" %
4272 (func.return_type, func.original_name,
4273 func.MakeTypedOriginalArgString("")))
4274 file.Write("\n")
4276 def WriteGLES2CLibImplementation(self, func, file):
4277 file.Write("%s GLES2%s(%s) {\n" %
4278 (func.return_type, func.name,
4279 func.MakeTypedOriginalArgString("")))
4280 result_string = "return "
4281 if func.return_type == "void":
4282 result_string = ""
4283 file.Write(" %sgles2::GetGLContext()->%s(%s);\n" %
4284 (result_string, func.original_name,
4285 func.MakeOriginalArgString("")))
4286 file.Write("}\n")
4288 def WriteGLES2Header(self, func, file):
4289 """Writes a re-write macro for GLES"""
4290 file.Write("#define gl%s GLES2_GET_FUN(%s)\n" %(func.name, func.name))
4292 def WriteClientGLCallLog(self, func, file):
4293 """Writes a logging macro for the client side code."""
4294 comma = ""
4295 if len(func.GetOriginalArgs()):
4296 comma = " << "
4297 file.Write(
4298 ' GPU_CLIENT_LOG("[" << GetLogPrefix() << "] gl%s("%s%s << ")");\n' %
4299 (func.original_name, comma, func.MakeLogArgString()))
4301 def WriteClientGLReturnLog(self, func, file):
4302 """Writes the return value logging code."""
4303 if func.return_type != "void":
4304 file.Write(' GPU_CLIENT_LOG("return:" << result)\n')
4306 def WriteGLES2ImplementationHeader(self, func, file):
4307 """Writes the GLES2 Implemention."""
4308 self.WriteGLES2ImplementationDeclaration(func, file)
4310 def WriteGLES2TraceImplementationHeader(self, func, file):
4311 """Writes the GLES2 Trace Implemention header."""
4312 file.Write("%s %s(%s) override;\n" %
4313 (func.return_type, func.original_name,
4314 func.MakeTypedOriginalArgString("")))
4316 def WriteGLES2TraceImplementation(self, func, file):
4317 """Writes the GLES2 Trace Implemention."""
4318 file.Write("%s GLES2TraceImplementation::%s(%s) {\n" %
4319 (func.return_type, func.original_name,
4320 func.MakeTypedOriginalArgString("")))
4321 result_string = "return "
4322 if func.return_type == "void":
4323 result_string = ""
4324 file.Write(' TRACE_EVENT_BINARY_EFFICIENT0("gpu", "GLES2Trace::%s");\n' %
4325 func.name)
4326 file.Write(" %sgl_->%s(%s);\n" %
4327 (result_string, func.name, func.MakeOriginalArgString("")))
4328 file.Write("}\n")
4329 file.Write("\n")
4331 def WriteGLES2Implementation(self, func, file):
4332 """Writes the GLES2 Implemention."""
4333 impl_func = func.GetInfo('impl_func')
4334 impl_decl = func.GetInfo('impl_decl')
4335 gen_cmd = func.GetInfo('gen_cmd')
4336 if (func.can_auto_generate and
4337 (impl_func == None or impl_func == True) and
4338 (impl_decl == None or impl_decl == True) and
4339 (gen_cmd == None or gen_cmd == True)):
4340 file.Write("%s GLES2Implementation::%s(%s) {\n" %
4341 (func.return_type, func.original_name,
4342 func.MakeTypedOriginalArgString("")))
4343 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
4344 self.WriteClientGLCallLog(func, file)
4345 func.WriteDestinationInitalizationValidation(file)
4346 for arg in func.GetOriginalArgs():
4347 arg.WriteClientSideValidationCode(file, func)
4348 file.Write(" helper_->%s(%s);\n" %
4349 (func.name, func.MakeHelperArgString("")))
4350 file.Write(" CheckGLError();\n")
4351 self.WriteClientGLReturnLog(func, file)
4352 file.Write("}\n")
4353 file.Write("\n")
4355 def WriteGLES2InterfaceHeader(self, func, file):
4356 """Writes the GLES2 Interface."""
4357 file.Write("virtual %s %s(%s) = 0;\n" %
4358 (func.return_type, func.original_name,
4359 func.MakeTypedOriginalArgString("")))
4361 def WriteMojoGLES2ImplHeader(self, func, file):
4362 """Writes the Mojo GLES2 implementation header."""
4363 file.Write("%s %s(%s) override;\n" %
4364 (func.return_type, func.original_name,
4365 func.MakeTypedOriginalArgString("")))
4367 def WriteMojoGLES2Impl(self, func, file):
4368 """Writes the Mojo GLES2 implementation."""
4369 file.Write("%s MojoGLES2Impl::%s(%s) {\n" %
4370 (func.return_type, func.original_name,
4371 func.MakeTypedOriginalArgString("")))
4372 extensions = ["CHROMIUM_sync_point", "CHROMIUM_texture_mailbox",
4373 "CHROMIUM_sub_image", "CHROMIUM_miscellaneous",
4374 "occlusion_query_EXT"]
4375 if func.IsCoreGLFunction() or func.GetInfo("extension") in extensions:
4376 file.Write("MojoGLES2MakeCurrent(context_);");
4377 func_return = "gl" + func.original_name + "(" + \
4378 func.MakeOriginalArgString("") + ");"
4379 if func.return_type == "void":
4380 file.Write(func_return);
4381 else:
4382 file.Write("return " + func_return);
4383 else:
4384 file.Write("NOTREACHED() << \"Unimplemented %s.\";\n" %
4385 func.original_name);
4386 if func.return_type != "void":
4387 file.Write("return 0;")
4388 file.Write("}")
4390 def WriteGLES2InterfaceStub(self, func, file):
4391 """Writes the GLES2 Interface stub declaration."""
4392 file.Write("%s %s(%s) override;\n" %
4393 (func.return_type, func.original_name,
4394 func.MakeTypedOriginalArgString("")))
4396 def WriteGLES2InterfaceStubImpl(self, func, file):
4397 """Writes the GLES2 Interface stub declaration."""
4398 args = func.GetOriginalArgs()
4399 arg_string = ", ".join(
4400 ["%s /* %s */" % (arg.type, arg.name) for arg in args])
4401 file.Write("%s GLES2InterfaceStub::%s(%s) {\n" %
4402 (func.return_type, func.original_name, arg_string))
4403 if func.return_type != "void":
4404 file.Write(" return 0;\n")
4405 file.Write("}\n")
4407 def WriteGLES2ImplementationUnitTest(self, func, file):
4408 """Writes the GLES2 Implemention unit test."""
4409 client_test = func.GetInfo('client_test')
4410 if (func.can_auto_generate and
4411 (client_test == None or client_test == True)):
4412 code = """
4413 TEST_F(GLES2ImplementationTest, %(name)s) {
4414 struct Cmds {
4415 cmds::%(name)s cmd;
4417 Cmds expected;
4418 expected.cmd.Init(%(cmd_args)s);
4420 gl_->%(name)s(%(args)s);
4421 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
4424 cmd_arg_strings = [
4425 arg.GetValidClientSideCmdArg(func) for arg in func.GetCmdArgs()
4428 gl_arg_strings = [
4429 arg.GetValidClientSideArg(func) for arg in func.GetOriginalArgs()
4432 file.Write(code % {
4433 'name': func.name,
4434 'args': ", ".join(gl_arg_strings),
4435 'cmd_args': ", ".join(cmd_arg_strings),
4438 # Test constants for invalid values, as they are not tested by the
4439 # service.
4440 constants = [arg for arg in func.GetOriginalArgs() if arg.IsConstant()]
4441 if constants:
4442 code = """
4443 TEST_F(GLES2ImplementationTest, %(name)sInvalidConstantArg%(invalid_index)d) {
4444 gl_->%(name)s(%(args)s);
4445 EXPECT_TRUE(NoCommandsWritten());
4446 EXPECT_EQ(%(gl_error)s, CheckError());
4449 for invalid_arg in constants:
4450 gl_arg_strings = []
4451 invalid = invalid_arg.GetInvalidArg(func)
4452 for arg in func.GetOriginalArgs():
4453 if arg is invalid_arg:
4454 gl_arg_strings.append(invalid[0])
4455 else:
4456 gl_arg_strings.append(arg.GetValidClientSideArg(func))
4458 file.Write(code % {
4459 'name': func.name,
4460 'invalid_index': func.GetOriginalArgs().index(invalid_arg),
4461 'args': ", ".join(gl_arg_strings),
4462 'gl_error': invalid[2],
4464 else:
4465 if client_test != False:
4466 file.Write("// TODO(zmo): Implement unit test for %s\n" % func.name)
4468 def WriteDestinationInitalizationValidation(self, func, file):
4469 """Writes the client side destintion initialization validation."""
4470 for arg in func.GetOriginalArgs():
4471 arg.WriteDestinationInitalizationValidation(file, func)
4473 def WriteTraceEvent(self, func, file):
4474 file.Write(' TRACE_EVENT0("gpu", "GLES2Implementation::%s");\n' %
4475 func.original_name)
4477 def WriteImmediateCmdComputeSize(self, func, file):
4478 """Writes the size computation code for the immediate version of a cmd."""
4479 file.Write(" static uint32_t ComputeSize(uint32_t size_in_bytes) {\n")
4480 file.Write(" return static_cast<uint32_t>(\n")
4481 file.Write(" sizeof(ValueType) + // NOLINT\n")
4482 file.Write(" RoundSizeToMultipleOfEntries(size_in_bytes));\n")
4483 file.Write(" }\n")
4484 file.Write("\n")
4486 def WriteImmediateCmdSetHeader(self, func, file):
4487 """Writes the SetHeader function for the immediate version of a cmd."""
4488 file.Write(" void SetHeader(uint32_t size_in_bytes) {\n")
4489 file.Write(" header.SetCmdByTotalSize<ValueType>(size_in_bytes);\n")
4490 file.Write(" }\n")
4491 file.Write("\n")
4493 def WriteImmediateCmdInit(self, func, file):
4494 """Writes the Init function for the immediate version of a command."""
4495 raise NotImplementedError(func.name)
4497 def WriteImmediateCmdSet(self, func, file):
4498 """Writes the Set function for the immediate version of a command."""
4499 raise NotImplementedError(func.name)
4501 def WriteCmdHelper(self, func, file):
4502 """Writes the cmd helper definition for a cmd."""
4503 code = """ void %(name)s(%(typed_args)s) {
4504 gles2::cmds::%(name)s* c = GetCmdSpace<gles2::cmds::%(name)s>();
4505 if (c) {
4506 c->Init(%(args)s);
4511 file.Write(code % {
4512 "name": func.name,
4513 "typed_args": func.MakeTypedCmdArgString(""),
4514 "args": func.MakeCmdArgString(""),
4517 def WriteImmediateCmdHelper(self, func, file):
4518 """Writes the cmd helper definition for the immediate version of a cmd."""
4519 code = """ void %(name)s(%(typed_args)s) {
4520 const uint32_t s = 0; // TODO(gman): compute correct size
4521 gles2::cmds::%(name)s* c =
4522 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(s);
4523 if (c) {
4524 c->Init(%(args)s);
4529 file.Write(code % {
4530 "name": func.name,
4531 "typed_args": func.MakeTypedCmdArgString(""),
4532 "args": func.MakeCmdArgString(""),
4536 class StateSetHandler(TypeHandler):
4537 """Handler for commands that simply set state."""
4539 def __init__(self):
4540 TypeHandler.__init__(self)
4542 def WriteHandlerImplementation(self, func, file):
4543 """Overrriden from TypeHandler."""
4544 state_name = func.GetInfo('state')
4545 state = _STATES[state_name]
4546 states = state['states']
4547 args = func.GetOriginalArgs()
4548 for ndx,item in enumerate(states):
4549 code = []
4550 if 'range_checks' in item:
4551 for range_check in item['range_checks']:
4552 code.append("%s %s" % (args[ndx].name, range_check['check']))
4553 if 'nan_check' in item:
4554 # Drivers might generate an INVALID_VALUE error when a value is set
4555 # to NaN. This is allowed behavior under GLES 3.0 section 2.1.1 or
4556 # OpenGL 4.5 section 2.3.4.1 - providing NaN allows undefined results.
4557 # Make this behavior consistent within Chromium, and avoid leaking GL
4558 # errors by generating the error in the command buffer instead of
4559 # letting the GL driver generate it.
4560 code.append("std::isnan(%s)" % args[ndx].name)
4561 if len(code):
4562 file.Write(" if (%s) {\n" % " ||\n ".join(code))
4563 file.Write(
4564 ' LOCAL_SET_GL_ERROR(GL_INVALID_VALUE,'
4565 ' "%s", "%s out of range");\n' %
4566 (func.name, args[ndx].name))
4567 file.Write(" return error::kNoError;\n")
4568 file.Write(" }\n")
4569 code = []
4570 for ndx,item in enumerate(states):
4571 code.append("state_.%s != %s" % (item['name'], args[ndx].name))
4572 file.Write(" if (%s) {\n" % " ||\n ".join(code))
4573 for ndx,item in enumerate(states):
4574 file.Write(" state_.%s = %s;\n" % (item['name'], args[ndx].name))
4575 if 'state_flag' in state:
4576 file.Write(" %s = true;\n" % state['state_flag'])
4577 if not func.GetInfo("no_gl"):
4578 for ndx,item in enumerate(states):
4579 if item.get('cached', False):
4580 file.Write(" state_.%s = %s;\n" %
4581 (CachedStateName(item), args[ndx].name))
4582 file.Write(" %s(%s);\n" %
4583 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
4584 file.Write(" }\n")
4586 def WriteServiceUnitTest(self, func, file, *extras):
4587 """Overrriden from TypeHandler."""
4588 TypeHandler.WriteServiceUnitTest(self, func, file, *extras)
4589 state_name = func.GetInfo('state')
4590 state = _STATES[state_name]
4591 states = state['states']
4592 for ndx,item in enumerate(states):
4593 if 'range_checks' in item:
4594 for check_ndx, range_check in enumerate(item['range_checks']):
4595 valid_test = """
4596 TEST_P(%(test_name)s, %(name)sInvalidValue%(ndx)d_%(check_ndx)d) {
4597 SpecializedSetup<cmds::%(name)s, 0>(false);
4598 cmds::%(name)s cmd;
4599 cmd.Init(%(args)s);
4600 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4601 EXPECT_EQ(GL_INVALID_VALUE, GetGLError());
4604 name = func.name
4605 arg_strings = [
4606 arg.GetValidArg(func) \
4607 for arg in func.GetOriginalArgs() if not arg.IsConstant()
4610 arg_strings[ndx] = range_check['test_value']
4611 vars = {
4612 'name': name,
4613 'ndx': ndx,
4614 'check_ndx': check_ndx,
4615 'args': ", ".join(arg_strings),
4617 for extra in extras:
4618 vars.update(extra)
4619 file.Write(valid_test % vars)
4620 if 'nan_check' in item:
4621 valid_test = """
4622 TEST_P(%(test_name)s, %(name)sNaNValue%(ndx)d) {
4623 SpecializedSetup<cmds::%(name)s, 0>(false);
4624 cmds::%(name)s cmd;
4625 cmd.Init(%(args)s);
4626 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4627 EXPECT_EQ(GL_INVALID_VALUE, GetGLError());
4630 name = func.name
4631 arg_strings = [
4632 arg.GetValidArg(func) \
4633 for arg in func.GetOriginalArgs() if not arg.IsConstant()
4636 arg_strings[ndx] = 'nanf("")'
4637 vars = {
4638 'name': name,
4639 'ndx': ndx,
4640 'args': ", ".join(arg_strings),
4642 for extra in extras:
4643 vars.update(extra)
4644 file.Write(valid_test % vars)
4647 class StateSetRGBAlphaHandler(TypeHandler):
4648 """Handler for commands that simply set state that have rgb/alpha."""
4650 def __init__(self):
4651 TypeHandler.__init__(self)
4653 def WriteHandlerImplementation(self, func, file):
4654 """Overrriden from TypeHandler."""
4655 state_name = func.GetInfo('state')
4656 state = _STATES[state_name]
4657 states = state['states']
4658 args = func.GetOriginalArgs()
4659 num_args = len(args)
4660 code = []
4661 for ndx,item in enumerate(states):
4662 code.append("state_.%s != %s" % (item['name'], args[ndx % num_args].name))
4663 file.Write(" if (%s) {\n" % " ||\n ".join(code))
4664 for ndx, item in enumerate(states):
4665 file.Write(" state_.%s = %s;\n" %
4666 (item['name'], args[ndx % num_args].name))
4667 if 'state_flag' in state:
4668 file.Write(" %s = true;\n" % state['state_flag'])
4669 if not func.GetInfo("no_gl"):
4670 file.Write(" %s(%s);\n" %
4671 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
4672 file.Write(" }\n")
4675 class StateSetFrontBackSeparateHandler(TypeHandler):
4676 """Handler for commands that simply set state that have front/back."""
4678 def __init__(self):
4679 TypeHandler.__init__(self)
4681 def WriteHandlerImplementation(self, func, file):
4682 """Overrriden from TypeHandler."""
4683 state_name = func.GetInfo('state')
4684 state = _STATES[state_name]
4685 states = state['states']
4686 args = func.GetOriginalArgs()
4687 face = args[0].name
4688 num_args = len(args)
4689 file.Write(" bool changed = false;\n")
4690 for group_ndx, group in enumerate(Grouper(num_args - 1, states)):
4691 file.Write(" if (%s == %s || %s == GL_FRONT_AND_BACK) {\n" %
4692 (face, ('GL_FRONT', 'GL_BACK')[group_ndx], face))
4693 code = []
4694 for ndx, item in enumerate(group):
4695 code.append("state_.%s != %s" % (item['name'], args[ndx + 1].name))
4696 file.Write(" changed |= %s;\n" % " ||\n ".join(code))
4697 file.Write(" }\n")
4698 file.Write(" if (changed) {\n")
4699 for group_ndx, group in enumerate(Grouper(num_args - 1, states)):
4700 file.Write(" if (%s == %s || %s == GL_FRONT_AND_BACK) {\n" %
4701 (face, ('GL_FRONT', 'GL_BACK')[group_ndx], face))
4702 for ndx, item in enumerate(group):
4703 file.Write(" state_.%s = %s;\n" %
4704 (item['name'], args[ndx + 1].name))
4705 file.Write(" }\n")
4706 if 'state_flag' in state:
4707 file.Write(" %s = true;\n" % state['state_flag'])
4708 if not func.GetInfo("no_gl"):
4709 file.Write(" %s(%s);\n" %
4710 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
4711 file.Write(" }\n")
4714 class StateSetFrontBackHandler(TypeHandler):
4715 """Handler for commands that simply set state that set both front/back."""
4717 def __init__(self):
4718 TypeHandler.__init__(self)
4720 def WriteHandlerImplementation(self, func, file):
4721 """Overrriden from TypeHandler."""
4722 state_name = func.GetInfo('state')
4723 state = _STATES[state_name]
4724 states = state['states']
4725 args = func.GetOriginalArgs()
4726 num_args = len(args)
4727 code = []
4728 for group_ndx, group in enumerate(Grouper(num_args, states)):
4729 for ndx, item in enumerate(group):
4730 code.append("state_.%s != %s" % (item['name'], args[ndx].name))
4731 file.Write(" if (%s) {\n" % " ||\n ".join(code))
4732 for group_ndx, group in enumerate(Grouper(num_args, states)):
4733 for ndx, item in enumerate(group):
4734 file.Write(" state_.%s = %s;\n" % (item['name'], args[ndx].name))
4735 if 'state_flag' in state:
4736 file.Write(" %s = true;\n" % state['state_flag'])
4737 if not func.GetInfo("no_gl"):
4738 file.Write(" %s(%s);\n" %
4739 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
4740 file.Write(" }\n")
4743 class StateSetNamedParameter(TypeHandler):
4744 """Handler for commands that set a state chosen with an enum parameter."""
4746 def __init__(self):
4747 TypeHandler.__init__(self)
4749 def WriteHandlerImplementation(self, func, file):
4750 """Overridden from TypeHandler."""
4751 state_name = func.GetInfo('state')
4752 state = _STATES[state_name]
4753 states = state['states']
4754 args = func.GetOriginalArgs()
4755 num_args = len(args)
4756 assert num_args == 2
4757 file.Write(" switch (%s) {\n" % args[0].name)
4758 for state in states:
4759 file.Write(" case %s:\n" % state['enum'])
4760 file.Write(" if (state_.%s != %s) {\n" %
4761 (state['name'], args[1].name))
4762 file.Write(" state_.%s = %s;\n" % (state['name'], args[1].name))
4763 if not func.GetInfo("no_gl"):
4764 file.Write(" %s(%s);\n" %
4765 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
4766 file.Write(" }\n")
4767 file.Write(" break;\n")
4768 file.Write(" default:\n")
4769 file.Write(" NOTREACHED();\n")
4770 file.Write(" }\n")
4773 class CustomHandler(TypeHandler):
4774 """Handler for commands that are auto-generated but require minor tweaks."""
4776 def __init__(self):
4777 TypeHandler.__init__(self)
4779 def WriteServiceImplementation(self, func, file):
4780 """Overrriden from TypeHandler."""
4781 pass
4783 def WriteImmediateServiceImplementation(self, func, file):
4784 """Overrriden from TypeHandler."""
4785 pass
4787 def WriteBucketServiceImplementation(self, func, file):
4788 """Overrriden from TypeHandler."""
4789 pass
4791 def WriteServiceUnitTest(self, func, file, *extras):
4792 """Overrriden from TypeHandler."""
4793 file.Write("// TODO(gman): %s\n\n" % func.name)
4795 def WriteImmediateServiceUnitTest(self, func, file, *extras):
4796 """Overrriden from TypeHandler."""
4797 file.Write("// TODO(gman): %s\n\n" % func.name)
4799 def WriteImmediateCmdGetTotalSize(self, func, file):
4800 """Overrriden from TypeHandler."""
4801 file.Write(
4802 " uint32_t total_size = 0; // TODO(gman): get correct size.\n")
4804 def WriteImmediateCmdInit(self, func, file):
4805 """Overrriden from TypeHandler."""
4806 file.Write(" void Init(%s) {\n" % func.MakeTypedCmdArgString("_"))
4807 self.WriteImmediateCmdGetTotalSize(func, file)
4808 file.Write(" SetHeader(total_size);\n")
4809 args = func.GetCmdArgs()
4810 for arg in args:
4811 file.Write(" %s = _%s;\n" % (arg.name, arg.name))
4812 file.Write(" }\n")
4813 file.Write("\n")
4815 def WriteImmediateCmdSet(self, func, file):
4816 """Overrriden from TypeHandler."""
4817 copy_args = func.MakeCmdArgString("_", False)
4818 file.Write(" void* Set(void* cmd%s) {\n" %
4819 func.MakeTypedCmdArgString("_", True))
4820 self.WriteImmediateCmdGetTotalSize(func, file)
4821 file.Write(" static_cast<ValueType*>(cmd)->Init(%s);\n" % copy_args)
4822 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
4823 "cmd, total_size);\n")
4824 file.Write(" }\n")
4825 file.Write("\n")
4828 class TodoHandler(CustomHandler):
4829 """Handle for commands that are not yet implemented."""
4831 def NeedsDataTransferFunction(self, func):
4832 """Overriden from TypeHandler."""
4833 return False
4835 def WriteImmediateFormatTest(self, func, file):
4836 """Overrriden from TypeHandler."""
4837 pass
4839 def WriteGLES2ImplementationUnitTest(self, func, file):
4840 """Overrriden from TypeHandler."""
4841 pass
4843 def WriteGLES2Implementation(self, func, file):
4844 """Overrriden from TypeHandler."""
4845 file.Write("%s GLES2Implementation::%s(%s) {\n" %
4846 (func.return_type, func.original_name,
4847 func.MakeTypedOriginalArgString("")))
4848 file.Write(" // TODO: for now this is a no-op\n")
4849 file.Write(
4850 " SetGLError("
4851 "GL_INVALID_OPERATION, \"gl%s\", \"not implemented\");\n" %
4852 func.name)
4853 if func.return_type != "void":
4854 file.Write(" return 0;\n")
4855 file.Write("}\n")
4856 file.Write("\n")
4858 def WriteServiceImplementation(self, func, file):
4859 """Overrriden from TypeHandler."""
4860 self.WriteServiceHandlerFunctionHeader(func, file)
4861 file.Write(" // TODO: for now this is a no-op\n")
4862 file.Write(
4863 " LOCAL_SET_GL_ERROR("
4864 "GL_INVALID_OPERATION, \"gl%s\", \"not implemented\");\n" %
4865 func.name)
4866 file.Write(" return error::kNoError;\n")
4867 file.Write("}\n")
4868 file.Write("\n")
4871 class HandWrittenHandler(CustomHandler):
4872 """Handler for comands where everything must be written by hand."""
4874 def InitFunction(self, func):
4875 """Add or adjust anything type specific for this function."""
4876 CustomHandler.InitFunction(self, func)
4877 func.can_auto_generate = False
4879 def NeedsDataTransferFunction(self, func):
4880 """Overriden from TypeHandler."""
4881 # If specified explicitly, force the data transfer method.
4882 if func.GetInfo('data_transfer_methods'):
4883 return True
4884 return False
4886 def WriteStruct(self, func, file):
4887 """Overrriden from TypeHandler."""
4888 pass
4890 def WriteDocs(self, func, file):
4891 """Overrriden from TypeHandler."""
4892 pass
4894 def WriteServiceUnitTest(self, func, file, *extras):
4895 """Overrriden from TypeHandler."""
4896 file.Write("// TODO(gman): %s\n\n" % func.name)
4898 def WriteImmediateServiceUnitTest(self, func, file, *extras):
4899 """Overrriden from TypeHandler."""
4900 file.Write("// TODO(gman): %s\n\n" % func.name)
4902 def WriteBucketServiceUnitTest(self, func, file, *extras):
4903 """Overrriden from TypeHandler."""
4904 file.Write("// TODO(gman): %s\n\n" % func.name)
4906 def WriteServiceImplementation(self, func, file):
4907 """Overrriden from TypeHandler."""
4908 pass
4910 def WriteImmediateServiceImplementation(self, func, file):
4911 """Overrriden from TypeHandler."""
4912 pass
4914 def WriteBucketServiceImplementation(self, func, file):
4915 """Overrriden from TypeHandler."""
4916 pass
4918 def WriteImmediateCmdHelper(self, func, file):
4919 """Overrriden from TypeHandler."""
4920 pass
4922 def WriteCmdHelper(self, func, file):
4923 """Overrriden from TypeHandler."""
4924 pass
4926 def WriteFormatTest(self, func, file):
4927 """Overrriden from TypeHandler."""
4928 file.Write("// TODO(gman): Write test for %s\n" % func.name)
4930 def WriteImmediateFormatTest(self, func, file):
4931 """Overrriden from TypeHandler."""
4932 file.Write("// TODO(gman): Write test for %s\n" % func.name)
4934 def WriteBucketFormatTest(self, func, file):
4935 """Overrriden from TypeHandler."""
4936 file.Write("// TODO(gman): Write test for %s\n" % func.name)
4940 class ManualHandler(CustomHandler):
4941 """Handler for commands who's handlers must be written by hand."""
4943 def __init__(self):
4944 CustomHandler.__init__(self)
4946 def InitFunction(self, func):
4947 """Overrriden from TypeHandler."""
4948 if (func.name == 'CompressedTexImage2DBucket' or
4949 func.name == 'CompressedTexImage3DBucket'):
4950 func.cmd_args = func.cmd_args[:-1]
4951 func.AddCmdArg(Argument('bucket_id', 'GLuint'))
4952 else:
4953 CustomHandler.InitFunction(self, func)
4955 def WriteServiceImplementation(self, func, file):
4956 """Overrriden from TypeHandler."""
4957 pass
4959 def WriteBucketServiceImplementation(self, func, file):
4960 """Overrriden from TypeHandler."""
4961 pass
4963 def WriteServiceUnitTest(self, func, file, *extras):
4964 """Overrriden from TypeHandler."""
4965 file.Write("// TODO(gman): %s\n\n" % func.name)
4967 def WriteImmediateServiceUnitTest(self, func, file, *extras):
4968 """Overrriden from TypeHandler."""
4969 file.Write("// TODO(gman): %s\n\n" % func.name)
4971 def WriteImmediateServiceImplementation(self, func, file):
4972 """Overrriden from TypeHandler."""
4973 pass
4975 def WriteImmediateFormatTest(self, func, file):
4976 """Overrriden from TypeHandler."""
4977 file.Write("// TODO(gman): Implement test for %s\n" % func.name)
4979 def WriteGLES2Implementation(self, func, file):
4980 """Overrriden from TypeHandler."""
4981 if func.GetInfo('impl_func'):
4982 super(ManualHandler, self).WriteGLES2Implementation(func, file)
4984 def WriteGLES2ImplementationHeader(self, func, file):
4985 """Overrriden from TypeHandler."""
4986 file.Write("%s %s(%s) override;\n" %
4987 (func.return_type, func.original_name,
4988 func.MakeTypedOriginalArgString("")))
4989 file.Write("\n")
4991 def WriteImmediateCmdGetTotalSize(self, func, file):
4992 """Overrriden from TypeHandler."""
4993 # TODO(gman): Move this data to _FUNCTION_INFO?
4994 CustomHandler.WriteImmediateCmdGetTotalSize(self, func, file)
4997 class DataHandler(TypeHandler):
4998 """Handler for glBufferData, glBufferSubData, glTexImage2D, glTexSubImage2D,
4999 glCompressedTexImage2D, glCompressedTexImageSub2D."""
5000 def __init__(self):
5001 TypeHandler.__init__(self)
5003 def InitFunction(self, func):
5004 """Overrriden from TypeHandler."""
5005 if func.name == 'CompressedTexSubImage2DBucket':
5006 func.cmd_args = func.cmd_args[:-1]
5007 func.AddCmdArg(Argument('bucket_id', 'GLuint'))
5009 def WriteGetDataSizeCode(self, func, file):
5010 """Overrriden from TypeHandler."""
5011 # TODO(gman): Move this data to _FUNCTION_INFO?
5012 name = func.name
5013 if name.endswith("Immediate"):
5014 name = name[0:-9]
5015 if name == 'BufferData' or name == 'BufferSubData':
5016 file.Write(" uint32_t data_size = size;\n")
5017 elif (name == 'CompressedTexImage2D' or
5018 name == 'CompressedTexSubImage2D'):
5019 file.Write(" uint32_t data_size = imageSize;\n")
5020 elif (name == 'CompressedTexSubImage2DBucket'):
5021 file.Write(" Bucket* bucket = GetBucket(c.bucket_id);\n")
5022 file.Write(" uint32_t data_size = bucket->size();\n")
5023 file.Write(" GLsizei imageSize = data_size;\n")
5024 elif name == 'TexImage2D' or name == 'TexSubImage2D':
5025 code = """ uint32_t data_size;
5026 if (!GLES2Util::ComputeImageDataSize(
5027 width, height, format, type, unpack_alignment_, &data_size)) {
5028 return error::kOutOfBounds;
5031 file.Write(code)
5032 else:
5033 file.Write(
5034 "// uint32_t data_size = 0; // TODO(gman): get correct size!\n")
5036 def WriteImmediateCmdGetTotalSize(self, func, file):
5037 """Overrriden from TypeHandler."""
5038 pass
5040 def WriteImmediateCmdSizeTest(self, func, file):
5041 """Overrriden from TypeHandler."""
5042 file.Write(" EXPECT_EQ(sizeof(cmd), total_size);\n")
5044 def WriteImmediateCmdInit(self, func, file):
5045 """Overrriden from TypeHandler."""
5046 file.Write(" void Init(%s) {\n" % func.MakeTypedCmdArgString("_"))
5047 self.WriteImmediateCmdGetTotalSize(func, file)
5048 file.Write(" SetHeader(total_size);\n")
5049 args = func.GetCmdArgs()
5050 for arg in args:
5051 file.Write(" %s = _%s;\n" % (arg.name, arg.name))
5052 file.Write(" }\n")
5053 file.Write("\n")
5055 def WriteImmediateCmdSet(self, func, file):
5056 """Overrriden from TypeHandler."""
5057 copy_args = func.MakeCmdArgString("_", False)
5058 file.Write(" void* Set(void* cmd%s) {\n" %
5059 func.MakeTypedCmdArgString("_", True))
5060 self.WriteImmediateCmdGetTotalSize(func, file)
5061 file.Write(" static_cast<ValueType*>(cmd)->Init(%s);\n" % copy_args)
5062 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
5063 "cmd, total_size);\n")
5064 file.Write(" }\n")
5065 file.Write("\n")
5067 def WriteImmediateFormatTest(self, func, file):
5068 """Overrriden from TypeHandler."""
5069 # TODO(gman): Remove this exception.
5070 file.Write("// TODO(gman): Implement test for %s\n" % func.name)
5071 return
5073 def WriteServiceUnitTest(self, func, file, *extras):
5074 """Overrriden from TypeHandler."""
5075 file.Write("// TODO(gman): %s\n\n" % func.name)
5077 def WriteImmediateServiceUnitTest(self, func, file, *extras):
5078 """Overrriden from TypeHandler."""
5079 file.Write("// TODO(gman): %s\n\n" % func.name)
5081 def WriteBucketServiceImplementation(self, func, file):
5082 """Overrriden from TypeHandler."""
5083 if not func.name == 'CompressedTexSubImage2DBucket':
5084 TypeHandler.WriteBucketServiceImplemenation(self, func, file)
5087 class BindHandler(TypeHandler):
5088 """Handler for glBind___ type functions."""
5090 def __init__(self):
5091 TypeHandler.__init__(self)
5093 def WriteServiceUnitTest(self, func, file, *extras):
5094 """Overrriden from TypeHandler."""
5096 if len(func.GetOriginalArgs()) == 1:
5097 valid_test = """
5098 TEST_P(%(test_name)s, %(name)sValidArgs) {
5099 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
5100 SpecializedSetup<cmds::%(name)s, 0>(true);
5101 cmds::%(name)s cmd;
5102 cmd.Init(%(args)s);"""
5103 if func.IsUnsafe():
5104 valid_test += """
5105 decoder_->set_unsafe_es3_apis_enabled(true);
5106 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5107 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5108 decoder_->set_unsafe_es3_apis_enabled(false);
5109 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));
5112 else:
5113 valid_test += """
5114 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5115 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5118 if func.GetInfo("gen_func"):
5119 valid_test += """
5120 TEST_P(%(test_name)s, %(name)sValidArgsNewId) {
5121 EXPECT_CALL(*gl_, %(gl_func_name)s(kNewServiceId));
5122 EXPECT_CALL(*gl_, %(gl_gen_func_name)s(1, _))
5123 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
5124 SpecializedSetup<cmds::%(name)s, 0>(true);
5125 cmds::%(name)s cmd;
5126 cmd.Init(kNewClientId);
5127 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5128 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5129 EXPECT_TRUE(Get%(resource_type)s(kNewClientId) != NULL);
5132 self.WriteValidUnitTest(func, file, valid_test, {
5133 'resource_type': func.GetOriginalArgs()[0].resource_type,
5134 'gl_gen_func_name': func.GetInfo("gen_func"),
5135 }, *extras)
5136 else:
5137 valid_test = """
5138 TEST_P(%(test_name)s, %(name)sValidArgs) {
5139 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
5140 SpecializedSetup<cmds::%(name)s, 0>(true);
5141 cmds::%(name)s cmd;
5142 cmd.Init(%(args)s);"""
5143 if func.IsUnsafe():
5144 valid_test += """
5145 decoder_->set_unsafe_es3_apis_enabled(true);
5146 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5147 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5148 decoder_->set_unsafe_es3_apis_enabled(false);
5149 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));
5152 else:
5153 valid_test += """
5154 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5155 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5158 if func.GetInfo("gen_func"):
5159 valid_test += """
5160 TEST_P(%(test_name)s, %(name)sValidArgsNewId) {
5161 EXPECT_CALL(*gl_,
5162 %(gl_func_name)s(%(gl_args_with_new_id)s));
5163 EXPECT_CALL(*gl_, %(gl_gen_func_name)s(1, _))
5164 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
5165 SpecializedSetup<cmds::%(name)s, 0>(true);
5166 cmds::%(name)s cmd;
5167 cmd.Init(%(args_with_new_id)s);"""
5168 if func.IsUnsafe():
5169 valid_test += """
5170 decoder_->set_unsafe_es3_apis_enabled(true);
5171 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5172 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5173 EXPECT_TRUE(Get%(resource_type)s(kNewClientId) != NULL);
5174 decoder_->set_unsafe_es3_apis_enabled(false);
5175 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));
5178 else:
5179 valid_test += """
5180 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5181 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5182 EXPECT_TRUE(Get%(resource_type)s(kNewClientId) != NULL);
5186 gl_args_with_new_id = []
5187 args_with_new_id = []
5188 for arg in func.GetOriginalArgs():
5189 if hasattr(arg, 'resource_type'):
5190 gl_args_with_new_id.append('kNewServiceId')
5191 args_with_new_id.append('kNewClientId')
5192 else:
5193 gl_args_with_new_id.append(arg.GetValidGLArg(func))
5194 args_with_new_id.append(arg.GetValidArg(func))
5195 self.WriteValidUnitTest(func, file, valid_test, {
5196 'args_with_new_id': ", ".join(args_with_new_id),
5197 'gl_args_with_new_id': ", ".join(gl_args_with_new_id),
5198 'resource_type': func.GetResourceIdArg().resource_type,
5199 'gl_gen_func_name': func.GetInfo("gen_func"),
5200 }, *extras)
5202 invalid_test = """
5203 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
5204 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
5205 SpecializedSetup<cmds::%(name)s, 0>(false);
5206 cmds::%(name)s cmd;
5207 cmd.Init(%(args)s);
5208 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
5211 self.WriteInvalidUnitTest(func, file, invalid_test, *extras)
5213 def WriteGLES2Implementation(self, func, file):
5214 """Writes the GLES2 Implemention."""
5216 impl_func = func.GetInfo('impl_func')
5217 impl_decl = func.GetInfo('impl_decl')
5219 if (func.can_auto_generate and
5220 (impl_func == None or impl_func == True) and
5221 (impl_decl == None or impl_decl == True)):
5223 file.Write("%s GLES2Implementation::%s(%s) {\n" %
5224 (func.return_type, func.original_name,
5225 func.MakeTypedOriginalArgString("")))
5226 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
5227 func.WriteDestinationInitalizationValidation(file)
5228 self.WriteClientGLCallLog(func, file)
5229 for arg in func.GetOriginalArgs():
5230 arg.WriteClientSideValidationCode(file, func)
5232 code = """ if (Is%(type)sReservedId(%(id)s)) {
5233 SetGLError(GL_INVALID_OPERATION, "%(name)s\", \"%(id)s reserved id");
5234 return;
5236 %(name)sHelper(%(arg_string)s);
5237 CheckGLError();
5241 name_arg = func.GetResourceIdArg()
5242 file.Write(code % {
5243 'name': func.name,
5244 'arg_string': func.MakeOriginalArgString(""),
5245 'id': name_arg.name,
5246 'type': name_arg.resource_type,
5247 'lc_type': name_arg.resource_type.lower(),
5250 def WriteGLES2ImplementationUnitTest(self, func, file):
5251 """Overrriden from TypeHandler."""
5252 client_test = func.GetInfo('client_test')
5253 if client_test == False:
5254 return
5255 code = """
5256 TEST_F(GLES2ImplementationTest, %(name)s) {
5257 struct Cmds {
5258 cmds::%(name)s cmd;
5260 Cmds expected;
5261 expected.cmd.Init(%(cmd_args)s);
5263 gl_->%(name)s(%(args)s);
5264 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));"""
5265 if not func.IsUnsafe():
5266 code += """
5267 ClearCommands();
5268 gl_->%(name)s(%(args)s);
5269 EXPECT_TRUE(NoCommandsWritten());"""
5270 code += """
5273 cmd_arg_strings = [
5274 arg.GetValidClientSideCmdArg(func) for arg in func.GetCmdArgs()
5276 gl_arg_strings = [
5277 arg.GetValidClientSideArg(func) for arg in func.GetOriginalArgs()
5280 file.Write(code % {
5281 'name': func.name,
5282 'args': ", ".join(gl_arg_strings),
5283 'cmd_args': ", ".join(cmd_arg_strings),
5287 class GENnHandler(TypeHandler):
5288 """Handler for glGen___ type functions."""
5290 def __init__(self):
5291 TypeHandler.__init__(self)
5293 def InitFunction(self, func):
5294 """Overrriden from TypeHandler."""
5295 pass
5297 def WriteGetDataSizeCode(self, func, file):
5298 """Overrriden from TypeHandler."""
5299 code = """ uint32_t data_size;
5300 if (!SafeMultiplyUint32(n, sizeof(GLuint), &data_size)) {
5301 return error::kOutOfBounds;
5304 file.Write(code)
5306 def WriteHandlerImplementation (self, func, file):
5307 """Overrriden from TypeHandler."""
5308 file.Write(" if (!%sHelper(n, %s)) {\n"
5309 " return error::kInvalidArguments;\n"
5310 " }\n" %
5311 (func.name, func.GetLastOriginalArg().name))
5313 def WriteImmediateHandlerImplementation(self, func, file):
5314 """Overrriden from TypeHandler."""
5315 if func.IsUnsafe():
5316 file.Write(""" for (GLsizei ii = 0; ii < n; ++ii) {
5317 if (group_->Get%(resource_name)sServiceId(%(last_arg_name)s[ii], NULL)) {
5318 return error::kInvalidArguments;
5321 scoped_ptr<GLuint[]> service_ids(new GLuint[n]);
5322 gl%(func_name)s(n, service_ids.get());
5323 for (GLsizei ii = 0; ii < n; ++ii) {
5324 group_->Add%(resource_name)sId(%(last_arg_name)s[ii], service_ids[ii]);
5326 """ % { 'func_name': func.original_name,
5327 'last_arg_name': func.GetLastOriginalArg().name,
5328 'resource_name': func.GetInfo('resource_type') })
5329 else:
5330 file.Write(" if (!%sHelper(n, %s)) {\n"
5331 " return error::kInvalidArguments;\n"
5332 " }\n" %
5333 (func.original_name, func.GetLastOriginalArg().name))
5335 def WriteGLES2Implementation(self, func, file):
5336 """Overrriden from TypeHandler."""
5337 log_code = (""" GPU_CLIENT_LOG_CODE_BLOCK({
5338 for (GLsizei i = 0; i < n; ++i) {
5339 GPU_CLIENT_LOG(" " << i << ": " << %s[i]);
5341 });""" % func.GetOriginalArgs()[1].name)
5342 args = {
5343 'log_code': log_code,
5344 'return_type': func.return_type,
5345 'name': func.original_name,
5346 'typed_args': func.MakeTypedOriginalArgString(""),
5347 'args': func.MakeOriginalArgString(""),
5348 'resource_types': func.GetInfo('resource_types'),
5349 'count_name': func.GetOriginalArgs()[0].name,
5351 file.Write(
5352 "%(return_type)s GLES2Implementation::%(name)s(%(typed_args)s) {\n" %
5353 args)
5354 func.WriteDestinationInitalizationValidation(file)
5355 self.WriteClientGLCallLog(func, file)
5356 for arg in func.GetOriginalArgs():
5357 arg.WriteClientSideValidationCode(file, func)
5358 not_shared = func.GetInfo('not_shared')
5359 if not_shared:
5360 alloc_code = (
5362 """ IdAllocator* id_allocator = GetIdAllocator(id_namespaces::k%s);
5363 for (GLsizei ii = 0; ii < n; ++ii)
5364 %s[ii] = id_allocator->AllocateID();""" %
5365 (func.GetInfo('resource_types'), func.GetOriginalArgs()[1].name))
5366 else:
5367 alloc_code = (""" GetIdHandler(id_namespaces::k%(resource_types)s)->
5368 MakeIds(this, 0, %(args)s);""" % args)
5369 args['alloc_code'] = alloc_code
5371 code = """ GPU_CLIENT_SINGLE_THREAD_CHECK();
5372 %(alloc_code)s
5373 %(name)sHelper(%(args)s);
5374 helper_->%(name)sImmediate(%(args)s);
5375 if (share_group_->bind_generates_resource())
5376 helper_->CommandBufferHelper::Flush();
5377 %(log_code)s
5378 CheckGLError();
5382 file.Write(code % args)
5384 def WriteGLES2ImplementationUnitTest(self, func, file):
5385 """Overrriden from TypeHandler."""
5386 code = """
5387 TEST_F(GLES2ImplementationTest, %(name)s) {
5388 GLuint ids[2] = { 0, };
5389 struct Cmds {
5390 cmds::%(name)sImmediate gen;
5391 GLuint data[2];
5393 Cmds expected;
5394 expected.gen.Init(arraysize(ids), &ids[0]);
5395 expected.data[0] = k%(types)sStartId;
5396 expected.data[1] = k%(types)sStartId + 1;
5397 gl_->%(name)s(arraysize(ids), &ids[0]);
5398 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
5399 EXPECT_EQ(k%(types)sStartId, ids[0]);
5400 EXPECT_EQ(k%(types)sStartId + 1, ids[1]);
5403 file.Write(code % {
5404 'name': func.name,
5405 'types': func.GetInfo('resource_types'),
5408 def WriteServiceUnitTest(self, func, file, *extras):
5409 """Overrriden from TypeHandler."""
5410 valid_test = """
5411 TEST_P(%(test_name)s, %(name)sValidArgs) {
5412 EXPECT_CALL(*gl_, %(gl_func_name)s(1, _))
5413 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
5414 GetSharedMemoryAs<GLuint*>()[0] = kNewClientId;
5415 SpecializedSetup<cmds::%(name)s, 0>(true);
5416 cmds::%(name)s cmd;
5417 cmd.Init(%(args)s);
5418 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5419 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
5420 if func.IsUnsafe():
5421 valid_test += """
5422 GLuint service_id;
5423 EXPECT_TRUE(Get%(resource_name)sServiceId(kNewClientId, &service_id));
5424 EXPECT_EQ(kNewServiceId, service_id)
5427 else:
5428 valid_test += """
5429 EXPECT_TRUE(Get%(resource_name)s(kNewClientId, &service_id) != NULL);
5432 self.WriteValidUnitTest(func, file, valid_test, {
5433 'resource_name': func.GetInfo('resource_type'),
5434 }, *extras)
5435 invalid_test = """
5436 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
5437 EXPECT_CALL(*gl_, %(gl_func_name)s(_, _)).Times(0);
5438 GetSharedMemoryAs<GLuint*>()[0] = client_%(resource_name)s_id_;
5439 SpecializedSetup<cmds::%(name)s, 0>(false);
5440 cmds::%(name)s cmd;
5441 cmd.Init(%(args)s);
5442 EXPECT_EQ(error::kInvalidArguments, ExecuteCmd(cmd));
5445 self.WriteValidUnitTest(func, file, invalid_test, {
5446 'resource_name': func.GetInfo('resource_type').lower(),
5447 }, *extras)
5449 def WriteImmediateServiceUnitTest(self, func, file, *extras):
5450 """Overrriden from TypeHandler."""
5451 valid_test = """
5452 TEST_P(%(test_name)s, %(name)sValidArgs) {
5453 EXPECT_CALL(*gl_, %(gl_func_name)s(1, _))
5454 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
5455 cmds::%(name)s* cmd = GetImmediateAs<cmds::%(name)s>();
5456 GLuint temp = kNewClientId;
5457 SpecializedSetup<cmds::%(name)s, 0>(true);"""
5458 if func.IsUnsafe():
5459 valid_test += """
5460 decoder_->set_unsafe_es3_apis_enabled(true);"""
5461 valid_test += """
5462 cmd->Init(1, &temp);
5463 EXPECT_EQ(error::kNoError,
5464 ExecuteImmediateCmd(*cmd, sizeof(temp)));
5465 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
5466 if func.IsUnsafe():
5467 valid_test += """
5468 GLuint service_id;
5469 EXPECT_TRUE(Get%(resource_name)sServiceId(kNewClientId, &service_id));
5470 EXPECT_EQ(kNewServiceId, service_id);
5471 decoder_->set_unsafe_es3_apis_enabled(false);
5472 EXPECT_EQ(error::kUnknownCommand,
5473 ExecuteImmediateCmd(*cmd, sizeof(temp)));
5476 else:
5477 valid_test += """
5478 EXPECT_TRUE(Get%(resource_name)s(kNewClientId) != NULL);
5481 self.WriteValidUnitTest(func, file, valid_test, {
5482 'resource_name': func.GetInfo('resource_type'),
5483 }, *extras)
5484 invalid_test = """
5485 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
5486 EXPECT_CALL(*gl_, %(gl_func_name)s(_, _)).Times(0);
5487 cmds::%(name)s* cmd = GetImmediateAs<cmds::%(name)s>();
5488 SpecializedSetup<cmds::%(name)s, 0>(false);
5489 cmd->Init(1, &client_%(resource_name)s_id_);"""
5490 if func.IsUnsafe():
5491 invalid_test += """
5492 decoder_->set_unsafe_es3_apis_enabled(true);
5493 EXPECT_EQ(error::kInvalidArguments,
5494 ExecuteImmediateCmd(*cmd, sizeof(&client_%(resource_name)s_id_)));
5495 decoder_->set_unsafe_es3_apis_enabled(false);
5498 else:
5499 invalid_test += """
5500 EXPECT_EQ(error::kInvalidArguments,
5501 ExecuteImmediateCmd(*cmd, sizeof(&client_%(resource_name)s_id_)));
5504 self.WriteValidUnitTest(func, file, invalid_test, {
5505 'resource_name': func.GetInfo('resource_type').lower(),
5506 }, *extras)
5508 def WriteImmediateCmdComputeSize(self, func, file):
5509 """Overrriden from TypeHandler."""
5510 file.Write(" static uint32_t ComputeDataSize(GLsizei n) {\n")
5511 file.Write(
5512 " return static_cast<uint32_t>(sizeof(GLuint) * n); // NOLINT\n")
5513 file.Write(" }\n")
5514 file.Write("\n")
5515 file.Write(" static uint32_t ComputeSize(GLsizei n) {\n")
5516 file.Write(" return static_cast<uint32_t>(\n")
5517 file.Write(" sizeof(ValueType) + ComputeDataSize(n)); // NOLINT\n")
5518 file.Write(" }\n")
5519 file.Write("\n")
5521 def WriteImmediateCmdSetHeader(self, func, file):
5522 """Overrriden from TypeHandler."""
5523 file.Write(" void SetHeader(GLsizei n) {\n")
5524 file.Write(" header.SetCmdByTotalSize<ValueType>(ComputeSize(n));\n")
5525 file.Write(" }\n")
5526 file.Write("\n")
5528 def WriteImmediateCmdInit(self, func, file):
5529 """Overrriden from TypeHandler."""
5530 last_arg = func.GetLastOriginalArg()
5531 file.Write(" void Init(%s, %s _%s) {\n" %
5532 (func.MakeTypedCmdArgString("_"),
5533 last_arg.type, last_arg.name))
5534 file.Write(" SetHeader(_n);\n")
5535 args = func.GetCmdArgs()
5536 for arg in args:
5537 file.Write(" %s = _%s;\n" % (arg.name, arg.name))
5538 file.Write(" memcpy(ImmediateDataAddress(this),\n")
5539 file.Write(" _%s, ComputeDataSize(_n));\n" % last_arg.name)
5540 file.Write(" }\n")
5541 file.Write("\n")
5543 def WriteImmediateCmdSet(self, func, file):
5544 """Overrriden from TypeHandler."""
5545 last_arg = func.GetLastOriginalArg()
5546 copy_args = func.MakeCmdArgString("_", False)
5547 file.Write(" void* Set(void* cmd%s, %s _%s) {\n" %
5548 (func.MakeTypedCmdArgString("_", True),
5549 last_arg.type, last_arg.name))
5550 file.Write(" static_cast<ValueType*>(cmd)->Init(%s, _%s);\n" %
5551 (copy_args, last_arg.name))
5552 file.Write(" const uint32_t size = ComputeSize(_n);\n")
5553 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
5554 "cmd, size);\n")
5555 file.Write(" }\n")
5556 file.Write("\n")
5558 def WriteImmediateCmdHelper(self, func, file):
5559 """Overrriden from TypeHandler."""
5560 code = """ void %(name)s(%(typed_args)s) {
5561 const uint32_t size = gles2::cmds::%(name)s::ComputeSize(n);
5562 gles2::cmds::%(name)s* c =
5563 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
5564 if (c) {
5565 c->Init(%(args)s);
5570 file.Write(code % {
5571 "name": func.name,
5572 "typed_args": func.MakeTypedOriginalArgString(""),
5573 "args": func.MakeOriginalArgString(""),
5576 def WriteImmediateFormatTest(self, func, file):
5577 """Overrriden from TypeHandler."""
5578 file.Write("TEST_F(GLES2FormatTest, %s) {\n" % func.name)
5579 file.Write(" static GLuint ids[] = { 12, 23, 34, };\n")
5580 file.Write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
5581 (func.name, func.name))
5582 file.Write(" void* next_cmd = cmd.Set(\n")
5583 file.Write(" &cmd, static_cast<GLsizei>(arraysize(ids)), ids);\n")
5584 file.Write(" EXPECT_EQ(static_cast<uint32_t>(cmds::%s::kCmdId),\n" %
5585 func.name)
5586 file.Write(" cmd.header.command);\n")
5587 file.Write(" EXPECT_EQ(sizeof(cmd) +\n")
5588 file.Write(" RoundSizeToMultipleOfEntries(cmd.n * 4u),\n")
5589 file.Write(" cmd.header.size * 4u);\n")
5590 file.Write(" EXPECT_EQ(static_cast<GLsizei>(arraysize(ids)), cmd.n);\n");
5591 file.Write(" CheckBytesWrittenMatchesExpectedSize(\n")
5592 file.Write(" next_cmd, sizeof(cmd) +\n")
5593 file.Write(" RoundSizeToMultipleOfEntries(arraysize(ids) * 4u));\n")
5594 file.Write(" // TODO(gman): Check that ids were inserted;\n")
5595 file.Write("}\n")
5596 file.Write("\n")
5599 class CreateHandler(TypeHandler):
5600 """Handler for glCreate___ type functions."""
5602 def __init__(self):
5603 TypeHandler.__init__(self)
5605 def InitFunction(self, func):
5606 """Overrriden from TypeHandler."""
5607 func.AddCmdArg(Argument("client_id", 'uint32_t'))
5609 def __GetResourceType(self, func):
5610 if func.return_type == "GLsync":
5611 return "Sync"
5612 else:
5613 return func.name[6:] # Create*
5615 def WriteServiceUnitTest(self, func, file, *extras):
5616 """Overrriden from TypeHandler."""
5617 valid_test = """
5618 TEST_P(%(test_name)s, %(name)sValidArgs) {
5619 %(id_type_cast)sEXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s))
5620 .WillOnce(Return(%(const_service_id)s));
5621 SpecializedSetup<cmds::%(name)s, 0>(true);
5622 cmds::%(name)s cmd;
5623 cmd.Init(%(args)s%(comma)skNewClientId);"""
5624 if func.IsUnsafe():
5625 valid_test += """
5626 decoder_->set_unsafe_es3_apis_enabled(true);"""
5627 valid_test += """
5628 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5629 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
5630 if func.IsUnsafe():
5631 valid_test += """
5632 %(return_type)s service_id = 0;
5633 EXPECT_TRUE(Get%(resource_type)sServiceId(kNewClientId, &service_id));
5634 EXPECT_EQ(%(const_service_id)s, service_id);
5635 decoder_->set_unsafe_es3_apis_enabled(false);
5636 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));
5639 else:
5640 valid_test += """
5641 EXPECT_TRUE(Get%(resource_type)s(kNewClientId));
5644 comma = ""
5645 cmd_arg_count = 0
5646 for arg in func.GetOriginalArgs():
5647 if not arg.IsConstant():
5648 cmd_arg_count += 1
5649 if cmd_arg_count:
5650 comma = ", "
5651 if func.return_type == 'GLsync':
5652 id_type_cast = ("const GLsync kNewServiceIdGLuint = reinterpret_cast"
5653 "<GLsync>(kNewServiceId);\n ")
5654 const_service_id = "kNewServiceIdGLuint"
5655 else:
5656 id_type_cast = ""
5657 const_service_id = "kNewServiceId"
5658 self.WriteValidUnitTest(func, file, valid_test, {
5659 'comma': comma,
5660 'resource_type': self.__GetResourceType(func),
5661 'return_type': func.return_type,
5662 'id_type_cast': id_type_cast,
5663 'const_service_id': const_service_id,
5664 }, *extras)
5665 invalid_test = """
5666 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
5667 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
5668 SpecializedSetup<cmds::%(name)s, 0>(false);
5669 cmds::%(name)s cmd;
5670 cmd.Init(%(args)s%(comma)skNewClientId);
5671 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));%(gl_error_test)s
5674 self.WriteInvalidUnitTest(func, file, invalid_test, {
5675 'comma': comma,
5676 }, *extras)
5678 def WriteHandlerImplementation (self, func, file):
5679 """Overrriden from TypeHandler."""
5680 if func.IsUnsafe():
5681 code = """ uint32_t client_id = c.client_id;
5682 %(return_type)s service_id = 0;
5683 if (group_->Get%(resource_name)sServiceId(client_id, &service_id)) {
5684 return error::kInvalidArguments;
5686 service_id = %(gl_func_name)s(%(gl_args)s);
5687 if (service_id) {
5688 group_->Add%(resource_name)sId(client_id, service_id);
5691 else:
5692 code = """ uint32_t client_id = c.client_id;
5693 if (Get%(resource_name)s(client_id)) {
5694 return error::kInvalidArguments;
5696 %(return_type)s service_id = %(gl_func_name)s(%(gl_args)s);
5697 if (service_id) {
5698 Create%(resource_name)s(client_id, service_id%(gl_args_with_comma)s);
5701 file.Write(code % {
5702 'resource_name': self.__GetResourceType(func),
5703 'return_type': func.return_type,
5704 'gl_func_name': func.GetGLFunctionName(),
5705 'gl_args': func.MakeOriginalArgString(""),
5706 'gl_args_with_comma': func.MakeOriginalArgString("", True) })
5708 def WriteGLES2Implementation(self, func, file):
5709 """Overrriden from TypeHandler."""
5710 file.Write("%s GLES2Implementation::%s(%s) {\n" %
5711 (func.return_type, func.original_name,
5712 func.MakeTypedOriginalArgString("")))
5713 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
5714 func.WriteDestinationInitalizationValidation(file)
5715 self.WriteClientGLCallLog(func, file)
5716 for arg in func.GetOriginalArgs():
5717 arg.WriteClientSideValidationCode(file, func)
5718 file.Write(" GLuint client_id;\n")
5719 if func.return_type == "GLsync":
5720 file.Write(
5721 " GetIdHandler(id_namespaces::kSyncs)->\n")
5722 else:
5723 file.Write(
5724 " GetIdHandler(id_namespaces::kProgramsAndShaders)->\n")
5725 file.Write(" MakeIds(this, 0, 1, &client_id);\n")
5726 file.Write(" helper_->%s(%s);\n" %
5727 (func.name, func.MakeCmdArgString("")))
5728 file.Write(' GPU_CLIENT_LOG("returned " << client_id);\n')
5729 file.Write(" CheckGLError();\n")
5730 if func.return_type == "GLsync":
5731 file.Write(" return reinterpret_cast<GLsync>(client_id);\n")
5732 else:
5733 file.Write(" return client_id;\n")
5734 file.Write("}\n")
5735 file.Write("\n")
5738 class DeleteHandler(TypeHandler):
5739 """Handler for glDelete___ single resource type functions."""
5741 def __init__(self):
5742 TypeHandler.__init__(self)
5744 def WriteServiceImplementation(self, func, file):
5745 """Overrriden from TypeHandler."""
5746 if func.IsUnsafe():
5747 TypeHandler.WriteServiceImplementation(self, func, file)
5748 # HandleDeleteShader and HandleDeleteProgram are manually written.
5749 pass
5751 def WriteGLES2Implementation(self, func, file):
5752 """Overrriden from TypeHandler."""
5753 file.Write("%s GLES2Implementation::%s(%s) {\n" %
5754 (func.return_type, func.original_name,
5755 func.MakeTypedOriginalArgString("")))
5756 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
5757 func.WriteDestinationInitalizationValidation(file)
5758 self.WriteClientGLCallLog(func, file)
5759 for arg in func.GetOriginalArgs():
5760 arg.WriteClientSideValidationCode(file, func)
5761 file.Write(
5762 " GPU_CLIENT_DCHECK(%s != 0);\n" % func.GetOriginalArgs()[-1].name)
5763 file.Write(" %sHelper(%s);\n" %
5764 (func.original_name, func.GetOriginalArgs()[-1].name))
5765 file.Write(" CheckGLError();\n")
5766 file.Write("}\n")
5767 file.Write("\n")
5769 def WriteHandlerImplementation (self, func, file):
5770 """Overrriden from TypeHandler."""
5771 assert len(func.GetOriginalArgs()) == 1
5772 arg = func.GetOriginalArgs()[0]
5773 if func.IsUnsafe():
5774 file.Write(""" %(arg_type)s service_id = 0;
5775 if (group_->Get%(resource_type)sServiceId(%(arg_name)s, &service_id)) {
5776 glDelete%(resource_type)s(service_id);
5777 group_->Remove%(resource_type)sId(%(arg_name)s);
5778 } else {
5779 LOCAL_SET_GL_ERROR(
5780 GL_INVALID_VALUE, "gl%(func_name)s", "unknown %(arg_name)s");
5782 """ % { 'resource_type': func.GetInfo('resource_type'),
5783 'arg_name': arg.name,
5784 'arg_type': arg.type,
5785 'func_name': func.original_name })
5786 else:
5787 file.Write(" %sHelper(%s);\n" % (func.original_name, arg.name))
5789 class DELnHandler(TypeHandler):
5790 """Handler for glDelete___ type functions."""
5792 def __init__(self):
5793 TypeHandler.__init__(self)
5795 def WriteGetDataSizeCode(self, func, file):
5796 """Overrriden from TypeHandler."""
5797 code = """ uint32_t data_size;
5798 if (!SafeMultiplyUint32(n, sizeof(GLuint), &data_size)) {
5799 return error::kOutOfBounds;
5802 file.Write(code)
5804 def WriteGLES2ImplementationUnitTest(self, func, file):
5805 """Overrriden from TypeHandler."""
5806 code = """
5807 TEST_F(GLES2ImplementationTest, %(name)s) {
5808 GLuint ids[2] = { k%(types)sStartId, k%(types)sStartId + 1 };
5809 struct Cmds {
5810 cmds::%(name)sImmediate del;
5811 GLuint data[2];
5813 Cmds expected;
5814 expected.del.Init(arraysize(ids), &ids[0]);
5815 expected.data[0] = k%(types)sStartId;
5816 expected.data[1] = k%(types)sStartId + 1;
5817 gl_->%(name)s(arraysize(ids), &ids[0]);
5818 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
5821 file.Write(code % {
5822 'name': func.name,
5823 'types': func.GetInfo('resource_types'),
5826 def WriteServiceUnitTest(self, func, file, *extras):
5827 """Overrriden from TypeHandler."""
5828 valid_test = """
5829 TEST_P(%(test_name)s, %(name)sValidArgs) {
5830 EXPECT_CALL(
5831 *gl_,
5832 %(gl_func_name)s(1, Pointee(kService%(upper_resource_name)sId)))
5833 .Times(1);
5834 GetSharedMemoryAs<GLuint*>()[0] = client_%(resource_name)s_id_;
5835 SpecializedSetup<cmds::%(name)s, 0>(true);
5836 cmds::%(name)s cmd;
5837 cmd.Init(%(args)s);
5838 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5839 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5840 EXPECT_TRUE(
5841 Get%(upper_resource_name)s(client_%(resource_name)s_id_) == NULL);
5844 self.WriteValidUnitTest(func, file, valid_test, {
5845 'resource_name': func.GetInfo('resource_type').lower(),
5846 'upper_resource_name': func.GetInfo('resource_type'),
5847 }, *extras)
5848 invalid_test = """
5849 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
5850 GetSharedMemoryAs<GLuint*>()[0] = kInvalidClientId;
5851 SpecializedSetup<cmds::%(name)s, 0>(false);
5852 cmds::%(name)s cmd;
5853 cmd.Init(%(args)s);
5854 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5857 self.WriteValidUnitTest(func, file, invalid_test, *extras)
5859 def WriteImmediateServiceUnitTest(self, func, file, *extras):
5860 """Overrriden from TypeHandler."""
5861 valid_test = """
5862 TEST_P(%(test_name)s, %(name)sValidArgs) {
5863 EXPECT_CALL(
5864 *gl_,
5865 %(gl_func_name)s(1, Pointee(kService%(upper_resource_name)sId)))
5866 .Times(1);
5867 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
5868 SpecializedSetup<cmds::%(name)s, 0>(true);
5869 cmd.Init(1, &client_%(resource_name)s_id_);"""
5870 if func.IsUnsafe():
5871 valid_test += """
5872 decoder_->set_unsafe_es3_apis_enabled(true);"""
5873 valid_test += """
5874 EXPECT_EQ(error::kNoError,
5875 ExecuteImmediateCmd(cmd, sizeof(client_%(resource_name)s_id_)));
5876 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
5877 if func.IsUnsafe():
5878 valid_test += """
5879 EXPECT_FALSE(Get%(upper_resource_name)sServiceId(
5880 client_%(resource_name)s_id_, NULL));
5881 decoder_->set_unsafe_es3_apis_enabled(false);
5882 EXPECT_EQ(error::kUnknownCommand,
5883 ExecuteImmediateCmd(cmd, sizeof(client_%(resource_name)s_id_)));
5886 else:
5887 valid_test += """
5888 EXPECT_TRUE(
5889 Get%(upper_resource_name)s(client_%(resource_name)s_id_) == NULL);
5892 self.WriteValidUnitTest(func, file, valid_test, {
5893 'resource_name': func.GetInfo('resource_type').lower(),
5894 'upper_resource_name': func.GetInfo('resource_type'),
5895 }, *extras)
5896 invalid_test = """
5897 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
5898 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
5899 SpecializedSetup<cmds::%(name)s, 0>(false);
5900 GLuint temp = kInvalidClientId;
5901 cmd.Init(1, &temp);"""
5902 if func.IsUnsafe():
5903 invalid_test += """
5904 decoder_->set_unsafe_es3_apis_enabled(true);
5905 EXPECT_EQ(error::kNoError,
5906 ExecuteImmediateCmd(cmd, sizeof(temp)));
5907 decoder_->set_unsafe_es3_apis_enabled(false);
5908 EXPECT_EQ(error::kUnknownCommand,
5909 ExecuteImmediateCmd(cmd, sizeof(temp)));
5912 else:
5913 invalid_test += """
5914 EXPECT_EQ(error::kNoError,
5915 ExecuteImmediateCmd(cmd, sizeof(temp)));
5918 self.WriteValidUnitTest(func, file, invalid_test, *extras)
5920 def WriteHandlerImplementation (self, func, file):
5921 """Overrriden from TypeHandler."""
5922 file.Write(" %sHelper(n, %s);\n" %
5923 (func.name, func.GetLastOriginalArg().name))
5925 def WriteImmediateHandlerImplementation (self, func, file):
5926 """Overrriden from TypeHandler."""
5927 if func.IsUnsafe():
5928 file.Write(""" for (GLsizei ii = 0; ii < n; ++ii) {
5929 GLuint service_id = 0;
5930 if (group_->Get%(resource_type)sServiceId(
5931 %(last_arg_name)s[ii], &service_id)) {
5932 glDelete%(resource_type)ss(1, &service_id);
5933 group_->Remove%(resource_type)sId(%(last_arg_name)s[ii]);
5936 """ % { 'resource_type': func.GetInfo('resource_type'),
5937 'last_arg_name': func.GetLastOriginalArg().name })
5938 else:
5939 file.Write(" %sHelper(n, %s);\n" %
5940 (func.original_name, func.GetLastOriginalArg().name))
5942 def WriteGLES2Implementation(self, func, file):
5943 """Overrriden from TypeHandler."""
5944 impl_decl = func.GetInfo('impl_decl')
5945 if impl_decl == None or impl_decl == True:
5946 args = {
5947 'return_type': func.return_type,
5948 'name': func.original_name,
5949 'typed_args': func.MakeTypedOriginalArgString(""),
5950 'args': func.MakeOriginalArgString(""),
5951 'resource_type': func.GetInfo('resource_type').lower(),
5952 'count_name': func.GetOriginalArgs()[0].name,
5954 file.Write(
5955 "%(return_type)s GLES2Implementation::%(name)s(%(typed_args)s) {\n" %
5956 args)
5957 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
5958 func.WriteDestinationInitalizationValidation(file)
5959 self.WriteClientGLCallLog(func, file)
5960 file.Write(""" GPU_CLIENT_LOG_CODE_BLOCK({
5961 for (GLsizei i = 0; i < n; ++i) {
5962 GPU_CLIENT_LOG(" " << i << ": " << %s[i]);
5965 """ % func.GetOriginalArgs()[1].name)
5966 file.Write(""" GPU_CLIENT_DCHECK_CODE_BLOCK({
5967 for (GLsizei i = 0; i < n; ++i) {
5968 DCHECK(%s[i] != 0);
5971 """ % func.GetOriginalArgs()[1].name)
5972 for arg in func.GetOriginalArgs():
5973 arg.WriteClientSideValidationCode(file, func)
5974 code = """ %(name)sHelper(%(args)s);
5975 CheckGLError();
5979 file.Write(code % args)
5981 def WriteImmediateCmdComputeSize(self, func, file):
5982 """Overrriden from TypeHandler."""
5983 file.Write(" static uint32_t ComputeDataSize(GLsizei n) {\n")
5984 file.Write(
5985 " return static_cast<uint32_t>(sizeof(GLuint) * n); // NOLINT\n")
5986 file.Write(" }\n")
5987 file.Write("\n")
5988 file.Write(" static uint32_t ComputeSize(GLsizei n) {\n")
5989 file.Write(" return static_cast<uint32_t>(\n")
5990 file.Write(" sizeof(ValueType) + ComputeDataSize(n)); // NOLINT\n")
5991 file.Write(" }\n")
5992 file.Write("\n")
5994 def WriteImmediateCmdSetHeader(self, func, file):
5995 """Overrriden from TypeHandler."""
5996 file.Write(" void SetHeader(GLsizei n) {\n")
5997 file.Write(" header.SetCmdByTotalSize<ValueType>(ComputeSize(n));\n")
5998 file.Write(" }\n")
5999 file.Write("\n")
6001 def WriteImmediateCmdInit(self, func, file):
6002 """Overrriden from TypeHandler."""
6003 last_arg = func.GetLastOriginalArg()
6004 file.Write(" void Init(%s, %s _%s) {\n" %
6005 (func.MakeTypedCmdArgString("_"),
6006 last_arg.type, last_arg.name))
6007 file.Write(" SetHeader(_n);\n")
6008 args = func.GetCmdArgs()
6009 for arg in args:
6010 file.Write(" %s = _%s;\n" % (arg.name, arg.name))
6011 file.Write(" memcpy(ImmediateDataAddress(this),\n")
6012 file.Write(" _%s, ComputeDataSize(_n));\n" % last_arg.name)
6013 file.Write(" }\n")
6014 file.Write("\n")
6016 def WriteImmediateCmdSet(self, func, file):
6017 """Overrriden from TypeHandler."""
6018 last_arg = func.GetLastOriginalArg()
6019 copy_args = func.MakeCmdArgString("_", False)
6020 file.Write(" void* Set(void* cmd%s, %s _%s) {\n" %
6021 (func.MakeTypedCmdArgString("_", True),
6022 last_arg.type, last_arg.name))
6023 file.Write(" static_cast<ValueType*>(cmd)->Init(%s, _%s);\n" %
6024 (copy_args, last_arg.name))
6025 file.Write(" const uint32_t size = ComputeSize(_n);\n")
6026 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
6027 "cmd, size);\n")
6028 file.Write(" }\n")
6029 file.Write("\n")
6031 def WriteImmediateCmdHelper(self, func, file):
6032 """Overrriden from TypeHandler."""
6033 code = """ void %(name)s(%(typed_args)s) {
6034 const uint32_t size = gles2::cmds::%(name)s::ComputeSize(n);
6035 gles2::cmds::%(name)s* c =
6036 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
6037 if (c) {
6038 c->Init(%(args)s);
6043 file.Write(code % {
6044 "name": func.name,
6045 "typed_args": func.MakeTypedOriginalArgString(""),
6046 "args": func.MakeOriginalArgString(""),
6049 def WriteImmediateFormatTest(self, func, file):
6050 """Overrriden from TypeHandler."""
6051 file.Write("TEST_F(GLES2FormatTest, %s) {\n" % func.name)
6052 file.Write(" static GLuint ids[] = { 12, 23, 34, };\n")
6053 file.Write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
6054 (func.name, func.name))
6055 file.Write(" void* next_cmd = cmd.Set(\n")
6056 file.Write(" &cmd, static_cast<GLsizei>(arraysize(ids)), ids);\n")
6057 file.Write(" EXPECT_EQ(static_cast<uint32_t>(cmds::%s::kCmdId),\n" %
6058 func.name)
6059 file.Write(" cmd.header.command);\n")
6060 file.Write(" EXPECT_EQ(sizeof(cmd) +\n")
6061 file.Write(" RoundSizeToMultipleOfEntries(cmd.n * 4u),\n")
6062 file.Write(" cmd.header.size * 4u);\n")
6063 file.Write(" EXPECT_EQ(static_cast<GLsizei>(arraysize(ids)), cmd.n);\n");
6064 file.Write(" CheckBytesWrittenMatchesExpectedSize(\n")
6065 file.Write(" next_cmd, sizeof(cmd) +\n")
6066 file.Write(" RoundSizeToMultipleOfEntries(arraysize(ids) * 4u));\n")
6067 file.Write(" // TODO(gman): Check that ids were inserted;\n")
6068 file.Write("}\n")
6069 file.Write("\n")
6072 class GETnHandler(TypeHandler):
6073 """Handler for GETn for glGetBooleanv, glGetFloatv, ... type functions."""
6075 def __init__(self):
6076 TypeHandler.__init__(self)
6078 def NeedsDataTransferFunction(self, func):
6079 """Overriden from TypeHandler."""
6080 return False
6082 def WriteServiceImplementation(self, func, file):
6083 """Overrriden from TypeHandler."""
6084 self.WriteServiceHandlerFunctionHeader(func, file)
6085 last_arg = func.GetLastOriginalArg()
6086 # All except shm_id and shm_offset.
6087 all_but_last_args = func.GetCmdArgs()[:-2]
6088 for arg in all_but_last_args:
6089 arg.WriteGetCode(file)
6091 code = """ typedef cmds::%(func_name)s::Result Result;
6092 GLsizei num_values = 0;
6093 GetNumValuesReturnedForGLGet(pname, &num_values);
6094 Result* result = GetSharedMemoryAs<Result*>(
6095 c.%(last_arg_name)s_shm_id, c.%(last_arg_name)s_shm_offset,
6096 Result::ComputeSize(num_values));
6097 %(last_arg_type)s %(last_arg_name)s = result ? result->GetData() : NULL;
6099 file.Write(code % {
6100 'last_arg_type': last_arg.type,
6101 'last_arg_name': last_arg.name,
6102 'func_name': func.name,
6104 func.WriteHandlerValidation(file)
6105 code = """ // Check that the client initialized the result.
6106 if (result->size != 0) {
6107 return error::kInvalidArguments;
6110 shadowed = func.GetInfo('shadowed')
6111 if not shadowed:
6112 file.Write(' LOCAL_COPY_REAL_GL_ERRORS_TO_WRAPPER("%s");\n' % func.name)
6113 file.Write(code)
6114 func.WriteHandlerImplementation(file)
6115 if shadowed:
6116 code = """ result->SetNumResults(num_values);
6117 return error::kNoError;
6120 else:
6121 code = """ GLenum error = glGetError();
6122 if (error == GL_NO_ERROR) {
6123 result->SetNumResults(num_values);
6124 } else {
6125 LOCAL_SET_GL_ERROR(error, "%(func_name)s", "");
6127 return error::kNoError;
6131 file.Write(code % {'func_name': func.name})
6133 def WriteGLES2Implementation(self, func, file):
6134 """Overrriden from TypeHandler."""
6135 impl_decl = func.GetInfo('impl_decl')
6136 if impl_decl == None or impl_decl == True:
6137 file.Write("%s GLES2Implementation::%s(%s) {\n" %
6138 (func.return_type, func.original_name,
6139 func.MakeTypedOriginalArgString("")))
6140 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
6141 func.WriteDestinationInitalizationValidation(file)
6142 self.WriteClientGLCallLog(func, file)
6143 for arg in func.GetOriginalArgs():
6144 arg.WriteClientSideValidationCode(file, func)
6145 all_but_last_args = func.GetOriginalArgs()[:-1]
6146 args = []
6147 has_length_arg = False
6148 for arg in all_but_last_args:
6149 if arg.type == 'GLsync':
6150 args.append('ToGLuint(%s)' % arg.name)
6151 elif arg.name.endswith('size') and arg.type == 'GLsizei':
6152 continue
6153 elif arg.name == 'length':
6154 has_length_arg = True
6155 continue
6156 else:
6157 args.append(arg.name)
6158 arg_string = ", ".join(args)
6159 all_arg_string = (
6160 ", ".join([
6161 "%s" % arg.name
6162 for arg in func.GetOriginalArgs() if not arg.IsConstant()]))
6163 self.WriteTraceEvent(func, file)
6164 code = """ if (%(func_name)sHelper(%(all_arg_string)s)) {
6165 return;
6167 typedef cmds::%(func_name)s::Result Result;
6168 Result* result = GetResultAs<Result*>();
6169 if (!result) {
6170 return;
6172 result->SetNumResults(0);
6173 helper_->%(func_name)s(%(arg_string)s,
6174 GetResultShmId(), GetResultShmOffset());
6175 WaitForCmd();
6176 result->CopyResult(%(last_arg_name)s);
6177 GPU_CLIENT_LOG_CODE_BLOCK({
6178 for (int32_t i = 0; i < result->GetNumResults(); ++i) {
6179 GPU_CLIENT_LOG(" " << i << ": " << result->GetData()[i]);
6181 });"""
6182 if has_length_arg:
6183 code += """
6184 if (length) {
6185 *length = result->GetNumResults();
6186 }"""
6187 code += """
6188 CheckGLError();
6191 file.Write(code % {
6192 'func_name': func.name,
6193 'arg_string': arg_string,
6194 'all_arg_string': all_arg_string,
6195 'last_arg_name': func.GetLastOriginalArg().name,
6198 def WriteGLES2ImplementationUnitTest(self, func, file):
6199 """Writes the GLES2 Implemention unit test."""
6200 code = """
6201 TEST_F(GLES2ImplementationTest, %(name)s) {
6202 struct Cmds {
6203 cmds::%(name)s cmd;
6205 typedef cmds::%(name)s::Result::Type ResultType;
6206 ResultType result = 0;
6207 Cmds expected;
6208 ExpectedMemoryInfo result1 = GetExpectedResultMemory(
6209 sizeof(uint32_t) + sizeof(ResultType));
6210 expected.cmd.Init(%(cmd_args)s, result1.id, result1.offset);
6211 EXPECT_CALL(*command_buffer(), OnFlush())
6212 .WillOnce(SetMemory(result1.ptr, SizedResultHelper<ResultType>(1)))
6213 .RetiresOnSaturation();
6214 gl_->%(name)s(%(args)s, &result);
6215 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
6216 EXPECT_EQ(static_cast<ResultType>(1), result);
6219 first_cmd_arg = func.GetCmdArgs()[0].GetValidNonCachedClientSideCmdArg(func)
6220 if not first_cmd_arg:
6221 return
6223 first_gl_arg = func.GetOriginalArgs()[0].GetValidNonCachedClientSideArg(
6224 func)
6226 cmd_arg_strings = [first_cmd_arg]
6227 for arg in func.GetCmdArgs()[1:-2]:
6228 cmd_arg_strings.append(arg.GetValidClientSideCmdArg(func))
6229 gl_arg_strings = [first_gl_arg]
6230 for arg in func.GetOriginalArgs()[1:-1]:
6231 gl_arg_strings.append(arg.GetValidClientSideArg(func))
6233 file.Write(code % {
6234 'name': func.name,
6235 'args': ", ".join(gl_arg_strings),
6236 'cmd_args': ", ".join(cmd_arg_strings),
6239 def WriteServiceUnitTest(self, func, file, *extras):
6240 """Overrriden from TypeHandler."""
6241 valid_test = """
6242 TEST_P(%(test_name)s, %(name)sValidArgs) {
6243 EXPECT_CALL(*gl_, GetError())
6244 .WillOnce(Return(GL_NO_ERROR))
6245 .WillOnce(Return(GL_NO_ERROR))
6246 .RetiresOnSaturation();
6247 SpecializedSetup<cmds::%(name)s, 0>(true);
6248 typedef cmds::%(name)s::Result Result;
6249 Result* result = static_cast<Result*>(shared_memory_address_);
6250 EXPECT_CALL(*gl_, %(gl_func_name)s(%(local_gl_args)s));
6251 result->size = 0;
6252 cmds::%(name)s cmd;
6253 cmd.Init(%(cmd_args)s);"""
6254 if func.IsUnsafe():
6255 valid_test += """
6256 decoder_->set_unsafe_es3_apis_enabled(true);"""
6257 valid_test += """
6258 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
6259 EXPECT_EQ(decoder_->GetGLES2Util()->GLGetNumValuesReturned(
6260 %(valid_pname)s),
6261 result->GetNumResults());
6262 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
6263 if func.IsUnsafe():
6264 valid_test += """
6265 decoder_->set_unsafe_es3_apis_enabled(false);
6266 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));"""
6267 valid_test += """
6270 gl_arg_strings = []
6271 cmd_arg_strings = []
6272 valid_pname = ''
6273 for arg in func.GetOriginalArgs()[:-1]:
6274 if arg.name == 'length':
6275 gl_arg_value = 'nullptr'
6276 elif arg.name.endswith('size'):
6277 gl_arg_value = ("decoder_->GetGLES2Util()->GLGetNumValuesReturned(%s)" %
6278 valid_pname)
6279 elif arg.type == 'GLsync':
6280 gl_arg_value = 'reinterpret_cast<GLsync>(kServiceSyncId)'
6281 else:
6282 gl_arg_value = arg.GetValidGLArg(func)
6283 gl_arg_strings.append(gl_arg_value)
6284 if arg.name == 'pname':
6285 valid_pname = gl_arg_value
6286 if arg.name.endswith('size') or arg.name == 'length':
6287 continue
6288 if arg.type == 'GLsync':
6289 arg_value = 'client_sync_id_'
6290 else:
6291 arg_value = arg.GetValidArg(func)
6292 cmd_arg_strings.append(arg_value)
6293 if func.GetInfo('gl_test_func') == 'glGetIntegerv':
6294 gl_arg_strings.append("_")
6295 else:
6296 gl_arg_strings.append("result->GetData()")
6297 cmd_arg_strings.append("shared_memory_id_")
6298 cmd_arg_strings.append("shared_memory_offset_")
6300 self.WriteValidUnitTest(func, file, valid_test, {
6301 'local_gl_args': ", ".join(gl_arg_strings),
6302 'cmd_args': ", ".join(cmd_arg_strings),
6303 'valid_pname': valid_pname,
6304 }, *extras)
6306 if not func.IsUnsafe():
6307 invalid_test = """
6308 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
6309 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
6310 SpecializedSetup<cmds::%(name)s, 0>(false);
6311 cmds::%(name)s::Result* result =
6312 static_cast<cmds::%(name)s::Result*>(shared_memory_address_);
6313 result->size = 0;
6314 cmds::%(name)s cmd;
6315 cmd.Init(%(args)s);
6316 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));
6317 EXPECT_EQ(0u, result->size);%(gl_error_test)s
6320 self.WriteInvalidUnitTest(func, file, invalid_test, *extras)
6322 class ArrayArgTypeHandler(TypeHandler):
6323 """Base class for type handlers that handle args that are arrays"""
6325 def __init__(self):
6326 TypeHandler.__init__(self)
6328 def GetArrayType(self, func):
6329 """Returns the type of the element in the element array being PUT to."""
6330 for arg in func.GetOriginalArgs():
6331 if arg.IsPointer():
6332 element_type = arg.GetPointedType()
6333 return element_type
6335 # Special case: array type handler is used for a function that is forwarded
6336 # to the actual array type implementation
6337 element_type = func.GetOriginalArgs()[-1].type
6338 assert all(arg.type == element_type \
6339 for arg in func.GetOriginalArgs()[-self.GetArrayCount(func):])
6340 return element_type
6342 def GetArrayCount(self, func):
6343 """Returns the count of the elements in the array being PUT to."""
6344 return func.GetInfo('count')
6346 class PUTHandler(ArrayArgTypeHandler):
6347 """Handler for glTexParameter_v, glVertexAttrib_v functions."""
6349 def __init__(self):
6350 ArrayArgTypeHandler.__init__(self)
6352 def WriteServiceUnitTest(self, func, file, *extras):
6353 """Writes the service unit test for a command."""
6354 expected_call = "EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));"
6355 if func.GetInfo("first_element_only"):
6356 gl_arg_strings = [
6357 arg.GetValidGLArg(func) for arg in func.GetOriginalArgs()
6359 gl_arg_strings[-1] = "*" + gl_arg_strings[-1]
6360 expected_call = ("EXPECT_CALL(*gl_, %%(gl_func_name)s(%s));" %
6361 ", ".join(gl_arg_strings))
6362 valid_test = """
6363 TEST_P(%(test_name)s, %(name)sValidArgs) {
6364 SpecializedSetup<cmds::%(name)s, 0>(true);
6365 cmds::%(name)s cmd;
6366 cmd.Init(%(args)s);
6367 GetSharedMemoryAs<%(data_type)s*>()[0] = %(data_value)s;
6368 %(expected_call)s
6369 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
6370 EXPECT_EQ(GL_NO_ERROR, GetGLError());
6373 extra = {
6374 'data_type': self.GetArrayType(func),
6375 'data_value': func.GetInfo('data_value') or '0',
6376 'expected_call': expected_call,
6378 self.WriteValidUnitTest(func, file, valid_test, extra, *extras)
6380 invalid_test = """
6381 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
6382 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
6383 SpecializedSetup<cmds::%(name)s, 0>(false);
6384 cmds::%(name)s cmd;
6385 cmd.Init(%(args)s);
6386 GetSharedMemoryAs<%(data_type)s*>()[0] = %(data_value)s;
6387 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
6390 self.WriteInvalidUnitTest(func, file, invalid_test, extra, *extras)
6392 def WriteImmediateServiceUnitTest(self, func, file, *extras):
6393 """Writes the service unit test for a command."""
6394 valid_test = """
6395 TEST_P(%(test_name)s, %(name)sValidArgs) {
6396 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
6397 SpecializedSetup<cmds::%(name)s, 0>(true);
6398 %(data_type)s temp[%(data_count)s] = { %(data_value)s, };
6399 cmd.Init(%(gl_args)s, &temp[0]);
6400 EXPECT_CALL(
6401 *gl_,
6402 %(gl_func_name)s(%(gl_args)s, %(data_ref)sreinterpret_cast<
6403 %(data_type)s*>(ImmediateDataAddress(&cmd))));"""
6404 if func.IsUnsafe():
6405 valid_test += """
6406 decoder_->set_unsafe_es3_apis_enabled(true);"""
6407 valid_test += """
6408 EXPECT_EQ(error::kNoError,
6409 ExecuteImmediateCmd(cmd, sizeof(temp)));
6410 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
6411 if func.IsUnsafe():
6412 valid_test += """
6413 decoder_->set_unsafe_es3_apis_enabled(false);
6414 EXPECT_EQ(error::kUnknownCommand,
6415 ExecuteImmediateCmd(cmd, sizeof(temp)));"""
6416 valid_test += """
6419 gl_arg_strings = [
6420 arg.GetValidGLArg(func) for arg in func.GetOriginalArgs()[0:-1]
6422 gl_any_strings = ["_"] * len(gl_arg_strings)
6424 extra = {
6425 'data_ref': ("*" if func.GetInfo('first_element_only') else ""),
6426 'data_type': self.GetArrayType(func),
6427 'data_count': self.GetArrayCount(func),
6428 'data_value': func.GetInfo('data_value') or '0',
6429 'gl_args': ", ".join(gl_arg_strings),
6430 'gl_any_args': ", ".join(gl_any_strings),
6432 self.WriteValidUnitTest(func, file, valid_test, extra, *extras)
6434 invalid_test = """
6435 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
6436 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();"""
6437 if func.IsUnsafe():
6438 invalid_test += """
6439 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_any_args)s, _)).Times(1);
6441 else:
6442 invalid_test += """
6443 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_any_args)s, _)).Times(0);
6445 invalid_test += """
6446 SpecializedSetup<cmds::%(name)s, 0>(false);
6447 %(data_type)s temp[%(data_count)s] = { %(data_value)s, };
6448 cmd.Init(%(all_but_last_args)s, &temp[0]);"""
6449 if func.IsUnsafe():
6450 invalid_test += """
6451 decoder_->set_unsafe_es3_apis_enabled(true);
6452 EXPECT_EQ(error::%(parse_result)s,
6453 ExecuteImmediateCmd(cmd, sizeof(temp)));
6454 decoder_->set_unsafe_es3_apis_enabled(false);
6457 else:
6458 invalid_test += """
6459 EXPECT_EQ(error::%(parse_result)s,
6460 ExecuteImmediateCmd(cmd, sizeof(temp)));
6461 %(gl_error_test)s
6464 self.WriteInvalidUnitTest(func, file, invalid_test, extra, *extras)
6466 def WriteGetDataSizeCode(self, func, file):
6467 """Overrriden from TypeHandler."""
6468 code = """ uint32_t data_size;
6469 if (!ComputeDataSize(1, sizeof(%s), %d, &data_size)) {
6470 return error::kOutOfBounds;
6473 file.Write(code % (self.GetArrayType(func), self.GetArrayCount(func)))
6474 if func.IsImmediate():
6475 file.Write(" if (data_size > immediate_data_size) {\n")
6476 file.Write(" return error::kOutOfBounds;\n")
6477 file.Write(" }\n")
6479 def __NeedsToCalcDataCount(self, func):
6480 use_count_func = func.GetInfo('use_count_func')
6481 return use_count_func != None and use_count_func != False
6483 def WriteGLES2Implementation(self, func, file):
6484 """Overrriden from TypeHandler."""
6485 impl_func = func.GetInfo('impl_func')
6486 if (impl_func != None and impl_func != True):
6487 return;
6488 file.Write("%s GLES2Implementation::%s(%s) {\n" %
6489 (func.return_type, func.original_name,
6490 func.MakeTypedOriginalArgString("")))
6491 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
6492 func.WriteDestinationInitalizationValidation(file)
6493 self.WriteClientGLCallLog(func, file)
6495 if self.__NeedsToCalcDataCount(func):
6496 file.Write(" size_t count = GLES2Util::Calc%sDataCount(%s);\n" %
6497 (func.name, func.GetOriginalArgs()[0].name))
6498 file.Write(" DCHECK_LE(count, %du);\n" % self.GetArrayCount(func))
6499 else:
6500 file.Write(" size_t count = %d;" % self.GetArrayCount(func))
6501 file.Write(" for (size_t ii = 0; ii < count; ++ii)\n")
6502 file.Write(' GPU_CLIENT_LOG("value[" << ii << "]: " << %s[ii]);\n' %
6503 func.GetLastOriginalArg().name)
6504 for arg in func.GetOriginalArgs():
6505 arg.WriteClientSideValidationCode(file, func)
6506 file.Write(" helper_->%sImmediate(%s);\n" %
6507 (func.name, func.MakeOriginalArgString("")))
6508 file.Write(" CheckGLError();\n")
6509 file.Write("}\n")
6510 file.Write("\n")
6512 def WriteGLES2ImplementationUnitTest(self, func, file):
6513 """Writes the GLES2 Implemention unit test."""
6514 client_test = func.GetInfo('client_test')
6515 if (client_test != None and client_test != True):
6516 return;
6517 code = """
6518 TEST_F(GLES2ImplementationTest, %(name)s) {
6519 %(type)s data[%(count)d] = {0};
6520 struct Cmds {
6521 cmds::%(name)sImmediate cmd;
6522 %(type)s data[%(count)d];
6525 for (int jj = 0; jj < %(count)d; ++jj) {
6526 data[jj] = static_cast<%(type)s>(jj);
6528 Cmds expected;
6529 expected.cmd.Init(%(cmd_args)s, &data[0]);
6530 gl_->%(name)s(%(args)s, &data[0]);
6531 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
6534 cmd_arg_strings = [
6535 arg.GetValidClientSideCmdArg(func) for arg in func.GetCmdArgs()[0:-2]
6537 gl_arg_strings = [
6538 arg.GetValidClientSideArg(func) for arg in func.GetOriginalArgs()[0:-1]
6541 file.Write(code % {
6542 'name': func.name,
6543 'type': self.GetArrayType(func),
6544 'count': self.GetArrayCount(func),
6545 'args': ", ".join(gl_arg_strings),
6546 'cmd_args': ", ".join(cmd_arg_strings),
6549 def WriteImmediateCmdComputeSize(self, func, file):
6550 """Overrriden from TypeHandler."""
6551 file.Write(" static uint32_t ComputeDataSize() {\n")
6552 file.Write(" return static_cast<uint32_t>(\n")
6553 file.Write(" sizeof(%s) * %d);\n" %
6554 (self.GetArrayType(func), self.GetArrayCount(func)))
6555 file.Write(" }\n")
6556 file.Write("\n")
6557 if self.__NeedsToCalcDataCount(func):
6558 file.Write(" static uint32_t ComputeEffectiveDataSize(%s %s) {\n" %
6559 (func.GetOriginalArgs()[0].type,
6560 func.GetOriginalArgs()[0].name))
6561 file.Write(" return static_cast<uint32_t>(\n")
6562 file.Write(" sizeof(%s) * GLES2Util::Calc%sDataCount(%s));\n" %
6563 (self.GetArrayType(func), func.original_name,
6564 func.GetOriginalArgs()[0].name))
6565 file.Write(" }\n")
6566 file.Write("\n")
6567 file.Write(" static uint32_t ComputeSize() {\n")
6568 file.Write(" return static_cast<uint32_t>(\n")
6569 file.Write(
6570 " sizeof(ValueType) + ComputeDataSize());\n")
6571 file.Write(" }\n")
6572 file.Write("\n")
6574 def WriteImmediateCmdSetHeader(self, func, file):
6575 """Overrriden from TypeHandler."""
6576 file.Write(" void SetHeader() {\n")
6577 file.Write(
6578 " header.SetCmdByTotalSize<ValueType>(ComputeSize());\n")
6579 file.Write(" }\n")
6580 file.Write("\n")
6582 def WriteImmediateCmdInit(self, func, file):
6583 """Overrriden from TypeHandler."""
6584 last_arg = func.GetLastOriginalArg()
6585 file.Write(" void Init(%s, %s _%s) {\n" %
6586 (func.MakeTypedCmdArgString("_"),
6587 last_arg.type, last_arg.name))
6588 file.Write(" SetHeader();\n")
6589 args = func.GetCmdArgs()
6590 for arg in args:
6591 file.Write(" %s = _%s;\n" % (arg.name, arg.name))
6592 file.Write(" memcpy(ImmediateDataAddress(this),\n")
6593 if self.__NeedsToCalcDataCount(func):
6594 file.Write(" _%s, ComputeEffectiveDataSize(%s));" %
6595 (last_arg.name, func.GetOriginalArgs()[0].name))
6596 file.Write("""
6597 DCHECK_GE(ComputeDataSize(), ComputeEffectiveDataSize(%(arg)s));
6598 char* pointer = reinterpret_cast<char*>(ImmediateDataAddress(this)) +
6599 ComputeEffectiveDataSize(%(arg)s);
6600 memset(pointer, 0, ComputeDataSize() - ComputeEffectiveDataSize(%(arg)s));
6601 """ % { 'arg': func.GetOriginalArgs()[0].name, })
6602 else:
6603 file.Write(" _%s, ComputeDataSize());\n" % last_arg.name)
6604 file.Write(" }\n")
6605 file.Write("\n")
6607 def WriteImmediateCmdSet(self, func, file):
6608 """Overrriden from TypeHandler."""
6609 last_arg = func.GetLastOriginalArg()
6610 copy_args = func.MakeCmdArgString("_", False)
6611 file.Write(" void* Set(void* cmd%s, %s _%s) {\n" %
6612 (func.MakeTypedCmdArgString("_", True),
6613 last_arg.type, last_arg.name))
6614 file.Write(" static_cast<ValueType*>(cmd)->Init(%s, _%s);\n" %
6615 (copy_args, last_arg.name))
6616 file.Write(" const uint32_t size = ComputeSize();\n")
6617 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
6618 "cmd, size);\n")
6619 file.Write(" }\n")
6620 file.Write("\n")
6622 def WriteImmediateCmdHelper(self, func, file):
6623 """Overrriden from TypeHandler."""
6624 code = """ void %(name)s(%(typed_args)s) {
6625 const uint32_t size = gles2::cmds::%(name)s::ComputeSize();
6626 gles2::cmds::%(name)s* c =
6627 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
6628 if (c) {
6629 c->Init(%(args)s);
6634 file.Write(code % {
6635 "name": func.name,
6636 "typed_args": func.MakeTypedOriginalArgString(""),
6637 "args": func.MakeOriginalArgString(""),
6640 def WriteImmediateFormatTest(self, func, file):
6641 """Overrriden from TypeHandler."""
6642 file.Write("TEST_F(GLES2FormatTest, %s) {\n" % func.name)
6643 file.Write(" const int kSomeBaseValueToTestWith = 51;\n")
6644 file.Write(" static %s data[] = {\n" % self.GetArrayType(func))
6645 for v in range(0, self.GetArrayCount(func)):
6646 file.Write(" static_cast<%s>(kSomeBaseValueToTestWith + %d),\n" %
6647 (self.GetArrayType(func), v))
6648 file.Write(" };\n")
6649 file.Write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
6650 (func.name, func.name))
6651 file.Write(" void* next_cmd = cmd.Set(\n")
6652 file.Write(" &cmd")
6653 args = func.GetCmdArgs()
6654 for value, arg in enumerate(args):
6655 file.Write(",\n static_cast<%s>(%d)" % (arg.type, value + 11))
6656 file.Write(",\n data);\n")
6657 args = func.GetCmdArgs()
6658 file.Write(" EXPECT_EQ(static_cast<uint32_t>(cmds::%s::kCmdId),\n"
6659 % func.name)
6660 file.Write(" cmd.header.command);\n")
6661 file.Write(" EXPECT_EQ(sizeof(cmd) +\n")
6662 file.Write(" RoundSizeToMultipleOfEntries(sizeof(data)),\n")
6663 file.Write(" cmd.header.size * 4u);\n")
6664 for value, arg in enumerate(args):
6665 file.Write(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);\n" %
6666 (arg.type, value + 11, arg.name))
6667 file.Write(" CheckBytesWrittenMatchesExpectedSize(\n")
6668 file.Write(" next_cmd, sizeof(cmd) +\n")
6669 file.Write(" RoundSizeToMultipleOfEntries(sizeof(data)));\n")
6670 file.Write(" // TODO(gman): Check that data was inserted;\n")
6671 file.Write("}\n")
6672 file.Write("\n")
6675 class PUTnHandler(ArrayArgTypeHandler):
6676 """Handler for PUTn 'glUniform__v' type functions."""
6678 def __init__(self):
6679 ArrayArgTypeHandler.__init__(self)
6681 def WriteServiceUnitTest(self, func, file, *extras):
6682 """Overridden from TypeHandler."""
6683 ArrayArgTypeHandler.WriteServiceUnitTest(self, func, file, *extras)
6685 valid_test = """
6686 TEST_P(%(test_name)s, %(name)sValidArgsCountTooLarge) {
6687 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
6688 SpecializedSetup<cmds::%(name)s, 0>(true);
6689 cmds::%(name)s cmd;
6690 cmd.Init(%(args)s);
6691 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
6692 EXPECT_EQ(GL_NO_ERROR, GetGLError());
6695 gl_arg_strings = []
6696 arg_strings = []
6697 for count, arg in enumerate(func.GetOriginalArgs()):
6698 # hardcoded to match unit tests.
6699 if count == 0:
6700 # the location of the second element of the 2nd uniform.
6701 # defined in GLES2DecoderBase::SetupShaderForUniform
6702 gl_arg_strings.append("3")
6703 arg_strings.append("ProgramManager::MakeFakeLocation(1, 1)")
6704 elif count == 1:
6705 # the number of elements that gl will be called with.
6706 gl_arg_strings.append("3")
6707 # the number of elements requested in the command.
6708 arg_strings.append("5")
6709 else:
6710 gl_arg_strings.append(arg.GetValidGLArg(func))
6711 if not arg.IsConstant():
6712 arg_strings.append(arg.GetValidArg(func))
6713 extra = {
6714 'gl_args': ", ".join(gl_arg_strings),
6715 'args': ", ".join(arg_strings),
6717 self.WriteValidUnitTest(func, file, valid_test, extra, *extras)
6719 def WriteImmediateServiceUnitTest(self, func, file, *extras):
6720 """Overridden from TypeHandler."""
6721 valid_test = """
6722 TEST_P(%(test_name)s, %(name)sValidArgs) {
6723 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
6724 EXPECT_CALL(
6725 *gl_,
6726 %(gl_func_name)s(%(gl_args)s,
6727 reinterpret_cast<%(data_type)s*>(ImmediateDataAddress(&cmd))));
6728 SpecializedSetup<cmds::%(name)s, 0>(true);
6729 %(data_type)s temp[%(data_count)s * 2] = { 0, };
6730 cmd.Init(%(args)s, &temp[0]);"""
6731 if func.IsUnsafe():
6732 valid_test += """
6733 decoder_->set_unsafe_es3_apis_enabled(true);"""
6734 valid_test += """
6735 EXPECT_EQ(error::kNoError,
6736 ExecuteImmediateCmd(cmd, sizeof(temp)));
6737 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
6738 if func.IsUnsafe():
6739 valid_test += """
6740 decoder_->set_unsafe_es3_apis_enabled(false);
6741 EXPECT_EQ(error::kUnknownCommand,
6742 ExecuteImmediateCmd(cmd, sizeof(temp)));"""
6743 valid_test += """
6746 gl_arg_strings = []
6747 gl_any_strings = []
6748 arg_strings = []
6749 for arg in func.GetOriginalArgs()[0:-1]:
6750 gl_arg_strings.append(arg.GetValidGLArg(func))
6751 gl_any_strings.append("_")
6752 if not arg.IsConstant():
6753 arg_strings.append(arg.GetValidArg(func))
6754 extra = {
6755 'data_type': self.GetArrayType(func),
6756 'data_count': self.GetArrayCount(func),
6757 'args': ", ".join(arg_strings),
6758 'gl_args': ", ".join(gl_arg_strings),
6759 'gl_any_args': ", ".join(gl_any_strings),
6761 self.WriteValidUnitTest(func, file, valid_test, extra, *extras)
6763 invalid_test = """
6764 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
6765 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
6766 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_any_args)s, _)).Times(0);
6767 SpecializedSetup<cmds::%(name)s, 0>(false);
6768 %(data_type)s temp[%(data_count)s * 2] = { 0, };
6769 cmd.Init(%(all_but_last_args)s, &temp[0]);
6770 EXPECT_EQ(error::%(parse_result)s,
6771 ExecuteImmediateCmd(cmd, sizeof(temp)));%(gl_error_test)s
6774 self.WriteInvalidUnitTest(func, file, invalid_test, extra, *extras)
6776 def WriteGetDataSizeCode(self, func, file):
6777 """Overrriden from TypeHandler."""
6778 code = """ uint32_t data_size;
6779 if (!ComputeDataSize(count, sizeof(%s), %d, &data_size)) {
6780 return error::kOutOfBounds;
6783 file.Write(code % (self.GetArrayType(func), self.GetArrayCount(func)))
6784 if func.IsImmediate():
6785 file.Write(" if (data_size > immediate_data_size) {\n")
6786 file.Write(" return error::kOutOfBounds;\n")
6787 file.Write(" }\n")
6789 def WriteGLES2Implementation(self, func, file):
6790 """Overrriden from TypeHandler."""
6791 file.Write("%s GLES2Implementation::%s(%s) {\n" %
6792 (func.return_type, func.original_name,
6793 func.MakeTypedOriginalArgString("")))
6794 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
6795 func.WriteDestinationInitalizationValidation(file)
6796 self.WriteClientGLCallLog(func, file)
6797 last_pointer_name = func.GetLastOriginalPointerArg().name
6798 file.Write(""" GPU_CLIENT_LOG_CODE_BLOCK({
6799 for (GLsizei i = 0; i < count; ++i) {
6800 """)
6801 values_str = ' << ", " << '.join(
6802 ["%s[%d + i * %d]" % (
6803 last_pointer_name, ndx, self.GetArrayCount(func)) for ndx in range(
6804 0, self.GetArrayCount(func))])
6805 file.Write(' GPU_CLIENT_LOG(" " << i << ": " << %s);\n' % values_str)
6806 file.Write(" }\n });\n")
6807 for arg in func.GetOriginalArgs():
6808 arg.WriteClientSideValidationCode(file, func)
6809 file.Write(" helper_->%sImmediate(%s);\n" %
6810 (func.name, func.MakeInitString("")))
6811 file.Write(" CheckGLError();\n")
6812 file.Write("}\n")
6813 file.Write("\n")
6815 def WriteGLES2ImplementationUnitTest(self, func, file):
6816 """Writes the GLES2 Implemention unit test."""
6817 code = """
6818 TEST_F(GLES2ImplementationTest, %(name)s) {
6819 %(type)s data[%(count_param)d][%(count)d] = {{0}};
6820 struct Cmds {
6821 cmds::%(name)sImmediate cmd;
6822 %(type)s data[%(count_param)d][%(count)d];
6825 Cmds expected;
6826 for (int ii = 0; ii < %(count_param)d; ++ii) {
6827 for (int jj = 0; jj < %(count)d; ++jj) {
6828 data[ii][jj] = static_cast<%(type)s>(ii * %(count)d + jj);
6831 expected.cmd.Init(%(cmd_args)s);
6832 gl_->%(name)s(%(args)s);
6833 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
6836 cmd_arg_strings = []
6837 for arg in func.GetCmdArgs():
6838 if arg.name.endswith("_shm_id"):
6839 cmd_arg_strings.append("&data[0][0]")
6840 elif arg.name.endswith("_shm_offset"):
6841 continue
6842 else:
6843 cmd_arg_strings.append(arg.GetValidClientSideCmdArg(func))
6844 gl_arg_strings = []
6845 count_param = 0
6846 for arg in func.GetOriginalArgs():
6847 if arg.IsPointer():
6848 valid_value = "&data[0][0]"
6849 else:
6850 valid_value = arg.GetValidClientSideArg(func)
6851 gl_arg_strings.append(valid_value)
6852 if arg.name == "count":
6853 count_param = int(valid_value)
6854 file.Write(code % {
6855 'name': func.name,
6856 'type': self.GetArrayType(func),
6857 'count': self.GetArrayCount(func),
6858 'args': ", ".join(gl_arg_strings),
6859 'cmd_args': ", ".join(cmd_arg_strings),
6860 'count_param': count_param,
6863 # Test constants for invalid values, as they are not tested by the
6864 # service.
6865 constants = [
6866 arg for arg in func.GetOriginalArgs()[0:-1] if arg.IsConstant()
6868 if not constants:
6869 return
6871 code = """
6872 TEST_F(GLES2ImplementationTest, %(name)sInvalidConstantArg%(invalid_index)d) {
6873 %(type)s data[%(count_param)d][%(count)d] = {{0}};
6874 for (int ii = 0; ii < %(count_param)d; ++ii) {
6875 for (int jj = 0; jj < %(count)d; ++jj) {
6876 data[ii][jj] = static_cast<%(type)s>(ii * %(count)d + jj);
6879 gl_->%(name)s(%(args)s);
6880 EXPECT_TRUE(NoCommandsWritten());
6881 EXPECT_EQ(%(gl_error)s, CheckError());
6884 for invalid_arg in constants:
6885 gl_arg_strings = []
6886 invalid = invalid_arg.GetInvalidArg(func)
6887 for arg in func.GetOriginalArgs():
6888 if arg is invalid_arg:
6889 gl_arg_strings.append(invalid[0])
6890 elif arg.IsPointer():
6891 gl_arg_strings.append("&data[0][0]")
6892 else:
6893 valid_value = arg.GetValidClientSideArg(func)
6894 gl_arg_strings.append(valid_value)
6895 if arg.name == "count":
6896 count_param = int(valid_value)
6898 file.Write(code % {
6899 'name': func.name,
6900 'invalid_index': func.GetOriginalArgs().index(invalid_arg),
6901 'type': self.GetArrayType(func),
6902 'count': self.GetArrayCount(func),
6903 'args': ", ".join(gl_arg_strings),
6904 'gl_error': invalid[2],
6905 'count_param': count_param,
6909 def WriteImmediateCmdComputeSize(self, func, file):
6910 """Overrriden from TypeHandler."""
6911 file.Write(" static uint32_t ComputeDataSize(GLsizei count) {\n")
6912 file.Write(" return static_cast<uint32_t>(\n")
6913 file.Write(" sizeof(%s) * %d * count); // NOLINT\n" %
6914 (self.GetArrayType(func), self.GetArrayCount(func)))
6915 file.Write(" }\n")
6916 file.Write("\n")
6917 file.Write(" static uint32_t ComputeSize(GLsizei count) {\n")
6918 file.Write(" return static_cast<uint32_t>(\n")
6919 file.Write(
6920 " sizeof(ValueType) + ComputeDataSize(count)); // NOLINT\n")
6921 file.Write(" }\n")
6922 file.Write("\n")
6924 def WriteImmediateCmdSetHeader(self, func, file):
6925 """Overrriden from TypeHandler."""
6926 file.Write(" void SetHeader(GLsizei count) {\n")
6927 file.Write(
6928 " header.SetCmdByTotalSize<ValueType>(ComputeSize(count));\n")
6929 file.Write(" }\n")
6930 file.Write("\n")
6932 def WriteImmediateCmdInit(self, func, file):
6933 """Overrriden from TypeHandler."""
6934 file.Write(" void Init(%s) {\n" %
6935 func.MakeTypedInitString("_"))
6936 file.Write(" SetHeader(_count);\n")
6937 args = func.GetCmdArgs()
6938 for arg in args:
6939 file.Write(" %s = _%s;\n" % (arg.name, arg.name))
6940 file.Write(" memcpy(ImmediateDataAddress(this),\n")
6941 pointer_arg = func.GetLastOriginalPointerArg()
6942 file.Write(" _%s, ComputeDataSize(_count));\n" % pointer_arg.name)
6943 file.Write(" }\n")
6944 file.Write("\n")
6946 def WriteImmediateCmdSet(self, func, file):
6947 """Overrriden from TypeHandler."""
6948 file.Write(" void* Set(void* cmd%s) {\n" %
6949 func.MakeTypedInitString("_", True))
6950 file.Write(" static_cast<ValueType*>(cmd)->Init(%s);\n" %
6951 func.MakeInitString("_"))
6952 file.Write(" const uint32_t size = ComputeSize(_count);\n")
6953 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
6954 "cmd, size);\n")
6955 file.Write(" }\n")
6956 file.Write("\n")
6958 def WriteImmediateCmdHelper(self, func, file):
6959 """Overrriden from TypeHandler."""
6960 code = """ void %(name)s(%(typed_args)s) {
6961 const uint32_t size = gles2::cmds::%(name)s::ComputeSize(count);
6962 gles2::cmds::%(name)s* c =
6963 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
6964 if (c) {
6965 c->Init(%(args)s);
6970 file.Write(code % {
6971 "name": func.name,
6972 "typed_args": func.MakeTypedInitString(""),
6973 "args": func.MakeInitString("")
6976 def WriteImmediateFormatTest(self, func, file):
6977 """Overrriden from TypeHandler."""
6978 args = func.GetOriginalArgs()
6979 count_param = 0
6980 for arg in args:
6981 if arg.name == "count":
6982 count_param = int(arg.GetValidClientSideCmdArg(func))
6983 file.Write("TEST_F(GLES2FormatTest, %s) {\n" % func.name)
6984 file.Write(" const int kSomeBaseValueToTestWith = 51;\n")
6985 file.Write(" static %s data[] = {\n" % self.GetArrayType(func))
6986 for v in range(0, self.GetArrayCount(func) * count_param):
6987 file.Write(" static_cast<%s>(kSomeBaseValueToTestWith + %d),\n" %
6988 (self.GetArrayType(func), v))
6989 file.Write(" };\n")
6990 file.Write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
6991 (func.name, func.name))
6992 file.Write(" const GLsizei kNumElements = %d;\n" % count_param)
6993 file.Write(" const size_t kExpectedCmdSize =\n")
6994 file.Write(" sizeof(cmd) + kNumElements * sizeof(%s) * %d;\n" %
6995 (self.GetArrayType(func), self.GetArrayCount(func)))
6996 file.Write(" void* next_cmd = cmd.Set(\n")
6997 file.Write(" &cmd")
6998 for value, arg in enumerate(args):
6999 if arg.IsPointer():
7000 file.Write(",\n data")
7001 elif arg.IsConstant():
7002 continue
7003 else:
7004 file.Write(",\n static_cast<%s>(%d)" % (arg.type, value + 1))
7005 file.Write(");\n")
7006 file.Write(" EXPECT_EQ(static_cast<uint32_t>(cmds::%s::kCmdId),\n" %
7007 func.name)
7008 file.Write(" cmd.header.command);\n")
7009 file.Write(" EXPECT_EQ(kExpectedCmdSize, cmd.header.size * 4u);\n")
7010 for value, arg in enumerate(args):
7011 if arg.IsPointer() or arg.IsConstant():
7012 continue
7013 file.Write(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);\n" %
7014 (arg.type, value + 1, arg.name))
7015 file.Write(" CheckBytesWrittenMatchesExpectedSize(\n")
7016 file.Write(" next_cmd, sizeof(cmd) +\n")
7017 file.Write(" RoundSizeToMultipleOfEntries(sizeof(data)));\n")
7018 file.Write(" // TODO(gman): Check that data was inserted;\n")
7019 file.Write("}\n")
7020 file.Write("\n")
7022 class PUTSTRHandler(ArrayArgTypeHandler):
7023 """Handler for functions that pass a string array."""
7025 def __init__(self):
7026 ArrayArgTypeHandler.__init__(self)
7028 def __GetDataArg(self, func):
7029 """Return the argument that points to the 2D char arrays"""
7030 for arg in func.GetOriginalArgs():
7031 if arg.IsPointer2D():
7032 return arg
7033 return None
7035 def __GetLengthArg(self, func):
7036 """Return the argument that holds length for each char array"""
7037 for arg in func.GetOriginalArgs():
7038 if arg.IsPointer() and not arg.IsPointer2D():
7039 return arg
7040 return None
7042 def WriteGLES2Implementation(self, func, file):
7043 """Overrriden from TypeHandler."""
7044 file.Write("%s GLES2Implementation::%s(%s) {\n" %
7045 (func.return_type, func.original_name,
7046 func.MakeTypedOriginalArgString("")))
7047 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
7048 func.WriteDestinationInitalizationValidation(file)
7049 self.WriteClientGLCallLog(func, file)
7050 data_arg = self.__GetDataArg(func)
7051 length_arg = self.__GetLengthArg(func)
7052 log_code_block = """ GPU_CLIENT_LOG_CODE_BLOCK({
7053 for (GLsizei ii = 0; ii < count; ++ii) {
7054 if (%(data)s[ii]) {"""
7055 if length_arg == None:
7056 log_code_block += """
7057 GPU_CLIENT_LOG(" " << ii << ": ---\\n" << %(data)s[ii] << "\\n---");"""
7058 else:
7059 log_code_block += """
7060 if (%(length)s && %(length)s[ii] >= 0) {
7061 const std::string my_str(%(data)s[ii], %(length)s[ii]);
7062 GPU_CLIENT_LOG(" " << ii << ": ---\\n" << my_str << "\\n---");
7063 } else {
7064 GPU_CLIENT_LOG(" " << ii << ": ---\\n" << %(data)s[ii] << "\\n---");
7065 }"""
7066 log_code_block += """
7067 } else {
7068 GPU_CLIENT_LOG(" " << ii << ": NULL");
7073 file.Write(log_code_block % {
7074 'data': data_arg.name,
7075 'length': length_arg.name if not length_arg == None else ''
7077 for arg in func.GetOriginalArgs():
7078 arg.WriteClientSideValidationCode(file, func)
7080 bucket_args = []
7081 for arg in func.GetOriginalArgs():
7082 if arg.name == 'count' or arg == self.__GetLengthArg(func):
7083 continue
7084 if arg == self.__GetDataArg(func):
7085 bucket_args.append('kResultBucketId')
7086 else:
7087 bucket_args.append(arg.name)
7088 code_block = """
7089 if (!PackStringsToBucket(count, %(data)s, %(length)s, "gl%(func_name)s")) {
7090 return;
7092 helper_->%(func_name)sBucket(%(bucket_args)s);
7093 helper_->SetBucketSize(kResultBucketId, 0);
7094 CheckGLError();
7098 file.Write(code_block % {
7099 'data': data_arg.name,
7100 'length': length_arg.name if not length_arg == None else 'NULL',
7101 'func_name': func.name,
7102 'bucket_args': ', '.join(bucket_args),
7105 def WriteGLES2ImplementationUnitTest(self, func, file):
7106 """Overrriden from TypeHandler."""
7107 code = """
7108 TEST_F(GLES2ImplementationTest, %(name)s) {
7109 const uint32 kBucketId = GLES2Implementation::kResultBucketId;
7110 const char* kString1 = "happy";
7111 const char* kString2 = "ending";
7112 const size_t kString1Size = ::strlen(kString1) + 1;
7113 const size_t kString2Size = ::strlen(kString2) + 1;
7114 const size_t kHeaderSize = sizeof(GLint) * 3;
7115 const size_t kSourceSize = kHeaderSize + kString1Size + kString2Size;
7116 const size_t kPaddedHeaderSize =
7117 transfer_buffer_->RoundToAlignment(kHeaderSize);
7118 const size_t kPaddedString1Size =
7119 transfer_buffer_->RoundToAlignment(kString1Size);
7120 const size_t kPaddedString2Size =
7121 transfer_buffer_->RoundToAlignment(kString2Size);
7122 struct Cmds {
7123 cmd::SetBucketSize set_bucket_size;
7124 cmd::SetBucketData set_bucket_header;
7125 cmd::SetToken set_token1;
7126 cmd::SetBucketData set_bucket_data1;
7127 cmd::SetToken set_token2;
7128 cmd::SetBucketData set_bucket_data2;
7129 cmd::SetToken set_token3;
7130 cmds::%(name)sBucket cmd_bucket;
7131 cmd::SetBucketSize clear_bucket_size;
7134 ExpectedMemoryInfo mem0 = GetExpectedMemory(kPaddedHeaderSize);
7135 ExpectedMemoryInfo mem1 = GetExpectedMemory(kPaddedString1Size);
7136 ExpectedMemoryInfo mem2 = GetExpectedMemory(kPaddedString2Size);
7138 Cmds expected;
7139 expected.set_bucket_size.Init(kBucketId, kSourceSize);
7140 expected.set_bucket_header.Init(
7141 kBucketId, 0, kHeaderSize, mem0.id, mem0.offset);
7142 expected.set_token1.Init(GetNextToken());
7143 expected.set_bucket_data1.Init(
7144 kBucketId, kHeaderSize, kString1Size, mem1.id, mem1.offset);
7145 expected.set_token2.Init(GetNextToken());
7146 expected.set_bucket_data2.Init(
7147 kBucketId, kHeaderSize + kString1Size, kString2Size, mem2.id,
7148 mem2.offset);
7149 expected.set_token3.Init(GetNextToken());
7150 expected.cmd_bucket.Init(%(bucket_args)s);
7151 expected.clear_bucket_size.Init(kBucketId, 0);
7152 const char* kStrings[] = { kString1, kString2 };
7153 gl_->%(name)s(%(gl_args)s);
7154 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
7157 gl_args = []
7158 bucket_args = []
7159 for arg in func.GetOriginalArgs():
7160 if arg == self.__GetDataArg(func):
7161 gl_args.append('kStrings')
7162 bucket_args.append('kBucketId')
7163 elif arg == self.__GetLengthArg(func):
7164 gl_args.append('NULL')
7165 elif arg.name == 'count':
7166 gl_args.append('2')
7167 else:
7168 gl_args.append(arg.GetValidClientSideArg(func))
7169 bucket_args.append(arg.GetValidClientSideArg(func))
7170 file.Write(code % {
7171 'name': func.name,
7172 'gl_args': ", ".join(gl_args),
7173 'bucket_args': ", ".join(bucket_args),
7176 if self.__GetLengthArg(func) == None:
7177 return
7178 code = """
7179 TEST_F(GLES2ImplementationTest, %(name)sWithLength) {
7180 const uint32 kBucketId = GLES2Implementation::kResultBucketId;
7181 const char* kString = "foobar******";
7182 const size_t kStringSize = 6; // We only need "foobar".
7183 const size_t kHeaderSize = sizeof(GLint) * 2;
7184 const size_t kSourceSize = kHeaderSize + kStringSize + 1;
7185 const size_t kPaddedHeaderSize =
7186 transfer_buffer_->RoundToAlignment(kHeaderSize);
7187 const size_t kPaddedStringSize =
7188 transfer_buffer_->RoundToAlignment(kStringSize + 1);
7189 struct Cmds {
7190 cmd::SetBucketSize set_bucket_size;
7191 cmd::SetBucketData set_bucket_header;
7192 cmd::SetToken set_token1;
7193 cmd::SetBucketData set_bucket_data;
7194 cmd::SetToken set_token2;
7195 cmds::ShaderSourceBucket shader_source_bucket;
7196 cmd::SetBucketSize clear_bucket_size;
7199 ExpectedMemoryInfo mem0 = GetExpectedMemory(kPaddedHeaderSize);
7200 ExpectedMemoryInfo mem1 = GetExpectedMemory(kPaddedStringSize);
7202 Cmds expected;
7203 expected.set_bucket_size.Init(kBucketId, kSourceSize);
7204 expected.set_bucket_header.Init(
7205 kBucketId, 0, kHeaderSize, mem0.id, mem0.offset);
7206 expected.set_token1.Init(GetNextToken());
7207 expected.set_bucket_data.Init(
7208 kBucketId, kHeaderSize, kStringSize + 1, mem1.id, mem1.offset);
7209 expected.set_token2.Init(GetNextToken());
7210 expected.shader_source_bucket.Init(%(bucket_args)s);
7211 expected.clear_bucket_size.Init(kBucketId, 0);
7212 const char* kStrings[] = { kString };
7213 const GLint kLength[] = { kStringSize };
7214 gl_->%(name)s(%(gl_args)s);
7215 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
7218 gl_args = []
7219 for arg in func.GetOriginalArgs():
7220 if arg == self.__GetDataArg(func):
7221 gl_args.append('kStrings')
7222 elif arg == self.__GetLengthArg(func):
7223 gl_args.append('kLength')
7224 elif arg.name == 'count':
7225 gl_args.append('1')
7226 else:
7227 gl_args.append(arg.GetValidClientSideArg(func))
7228 file.Write(code % {
7229 'name': func.name,
7230 'gl_args': ", ".join(gl_args),
7231 'bucket_args': ", ".join(bucket_args),
7234 def WriteBucketServiceUnitTest(self, func, file, *extras):
7235 """Overrriden from TypeHandler."""
7236 cmd_args = []
7237 cmd_args_with_invalid_id = []
7238 gl_args = []
7239 for index, arg in enumerate(func.GetOriginalArgs()):
7240 if arg == self.__GetLengthArg(func):
7241 gl_args.append('_')
7242 elif arg.name == 'count':
7243 gl_args.append('1')
7244 elif arg == self.__GetDataArg(func):
7245 cmd_args.append('kBucketId')
7246 cmd_args_with_invalid_id.append('kBucketId')
7247 gl_args.append('_')
7248 elif index == 0: # Resource ID arg
7249 cmd_args.append(arg.GetValidArg(func))
7250 cmd_args_with_invalid_id.append('kInvalidClientId')
7251 gl_args.append(arg.GetValidGLArg(func))
7252 else:
7253 cmd_args.append(arg.GetValidArg(func))
7254 cmd_args_with_invalid_id.append(arg.GetValidArg(func))
7255 gl_args.append(arg.GetValidGLArg(func))
7257 test = """
7258 TEST_P(%(test_name)s, %(name)sValidArgs) {
7259 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
7260 const uint32 kBucketId = 123;
7261 const char kSource0[] = "hello";
7262 const char* kSource[] = { kSource0 };
7263 const char kValidStrEnd = 0;
7264 SetBucketAsCStrings(kBucketId, 1, kSource, 1, kValidStrEnd);
7265 cmds::%(name)s cmd;
7266 cmd.Init(%(cmd_args)s);
7267 decoder_->set_unsafe_es3_apis_enabled(true);
7268 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));"""
7269 if func.IsUnsafe():
7270 test += """
7271 decoder_->set_unsafe_es3_apis_enabled(false);
7272 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));
7274 test += """
7277 self.WriteValidUnitTest(func, file, test, {
7278 'cmd_args': ", ".join(cmd_args),
7279 'gl_args': ", ".join(gl_args),
7280 }, *extras)
7282 test = """
7283 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
7284 const uint32 kBucketId = 123;
7285 const char kSource0[] = "hello";
7286 const char* kSource[] = { kSource0 };
7287 const char kValidStrEnd = 0;
7288 decoder_->set_unsafe_es3_apis_enabled(true);
7289 cmds::%(name)s cmd;
7290 // Test no bucket.
7291 cmd.Init(%(cmd_args)s);
7292 EXPECT_NE(error::kNoError, ExecuteCmd(cmd));
7293 // Test invalid client.
7294 SetBucketAsCStrings(kBucketId, 1, kSource, 1, kValidStrEnd);
7295 cmd.Init(%(cmd_args_with_invalid_id)s);
7296 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
7297 EXPECT_EQ(GL_INVALID_VALUE, GetGLError());
7300 self.WriteValidUnitTest(func, file, test, {
7301 'cmd_args': ", ".join(cmd_args),
7302 'cmd_args_with_invalid_id': ", ".join(cmd_args_with_invalid_id),
7303 }, *extras)
7305 test = """
7306 TEST_P(%(test_name)s, %(name)sInvalidHeader) {
7307 const uint32 kBucketId = 123;
7308 const char kSource0[] = "hello";
7309 const char* kSource[] = { kSource0 };
7310 const char kValidStrEnd = 0;
7311 const GLsizei kCount = static_cast<GLsizei>(arraysize(kSource));
7312 const GLsizei kTests[] = {
7313 kCount + 1,
7315 std::numeric_limits<GLsizei>::max(),
7318 decoder_->set_unsafe_es3_apis_enabled(true);
7319 for (size_t ii = 0; ii < arraysize(kTests); ++ii) {
7320 SetBucketAsCStrings(kBucketId, 1, kSource, kTests[ii], kValidStrEnd);
7321 cmds::%(name)s cmd;
7322 cmd.Init(%(cmd_args)s);
7323 EXPECT_EQ(error::kInvalidArguments, ExecuteCmd(cmd));
7327 self.WriteValidUnitTest(func, file, test, {
7328 'cmd_args': ", ".join(cmd_args),
7329 }, *extras)
7331 test = """
7332 TEST_P(%(test_name)s, %(name)sInvalidStringEnding) {
7333 const uint32 kBucketId = 123;
7334 const char kSource0[] = "hello";
7335 const char* kSource[] = { kSource0 };
7336 const char kInvalidStrEnd = '*';
7337 SetBucketAsCStrings(kBucketId, 1, kSource, 1, kInvalidStrEnd);
7338 cmds::%(name)s cmd;
7339 cmd.Init(%(cmd_args)s);
7340 decoder_->set_unsafe_es3_apis_enabled(true);
7341 EXPECT_EQ(error::kInvalidArguments, ExecuteCmd(cmd));
7344 self.WriteValidUnitTest(func, file, test, {
7345 'cmd_args': ", ".join(cmd_args),
7346 }, *extras)
7349 class PUTXnHandler(ArrayArgTypeHandler):
7350 """Handler for glUniform?f functions."""
7351 def __init__(self):
7352 ArrayArgTypeHandler.__init__(self)
7354 def WriteHandlerImplementation(self, func, file):
7355 """Overrriden from TypeHandler."""
7356 code = """ %(type)s temp[%(count)s] = { %(values)s};"""
7357 if func.IsUnsafe():
7358 code += """
7359 gl%(name)sv(%(location)s, 1, &temp[0]);
7361 else:
7362 code += """
7363 Do%(name)sv(%(location)s, 1, &temp[0]);
7365 values = ""
7366 args = func.GetOriginalArgs()
7367 count = int(self.GetArrayCount(func))
7368 num_args = len(args)
7369 for ii in range(count):
7370 values += "%s, " % args[len(args) - count + ii].name
7372 file.Write(code % {
7373 'name': func.name,
7374 'count': self.GetArrayCount(func),
7375 'type': self.GetArrayType(func),
7376 'location': args[0].name,
7377 'args': func.MakeOriginalArgString(""),
7378 'values': values,
7381 def WriteServiceUnitTest(self, func, file, *extras):
7382 """Overrriden from TypeHandler."""
7383 valid_test = """
7384 TEST_P(%(test_name)s, %(name)sValidArgs) {
7385 EXPECT_CALL(*gl_, %(name)sv(%(local_args)s));
7386 SpecializedSetup<cmds::%(name)s, 0>(true);
7387 cmds::%(name)s cmd;
7388 cmd.Init(%(args)s);"""
7389 if func.IsUnsafe():
7390 valid_test += """
7391 decoder_->set_unsafe_es3_apis_enabled(true);"""
7392 valid_test += """
7393 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
7394 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
7395 if func.IsUnsafe():
7396 valid_test += """
7397 decoder_->set_unsafe_es3_apis_enabled(false);
7398 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));"""
7399 valid_test += """
7402 args = func.GetOriginalArgs()
7403 local_args = "%s, 1, _" % args[0].GetValidGLArg(func)
7404 self.WriteValidUnitTest(func, file, valid_test, {
7405 'name': func.name,
7406 'count': self.GetArrayCount(func),
7407 'local_args': local_args,
7408 }, *extras)
7410 invalid_test = """
7411 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
7412 EXPECT_CALL(*gl_, %(name)sv(_, _, _).Times(0);
7413 SpecializedSetup<cmds::%(name)s, 0>(false);
7414 cmds::%(name)s cmd;
7415 cmd.Init(%(args)s);
7416 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
7419 self.WriteInvalidUnitTest(func, file, invalid_test, {
7420 'name': func.GetInfo('name'),
7421 'count': self.GetArrayCount(func),
7425 class GLcharHandler(CustomHandler):
7426 """Handler for functions that pass a single string ."""
7428 def __init__(self):
7429 CustomHandler.__init__(self)
7431 def WriteImmediateCmdComputeSize(self, func, file):
7432 """Overrriden from TypeHandler."""
7433 file.Write(" static uint32_t ComputeSize(uint32_t data_size) {\n")
7434 file.Write(" return static_cast<uint32_t>(\n")
7435 file.Write(" sizeof(ValueType) + data_size); // NOLINT\n")
7436 file.Write(" }\n")
7438 def WriteImmediateCmdSetHeader(self, func, file):
7439 """Overrriden from TypeHandler."""
7440 code = """
7441 void SetHeader(uint32_t data_size) {
7442 header.SetCmdBySize<ValueType>(data_size);
7445 file.Write(code)
7447 def WriteImmediateCmdInit(self, func, file):
7448 """Overrriden from TypeHandler."""
7449 last_arg = func.GetLastOriginalArg()
7450 args = func.GetCmdArgs()
7451 set_code = []
7452 for arg in args:
7453 set_code.append(" %s = _%s;" % (arg.name, arg.name))
7454 code = """
7455 void Init(%(typed_args)s, uint32_t _data_size) {
7456 SetHeader(_data_size);
7457 %(set_code)s
7458 memcpy(ImmediateDataAddress(this), _%(last_arg)s, _data_size);
7462 file.Write(code % {
7463 "typed_args": func.MakeTypedArgString("_"),
7464 "set_code": "\n".join(set_code),
7465 "last_arg": last_arg.name
7468 def WriteImmediateCmdSet(self, func, file):
7469 """Overrriden from TypeHandler."""
7470 last_arg = func.GetLastOriginalArg()
7471 file.Write(" void* Set(void* cmd%s, uint32_t _data_size) {\n" %
7472 func.MakeTypedCmdArgString("_", True))
7473 file.Write(" static_cast<ValueType*>(cmd)->Init(%s, _data_size);\n" %
7474 func.MakeCmdArgString("_"))
7475 file.Write(" return NextImmediateCmdAddress<ValueType>("
7476 "cmd, _data_size);\n")
7477 file.Write(" }\n")
7478 file.Write("\n")
7480 def WriteImmediateCmdHelper(self, func, file):
7481 """Overrriden from TypeHandler."""
7482 code = """ void %(name)s(%(typed_args)s) {
7483 const uint32_t data_size = strlen(name);
7484 gles2::cmds::%(name)s* c =
7485 GetImmediateCmdSpace<gles2::cmds::%(name)s>(data_size);
7486 if (c) {
7487 c->Init(%(args)s, data_size);
7492 file.Write(code % {
7493 "name": func.name,
7494 "typed_args": func.MakeTypedOriginalArgString(""),
7495 "args": func.MakeOriginalArgString(""),
7499 def WriteImmediateFormatTest(self, func, file):
7500 """Overrriden from TypeHandler."""
7501 init_code = []
7502 check_code = []
7503 all_but_last_arg = func.GetCmdArgs()[:-1]
7504 for value, arg in enumerate(all_but_last_arg):
7505 init_code.append(" static_cast<%s>(%d)," % (arg.type, value + 11))
7506 for value, arg in enumerate(all_but_last_arg):
7507 check_code.append(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);" %
7508 (arg.type, value + 11, arg.name))
7509 code = """
7510 TEST_F(GLES2FormatTest, %(func_name)s) {
7511 cmds::%(func_name)s& cmd = *GetBufferAs<cmds::%(func_name)s>();
7512 static const char* const test_str = \"test string\";
7513 void* next_cmd = cmd.Set(
7514 &cmd,
7515 %(init_code)s
7516 test_str,
7517 strlen(test_str));
7518 EXPECT_EQ(static_cast<uint32_t>(cmds::%(func_name)s::kCmdId),
7519 cmd.header.command);
7520 EXPECT_EQ(sizeof(cmd) +
7521 RoundSizeToMultipleOfEntries(strlen(test_str)),
7522 cmd.header.size * 4u);
7523 EXPECT_EQ(static_cast<char*>(next_cmd),
7524 reinterpret_cast<char*>(&cmd) + sizeof(cmd) +
7525 RoundSizeToMultipleOfEntries(strlen(test_str)));
7526 %(check_code)s
7527 EXPECT_EQ(static_cast<uint32_t>(strlen(test_str)), cmd.data_size);
7528 EXPECT_EQ(0, memcmp(test_str, ImmediateDataAddress(&cmd), strlen(test_str)));
7529 CheckBytesWritten(
7530 next_cmd,
7531 sizeof(cmd) + RoundSizeToMultipleOfEntries(strlen(test_str)),
7532 sizeof(cmd) + strlen(test_str));
7536 file.Write(code % {
7537 'func_name': func.name,
7538 'init_code': "\n".join(init_code),
7539 'check_code': "\n".join(check_code),
7543 class GLcharNHandler(CustomHandler):
7544 """Handler for functions that pass a single string with an optional len."""
7546 def __init__(self):
7547 CustomHandler.__init__(self)
7549 def InitFunction(self, func):
7550 """Overrriden from TypeHandler."""
7551 func.cmd_args = []
7552 func.AddCmdArg(Argument('bucket_id', 'GLuint'))
7554 def NeedsDataTransferFunction(self, func):
7555 """Overriden from TypeHandler."""
7556 return False
7558 def AddBucketFunction(self, generator, func):
7559 """Overrriden from TypeHandler."""
7560 pass
7562 def WriteServiceImplementation(self, func, file):
7563 """Overrriden from TypeHandler."""
7564 self.WriteServiceHandlerFunctionHeader(func, file)
7565 file.Write("""
7566 GLuint bucket_id = static_cast<GLuint>(c.%(bucket_id)s);
7567 Bucket* bucket = GetBucket(bucket_id);
7568 if (!bucket || bucket->size() == 0) {
7569 return error::kInvalidArguments;
7571 std::string str;
7572 if (!bucket->GetAsString(&str)) {
7573 return error::kInvalidArguments;
7575 %(gl_func_name)s(0, str.c_str());
7576 return error::kNoError;
7579 """ % {
7580 'name': func.name,
7581 'gl_func_name': func.GetGLFunctionName(),
7582 'bucket_id': func.cmd_args[0].name,
7586 class IsHandler(TypeHandler):
7587 """Handler for glIs____ type and glGetError functions."""
7589 def __init__(self):
7590 TypeHandler.__init__(self)
7592 def InitFunction(self, func):
7593 """Overrriden from TypeHandler."""
7594 func.AddCmdArg(Argument("result_shm_id", 'uint32_t'))
7595 func.AddCmdArg(Argument("result_shm_offset", 'uint32_t'))
7596 if func.GetInfo('result') == None:
7597 func.AddInfo('result', ['uint32_t'])
7599 def WriteServiceUnitTest(self, func, file, *extras):
7600 """Overrriden from TypeHandler."""
7601 valid_test = """
7602 TEST_P(%(test_name)s, %(name)sValidArgs) {
7603 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
7604 SpecializedSetup<cmds::%(name)s, 0>(true);
7605 cmds::%(name)s cmd;
7606 cmd.Init(%(args)s%(comma)sshared_memory_id_, shared_memory_offset_);"""
7607 if func.IsUnsafe():
7608 valid_test += """
7609 decoder_->set_unsafe_es3_apis_enabled(true);"""
7610 valid_test += """
7611 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
7612 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
7613 if func.IsUnsafe():
7614 valid_test += """
7615 decoder_->set_unsafe_es3_apis_enabled(false);
7616 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));"""
7617 valid_test += """
7620 comma = ""
7621 if len(func.GetOriginalArgs()):
7622 comma =", "
7623 self.WriteValidUnitTest(func, file, valid_test, {
7624 'comma': comma,
7625 }, *extras)
7627 invalid_test = """
7628 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
7629 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
7630 SpecializedSetup<cmds::%(name)s, 0>(false);
7631 cmds::%(name)s cmd;
7632 cmd.Init(%(args)s%(comma)sshared_memory_id_, shared_memory_offset_);
7633 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
7636 self.WriteInvalidUnitTest(func, file, invalid_test, {
7637 'comma': comma,
7638 }, *extras)
7640 invalid_test = """
7641 TEST_P(%(test_name)s, %(name)sInvalidArgsBadSharedMemoryId) {
7642 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
7643 SpecializedSetup<cmds::%(name)s, 0>(false);"""
7644 if func.IsUnsafe():
7645 invalid_test += """
7646 decoder_->set_unsafe_es3_apis_enabled(true);"""
7647 invalid_test += """
7648 cmds::%(name)s cmd;
7649 cmd.Init(%(args)s%(comma)skInvalidSharedMemoryId, shared_memory_offset_);
7650 EXPECT_EQ(error::kOutOfBounds, ExecuteCmd(cmd));
7651 cmd.Init(%(args)s%(comma)sshared_memory_id_, kInvalidSharedMemoryOffset);
7652 EXPECT_EQ(error::kOutOfBounds, ExecuteCmd(cmd));"""
7653 if func.IsUnsafe():
7654 invalid_test += """
7655 decoder_->set_unsafe_es3_apis_enabled(true);"""
7656 invalid_test += """
7659 self.WriteValidUnitTest(func, file, invalid_test, {
7660 'comma': comma,
7661 }, *extras)
7663 def WriteServiceImplementation(self, func, file):
7664 """Overrriden from TypeHandler."""
7665 self.WriteServiceHandlerFunctionHeader(func, file)
7666 args = func.GetOriginalArgs()
7667 for arg in args:
7668 arg.WriteGetCode(file)
7670 code = """ typedef cmds::%(func_name)s::Result Result;
7671 Result* result_dst = GetSharedMemoryAs<Result*>(
7672 c.result_shm_id, c.result_shm_offset, sizeof(*result_dst));
7673 if (!result_dst) {
7674 return error::kOutOfBounds;
7677 file.Write(code % {'func_name': func.name})
7678 func.WriteHandlerValidation(file)
7679 if func.IsUnsafe():
7680 assert func.GetInfo('id_mapping')
7681 assert len(func.GetInfo('id_mapping')) == 1
7682 assert len(args) == 1
7683 id_type = func.GetInfo('id_mapping')[0]
7684 file.Write(" %s service_%s = 0;\n" % (args[0].type, id_type.lower()))
7685 file.Write(" *result_dst = group_->Get%sServiceId(%s, &service_%s);\n" %
7686 (id_type, id_type.lower(), id_type.lower()))
7687 else:
7688 file.Write(" *result_dst = %s(%s);\n" %
7689 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
7690 file.Write(" return error::kNoError;\n")
7691 file.Write("}\n")
7692 file.Write("\n")
7694 def WriteGLES2Implementation(self, func, file):
7695 """Overrriden from TypeHandler."""
7696 impl_func = func.GetInfo('impl_func')
7697 if impl_func == None or impl_func == True:
7698 error_value = func.GetInfo("error_value") or "GL_FALSE"
7699 file.Write("%s GLES2Implementation::%s(%s) {\n" %
7700 (func.return_type, func.original_name,
7701 func.MakeTypedOriginalArgString("")))
7702 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
7703 self.WriteTraceEvent(func, file)
7704 func.WriteDestinationInitalizationValidation(file)
7705 self.WriteClientGLCallLog(func, file)
7706 file.Write(" typedef cmds::%s::Result Result;\n" % func.name)
7707 file.Write(" Result* result = GetResultAs<Result*>();\n")
7708 file.Write(" if (!result) {\n")
7709 file.Write(" return %s;\n" % error_value)
7710 file.Write(" }\n")
7711 file.Write(" *result = 0;\n")
7712 assert len(func.GetOriginalArgs()) == 1
7713 id_arg = func.GetOriginalArgs()[0]
7714 if id_arg.type == 'GLsync':
7715 arg_string = "ToGLuint(%s)" % func.MakeOriginalArgString("")
7716 else:
7717 arg_string = func.MakeOriginalArgString("")
7718 file.Write(
7719 " helper_->%s(%s, GetResultShmId(), GetResultShmOffset());\n" %
7720 (func.name, arg_string))
7721 file.Write(" WaitForCmd();\n")
7722 file.Write(" %s result_value = *result" % func.return_type)
7723 if func.return_type == "GLboolean":
7724 file.Write(" != 0")
7725 file.Write(';\n GPU_CLIENT_LOG("returned " << result_value);\n')
7726 file.Write(" CheckGLError();\n")
7727 file.Write(" return result_value;\n")
7728 file.Write("}\n")
7729 file.Write("\n")
7731 def WriteGLES2ImplementationUnitTest(self, func, file):
7732 """Overrriden from TypeHandler."""
7733 client_test = func.GetInfo('client_test')
7734 if client_test == None or client_test == True:
7735 code = """
7736 TEST_F(GLES2ImplementationTest, %(name)s) {
7737 struct Cmds {
7738 cmds::%(name)s cmd;
7741 Cmds expected;
7742 ExpectedMemoryInfo result1 =
7743 GetExpectedResultMemory(sizeof(cmds::%(name)s::Result));
7744 expected.cmd.Init(%(cmd_id_value)s, result1.id, result1.offset);
7746 EXPECT_CALL(*command_buffer(), OnFlush())
7747 .WillOnce(SetMemory(result1.ptr, uint32_t(GL_TRUE)))
7748 .RetiresOnSaturation();
7750 GLboolean result = gl_->%(name)s(%(gl_id_value)s);
7751 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
7752 EXPECT_TRUE(result);
7755 args = func.GetOriginalArgs()
7756 assert len(args) == 1
7757 file.Write(code % {
7758 'name': func.name,
7759 'cmd_id_value': args[0].GetValidClientSideCmdArg(func),
7760 'gl_id_value': args[0].GetValidClientSideArg(func) })
7763 class STRnHandler(TypeHandler):
7764 """Handler for GetProgramInfoLog, GetShaderInfoLog, GetShaderSource, and
7765 GetTranslatedShaderSourceANGLE."""
7767 def __init__(self):
7768 TypeHandler.__init__(self)
7770 def InitFunction(self, func):
7771 """Overrriden from TypeHandler."""
7772 # remove all but the first cmd args.
7773 cmd_args = func.GetCmdArgs()
7774 func.ClearCmdArgs()
7775 func.AddCmdArg(cmd_args[0])
7776 # add on a bucket id.
7777 func.AddCmdArg(Argument('bucket_id', 'uint32_t'))
7779 def WriteGLES2Implementation(self, func, file):
7780 """Overrriden from TypeHandler."""
7781 code_1 = """%(return_type)s GLES2Implementation::%(func_name)s(%(args)s) {
7782 GPU_CLIENT_SINGLE_THREAD_CHECK();
7784 code_2 = """ GPU_CLIENT_LOG("[" << GetLogPrefix()
7785 << "] gl%(func_name)s" << "("
7786 << %(arg0)s << ", "
7787 << %(arg1)s << ", "
7788 << static_cast<void*>(%(arg2)s) << ", "
7789 << static_cast<void*>(%(arg3)s) << ")");
7790 helper_->SetBucketSize(kResultBucketId, 0);
7791 helper_->%(func_name)s(%(id_name)s, kResultBucketId);
7792 std::string str;
7793 GLsizei max_size = 0;
7794 if (GetBucketAsString(kResultBucketId, &str)) {
7795 if (bufsize > 0) {
7796 max_size =
7797 std::min(static_cast<size_t>(%(bufsize_name)s) - 1, str.size());
7798 memcpy(%(dest_name)s, str.c_str(), max_size);
7799 %(dest_name)s[max_size] = '\\0';
7800 GPU_CLIENT_LOG("------\\n" << %(dest_name)s << "\\n------");
7803 if (%(length_name)s != NULL) {
7804 *%(length_name)s = max_size;
7806 CheckGLError();
7809 args = func.GetOriginalArgs()
7810 str_args = {
7811 'return_type': func.return_type,
7812 'func_name': func.original_name,
7813 'args': func.MakeTypedOriginalArgString(""),
7814 'id_name': args[0].name,
7815 'bufsize_name': args[1].name,
7816 'length_name': args[2].name,
7817 'dest_name': args[3].name,
7818 'arg0': args[0].name,
7819 'arg1': args[1].name,
7820 'arg2': args[2].name,
7821 'arg3': args[3].name,
7823 file.Write(code_1 % str_args)
7824 func.WriteDestinationInitalizationValidation(file)
7825 file.Write(code_2 % str_args)
7827 def WriteServiceUnitTest(self, func, file, *extras):
7828 """Overrriden from TypeHandler."""
7829 valid_test = """
7830 TEST_P(%(test_name)s, %(name)sValidArgs) {
7831 const char* kInfo = "hello";
7832 const uint32_t kBucketId = 123;
7833 SpecializedSetup<cmds::%(name)s, 0>(true);
7834 %(expect_len_code)s
7835 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s))
7836 .WillOnce(DoAll(SetArgumentPointee<2>(strlen(kInfo)),
7837 SetArrayArgument<3>(kInfo, kInfo + strlen(kInfo) + 1)));
7838 cmds::%(name)s cmd;
7839 cmd.Init(%(args)s);
7840 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
7841 CommonDecoder::Bucket* bucket = decoder_->GetBucket(kBucketId);
7842 ASSERT_TRUE(bucket != NULL);
7843 EXPECT_EQ(strlen(kInfo) + 1, bucket->size());
7844 EXPECT_EQ(0, memcmp(bucket->GetData(0, bucket->size()), kInfo,
7845 bucket->size()));
7846 EXPECT_EQ(GL_NO_ERROR, GetGLError());
7849 args = func.GetOriginalArgs()
7850 id_name = args[0].GetValidGLArg(func)
7851 get_len_func = func.GetInfo('get_len_func')
7852 get_len_enum = func.GetInfo('get_len_enum')
7853 sub = {
7854 'id_name': id_name,
7855 'get_len_func': get_len_func,
7856 'get_len_enum': get_len_enum,
7857 'gl_args': '%s, strlen(kInfo) + 1, _, _' %
7858 args[0].GetValidGLArg(func),
7859 'args': '%s, kBucketId' % args[0].GetValidArg(func),
7860 'expect_len_code': '',
7862 if get_len_func and get_len_func[0:2] == 'gl':
7863 sub['expect_len_code'] = (
7864 " EXPECT_CALL(*gl_, %s(%s, %s, _))\n"
7865 " .WillOnce(SetArgumentPointee<2>(strlen(kInfo) + 1));") % (
7866 get_len_func[2:], id_name, get_len_enum)
7867 self.WriteValidUnitTest(func, file, valid_test, sub, *extras)
7869 invalid_test = """
7870 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
7871 const uint32_t kBucketId = 123;
7872 EXPECT_CALL(*gl_, %(gl_func_name)s(_, _, _, _))
7873 .Times(0);
7874 cmds::%(name)s cmd;
7875 cmd.Init(kInvalidClientId, kBucketId);
7876 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
7877 EXPECT_EQ(GL_INVALID_VALUE, GetGLError());
7880 self.WriteValidUnitTest(func, file, invalid_test, *extras)
7882 def WriteServiceImplementation(self, func, file):
7883 """Overrriden from TypeHandler."""
7884 pass
7886 class NamedType(object):
7887 """A class that represents a type of an argument in a client function.
7889 A type of an argument that is to be passed through in the command buffer
7890 command. Currently used only for the arguments that are specificly named in
7891 the 'cmd_buffer_functions.txt' file, mostly enums.
7894 def __init__(self, info):
7895 assert not 'is_complete' in info or info['is_complete'] == True
7896 self.info = info
7897 self.valid = info['valid']
7898 if 'invalid' in info:
7899 self.invalid = info['invalid']
7900 else:
7901 self.invalid = []
7902 if 'valid_es3' in info:
7903 self.valid_es3 = info['valid_es3']
7904 else:
7905 self.valid_es3 = []
7906 if 'deprecated_es3' in info:
7907 self.deprecated_es3 = info['deprecated_es3']
7908 else:
7909 self.deprecated_es3 = []
7911 def GetType(self):
7912 return self.info['type']
7914 def GetInvalidValues(self):
7915 return self.invalid
7917 def GetValidValues(self):
7918 return self.valid
7920 def GetValidValuesES3(self):
7921 return self.valid_es3
7923 def GetDeprecatedValuesES3(self):
7924 return self.deprecated_es3
7926 def IsConstant(self):
7927 if not 'is_complete' in self.info:
7928 return False
7930 return len(self.GetValidValues()) == 1
7932 def GetConstantValue(self):
7933 return self.GetValidValues()[0]
7935 class Argument(object):
7936 """A class that represents a function argument."""
7938 cmd_type_map_ = {
7939 'GLenum': 'uint32_t',
7940 'GLint': 'int32_t',
7941 'GLintptr': 'int32_t',
7942 'GLsizei': 'int32_t',
7943 'GLsizeiptr': 'int32_t',
7944 'GLfloat': 'float',
7945 'GLclampf': 'float',
7947 need_validation_ = ['GLsizei*', 'GLboolean*', 'GLenum*', 'GLint*']
7949 def __init__(self, name, type):
7950 self.name = name
7951 self.optional = type.endswith("Optional*")
7952 if self.optional:
7953 type = type[:-9] + "*"
7954 self.type = type
7956 if type in self.cmd_type_map_:
7957 self.cmd_type = self.cmd_type_map_[type]
7958 else:
7959 self.cmd_type = 'uint32_t'
7961 def IsPointer(self):
7962 """Returns true if argument is a pointer."""
7963 return False
7965 def IsPointer2D(self):
7966 """Returns true if argument is a 2D pointer."""
7967 return False
7969 def IsConstant(self):
7970 """Returns true if the argument has only one valid value."""
7971 return False
7973 def AddCmdArgs(self, args):
7974 """Adds command arguments for this argument to the given list."""
7975 if not self.IsConstant():
7976 return args.append(self)
7978 def AddInitArgs(self, args):
7979 """Adds init arguments for this argument to the given list."""
7980 if not self.IsConstant():
7981 return args.append(self)
7983 def GetValidArg(self, func):
7984 """Gets a valid value for this argument."""
7985 valid_arg = func.GetValidArg(self)
7986 if valid_arg != None:
7987 return valid_arg
7989 index = func.GetOriginalArgs().index(self)
7990 return str(index + 1)
7992 def GetValidClientSideArg(self, func):
7993 """Gets a valid value for this argument."""
7994 valid_arg = func.GetValidArg(self)
7995 if valid_arg != None:
7996 return valid_arg
7998 if self.IsPointer():
7999 return 'nullptr'
8000 index = func.GetOriginalArgs().index(self)
8001 if self.type == 'GLsync':
8002 return ("reinterpret_cast<GLsync>(%d)" % (index + 1))
8003 return str(index + 1)
8005 def GetValidClientSideCmdArg(self, func):
8006 """Gets a valid value for this argument."""
8007 valid_arg = func.GetValidArg(self)
8008 if valid_arg != None:
8009 return valid_arg
8010 try:
8011 index = func.GetOriginalArgs().index(self)
8012 return str(index + 1)
8013 except ValueError:
8014 pass
8015 index = func.GetCmdArgs().index(self)
8016 return str(index + 1)
8018 def GetValidGLArg(self, func):
8019 """Gets a valid GL value for this argument."""
8020 value = self.GetValidArg(func)
8021 if self.type == 'GLsync':
8022 return ("reinterpret_cast<GLsync>(%s)" % value)
8023 return value
8025 def GetValidNonCachedClientSideArg(self, func):
8026 """Returns a valid value for this argument in a GL call.
8027 Using the value will produce a command buffer service invocation.
8028 Returns None if there is no such value."""
8029 value = '123'
8030 if self.type == 'GLsync':
8031 return ("reinterpret_cast<GLsync>(%s)" % value)
8032 return value
8034 def GetValidNonCachedClientSideCmdArg(self, func):
8035 """Returns a valid value for this argument in a command buffer command.
8036 Calling the GL function with the value returned by
8037 GetValidNonCachedClientSideArg will result in a command buffer command
8038 that contains the value returned by this function. """
8039 return '123'
8041 def GetNumInvalidValues(self, func):
8042 """returns the number of invalid values to be tested."""
8043 return 0
8045 def GetInvalidArg(self, index):
8046 """returns an invalid value and expected parse result by index."""
8047 return ("---ERROR0---", "---ERROR2---", None)
8049 def GetLogArg(self):
8050 """Get argument appropriate for LOG macro."""
8051 if self.type == 'GLboolean':
8052 return 'GLES2Util::GetStringBool(%s)' % self.name
8053 if self.type == 'GLenum':
8054 return 'GLES2Util::GetStringEnum(%s)' % self.name
8055 return self.name
8057 def WriteGetCode(self, file):
8058 """Writes the code to get an argument from a command structure."""
8059 if self.type == 'GLsync':
8060 my_type = 'GLuint'
8061 else:
8062 my_type = self.type
8063 file.Write(" %s %s = static_cast<%s>(c.%s);\n" %
8064 (my_type, self.name, my_type, self.name))
8066 def WriteValidationCode(self, file, func):
8067 """Writes the validation code for an argument."""
8068 pass
8070 def WriteClientSideValidationCode(self, file, func):
8071 """Writes the validation code for an argument."""
8072 pass
8074 def WriteDestinationInitalizationValidation(self, file, func):
8075 """Writes the client side destintion initialization validation."""
8076 pass
8078 def WriteDestinationInitalizationValidatationIfNeeded(self, file, func):
8079 """Writes the client side destintion initialization validation if needed."""
8080 parts = self.type.split(" ")
8081 if len(parts) > 1:
8082 return
8083 if parts[0] in self.need_validation_:
8084 file.Write(
8085 " GPU_CLIENT_VALIDATE_DESTINATION_%sINITALIZATION(%s, %s);\n" %
8086 ("OPTIONAL_" if self.optional else "", self.type[:-1], self.name))
8089 def WriteGetAddress(self, file):
8090 """Writes the code to get the address this argument refers to."""
8091 pass
8093 def GetImmediateVersion(self):
8094 """Gets the immediate version of this argument."""
8095 return self
8097 def GetBucketVersion(self):
8098 """Gets the bucket version of this argument."""
8099 return self
8102 class BoolArgument(Argument):
8103 """class for GLboolean"""
8105 def __init__(self, name, type):
8106 Argument.__init__(self, name, 'GLboolean')
8108 def GetValidArg(self, func):
8109 """Gets a valid value for this argument."""
8110 return 'true'
8112 def GetValidClientSideArg(self, func):
8113 """Gets a valid value for this argument."""
8114 return 'true'
8116 def GetValidClientSideCmdArg(self, func):
8117 """Gets a valid value for this argument."""
8118 return 'true'
8120 def GetValidGLArg(self, func):
8121 """Gets a valid GL value for this argument."""
8122 return 'true'
8125 class UniformLocationArgument(Argument):
8126 """class for uniform locations."""
8128 def __init__(self, name):
8129 Argument.__init__(self, name, "GLint")
8131 def WriteGetCode(self, file):
8132 """Writes the code to get an argument from a command structure."""
8133 code = """ %s %s = static_cast<%s>(c.%s);
8135 file.Write(code % (self.type, self.name, self.type, self.name))
8137 class DataSizeArgument(Argument):
8138 """class for data_size which Bucket commands do not need."""
8140 def __init__(self, name):
8141 Argument.__init__(self, name, "uint32_t")
8143 def GetBucketVersion(self):
8144 return None
8147 class SizeArgument(Argument):
8148 """class for GLsizei and GLsizeiptr."""
8150 def __init__(self, name, type):
8151 Argument.__init__(self, name, type)
8153 def GetNumInvalidValues(self, func):
8154 """overridden from Argument."""
8155 if func.IsImmediate():
8156 return 0
8157 return 1
8159 def GetInvalidArg(self, index):
8160 """overridden from Argument."""
8161 return ("-1", "kNoError", "GL_INVALID_VALUE")
8163 def WriteValidationCode(self, file, func):
8164 """overridden from Argument."""
8165 if func.IsUnsafe():
8166 return
8167 code = """ if (%(var_name)s < 0) {
8168 LOCAL_SET_GL_ERROR(GL_INVALID_VALUE, "gl%(func_name)s", "%(var_name)s < 0");
8169 return error::kNoError;
8172 file.Write(code % {
8173 "var_name": self.name,
8174 "func_name": func.original_name,
8177 def WriteClientSideValidationCode(self, file, func):
8178 """overridden from Argument."""
8179 code = """ if (%(var_name)s < 0) {
8180 SetGLError(GL_INVALID_VALUE, "gl%(func_name)s", "%(var_name)s < 0");
8181 return;
8184 file.Write(code % {
8185 "var_name": self.name,
8186 "func_name": func.original_name,
8190 class SizeNotNegativeArgument(SizeArgument):
8191 """class for GLsizeiNotNegative. It's NEVER allowed to be negative"""
8193 def __init__(self, name, type, gl_type):
8194 SizeArgument.__init__(self, name, gl_type)
8196 def GetInvalidArg(self, index):
8197 """overridden from SizeArgument."""
8198 return ("-1", "kOutOfBounds", "GL_NO_ERROR")
8200 def WriteValidationCode(self, file, func):
8201 """overridden from SizeArgument."""
8202 pass
8205 class EnumBaseArgument(Argument):
8206 """Base class for EnumArgument, IntArgument, BitfieldArgument, and
8207 ValidatedBoolArgument."""
8209 def __init__(self, name, gl_type, type, gl_error):
8210 Argument.__init__(self, name, gl_type)
8212 self.local_type = type
8213 self.gl_error = gl_error
8214 name = type[len(gl_type):]
8215 self.type_name = name
8216 self.named_type = NamedType(_NAMED_TYPE_INFO[name])
8218 def IsConstant(self):
8219 return self.named_type.IsConstant()
8221 def GetConstantValue(self):
8222 return self.named_type.GetConstantValue()
8224 def WriteValidationCode(self, file, func):
8225 if func.IsUnsafe():
8226 return
8227 if self.named_type.IsConstant():
8228 return
8229 file.Write(" if (!validators_->%s.IsValid(%s)) {\n" %
8230 (ToUnderscore(self.type_name), self.name))
8231 if self.gl_error == "GL_INVALID_ENUM":
8232 file.Write(
8233 " LOCAL_SET_GL_ERROR_INVALID_ENUM(\"gl%s\", %s, \"%s\");\n" %
8234 (func.original_name, self.name, self.name))
8235 else:
8236 file.Write(
8237 " LOCAL_SET_GL_ERROR(%s, \"gl%s\", \"%s %s\");\n" %
8238 (self.gl_error, func.original_name, self.name, self.gl_error))
8239 file.Write(" return error::kNoError;\n")
8240 file.Write(" }\n")
8242 def WriteClientSideValidationCode(self, file, func):
8243 if not self.named_type.IsConstant():
8244 return
8245 file.Write(" if (%s != %s) {" % (self.name,
8246 self.GetConstantValue()))
8247 file.Write(
8248 " SetGLError(%s, \"gl%s\", \"%s %s\");\n" %
8249 (self.gl_error, func.original_name, self.name, self.gl_error))
8250 if func.return_type == "void":
8251 file.Write(" return;\n")
8252 else:
8253 file.Write(" return %s;\n" % func.GetErrorReturnString())
8254 file.Write(" }\n")
8256 def GetValidArg(self, func):
8257 valid_arg = func.GetValidArg(self)
8258 if valid_arg != None:
8259 return valid_arg
8260 valid = self.named_type.GetValidValues()
8261 if valid:
8262 num_valid = len(valid)
8263 return valid[0]
8265 index = func.GetOriginalArgs().index(self)
8266 return str(index + 1)
8268 def GetValidClientSideArg(self, func):
8269 """Gets a valid value for this argument."""
8270 return self.GetValidArg(func)
8272 def GetValidClientSideCmdArg(self, func):
8273 """Gets a valid value for this argument."""
8274 valid_arg = func.GetValidArg(self)
8275 if valid_arg != None:
8276 return valid_arg
8278 valid = self.named_type.GetValidValues()
8279 if valid:
8280 num_valid = len(valid)
8281 return valid[0]
8283 try:
8284 index = func.GetOriginalArgs().index(self)
8285 return str(index + 1)
8286 except ValueError:
8287 pass
8288 index = func.GetCmdArgs().index(self)
8289 return str(index + 1)
8291 def GetValidGLArg(self, func):
8292 """Gets a valid value for this argument."""
8293 return self.GetValidArg(func)
8295 def GetNumInvalidValues(self, func):
8296 """returns the number of invalid values to be tested."""
8297 return len(self.named_type.GetInvalidValues())
8299 def GetInvalidArg(self, index):
8300 """returns an invalid value by index."""
8301 invalid = self.named_type.GetInvalidValues()
8302 if invalid:
8303 num_invalid = len(invalid)
8304 if index >= num_invalid:
8305 index = num_invalid - 1
8306 return (invalid[index], "kNoError", self.gl_error)
8307 return ("---ERROR1---", "kNoError", self.gl_error)
8310 class EnumArgument(EnumBaseArgument):
8311 """A class that represents a GLenum argument"""
8313 def __init__(self, name, type):
8314 EnumBaseArgument.__init__(self, name, "GLenum", type, "GL_INVALID_ENUM")
8316 def GetLogArg(self):
8317 """Overridden from Argument."""
8318 return ("GLES2Util::GetString%s(%s)" %
8319 (self.type_name, self.name))
8322 class IntArgument(EnumBaseArgument):
8323 """A class for a GLint argument that can only accept specific values.
8325 For example glTexImage2D takes a GLint for its internalformat
8326 argument instead of a GLenum.
8329 def __init__(self, name, type):
8330 EnumBaseArgument.__init__(self, name, "GLint", type, "GL_INVALID_VALUE")
8333 class ValidatedBoolArgument(EnumBaseArgument):
8334 """A class for a GLboolean argument that can only accept specific values.
8336 For example glUniformMatrix takes a GLboolean for it's transpose but it
8337 must be false.
8340 def __init__(self, name, type):
8341 EnumBaseArgument.__init__(self, name, "GLboolean", type, "GL_INVALID_VALUE")
8343 def GetLogArg(self):
8344 """Overridden from Argument."""
8345 return 'GLES2Util::GetStringBool(%s)' % self.name
8348 class BitFieldArgument(EnumBaseArgument):
8349 """A class for a GLbitfield argument that can only accept specific values.
8351 For example glFenceSync takes a GLbitfield for its flags argument bit it
8352 must be 0.
8355 def __init__(self, name, type):
8356 EnumBaseArgument.__init__(self, name, "GLbitfield", type,
8357 "GL_INVALID_VALUE")
8360 class ImmediatePointerArgument(Argument):
8361 """A class that represents an immediate argument to a function.
8363 An immediate argument is one where the data follows the command.
8366 def __init__(self, name, type):
8367 Argument.__init__(self, name, type)
8369 def IsPointer(self):
8370 return True
8372 def GetPointedType(self):
8373 match = re.match('(const\s+)?(?P<element_type>[\w]+)\s*\*', self.type)
8374 assert match
8375 return match.groupdict()['element_type']
8377 def AddCmdArgs(self, args):
8378 """Overridden from Argument."""
8379 pass
8381 def WriteGetCode(self, file):
8382 """Overridden from Argument."""
8383 file.Write(
8384 " %s %s = GetImmediateDataAs<%s>(\n" %
8385 (self.type, self.name, self.type))
8386 file.Write(" c, data_size, immediate_data_size);\n")
8388 def WriteValidationCode(self, file, func):
8389 """Overridden from Argument."""
8390 if self.optional:
8391 return
8392 file.Write(" if (%s == NULL) {\n" % self.name)
8393 file.Write(" return error::kOutOfBounds;\n")
8394 file.Write(" }\n")
8396 def GetImmediateVersion(self):
8397 """Overridden from Argument."""
8398 return None
8400 def WriteDestinationInitalizationValidation(self, file, func):
8401 """Overridden from Argument."""
8402 self.WriteDestinationInitalizationValidatationIfNeeded(file, func)
8404 def GetLogArg(self):
8405 """Overridden from Argument."""
8406 return "static_cast<const void*>(%s)" % self.name
8409 class PointerArgument(Argument):
8410 """A class that represents a pointer argument to a function."""
8412 def __init__(self, name, type):
8413 Argument.__init__(self, name, type)
8415 def IsPointer(self):
8416 """Overridden from Argument."""
8417 return True
8419 def IsPointer2D(self):
8420 """Overridden from Argument."""
8421 return self.type.count('*') == 2
8423 def GetPointedType(self):
8424 match = re.match('(const\s+)?(?P<element_type>[\w]+)\s*\*', self.type)
8425 assert match
8426 return match.groupdict()['element_type']
8428 def GetValidArg(self, func):
8429 """Overridden from Argument."""
8430 return "shared_memory_id_, shared_memory_offset_"
8432 def GetValidGLArg(self, func):
8433 """Overridden from Argument."""
8434 return "reinterpret_cast<%s>(shared_memory_address_)" % self.type
8436 def GetNumInvalidValues(self, func):
8437 """Overridden from Argument."""
8438 return 2
8440 def GetInvalidArg(self, index):
8441 """Overridden from Argument."""
8442 if index == 0:
8443 return ("kInvalidSharedMemoryId, 0", "kOutOfBounds", None)
8444 else:
8445 return ("shared_memory_id_, kInvalidSharedMemoryOffset",
8446 "kOutOfBounds", None)
8448 def GetLogArg(self):
8449 """Overridden from Argument."""
8450 return "static_cast<const void*>(%s)" % self.name
8452 def AddCmdArgs(self, args):
8453 """Overridden from Argument."""
8454 args.append(Argument("%s_shm_id" % self.name, 'uint32_t'))
8455 args.append(Argument("%s_shm_offset" % self.name, 'uint32_t'))
8457 def WriteGetCode(self, file):
8458 """Overridden from Argument."""
8459 file.Write(
8460 " %s %s = GetSharedMemoryAs<%s>(\n" %
8461 (self.type, self.name, self.type))
8462 file.Write(
8463 " c.%s_shm_id, c.%s_shm_offset, data_size);\n" %
8464 (self.name, self.name))
8466 def WriteGetAddress(self, file):
8467 """Overridden from Argument."""
8468 file.Write(
8469 " %s %s = GetSharedMemoryAs<%s>(\n" %
8470 (self.type, self.name, self.type))
8471 file.Write(
8472 " %s_shm_id, %s_shm_offset, %s_size);\n" %
8473 (self.name, self.name, self.name))
8475 def WriteValidationCode(self, file, func):
8476 """Overridden from Argument."""
8477 if self.optional:
8478 return
8479 file.Write(" if (%s == NULL) {\n" % self.name)
8480 file.Write(" return error::kOutOfBounds;\n")
8481 file.Write(" }\n")
8483 def GetImmediateVersion(self):
8484 """Overridden from Argument."""
8485 return ImmediatePointerArgument(self.name, self.type)
8487 def GetBucketVersion(self):
8488 """Overridden from Argument."""
8489 if self.type.find('char') >= 0:
8490 if self.IsPointer2D():
8491 return InputStringArrayBucketArgument(self.name, self.type)
8492 return InputStringBucketArgument(self.name, self.type)
8493 return BucketPointerArgument(self.name, self.type)
8495 def WriteDestinationInitalizationValidation(self, file, func):
8496 """Overridden from Argument."""
8497 self.WriteDestinationInitalizationValidatationIfNeeded(file, func)
8500 class BucketPointerArgument(PointerArgument):
8501 """A class that represents an bucket argument to a function."""
8503 def __init__(self, name, type):
8504 Argument.__init__(self, name, type)
8506 def AddCmdArgs(self, args):
8507 """Overridden from Argument."""
8508 pass
8510 def WriteGetCode(self, file):
8511 """Overridden from Argument."""
8512 file.Write(
8513 " %s %s = bucket->GetData(0, data_size);\n" %
8514 (self.type, self.name))
8516 def WriteValidationCode(self, file, func):
8517 """Overridden from Argument."""
8518 pass
8520 def GetImmediateVersion(self):
8521 """Overridden from Argument."""
8522 return None
8524 def WriteDestinationInitalizationValidation(self, file, func):
8525 """Overridden from Argument."""
8526 self.WriteDestinationInitalizationValidatationIfNeeded(file, func)
8528 def GetLogArg(self):
8529 """Overridden from Argument."""
8530 return "static_cast<const void*>(%s)" % self.name
8533 class InputStringBucketArgument(Argument):
8534 """A string input argument where the string is passed in a bucket."""
8536 def __init__(self, name, type):
8537 Argument.__init__(self, name + "_bucket_id", "uint32_t")
8539 def IsPointer(self):
8540 """Overridden from Argument."""
8541 return True
8543 def IsPointer2D(self):
8544 """Overridden from Argument."""
8545 return False
8548 class InputStringArrayBucketArgument(Argument):
8549 """A string array input argument where the strings are passed in a bucket."""
8551 def __init__(self, name, type):
8552 Argument.__init__(self, name + "_bucket_id", "uint32_t")
8553 self._original_name = name
8555 def WriteGetCode(self, file):
8556 """Overridden from Argument."""
8557 code = """
8558 Bucket* bucket = GetBucket(c.%(name)s);
8559 if (!bucket) {
8560 return error::kInvalidArguments;
8562 GLsizei count = 0;
8563 std::vector<char*> strs;
8564 std::vector<GLint> len;
8565 if (!bucket->GetAsStrings(&count, &strs, &len)) {
8566 return error::kInvalidArguments;
8568 const char** %(original_name)s =
8569 strs.size() > 0 ? const_cast<const char**>(&strs[0]) : NULL;
8570 const GLint* length =
8571 len.size() > 0 ? const_cast<const GLint*>(&len[0]) : NULL;
8572 (void)length;
8574 file.Write(code % {
8575 'name': self.name,
8576 'original_name': self._original_name,
8579 def GetValidArg(self, func):
8580 return "kNameBucketId"
8582 def GetValidGLArg(self, func):
8583 return "_"
8585 def IsPointer(self):
8586 """Overridden from Argument."""
8587 return True
8589 def IsPointer2D(self):
8590 """Overridden from Argument."""
8591 return True
8594 class ResourceIdArgument(Argument):
8595 """A class that represents a resource id argument to a function."""
8597 def __init__(self, name, type):
8598 match = re.match("(GLid\w+)", type)
8599 self.resource_type = match.group(1)[4:]
8600 if self.resource_type == "Sync":
8601 type = type.replace(match.group(1), "GLsync")
8602 else:
8603 type = type.replace(match.group(1), "GLuint")
8604 Argument.__init__(self, name, type)
8606 def WriteGetCode(self, file):
8607 """Overridden from Argument."""
8608 if self.type == "GLsync":
8609 my_type = "GLuint"
8610 else:
8611 my_type = self.type
8612 file.Write(" %s %s = c.%s;\n" % (my_type, self.name, self.name))
8614 def GetValidArg(self, func):
8615 return "client_%s_id_" % self.resource_type.lower()
8617 def GetValidGLArg(self, func):
8618 if self.resource_type == "Sync":
8619 return "reinterpret_cast<GLsync>(kService%sId)" % self.resource_type
8620 return "kService%sId" % self.resource_type
8623 class ResourceIdBindArgument(Argument):
8624 """Represents a resource id argument to a bind function."""
8626 def __init__(self, name, type):
8627 match = re.match("(GLidBind\w+)", type)
8628 self.resource_type = match.group(1)[8:]
8629 type = type.replace(match.group(1), "GLuint")
8630 Argument.__init__(self, name, type)
8632 def WriteGetCode(self, file):
8633 """Overridden from Argument."""
8634 code = """ %(type)s %(name)s = c.%(name)s;
8636 file.Write(code % {'type': self.type, 'name': self.name})
8638 def GetValidArg(self, func):
8639 return "client_%s_id_" % self.resource_type.lower()
8641 def GetValidGLArg(self, func):
8642 return "kService%sId" % self.resource_type
8645 class ResourceIdZeroArgument(Argument):
8646 """Represents a resource id argument to a function that can be zero."""
8648 def __init__(self, name, type):
8649 match = re.match("(GLidZero\w+)", type)
8650 self.resource_type = match.group(1)[8:]
8651 type = type.replace(match.group(1), "GLuint")
8652 Argument.__init__(self, name, type)
8654 def WriteGetCode(self, file):
8655 """Overridden from Argument."""
8656 file.Write(" %s %s = c.%s;\n" % (self.type, self.name, self.name))
8658 def GetValidArg(self, func):
8659 return "client_%s_id_" % self.resource_type.lower()
8661 def GetValidGLArg(self, func):
8662 return "kService%sId" % self.resource_type
8664 def GetNumInvalidValues(self, func):
8665 """returns the number of invalid values to be tested."""
8666 return 1
8668 def GetInvalidArg(self, index):
8669 """returns an invalid value by index."""
8670 return ("kInvalidClientId", "kNoError", "GL_INVALID_VALUE")
8673 class Function(object):
8674 """A class that represents a function."""
8676 type_handlers = {
8677 '': TypeHandler(),
8678 'Bind': BindHandler(),
8679 'Create': CreateHandler(),
8680 'Custom': CustomHandler(),
8681 'Data': DataHandler(),
8682 'Delete': DeleteHandler(),
8683 'DELn': DELnHandler(),
8684 'GENn': GENnHandler(),
8685 'GETn': GETnHandler(),
8686 'GLchar': GLcharHandler(),
8687 'GLcharN': GLcharNHandler(),
8688 'HandWritten': HandWrittenHandler(),
8689 'Is': IsHandler(),
8690 'Manual': ManualHandler(),
8691 'PUT': PUTHandler(),
8692 'PUTn': PUTnHandler(),
8693 'PUTSTR': PUTSTRHandler(),
8694 'PUTXn': PUTXnHandler(),
8695 'StateSet': StateSetHandler(),
8696 'StateSetRGBAlpha': StateSetRGBAlphaHandler(),
8697 'StateSetFrontBack': StateSetFrontBackHandler(),
8698 'StateSetFrontBackSeparate': StateSetFrontBackSeparateHandler(),
8699 'StateSetNamedParameter': StateSetNamedParameter(),
8700 'STRn': STRnHandler(),
8701 'Todo': TodoHandler(),
8704 def __init__(self, name, info):
8705 self.name = name
8706 self.original_name = info['original_name']
8708 self.original_args = self.ParseArgs(info['original_args'])
8710 if 'cmd_args' in info:
8711 self.args_for_cmds = self.ParseArgs(info['cmd_args'])
8712 else:
8713 self.args_for_cmds = self.original_args[:]
8715 self.return_type = info['return_type']
8716 if self.return_type != 'void':
8717 self.return_arg = CreateArg(info['return_type'] + " result")
8718 else:
8719 self.return_arg = None
8721 self.num_pointer_args = sum(
8722 [1 for arg in self.args_for_cmds if arg.IsPointer()])
8723 if self.num_pointer_args > 0:
8724 for arg in reversed(self.original_args):
8725 if arg.IsPointer():
8726 self.last_original_pointer_arg = arg
8727 break
8728 else:
8729 self.last_original_pointer_arg = None
8730 self.info = info
8731 self.type_handler = self.type_handlers[info['type']]
8732 self.can_auto_generate = (self.num_pointer_args == 0 and
8733 info['return_type'] == "void")
8734 self.InitFunction()
8736 def ParseArgs(self, arg_string):
8737 """Parses a function arg string."""
8738 args = []
8739 parts = arg_string.split(',')
8740 for arg_string in parts:
8741 arg = CreateArg(arg_string)
8742 if arg:
8743 args.append(arg)
8744 return args
8746 def IsType(self, type_name):
8747 """Returns true if function is a certain type."""
8748 return self.info['type'] == type_name
8750 def InitFunction(self):
8751 """Creates command args and calls the init function for the type handler.
8753 Creates argument lists for command buffer commands, eg. self.cmd_args and
8754 self.init_args.
8755 Calls the type function initialization.
8756 Override to create different kind of command buffer command argument lists.
8758 self.cmd_args = []
8759 for arg in self.args_for_cmds:
8760 arg.AddCmdArgs(self.cmd_args)
8762 self.init_args = []
8763 for arg in self.args_for_cmds:
8764 arg.AddInitArgs(self.init_args)
8766 if self.return_arg:
8767 self.init_args.append(self.return_arg)
8769 self.type_handler.InitFunction(self)
8771 def IsImmediate(self):
8772 """Returns whether the function is immediate data function or not."""
8773 return False
8775 def IsUnsafe(self):
8776 """Returns whether the function has service side validation or not."""
8777 return self.GetInfo('unsafe', False)
8779 def GetInfo(self, name, default = None):
8780 """Returns a value from the function info for this function."""
8781 if name in self.info:
8782 return self.info[name]
8783 return default
8785 def GetValidArg(self, arg):
8786 """Gets a valid argument value for the parameter arg from the function info
8787 if one exists."""
8788 try:
8789 index = self.GetOriginalArgs().index(arg)
8790 except ValueError:
8791 return None
8793 valid_args = self.GetInfo('valid_args')
8794 if valid_args and str(index) in valid_args:
8795 return valid_args[str(index)]
8796 return None
8798 def AddInfo(self, name, value):
8799 """Adds an info."""
8800 self.info[name] = value
8802 def IsExtension(self):
8803 return self.GetInfo('extension') or self.GetInfo('extension_flag')
8805 def IsCoreGLFunction(self):
8806 return (not self.IsExtension() and
8807 not self.GetInfo('pepper_interface') and
8808 not self.IsUnsafe())
8810 def InPepperInterface(self, interface):
8811 ext = self.GetInfo('pepper_interface')
8812 if not interface.GetName():
8813 return self.IsCoreGLFunction()
8814 return ext == interface.GetName()
8816 def InAnyPepperExtension(self):
8817 return self.IsCoreGLFunction() or self.GetInfo('pepper_interface')
8819 def GetErrorReturnString(self):
8820 if self.GetInfo("error_return"):
8821 return self.GetInfo("error_return")
8822 elif self.return_type == "GLboolean":
8823 return "GL_FALSE"
8824 elif "*" in self.return_type:
8825 return "NULL"
8826 return "0"
8828 def GetGLFunctionName(self):
8829 """Gets the function to call to execute GL for this command."""
8830 if self.GetInfo('decoder_func'):
8831 return self.GetInfo('decoder_func')
8832 return "gl%s" % self.original_name
8834 def GetGLTestFunctionName(self):
8835 gl_func_name = self.GetInfo('gl_test_func')
8836 if gl_func_name == None:
8837 gl_func_name = self.GetGLFunctionName()
8838 if gl_func_name.startswith("gl"):
8839 gl_func_name = gl_func_name[2:]
8840 else:
8841 gl_func_name = self.original_name
8842 return gl_func_name
8844 def GetDataTransferMethods(self):
8845 return self.GetInfo('data_transfer_methods',
8846 ['immediate' if self.num_pointer_args == 1 else 'shm'])
8848 def AddCmdArg(self, arg):
8849 """Adds a cmd argument to this function."""
8850 self.cmd_args.append(arg)
8852 def GetCmdArgs(self):
8853 """Gets the command args for this function."""
8854 return self.cmd_args
8856 def ClearCmdArgs(self):
8857 """Clears the command args for this function."""
8858 self.cmd_args = []
8860 def GetCmdConstants(self):
8861 """Gets the constants for this function."""
8862 return [arg for arg in self.args_for_cmds if arg.IsConstant()]
8864 def GetInitArgs(self):
8865 """Gets the init args for this function."""
8866 return self.init_args
8868 def GetOriginalArgs(self):
8869 """Gets the original arguments to this function."""
8870 return self.original_args
8872 def GetLastOriginalArg(self):
8873 """Gets the last original argument to this function."""
8874 return self.original_args[len(self.original_args) - 1]
8876 def GetLastOriginalPointerArg(self):
8877 return self.last_original_pointer_arg
8879 def GetResourceIdArg(self):
8880 for arg in self.original_args:
8881 if hasattr(arg, 'resource_type'):
8882 return arg
8883 return None
8885 def _MaybePrependComma(self, arg_string, add_comma):
8886 """Adds a comma if arg_string is not empty and add_comma is true."""
8887 comma = ""
8888 if add_comma and len(arg_string):
8889 comma = ", "
8890 return "%s%s" % (comma, arg_string)
8892 def MakeTypedOriginalArgString(self, prefix, add_comma = False):
8893 """Gets a list of arguments as they are in GL."""
8894 args = self.GetOriginalArgs()
8895 arg_string = ", ".join(
8896 ["%s %s%s" % (arg.type, prefix, arg.name) for arg in args])
8897 return self._MaybePrependComma(arg_string, add_comma)
8899 def MakeOriginalArgString(self, prefix, add_comma = False, separator = ", "):
8900 """Gets the list of arguments as they are in GL."""
8901 args = self.GetOriginalArgs()
8902 arg_string = separator.join(
8903 ["%s%s" % (prefix, arg.name) for arg in args])
8904 return self._MaybePrependComma(arg_string, add_comma)
8906 def MakeTypedHelperArgString(self, prefix, add_comma = False):
8907 """Gets a list of typed GL arguments after removing unneeded arguments."""
8908 args = self.GetOriginalArgs()
8909 arg_string = ", ".join(
8910 ["%s %s%s" % (
8911 arg.type,
8912 prefix,
8913 arg.name,
8914 ) for arg in args if not arg.IsConstant()])
8915 return self._MaybePrependComma(arg_string, add_comma)
8917 def MakeHelperArgString(self, prefix, add_comma = False, separator = ", "):
8918 """Gets a list of GL arguments after removing unneeded arguments."""
8919 args = self.GetOriginalArgs()
8920 arg_string = separator.join(
8921 ["%s%s" % (prefix, arg.name)
8922 for arg in args if not arg.IsConstant()])
8923 return self._MaybePrependComma(arg_string, add_comma)
8925 def MakeTypedPepperArgString(self, prefix):
8926 """Gets a list of arguments as they need to be for Pepper."""
8927 if self.GetInfo("pepper_args"):
8928 return self.GetInfo("pepper_args")
8929 else:
8930 return self.MakeTypedOriginalArgString(prefix, False)
8932 def MapCTypeToPepperIdlType(self, ctype, is_for_return_type=False):
8933 """Converts a C type name to the corresponding Pepper IDL type."""
8934 idltype = {
8935 'char*': '[out] str_t',
8936 'const GLchar* const*': '[out] cstr_t',
8937 'const char*': 'cstr_t',
8938 'const void*': 'mem_t',
8939 'void*': '[out] mem_t',
8940 'void**': '[out] mem_ptr_t',
8941 }.get(ctype, ctype)
8942 # We use "GLxxx_ptr_t" for "GLxxx*".
8943 matched = re.match(r'(const )?(GL\w+)\*$', ctype)
8944 if matched:
8945 idltype = matched.group(2) + '_ptr_t'
8946 if not matched.group(1):
8947 idltype = '[out] ' + idltype
8948 # If an in/out specifier is not specified yet, prepend [in].
8949 if idltype[0] != '[':
8950 idltype = '[in] ' + idltype
8951 # Strip the in/out specifier for a return type.
8952 if is_for_return_type:
8953 idltype = re.sub(r'\[\w+\] ', '', idltype)
8954 return idltype
8956 def MakeTypedPepperIdlArgStrings(self):
8957 """Gets a list of arguments as they need to be for Pepper IDL."""
8958 args = self.GetOriginalArgs()
8959 return ["%s %s" % (self.MapCTypeToPepperIdlType(arg.type), arg.name)
8960 for arg in args]
8962 def GetPepperName(self):
8963 if self.GetInfo("pepper_name"):
8964 return self.GetInfo("pepper_name")
8965 return self.name
8967 def MakeTypedCmdArgString(self, prefix, add_comma = False):
8968 """Gets a typed list of arguments as they need to be for command buffers."""
8969 args = self.GetCmdArgs()
8970 arg_string = ", ".join(
8971 ["%s %s%s" % (arg.type, prefix, arg.name) for arg in args])
8972 return self._MaybePrependComma(arg_string, add_comma)
8974 def MakeCmdArgString(self, prefix, add_comma = False):
8975 """Gets the list of arguments as they need to be for command buffers."""
8976 args = self.GetCmdArgs()
8977 arg_string = ", ".join(
8978 ["%s%s" % (prefix, arg.name) for arg in args])
8979 return self._MaybePrependComma(arg_string, add_comma)
8981 def MakeTypedInitString(self, prefix, add_comma = False):
8982 """Gets a typed list of arguments as they need to be for cmd Init/Set."""
8983 args = self.GetInitArgs()
8984 arg_string = ", ".join(
8985 ["%s %s%s" % (arg.type, prefix, arg.name) for arg in args])
8986 return self._MaybePrependComma(arg_string, add_comma)
8988 def MakeInitString(self, prefix, add_comma = False):
8989 """Gets the list of arguments as they need to be for cmd Init/Set."""
8990 args = self.GetInitArgs()
8991 arg_string = ", ".join(
8992 ["%s%s" % (prefix, arg.name) for arg in args])
8993 return self._MaybePrependComma(arg_string, add_comma)
8995 def MakeLogArgString(self):
8996 """Makes a string of the arguments for the LOG macros"""
8997 args = self.GetOriginalArgs()
8998 return ' << ", " << '.join([arg.GetLogArg() for arg in args])
9000 def WriteCommandDescription(self, file):
9001 """Writes a description of the command."""
9002 file.Write("//! Command that corresponds to gl%s.\n" % self.original_name)
9004 def WriteHandlerValidation(self, file):
9005 """Writes validation code for the function."""
9006 for arg in self.GetOriginalArgs():
9007 arg.WriteValidationCode(file, self)
9008 self.WriteValidationCode(file)
9010 def WriteHandlerImplementation(self, file):
9011 """Writes the handler implementation for this command."""
9012 self.type_handler.WriteHandlerImplementation(self, file)
9014 def WriteValidationCode(self, file):
9015 """Writes the validation code for a command."""
9016 pass
9018 def WriteCmdFlag(self, file):
9019 """Writes the cmd cmd_flags constant."""
9020 flags = []
9021 # By default trace only at the highest level 3.
9022 trace_level = int(self.GetInfo('trace_level', default = 3))
9023 if trace_level not in xrange(0, 4):
9024 raise KeyError("Unhandled trace_level: %d" % trace_level)
9026 flags.append('CMD_FLAG_SET_TRACE_LEVEL(%d)' % trace_level)
9028 if len(flags) > 0:
9029 cmd_flags = ' | '.join(flags)
9030 else:
9031 cmd_flags = 0
9033 file.Write(" static const uint8 cmd_flags = %s;\n" % cmd_flags)
9036 def WriteCmdArgFlag(self, file):
9037 """Writes the cmd kArgFlags constant."""
9038 file.Write(" static const cmd::ArgFlags kArgFlags = cmd::kFixed;\n")
9040 def WriteCmdComputeSize(self, file):
9041 """Writes the ComputeSize function for the command."""
9042 file.Write(" static uint32_t ComputeSize() {\n")
9043 file.Write(
9044 " return static_cast<uint32_t>(sizeof(ValueType)); // NOLINT\n")
9045 file.Write(" }\n")
9046 file.Write("\n")
9048 def WriteCmdSetHeader(self, file):
9049 """Writes the cmd's SetHeader function."""
9050 file.Write(" void SetHeader() {\n")
9051 file.Write(" header.SetCmd<ValueType>();\n")
9052 file.Write(" }\n")
9053 file.Write("\n")
9055 def WriteCmdInit(self, file):
9056 """Writes the cmd's Init function."""
9057 file.Write(" void Init(%s) {\n" % self.MakeTypedCmdArgString("_"))
9058 file.Write(" SetHeader();\n")
9059 args = self.GetCmdArgs()
9060 for arg in args:
9061 file.Write(" %s = _%s;\n" % (arg.name, arg.name))
9062 file.Write(" }\n")
9063 file.Write("\n")
9065 def WriteCmdSet(self, file):
9066 """Writes the cmd's Set function."""
9067 copy_args = self.MakeCmdArgString("_", False)
9068 file.Write(" void* Set(void* cmd%s) {\n" %
9069 self.MakeTypedCmdArgString("_", True))
9070 file.Write(" static_cast<ValueType*>(cmd)->Init(%s);\n" % copy_args)
9071 file.Write(" return NextCmdAddress<ValueType>(cmd);\n")
9072 file.Write(" }\n")
9073 file.Write("\n")
9075 def WriteStruct(self, file):
9076 self.type_handler.WriteStruct(self, file)
9078 def WriteDocs(self, file):
9079 self.type_handler.WriteDocs(self, file)
9081 def WriteCmdHelper(self, file):
9082 """Writes the cmd's helper."""
9083 self.type_handler.WriteCmdHelper(self, file)
9085 def WriteServiceImplementation(self, file):
9086 """Writes the service implementation for a command."""
9087 self.type_handler.WriteServiceImplementation(self, file)
9089 def WriteServiceUnitTest(self, file, *extras):
9090 """Writes the service implementation for a command."""
9091 self.type_handler.WriteServiceUnitTest(self, file, *extras)
9093 def WriteGLES2CLibImplementation(self, file):
9094 """Writes the GLES2 C Lib Implemention."""
9095 self.type_handler.WriteGLES2CLibImplementation(self, file)
9097 def WriteGLES2InterfaceHeader(self, file):
9098 """Writes the GLES2 Interface declaration."""
9099 self.type_handler.WriteGLES2InterfaceHeader(self, file)
9101 def WriteMojoGLES2ImplHeader(self, file):
9102 """Writes the Mojo GLES2 implementation header declaration."""
9103 self.type_handler.WriteMojoGLES2ImplHeader(self, file)
9105 def WriteMojoGLES2Impl(self, file):
9106 """Writes the Mojo GLES2 implementation declaration."""
9107 self.type_handler.WriteMojoGLES2Impl(self, file)
9109 def WriteGLES2InterfaceStub(self, file):
9110 """Writes the GLES2 Interface Stub declaration."""
9111 self.type_handler.WriteGLES2InterfaceStub(self, file)
9113 def WriteGLES2InterfaceStubImpl(self, file):
9114 """Writes the GLES2 Interface Stub declaration."""
9115 self.type_handler.WriteGLES2InterfaceStubImpl(self, file)
9117 def WriteGLES2ImplementationHeader(self, file):
9118 """Writes the GLES2 Implemention declaration."""
9119 self.type_handler.WriteGLES2ImplementationHeader(self, file)
9121 def WriteGLES2Implementation(self, file):
9122 """Writes the GLES2 Implemention definition."""
9123 self.type_handler.WriteGLES2Implementation(self, file)
9125 def WriteGLES2TraceImplementationHeader(self, file):
9126 """Writes the GLES2 Trace Implemention declaration."""
9127 self.type_handler.WriteGLES2TraceImplementationHeader(self, file)
9129 def WriteGLES2TraceImplementation(self, file):
9130 """Writes the GLES2 Trace Implemention definition."""
9131 self.type_handler.WriteGLES2TraceImplementation(self, file)
9133 def WriteGLES2Header(self, file):
9134 """Writes the GLES2 Implemention unit test."""
9135 self.type_handler.WriteGLES2Header(self, file)
9137 def WriteGLES2ImplementationUnitTest(self, file):
9138 """Writes the GLES2 Implemention unit test."""
9139 self.type_handler.WriteGLES2ImplementationUnitTest(self, file)
9141 def WriteDestinationInitalizationValidation(self, file):
9142 """Writes the client side destintion initialization validation."""
9143 self.type_handler.WriteDestinationInitalizationValidation(self, file)
9145 def WriteFormatTest(self, file):
9146 """Writes the cmd's format test."""
9147 self.type_handler.WriteFormatTest(self, file)
9150 class PepperInterface(object):
9151 """A class that represents a function."""
9153 def __init__(self, info):
9154 self.name = info["name"]
9155 self.dev = info["dev"]
9157 def GetName(self):
9158 return self.name
9160 def GetInterfaceName(self):
9161 upperint = ""
9162 dev = ""
9163 if self.name:
9164 upperint = "_" + self.name.upper()
9165 if self.dev:
9166 dev = "_DEV"
9167 return "PPB_OPENGLES2%s%s_INTERFACE" % (upperint, dev)
9169 def GetInterfaceString(self):
9170 dev = ""
9171 if self.dev:
9172 dev = "(Dev)"
9173 return "PPB_OpenGLES2%s%s" % (self.name, dev)
9175 def GetStructName(self):
9176 dev = ""
9177 if self.dev:
9178 dev = "_Dev"
9179 return "PPB_OpenGLES2%s%s" % (self.name, dev)
9182 class ImmediateFunction(Function):
9183 """A class that represnets an immediate function command."""
9185 def __init__(self, func):
9186 Function.__init__(
9187 self,
9188 "%sImmediate" % func.name,
9189 func.info)
9191 def InitFunction(self):
9192 # Override args in original_args and args_for_cmds with immediate versions
9193 # of the args.
9195 new_original_args = []
9196 for arg in self.original_args:
9197 new_arg = arg.GetImmediateVersion()
9198 if new_arg:
9199 new_original_args.append(new_arg)
9200 self.original_args = new_original_args
9202 new_args_for_cmds = []
9203 for arg in self.args_for_cmds:
9204 new_arg = arg.GetImmediateVersion()
9205 if new_arg:
9206 new_args_for_cmds.append(new_arg)
9208 self.args_for_cmds = new_args_for_cmds
9210 Function.InitFunction(self)
9212 def IsImmediate(self):
9213 return True
9215 def WriteCommandDescription(self, file):
9216 """Overridden from Function"""
9217 file.Write("//! Immediate version of command that corresponds to gl%s.\n" %
9218 self.original_name)
9220 def WriteServiceImplementation(self, file):
9221 """Overridden from Function"""
9222 self.type_handler.WriteImmediateServiceImplementation(self, file)
9224 def WriteHandlerImplementation(self, file):
9225 """Overridden from Function"""
9226 self.type_handler.WriteImmediateHandlerImplementation(self, file)
9228 def WriteServiceUnitTest(self, file, *extras):
9229 """Writes the service implementation for a command."""
9230 self.type_handler.WriteImmediateServiceUnitTest(self, file, *extras)
9232 def WriteValidationCode(self, file):
9233 """Overridden from Function"""
9234 self.type_handler.WriteImmediateValidationCode(self, file)
9236 def WriteCmdArgFlag(self, file):
9237 """Overridden from Function"""
9238 file.Write(" static const cmd::ArgFlags kArgFlags = cmd::kAtLeastN;\n")
9240 def WriteCmdComputeSize(self, file):
9241 """Overridden from Function"""
9242 self.type_handler.WriteImmediateCmdComputeSize(self, file)
9244 def WriteCmdSetHeader(self, file):
9245 """Overridden from Function"""
9246 self.type_handler.WriteImmediateCmdSetHeader(self, file)
9248 def WriteCmdInit(self, file):
9249 """Overridden from Function"""
9250 self.type_handler.WriteImmediateCmdInit(self, file)
9252 def WriteCmdSet(self, file):
9253 """Overridden from Function"""
9254 self.type_handler.WriteImmediateCmdSet(self, file)
9256 def WriteCmdHelper(self, file):
9257 """Overridden from Function"""
9258 self.type_handler.WriteImmediateCmdHelper(self, file)
9260 def WriteFormatTest(self, file):
9261 """Overridden from Function"""
9262 self.type_handler.WriteImmediateFormatTest(self, file)
9265 class BucketFunction(Function):
9266 """A class that represnets a bucket version of a function command."""
9268 def __init__(self, func):
9269 Function.__init__(
9270 self,
9271 "%sBucket" % func.name,
9272 func.info)
9274 def InitFunction(self):
9275 # Override args in original_args and args_for_cmds with bucket versions
9276 # of the args.
9278 new_original_args = []
9279 for arg in self.original_args:
9280 new_arg = arg.GetBucketVersion()
9281 if new_arg:
9282 new_original_args.append(new_arg)
9283 self.original_args = new_original_args
9285 new_args_for_cmds = []
9286 for arg in self.args_for_cmds:
9287 new_arg = arg.GetBucketVersion()
9288 if new_arg:
9289 new_args_for_cmds.append(new_arg)
9291 self.args_for_cmds = new_args_for_cmds
9293 Function.InitFunction(self)
9295 def WriteCommandDescription(self, file):
9296 """Overridden from Function"""
9297 file.Write("//! Bucket version of command that corresponds to gl%s.\n" %
9298 self.original_name)
9300 def WriteServiceImplementation(self, file):
9301 """Overridden from Function"""
9302 self.type_handler.WriteBucketServiceImplementation(self, file)
9304 def WriteHandlerImplementation(self, file):
9305 """Overridden from Function"""
9306 self.type_handler.WriteBucketHandlerImplementation(self, file)
9308 def WriteServiceUnitTest(self, file, *extras):
9309 """Overridden from Function"""
9310 self.type_handler.WriteBucketServiceUnitTest(self, file, *extras)
9312 def MakeOriginalArgString(self, prefix, add_comma = False, separator = ", "):
9313 """Overridden from Function"""
9314 args = self.GetOriginalArgs()
9315 arg_string = separator.join(
9316 ["%s%s" % (prefix, arg.name[0:-10] if arg.name.endswith("_bucket_id")
9317 else arg.name) for arg in args])
9318 return super(BucketFunction, self)._MaybePrependComma(arg_string, add_comma)
9321 def CreateArg(arg_string):
9322 """Creates an Argument."""
9323 arg_parts = arg_string.split()
9324 if len(arg_parts) == 1 and arg_parts[0] == 'void':
9325 return None
9326 # Is this a pointer argument?
9327 elif arg_string.find('*') >= 0:
9328 return PointerArgument(
9329 arg_parts[-1],
9330 " ".join(arg_parts[0:-1]))
9331 # Is this a resource argument? Must come after pointer check.
9332 elif arg_parts[0].startswith('GLidBind'):
9333 return ResourceIdBindArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
9334 elif arg_parts[0].startswith('GLidZero'):
9335 return ResourceIdZeroArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
9336 elif arg_parts[0].startswith('GLid'):
9337 return ResourceIdArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
9338 elif arg_parts[0].startswith('GLenum') and len(arg_parts[0]) > 6:
9339 return EnumArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
9340 elif arg_parts[0].startswith('GLbitfield') and len(arg_parts[0]) > 10:
9341 return BitFieldArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
9342 elif arg_parts[0].startswith('GLboolean') and len(arg_parts[0]) > 9:
9343 return ValidatedBoolArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
9344 elif arg_parts[0].startswith('GLboolean'):
9345 return BoolArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
9346 elif arg_parts[0].startswith('GLintUniformLocation'):
9347 return UniformLocationArgument(arg_parts[-1])
9348 elif (arg_parts[0].startswith('GLint') and len(arg_parts[0]) > 5 and
9349 not arg_parts[0].startswith('GLintptr')):
9350 return IntArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
9351 elif (arg_parts[0].startswith('GLsizeiNotNegative') or
9352 arg_parts[0].startswith('GLintptrNotNegative')):
9353 return SizeNotNegativeArgument(arg_parts[-1],
9354 " ".join(arg_parts[0:-1]),
9355 arg_parts[0][0:-11])
9356 elif arg_parts[0].startswith('GLsize'):
9357 return SizeArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
9358 else:
9359 return Argument(arg_parts[-1], " ".join(arg_parts[0:-1]))
9362 class GLGenerator(object):
9363 """A class to generate GL command buffers."""
9365 _function_re = re.compile(r'GL_APICALL(.*?)GL_APIENTRY (.*?) \((.*?)\);')
9367 def __init__(self, verbose):
9368 self.original_functions = []
9369 self.functions = []
9370 self.verbose = verbose
9371 self.errors = 0
9372 self.pepper_interfaces = []
9373 self.interface_info = {}
9374 self.generated_cpp_filenames = []
9376 for interface in _PEPPER_INTERFACES:
9377 interface = PepperInterface(interface)
9378 self.pepper_interfaces.append(interface)
9379 self.interface_info[interface.GetName()] = interface
9381 def AddFunction(self, func):
9382 """Adds a function."""
9383 self.functions.append(func)
9385 def GetFunctionInfo(self, name):
9386 """Gets a type info for the given function name."""
9387 if name in _FUNCTION_INFO:
9388 func_info = _FUNCTION_INFO[name].copy()
9389 else:
9390 func_info = {}
9392 if not 'type' in func_info:
9393 func_info['type'] = ''
9395 return func_info
9397 def Log(self, msg):
9398 """Prints something if verbose is true."""
9399 if self.verbose:
9400 print msg
9402 def Error(self, msg):
9403 """Prints an error."""
9404 print "Error: %s" % msg
9405 self.errors += 1
9407 def WriteLicense(self, file):
9408 """Writes the license."""
9409 file.Write(_LICENSE)
9411 def WriteNamespaceOpen(self, file):
9412 """Writes the code for the namespace."""
9413 file.Write("namespace gpu {\n")
9414 file.Write("namespace gles2 {\n")
9415 file.Write("\n")
9417 def WriteNamespaceClose(self, file):
9418 """Writes the code to close the namespace."""
9419 file.Write("} // namespace gles2\n")
9420 file.Write("} // namespace gpu\n")
9421 file.Write("\n")
9423 def ParseGLH(self, filename):
9424 """Parses the cmd_buffer_functions.txt file and extracts the functions"""
9425 f = open(filename, "r")
9426 functions = f.read()
9427 f.close()
9428 for line in functions.splitlines():
9429 match = self._function_re.match(line)
9430 if match:
9431 func_name = match.group(2)[2:]
9432 func_info = self.GetFunctionInfo(func_name)
9433 if func_info['type'] == 'Noop':
9434 continue
9436 parsed_func_info = {
9437 'original_name': func_name,
9438 'original_args': match.group(3),
9439 'return_type': match.group(1).strip(),
9442 for k in parsed_func_info.keys():
9443 if not k in func_info:
9444 func_info[k] = parsed_func_info[k]
9446 f = Function(func_name, func_info)
9447 self.original_functions.append(f)
9449 #for arg in f.GetOriginalArgs():
9450 # if not isinstance(arg, EnumArgument) and arg.type == 'GLenum':
9451 # self.Log("%s uses bare GLenum %s." % (func_name, arg.name))
9453 gen_cmd = f.GetInfo('gen_cmd')
9454 if gen_cmd == True or gen_cmd == None:
9455 if f.type_handler.NeedsDataTransferFunction(f):
9456 methods = f.GetDataTransferMethods()
9457 if 'immediate' in methods:
9458 self.AddFunction(ImmediateFunction(f))
9459 if 'bucket' in methods:
9460 self.AddFunction(BucketFunction(f))
9461 if 'shm' in methods:
9462 self.AddFunction(f)
9463 else:
9464 self.AddFunction(f)
9466 self.Log("Auto Generated Functions : %d" %
9467 len([f for f in self.functions if f.can_auto_generate or
9468 (not f.IsType('') and not f.IsType('Custom') and
9469 not f.IsType('Todo'))]))
9471 funcs = [f for f in self.functions if not f.can_auto_generate and
9472 (f.IsType('') or f.IsType('Custom') or f.IsType('Todo'))]
9473 self.Log("Non Auto Generated Functions: %d" % len(funcs))
9475 for f in funcs:
9476 self.Log(" %-10s %-20s gl%s" % (f.info['type'], f.return_type, f.name))
9478 def WriteCommandIds(self, filename):
9479 """Writes the command buffer format"""
9480 file = CHeaderWriter(filename)
9481 file.Write("#define GLES2_COMMAND_LIST(OP) \\\n")
9482 id = 256
9483 for func in self.functions:
9484 file.Write(" %-60s /* %d */ \\\n" %
9485 ("OP(%s)" % func.name, id))
9486 id += 1
9487 file.Write("\n")
9489 file.Write("enum CommandId {\n")
9490 file.Write(" kStartPoint = cmd::kLastCommonId, "
9491 "// All GLES2 commands start after this.\n")
9492 file.Write("#define GLES2_CMD_OP(name) k ## name,\n")
9493 file.Write(" GLES2_COMMAND_LIST(GLES2_CMD_OP)\n")
9494 file.Write("#undef GLES2_CMD_OP\n")
9495 file.Write(" kNumCommands\n")
9496 file.Write("};\n")
9497 file.Write("\n")
9498 file.Close()
9499 self.generated_cpp_filenames.append(file.filename)
9501 def WriteFormat(self, filename):
9502 """Writes the command buffer format"""
9503 file = CHeaderWriter(filename)
9504 # Forward declaration of a few enums used in constant argument
9505 # to avoid including GL header files.
9506 enum_defines = {
9507 'GL_SYNC_GPU_COMMANDS_COMPLETE': '0x9117',
9508 'GL_SYNC_FLUSH_COMMANDS_BIT': '0x00000001',
9510 file.Write('\n')
9511 for enum in enum_defines:
9512 file.Write("#define %s %s\n" % (enum, enum_defines[enum]))
9513 file.Write('\n')
9514 for func in self.functions:
9515 if True:
9516 #gen_cmd = func.GetInfo('gen_cmd')
9517 #if gen_cmd == True or gen_cmd == None:
9518 func.WriteStruct(file)
9519 file.Write("\n")
9520 file.Close()
9521 self.generated_cpp_filenames.append(file.filename)
9523 def WriteDocs(self, filename):
9524 """Writes the command buffer doc version of the commands"""
9525 file = CWriter(filename)
9526 for func in self.functions:
9527 if True:
9528 #gen_cmd = func.GetInfo('gen_cmd')
9529 #if gen_cmd == True or gen_cmd == None:
9530 func.WriteDocs(file)
9531 file.Write("\n")
9532 file.Close()
9533 self.generated_cpp_filenames.append(file.filename)
9535 def WriteFormatTest(self, filename):
9536 """Writes the command buffer format test."""
9537 file = CHeaderWriter(
9538 filename,
9539 "// This file contains unit tests for gles2 commmands\n"
9540 "// It is included by gles2_cmd_format_test.cc\n"
9541 "\n")
9543 for func in self.functions:
9544 if True:
9545 #gen_cmd = func.GetInfo('gen_cmd')
9546 #if gen_cmd == True or gen_cmd == None:
9547 func.WriteFormatTest(file)
9549 file.Close()
9550 self.generated_cpp_filenames.append(file.filename)
9552 def WriteCmdHelperHeader(self, filename):
9553 """Writes the gles2 command helper."""
9554 file = CHeaderWriter(filename)
9556 for func in self.functions:
9557 if True:
9558 #gen_cmd = func.GetInfo('gen_cmd')
9559 #if gen_cmd == True or gen_cmd == None:
9560 func.WriteCmdHelper(file)
9562 file.Close()
9563 self.generated_cpp_filenames.append(file.filename)
9565 def WriteServiceContextStateHeader(self, filename):
9566 """Writes the service context state header."""
9567 file = CHeaderWriter(
9568 filename,
9569 "// It is included by context_state.h\n")
9570 file.Write("struct EnableFlags {\n")
9571 file.Write(" EnableFlags();\n")
9572 for capability in _CAPABILITY_FLAGS:
9573 file.Write(" bool %s;\n" % capability['name'])
9574 file.Write(" bool cached_%s;\n" % capability['name'])
9575 file.Write("};\n\n")
9577 for state_name in sorted(_STATES.keys()):
9578 state = _STATES[state_name]
9579 for item in state['states']:
9580 if isinstance(item['default'], list):
9581 file.Write("%s %s[%d];\n" % (item['type'], item['name'],
9582 len(item['default'])))
9583 else:
9584 file.Write("%s %s;\n" % (item['type'], item['name']))
9586 if item.get('cached', False):
9587 if isinstance(item['default'], list):
9588 file.Write("%s cached_%s[%d];\n" % (item['type'], item['name'],
9589 len(item['default'])))
9590 else:
9591 file.Write("%s cached_%s;\n" % (item['type'], item['name']))
9593 file.Write("\n")
9595 file.Write("""
9596 inline void SetDeviceCapabilityState(GLenum cap, bool enable) {
9597 switch (cap) {
9598 """)
9599 for capability in _CAPABILITY_FLAGS:
9600 file.Write("""\
9601 case GL_%s:
9602 """ % capability['name'].upper())
9603 file.Write("""\
9604 if (enable_flags.cached_%(name)s == enable &&
9605 !ignore_cached_state)
9606 return;
9607 enable_flags.cached_%(name)s = enable;
9608 break;
9609 """ % capability)
9611 file.Write("""\
9612 default:
9613 NOTREACHED();
9614 return;
9616 if (enable)
9617 glEnable(cap);
9618 else
9619 glDisable(cap);
9621 """)
9623 file.Close()
9624 self.generated_cpp_filenames.append(file.filename)
9626 def WriteClientContextStateHeader(self, filename):
9627 """Writes the client context state header."""
9628 file = CHeaderWriter(
9629 filename,
9630 "// It is included by client_context_state.h\n")
9631 file.Write("struct EnableFlags {\n")
9632 file.Write(" EnableFlags();\n")
9633 for capability in _CAPABILITY_FLAGS:
9634 file.Write(" bool %s;\n" % capability['name'])
9635 file.Write("};\n\n")
9637 file.Close()
9638 self.generated_cpp_filenames.append(file.filename)
9640 def WriteContextStateGetters(self, file, class_name):
9641 """Writes the state getters."""
9642 for gl_type in ["GLint", "GLfloat"]:
9643 file.Write("""
9644 bool %s::GetStateAs%s(
9645 GLenum pname, %s* params, GLsizei* num_written) const {
9646 switch (pname) {
9647 """ % (class_name, gl_type, gl_type))
9648 for state_name in sorted(_STATES.keys()):
9649 state = _STATES[state_name]
9650 if 'enum' in state:
9651 file.Write(" case %s:\n" % state['enum'])
9652 file.Write(" *num_written = %d;\n" % len(state['states']))
9653 file.Write(" if (params) {\n")
9654 for ndx,item in enumerate(state['states']):
9655 file.Write(" params[%d] = static_cast<%s>(%s);\n" %
9656 (ndx, gl_type, item['name']))
9657 file.Write(" }\n")
9658 file.Write(" return true;\n")
9659 else:
9660 for item in state['states']:
9661 file.Write(" case %s:\n" % item['enum'])
9662 if isinstance(item['default'], list):
9663 item_len = len(item['default'])
9664 file.Write(" *num_written = %d;\n" % item_len)
9665 file.Write(" if (params) {\n")
9666 if item['type'] == gl_type:
9667 file.Write(" memcpy(params, %s, sizeof(%s) * %d);\n" %
9668 (item['name'], item['type'], item_len))
9669 else:
9670 file.Write(" for (size_t i = 0; i < %s; ++i) {\n" %
9671 item_len)
9672 file.Write(" params[i] = %s;\n" %
9673 (GetGLGetTypeConversion(gl_type, item['type'],
9674 "%s[i]" % item['name'])))
9675 file.Write(" }\n");
9676 else:
9677 file.Write(" *num_written = 1;\n")
9678 file.Write(" if (params) {\n")
9679 file.Write(" params[0] = %s;\n" %
9680 (GetGLGetTypeConversion(gl_type, item['type'],
9681 item['name'])))
9682 file.Write(" }\n")
9683 file.Write(" return true;\n")
9684 for capability in _CAPABILITY_FLAGS:
9685 file.Write(" case GL_%s:\n" % capability['name'].upper())
9686 file.Write(" *num_written = 1;\n")
9687 file.Write(" if (params) {\n")
9688 file.Write(
9689 " params[0] = static_cast<%s>(enable_flags.%s);\n" %
9690 (gl_type, capability['name']))
9691 file.Write(" }\n")
9692 file.Write(" return true;\n")
9693 file.Write(""" default:
9694 return false;
9697 """)
9699 def WriteServiceContextStateImpl(self, filename):
9700 """Writes the context state service implementation."""
9701 file = CHeaderWriter(
9702 filename,
9703 "// It is included by context_state.cc\n")
9704 code = []
9705 for capability in _CAPABILITY_FLAGS:
9706 code.append("%s(%s)" %
9707 (capability['name'],
9708 ('false', 'true')['default' in capability]))
9709 code.append("cached_%s(%s)" %
9710 (capability['name'],
9711 ('false', 'true')['default' in capability]))
9712 file.Write("ContextState::EnableFlags::EnableFlags()\n : %s {\n}\n" %
9713 ",\n ".join(code))
9714 file.Write("\n")
9716 file.Write("void ContextState::Initialize() {\n")
9717 for state_name in sorted(_STATES.keys()):
9718 state = _STATES[state_name]
9719 for item in state['states']:
9720 if isinstance(item['default'], list):
9721 for ndx, value in enumerate(item['default']):
9722 file.Write(" %s[%d] = %s;\n" % (item['name'], ndx, value))
9723 else:
9724 file.Write(" %s = %s;\n" % (item['name'], item['default']))
9725 if item.get('cached', False):
9726 if isinstance(item['default'], list):
9727 for ndx, value in enumerate(item['default']):
9728 file.Write(" cached_%s[%d] = %s;\n" % (item['name'], ndx, value))
9729 else:
9730 file.Write(" cached_%s = %s;\n" % (item['name'], item['default']))
9731 file.Write("}\n")
9733 file.Write("""
9734 void ContextState::InitCapabilities(const ContextState* prev_state) const {
9735 """)
9736 def WriteCapabilities(test_prev, es3_caps):
9737 for capability in _CAPABILITY_FLAGS:
9738 capability_name = capability['name']
9739 capability_es3 = 'es3' in capability and capability['es3'] == True
9740 if capability_es3 and not es3_caps or not capability_es3 and es3_caps:
9741 continue
9742 if test_prev:
9743 file.Write(""" if (prev_state->enable_flags.cached_%s !=
9744 enable_flags.cached_%s) {\n""" %
9745 (capability_name, capability_name))
9746 file.Write(" EnableDisable(GL_%s, enable_flags.cached_%s);\n" %
9747 (capability_name.upper(), capability_name))
9748 if test_prev:
9749 file.Write(" }")
9751 file.Write(" if (prev_state) {")
9752 WriteCapabilities(True, False)
9753 file.Write(" if (feature_info_->IsES3Capable()) {\n")
9754 WriteCapabilities(True, True)
9755 file.Write(" }\n")
9756 file.Write(" } else {")
9757 WriteCapabilities(False, False)
9758 file.Write(" if (feature_info_->IsES3Capable()) {\n")
9759 WriteCapabilities(False, True)
9760 file.Write(" }\n")
9761 file.Write(" }")
9763 file.Write("""}
9765 void ContextState::InitState(const ContextState *prev_state) const {
9766 """)
9768 def WriteStates(test_prev):
9769 # We need to sort the keys so the expectations match
9770 for state_name in sorted(_STATES.keys()):
9771 state = _STATES[state_name]
9772 if state['type'] == 'FrontBack':
9773 num_states = len(state['states'])
9774 for ndx, group in enumerate(Grouper(num_states / 2, state['states'])):
9775 if test_prev:
9776 file.Write(" if (")
9777 args = []
9778 for place, item in enumerate(group):
9779 item_name = CachedStateName(item)
9780 args.append('%s' % item_name)
9781 if test_prev:
9782 if place > 0:
9783 file.Write(' ||\n')
9784 file.Write("(%s != prev_state->%s)" % (item_name, item_name))
9785 if test_prev:
9786 file.Write(")\n")
9787 file.Write(
9788 " gl%s(%s, %s);\n" %
9789 (state['func'], ('GL_FRONT', 'GL_BACK')[ndx], ", ".join(args)))
9790 elif state['type'] == 'NamedParameter':
9791 for item in state['states']:
9792 item_name = CachedStateName(item)
9794 if 'extension_flag' in item:
9795 file.Write(" if (feature_info_->feature_flags().%s) {\n " %
9796 item['extension_flag'])
9797 if test_prev:
9798 if isinstance(item['default'], list):
9799 file.Write(" if (memcmp(prev_state->%s, %s, "
9800 "sizeof(%s) * %d)) {\n" %
9801 (item_name, item_name, item['type'],
9802 len(item['default'])))
9803 else:
9804 file.Write(" if (prev_state->%s != %s) {\n " %
9805 (item_name, item_name))
9806 if 'gl_version_flag' in item:
9807 item_name = item['gl_version_flag']
9808 inverted = ''
9809 if item_name[0] == '!':
9810 inverted = '!'
9811 item_name = item_name[1:]
9812 file.Write(" if (%sfeature_info_->gl_version_info().%s) {\n" %
9813 (inverted, item_name))
9814 file.Write(" gl%s(%s, %s);\n" %
9815 (state['func'],
9816 (item['enum_set']
9817 if 'enum_set' in item else item['enum']),
9818 item['name']))
9819 if 'gl_version_flag' in item:
9820 file.Write(" }\n")
9821 if test_prev:
9822 if 'extension_flag' in item:
9823 file.Write(" ")
9824 file.Write(" }")
9825 if 'extension_flag' in item:
9826 file.Write(" }")
9827 else:
9828 if 'extension_flag' in state:
9829 file.Write(" if (feature_info_->feature_flags().%s)\n " %
9830 state['extension_flag'])
9831 if test_prev:
9832 file.Write(" if (")
9833 args = []
9834 for place, item in enumerate(state['states']):
9835 item_name = CachedStateName(item)
9836 args.append('%s' % item_name)
9837 if test_prev:
9838 if place > 0:
9839 file.Write(' ||\n')
9840 file.Write("(%s != prev_state->%s)" %
9841 (item_name, item_name))
9842 if test_prev:
9843 file.Write(" )\n")
9844 file.Write(" gl%s(%s);\n" % (state['func'], ", ".join(args)))
9846 file.Write(" if (prev_state) {")
9847 WriteStates(True)
9848 file.Write(" } else {")
9849 WriteStates(False)
9850 file.Write(" }")
9851 file.Write("}\n")
9853 file.Write("""bool ContextState::GetEnabled(GLenum cap) const {
9854 switch (cap) {
9855 """)
9856 for capability in _CAPABILITY_FLAGS:
9857 file.Write(" case GL_%s:\n" % capability['name'].upper())
9858 file.Write(" return enable_flags.%s;\n" % capability['name'])
9859 file.Write(""" default:
9860 NOTREACHED();
9861 return false;
9864 """)
9866 self.WriteContextStateGetters(file, "ContextState")
9867 file.Close()
9868 self.generated_cpp_filenames.append(file.filename)
9870 def WriteClientContextStateImpl(self, filename):
9871 """Writes the context state client side implementation."""
9872 file = CHeaderWriter(
9873 filename,
9874 "// It is included by client_context_state.cc\n")
9875 code = []
9876 for capability in _CAPABILITY_FLAGS:
9877 code.append("%s(%s)" %
9878 (capability['name'],
9879 ('false', 'true')['default' in capability]))
9880 file.Write(
9881 "ClientContextState::EnableFlags::EnableFlags()\n : %s {\n}\n" %
9882 ",\n ".join(code))
9883 file.Write("\n")
9885 file.Write("""
9886 bool ClientContextState::SetCapabilityState(
9887 GLenum cap, bool enabled, bool* changed) {
9888 *changed = false;
9889 switch (cap) {
9890 """)
9891 for capability in _CAPABILITY_FLAGS:
9892 file.Write(" case GL_%s:\n" % capability['name'].upper())
9893 file.Write(""" if (enable_flags.%(name)s != enabled) {
9894 *changed = true;
9895 enable_flags.%(name)s = enabled;
9897 return true;
9898 """ % capability)
9899 file.Write(""" default:
9900 return false;
9903 """)
9904 file.Write("""bool ClientContextState::GetEnabled(
9905 GLenum cap, bool* enabled) const {
9906 switch (cap) {
9907 """)
9908 for capability in _CAPABILITY_FLAGS:
9909 file.Write(" case GL_%s:\n" % capability['name'].upper())
9910 file.Write(" *enabled = enable_flags.%s;\n" % capability['name'])
9911 file.Write(" return true;\n")
9912 file.Write(""" default:
9913 return false;
9916 """)
9917 file.Close()
9918 self.generated_cpp_filenames.append(file.filename)
9920 def WriteServiceImplementation(self, filename):
9921 """Writes the service decorder implementation."""
9922 file = CHeaderWriter(
9923 filename,
9924 "// It is included by gles2_cmd_decoder.cc\n")
9926 for func in self.functions:
9927 if True:
9928 #gen_cmd = func.GetInfo('gen_cmd')
9929 #if gen_cmd == True or gen_cmd == None:
9930 func.WriteServiceImplementation(file)
9932 file.Write("""
9933 bool GLES2DecoderImpl::SetCapabilityState(GLenum cap, bool enabled) {
9934 switch (cap) {
9935 """)
9936 for capability in _CAPABILITY_FLAGS:
9937 file.Write(" case GL_%s:\n" % capability['name'].upper())
9938 if 'state_flag' in capability:
9940 file.Write("""\
9941 state_.enable_flags.%(name)s = enabled;
9942 if (state_.enable_flags.cached_%(name)s != enabled
9943 || state_.ignore_cached_state) {
9944 %(state_flag)s = true;
9946 return false;
9947 """ % capability)
9948 else:
9949 file.Write("""\
9950 state_.enable_flags.%(name)s = enabled;
9951 if (state_.enable_flags.cached_%(name)s != enabled
9952 || state_.ignore_cached_state) {
9953 state_.enable_flags.cached_%(name)s = enabled;
9954 return true;
9956 return false;
9957 """ % capability)
9958 file.Write(""" default:
9959 NOTREACHED();
9960 return false;
9963 """)
9964 file.Close()
9965 self.generated_cpp_filenames.append(file.filename)
9967 def WriteServiceUnitTests(self, filename):
9968 """Writes the service decorder unit tests."""
9969 num_tests = len(self.functions)
9970 FUNCTIONS_PER_FILE = 98 # hard code this so it doesn't change.
9971 count = 0
9972 for test_num in range(0, num_tests, FUNCTIONS_PER_FILE):
9973 count += 1
9974 name = filename % count
9975 file = CHeaderWriter(
9976 name,
9977 "// It is included by gles2_cmd_decoder_unittest_%d.cc\n" % count)
9978 test_name = 'GLES2DecoderTest%d' % count
9979 end = test_num + FUNCTIONS_PER_FILE
9980 if end > num_tests:
9981 end = num_tests
9982 for idx in range(test_num, end):
9983 func = self.functions[idx]
9985 # Do any filtering of the functions here, so that the functions
9986 # will not move between the numbered files if filtering properties
9987 # are changed.
9988 if func.GetInfo('extension_flag'):
9989 continue
9991 if True:
9992 #gen_cmd = func.GetInfo('gen_cmd')
9993 #if gen_cmd == True or gen_cmd == None:
9994 if func.GetInfo('unit_test') == False:
9995 file.Write("// TODO(gman): %s\n" % func.name)
9996 else:
9997 func.WriteServiceUnitTest(file, {
9998 'test_name': test_name
10000 file.Close()
10001 self.generated_cpp_filenames.append(file.filename)
10002 file = CHeaderWriter(
10003 filename % 0,
10004 "// It is included by gles2_cmd_decoder_unittest_base.cc\n")
10005 file.Write(
10006 """void GLES2DecoderTestBase::SetupInitCapabilitiesExpectations(
10007 bool es3_capable) {""")
10008 for capability in _CAPABILITY_FLAGS:
10009 capability_es3 = 'es3' in capability and capability['es3'] == True
10010 if not capability_es3:
10011 file.Write(" ExpectEnableDisable(GL_%s, %s);\n" %
10012 (capability['name'].upper(),
10013 ('false', 'true')['default' in capability]))
10015 file.Write(" if (es3_capable) {")
10016 for capability in _CAPABILITY_FLAGS:
10017 capability_es3 = 'es3' in capability and capability['es3'] == True
10018 if capability_es3:
10019 file.Write(" ExpectEnableDisable(GL_%s, %s);\n" %
10020 (capability['name'].upper(),
10021 ('false', 'true')['default' in capability]))
10022 file.Write(""" }
10025 void GLES2DecoderTestBase::SetupInitStateExpectations() {
10026 """)
10028 # We need to sort the keys so the expectations match
10029 for state_name in sorted(_STATES.keys()):
10030 state = _STATES[state_name]
10031 if state['type'] == 'FrontBack':
10032 num_states = len(state['states'])
10033 for ndx, group in enumerate(Grouper(num_states / 2, state['states'])):
10034 args = []
10035 for item in group:
10036 if 'expected' in item:
10037 args.append(item['expected'])
10038 else:
10039 args.append(item['default'])
10040 file.Write(
10041 " EXPECT_CALL(*gl_, %s(%s, %s))\n" %
10042 (state['func'], ('GL_FRONT', 'GL_BACK')[ndx], ", ".join(args)))
10043 file.Write(" .Times(1)\n")
10044 file.Write(" .RetiresOnSaturation();\n")
10045 elif state['type'] == 'NamedParameter':
10046 for item in state['states']:
10047 if 'extension_flag' in item:
10048 file.Write(" if (group_->feature_info()->feature_flags().%s) {\n" %
10049 item['extension_flag'])
10050 file.Write(" ")
10051 expect_value = item['default']
10052 if isinstance(expect_value, list):
10053 # TODO: Currently we do not check array values.
10054 expect_value = "_"
10056 file.Write(
10057 " EXPECT_CALL(*gl_, %s(%s, %s))\n" %
10058 (state['func'],
10059 (item['enum_set']
10060 if 'enum_set' in item else item['enum']),
10061 expect_value))
10062 file.Write(" .Times(1)\n")
10063 file.Write(" .RetiresOnSaturation();\n")
10064 if 'extension_flag' in item:
10065 file.Write(" }\n")
10066 else:
10067 if 'extension_flag' in state:
10068 file.Write(" if (group_->feature_info()->feature_flags().%s) {\n" %
10069 state['extension_flag'])
10070 file.Write(" ")
10071 args = []
10072 for item in state['states']:
10073 if 'expected' in item:
10074 args.append(item['expected'])
10075 else:
10076 args.append(item['default'])
10077 # TODO: Currently we do not check array values.
10078 args = ["_" if isinstance(arg, list) else arg for arg in args]
10079 file.Write(" EXPECT_CALL(*gl_, %s(%s))\n" %
10080 (state['func'], ", ".join(args)))
10081 file.Write(" .Times(1)\n")
10082 file.Write(" .RetiresOnSaturation();\n")
10083 if 'extension_flag' in state:
10084 file.Write(" }\n")
10085 file.Write("""}
10086 """)
10087 file.Close()
10088 self.generated_cpp_filenames.append(file.filename)
10090 def WriteServiceUnitTestsForExtensions(self, filename):
10091 """Writes the service decorder unit tests for functions with extension_flag.
10093 The functions are special in that they need a specific unit test
10094 baseclass to turn on the extension.
10096 functions = [f for f in self.functions if f.GetInfo('extension_flag')]
10097 file = CHeaderWriter(
10098 filename,
10099 "// It is included by gles2_cmd_decoder_unittest_extensions.cc\n")
10100 for func in functions:
10101 if True:
10102 if func.GetInfo('unit_test') == False:
10103 file.Write("// TODO(gman): %s\n" % func.name)
10104 else:
10105 extension = ToCamelCase(
10106 ToGLExtensionString(func.GetInfo('extension_flag')))
10107 func.WriteServiceUnitTest(file, {
10108 'test_name': 'GLES2DecoderTestWith%s' % extension
10111 file.Close()
10112 self.generated_cpp_filenames.append(file.filename)
10114 def WriteGLES2Header(self, filename):
10115 """Writes the GLES2 header."""
10116 file = CHeaderWriter(
10117 filename,
10118 "// This file contains Chromium-specific GLES2 declarations.\n\n")
10120 for func in self.original_functions:
10121 func.WriteGLES2Header(file)
10123 file.Write("\n")
10124 file.Close()
10125 self.generated_cpp_filenames.append(file.filename)
10127 def WriteGLES2CLibImplementation(self, filename):
10128 """Writes the GLES2 c lib implementation."""
10129 file = CHeaderWriter(
10130 filename,
10131 "// These functions emulate GLES2 over command buffers.\n")
10133 for func in self.original_functions:
10134 func.WriteGLES2CLibImplementation(file)
10136 file.Write("""
10137 namespace gles2 {
10139 extern const NameToFunc g_gles2_function_table[] = {
10140 """)
10141 for func in self.original_functions:
10142 file.Write(
10143 ' { "gl%s", reinterpret_cast<GLES2FunctionPointer>(gl%s), },\n' %
10144 (func.name, func.name))
10145 file.Write(""" { NULL, NULL, },
10148 } // namespace gles2
10149 """)
10150 file.Close()
10151 self.generated_cpp_filenames.append(file.filename)
10153 def WriteGLES2InterfaceHeader(self, filename):
10154 """Writes the GLES2 interface header."""
10155 file = CHeaderWriter(
10156 filename,
10157 "// This file is included by gles2_interface.h to declare the\n"
10158 "// GL api functions.\n")
10159 for func in self.original_functions:
10160 func.WriteGLES2InterfaceHeader(file)
10161 file.Close()
10162 self.generated_cpp_filenames.append(file.filename)
10164 def WriteMojoGLES2ImplHeader(self, filename):
10165 """Writes the Mojo GLES2 implementation header."""
10166 file = CHeaderWriter(
10167 filename,
10168 "// This file is included by gles2_interface.h to declare the\n"
10169 "// GL api functions.\n")
10171 code = """
10172 #include "gpu/command_buffer/client/gles2_interface.h"
10173 #include "third_party/mojo/src/mojo/public/c/gles2/gles2.h"
10175 namespace mojo {
10177 class MojoGLES2Impl : public gpu::gles2::GLES2Interface {
10178 public:
10179 explicit MojoGLES2Impl(MojoGLES2Context context) {
10180 context_ = context;
10182 ~MojoGLES2Impl() override {}
10184 file.Write(code);
10185 for func in self.original_functions:
10186 func.WriteMojoGLES2ImplHeader(file)
10187 code = """
10188 private:
10189 MojoGLES2Context context_;
10192 } // namespace mojo
10194 file.Write(code);
10195 file.Close()
10196 self.generated_cpp_filenames.append(file.filename)
10198 def WriteMojoGLES2Impl(self, filename):
10199 """Writes the Mojo GLES2 implementation."""
10200 file = CWriter(filename)
10201 file.Write(_LICENSE)
10202 file.Write(_DO_NOT_EDIT_WARNING)
10204 code = """
10205 #include "mojo/gpu/mojo_gles2_impl_autogen.h"
10207 #include "base/logging.h"
10208 #include "third_party/mojo/src/mojo/public/c/gles2/chromium_miscellaneous.h"
10209 #include "third_party/mojo/src/mojo/public/c/gles2/chromium_sub_image.h"
10210 #include "third_party/mojo/src/mojo/public/c/gles2/chromium_sync_point.h"
10211 #include "third_party/mojo/src/mojo/public/c/gles2/chromium_texture_mailbox.h"
10212 #include "third_party/mojo/src/mojo/public/c/gles2/gles2.h"
10213 #include "third_party/mojo/src/mojo/public/c/gles2/occlusion_query_ext.h"
10215 namespace mojo {
10218 file.Write(code);
10219 for func in self.original_functions:
10220 func.WriteMojoGLES2Impl(file)
10221 code = """
10223 } // namespace mojo
10225 file.Write(code);
10226 file.Close()
10227 self.generated_cpp_filenames.append(file.filename)
10229 def WriteGLES2InterfaceStub(self, filename):
10230 """Writes the GLES2 interface stub header."""
10231 file = CHeaderWriter(
10232 filename,
10233 "// This file is included by gles2_interface_stub.h.\n")
10234 for func in self.original_functions:
10235 func.WriteGLES2InterfaceStub(file)
10236 file.Close()
10237 self.generated_cpp_filenames.append(file.filename)
10239 def WriteGLES2InterfaceStubImpl(self, filename):
10240 """Writes the GLES2 interface header."""
10241 file = CHeaderWriter(
10242 filename,
10243 "// This file is included by gles2_interface_stub.cc.\n")
10244 for func in self.original_functions:
10245 func.WriteGLES2InterfaceStubImpl(file)
10246 file.Close()
10247 self.generated_cpp_filenames.append(file.filename)
10249 def WriteGLES2ImplementationHeader(self, filename):
10250 """Writes the GLES2 Implementation header."""
10251 file = CHeaderWriter(
10252 filename,
10253 "// This file is included by gles2_implementation.h to declare the\n"
10254 "// GL api functions.\n")
10255 for func in self.original_functions:
10256 func.WriteGLES2ImplementationHeader(file)
10257 file.Close()
10258 self.generated_cpp_filenames.append(file.filename)
10260 def WriteGLES2Implementation(self, filename):
10261 """Writes the GLES2 Implementation."""
10262 file = CHeaderWriter(
10263 filename,
10264 "// This file is included by gles2_implementation.cc to define the\n"
10265 "// GL api functions.\n")
10266 for func in self.original_functions:
10267 func.WriteGLES2Implementation(file)
10268 file.Close()
10269 self.generated_cpp_filenames.append(file.filename)
10271 def WriteGLES2TraceImplementationHeader(self, filename):
10272 """Writes the GLES2 Trace Implementation header."""
10273 file = CHeaderWriter(
10274 filename,
10275 "// This file is included by gles2_trace_implementation.h\n")
10276 for func in self.original_functions:
10277 func.WriteGLES2TraceImplementationHeader(file)
10278 file.Close()
10279 self.generated_cpp_filenames.append(file.filename)
10281 def WriteGLES2TraceImplementation(self, filename):
10282 """Writes the GLES2 Trace Implementation."""
10283 file = CHeaderWriter(
10284 filename,
10285 "// This file is included by gles2_trace_implementation.cc\n")
10286 for func in self.original_functions:
10287 func.WriteGLES2TraceImplementation(file)
10288 file.Close()
10289 self.generated_cpp_filenames.append(file.filename)
10291 def WriteGLES2ImplementationUnitTests(self, filename):
10292 """Writes the GLES2 helper header."""
10293 file = CHeaderWriter(
10294 filename,
10295 "// This file is included by gles2_implementation.h to declare the\n"
10296 "// GL api functions.\n")
10297 for func in self.original_functions:
10298 func.WriteGLES2ImplementationUnitTest(file)
10299 file.Close()
10300 self.generated_cpp_filenames.append(file.filename)
10302 def WriteServiceUtilsHeader(self, filename):
10303 """Writes the gles2 auto generated utility header."""
10304 file = CHeaderWriter(filename)
10305 for name in sorted(_NAMED_TYPE_INFO.keys()):
10306 named_type = NamedType(_NAMED_TYPE_INFO[name])
10307 if named_type.IsConstant():
10308 continue
10309 file.Write("ValueValidator<%s> %s;\n" %
10310 (named_type.GetType(), ToUnderscore(name)))
10311 file.Write("\n")
10312 file.Close()
10313 self.generated_cpp_filenames.append(file.filename)
10315 def WriteServiceUtilsImplementation(self, filename):
10316 """Writes the gles2 auto generated utility implementation."""
10317 file = CHeaderWriter(filename)
10318 names = sorted(_NAMED_TYPE_INFO.keys())
10319 for name in names:
10320 named_type = NamedType(_NAMED_TYPE_INFO[name])
10321 if named_type.IsConstant():
10322 continue
10323 if named_type.GetValidValues():
10324 file.Write("static const %s valid_%s_table[] = {\n" %
10325 (named_type.GetType(), ToUnderscore(name)))
10326 for value in named_type.GetValidValues():
10327 file.Write(" %s,\n" % value)
10328 file.Write("};\n")
10329 file.Write("\n")
10330 if named_type.GetValidValuesES3():
10331 file.Write("static const %s valid_%s_table_es3[] = {\n" %
10332 (named_type.GetType(), ToUnderscore(name)))
10333 for value in named_type.GetValidValuesES3():
10334 file.Write(" %s,\n" % value)
10335 file.Write("};\n")
10336 file.Write("\n")
10337 if named_type.GetDeprecatedValuesES3():
10338 file.Write("static const %s deprecated_%s_table_es3[] = {\n" %
10339 (named_type.GetType(), ToUnderscore(name)))
10340 for value in named_type.GetDeprecatedValuesES3():
10341 file.Write(" %s,\n" % value)
10342 file.Write("};\n")
10343 file.Write("\n")
10344 file.Write("Validators::Validators()")
10345 pre = ' : '
10346 for count, name in enumerate(names):
10347 named_type = NamedType(_NAMED_TYPE_INFO[name])
10348 if named_type.IsConstant():
10349 continue
10350 if named_type.GetValidValues():
10351 code = """%(pre)s%(name)s(
10352 valid_%(name)s_table, arraysize(valid_%(name)s_table))"""
10353 else:
10354 code = "%(pre)s%(name)s()"
10355 file.Write(code % {
10356 'name': ToUnderscore(name),
10357 'pre': pre,
10359 pre = ',\n '
10360 file.Write(" {\n");
10361 file.Write("}\n\n");
10363 file.Write("void Validators::UpdateValuesES3() {\n")
10364 for name in names:
10365 named_type = NamedType(_NAMED_TYPE_INFO[name])
10366 if named_type.GetDeprecatedValuesES3():
10367 code = """ %(name)s.RemoveValues(
10368 deprecated_%(name)s_table_es3, arraysize(deprecated_%(name)s_table_es3));
10370 file.Write(code % {
10371 'name': ToUnderscore(name),
10373 if named_type.GetValidValuesES3():
10374 code = """ %(name)s.AddValues(
10375 valid_%(name)s_table_es3, arraysize(valid_%(name)s_table_es3));
10377 file.Write(code % {
10378 'name': ToUnderscore(name),
10380 file.Write("}\n\n");
10381 file.Close()
10382 self.generated_cpp_filenames.append(file.filename)
10384 def WriteCommonUtilsHeader(self, filename):
10385 """Writes the gles2 common utility header."""
10386 file = CHeaderWriter(filename)
10387 type_infos = sorted(_NAMED_TYPE_INFO.keys())
10388 for type_info in type_infos:
10389 if _NAMED_TYPE_INFO[type_info]['type'] == 'GLenum':
10390 file.Write("static std::string GetString%s(uint32_t value);\n" %
10391 type_info)
10392 file.Write("\n")
10393 file.Close()
10394 self.generated_cpp_filenames.append(file.filename)
10396 def WriteCommonUtilsImpl(self, filename):
10397 """Writes the gles2 common utility header."""
10398 enum_re = re.compile(r'\#define\s+(GL_[a-zA-Z0-9_]+)\s+([0-9A-Fa-fx]+)')
10399 dict = {}
10400 for fname in ['third_party/khronos/GLES2/gl2.h',
10401 'third_party/khronos/GLES2/gl2ext.h',
10402 'third_party/khronos/GLES3/gl3.h',
10403 'gpu/GLES2/gl2chromium.h',
10404 'gpu/GLES2/gl2extchromium.h']:
10405 lines = open(fname).readlines()
10406 for line in lines:
10407 m = enum_re.match(line)
10408 if m:
10409 name = m.group(1)
10410 value = m.group(2)
10411 if len(value) <= 10:
10412 if not value in dict:
10413 dict[value] = name
10414 # check our own _CHROMIUM macro conflicts with khronos GL headers.
10415 elif dict[value] != name and (name.endswith('_CHROMIUM') or
10416 dict[value].endswith('_CHROMIUM')):
10417 self.Error("code collision: %s and %s have the same code %s" %
10418 (dict[value], name, value))
10420 file = CHeaderWriter(filename)
10421 file.Write("static const GLES2Util::EnumToString "
10422 "enum_to_string_table[] = {\n")
10423 for value in dict:
10424 file.Write(' { %s, "%s", },\n' % (value, dict[value]))
10425 file.Write("""};
10427 const GLES2Util::EnumToString* const GLES2Util::enum_to_string_table_ =
10428 enum_to_string_table;
10429 const size_t GLES2Util::enum_to_string_table_len_ =
10430 sizeof(enum_to_string_table) / sizeof(enum_to_string_table[0]);
10432 """)
10434 enums = sorted(_NAMED_TYPE_INFO.keys())
10435 for enum in enums:
10436 if _NAMED_TYPE_INFO[enum]['type'] == 'GLenum':
10437 file.Write("std::string GLES2Util::GetString%s(uint32_t value) {\n" %
10438 enum)
10439 valid_list = _NAMED_TYPE_INFO[enum]['valid']
10440 if 'valid_es3' in _NAMED_TYPE_INFO[enum]:
10441 valid_list = valid_list + _NAMED_TYPE_INFO[enum]['valid_es3']
10442 assert len(valid_list) == len(set(valid_list))
10443 if len(valid_list) > 0:
10444 file.Write(" static const EnumToString string_table[] = {\n")
10445 for value in valid_list:
10446 file.Write(' { %s, "%s" },\n' % (value, value))
10447 file.Write(""" };
10448 return GLES2Util::GetQualifiedEnumString(
10449 string_table, arraysize(string_table), value);
10452 """)
10453 else:
10454 file.Write(""" return GLES2Util::GetQualifiedEnumString(
10455 NULL, 0, value);
10458 """)
10459 file.Close()
10460 self.generated_cpp_filenames.append(file.filename)
10462 def WritePepperGLES2Interface(self, filename, dev):
10463 """Writes the Pepper OpenGLES interface definition."""
10464 file = CWriter(filename)
10465 file.Write(_LICENSE)
10466 file.Write(_DO_NOT_EDIT_WARNING)
10468 file.Write("label Chrome {\n")
10469 file.Write(" M39 = 1.0\n")
10470 file.Write("};\n\n")
10472 if not dev:
10473 # Declare GL types.
10474 file.Write("[version=1.0]\n")
10475 file.Write("describe {\n")
10476 for gltype in ['GLbitfield', 'GLboolean', 'GLbyte', 'GLclampf',
10477 'GLclampx', 'GLenum', 'GLfixed', 'GLfloat', 'GLint',
10478 'GLintptr', 'GLshort', 'GLsizei', 'GLsizeiptr',
10479 'GLubyte', 'GLuint', 'GLushort']:
10480 file.Write(" %s;\n" % gltype)
10481 file.Write(" %s_ptr_t;\n" % gltype)
10482 file.Write("};\n\n")
10484 # C level typedefs.
10485 file.Write("#inline c\n")
10486 file.Write("#include \"ppapi/c/pp_resource.h\"\n")
10487 if dev:
10488 file.Write("#include \"ppapi/c/ppb_opengles2.h\"\n\n")
10489 else:
10490 file.Write("\n#ifndef __gl2_h_\n")
10491 for (k, v) in _GL_TYPES.iteritems():
10492 file.Write("typedef %s %s;\n" % (v, k))
10493 file.Write("#ifdef _WIN64\n")
10494 for (k, v) in _GL_TYPES_64.iteritems():
10495 file.Write("typedef %s %s;\n" % (v, k))
10496 file.Write("#else\n")
10497 for (k, v) in _GL_TYPES_32.iteritems():
10498 file.Write("typedef %s %s;\n" % (v, k))
10499 file.Write("#endif // _WIN64\n")
10500 file.Write("#endif // __gl2_h_\n\n")
10501 file.Write("#endinl\n")
10503 for interface in self.pepper_interfaces:
10504 if interface.dev != dev:
10505 continue
10506 # Historically, we provide OpenGLES2 interfaces with struct
10507 # namespace. Not to break code which uses the interface as
10508 # "struct OpenGLES2", we put it in struct namespace.
10509 file.Write('\n[macro="%s", force_struct_namespace]\n' %
10510 interface.GetInterfaceName())
10511 file.Write("interface %s {\n" % interface.GetStructName())
10512 for func in self.original_functions:
10513 if not func.InPepperInterface(interface):
10514 continue
10516 ret_type = func.MapCTypeToPepperIdlType(func.return_type,
10517 is_for_return_type=True)
10518 func_prefix = " %s %s(" % (ret_type, func.GetPepperName())
10519 file.Write(func_prefix)
10520 file.Write("[in] PP_Resource context")
10521 for arg in func.MakeTypedPepperIdlArgStrings():
10522 file.Write(",\n" + " " * len(func_prefix) + arg)
10523 file.Write(");\n")
10524 file.Write("};\n\n")
10527 file.Close()
10529 def WritePepperGLES2Implementation(self, filename):
10530 """Writes the Pepper OpenGLES interface implementation."""
10532 file = CWriter(filename)
10533 file.Write(_LICENSE)
10534 file.Write(_DO_NOT_EDIT_WARNING)
10536 file.Write("#include \"ppapi/shared_impl/ppb_opengles2_shared.h\"\n\n")
10537 file.Write("#include \"base/logging.h\"\n")
10538 file.Write("#include \"gpu/command_buffer/client/gles2_implementation.h\"\n")
10539 file.Write("#include \"ppapi/shared_impl/ppb_graphics_3d_shared.h\"\n")
10540 file.Write("#include \"ppapi/thunk/enter.h\"\n\n")
10542 file.Write("namespace ppapi {\n\n")
10543 file.Write("namespace {\n\n")
10545 file.Write("typedef thunk::EnterResource<thunk::PPB_Graphics3D_API>"
10546 " Enter3D;\n\n")
10548 file.Write("gpu::gles2::GLES2Implementation* ToGles2Impl(Enter3D*"
10549 " enter) {\n")
10550 file.Write(" DCHECK(enter);\n")
10551 file.Write(" DCHECK(enter->succeeded());\n")
10552 file.Write(" return static_cast<PPB_Graphics3D_Shared*>(enter->object())->"
10553 "gles2_impl();\n");
10554 file.Write("}\n\n");
10556 for func in self.original_functions:
10557 if not func.InAnyPepperExtension():
10558 continue
10560 original_arg = func.MakeTypedPepperArgString("")
10561 context_arg = "PP_Resource context_id"
10562 if len(original_arg):
10563 arg = context_arg + ", " + original_arg
10564 else:
10565 arg = context_arg
10566 file.Write("%s %s(%s) {\n" %
10567 (func.return_type, func.GetPepperName(), arg))
10568 file.Write(" Enter3D enter(context_id, true);\n")
10569 file.Write(" if (enter.succeeded()) {\n")
10571 return_str = "" if func.return_type == "void" else "return "
10572 file.Write(" %sToGles2Impl(&enter)->%s(%s);\n" %
10573 (return_str, func.original_name,
10574 func.MakeOriginalArgString("")))
10575 file.Write(" }")
10576 if func.return_type == "void":
10577 file.Write("\n")
10578 else:
10579 file.Write(" else {\n")
10580 file.Write(" return %s;\n" % func.GetErrorReturnString())
10581 file.Write(" }\n")
10582 file.Write("}\n\n")
10584 file.Write("} // namespace\n")
10586 for interface in self.pepper_interfaces:
10587 file.Write("const %s* PPB_OpenGLES2_Shared::Get%sInterface() {\n" %
10588 (interface.GetStructName(), interface.GetName()))
10589 file.Write(" static const struct %s "
10590 "ppb_opengles2 = {\n" % interface.GetStructName())
10591 file.Write(" &")
10592 file.Write(",\n &".join(
10593 f.GetPepperName() for f in self.original_functions
10594 if f.InPepperInterface(interface)))
10595 file.Write("\n")
10597 file.Write(" };\n")
10598 file.Write(" return &ppb_opengles2;\n")
10599 file.Write("}\n")
10601 file.Write("} // namespace ppapi\n")
10602 file.Close()
10603 self.generated_cpp_filenames.append(file.filename)
10605 def WriteGLES2ToPPAPIBridge(self, filename):
10606 """Connects GLES2 helper library to PPB_OpenGLES2 interface"""
10608 file = CWriter(filename)
10609 file.Write(_LICENSE)
10610 file.Write(_DO_NOT_EDIT_WARNING)
10612 file.Write("#ifndef GL_GLEXT_PROTOTYPES\n")
10613 file.Write("#define GL_GLEXT_PROTOTYPES\n")
10614 file.Write("#endif\n")
10615 file.Write("#include <GLES2/gl2.h>\n")
10616 file.Write("#include <GLES2/gl2ext.h>\n")
10617 file.Write("#include \"ppapi/lib/gl/gles2/gl2ext_ppapi.h\"\n\n")
10619 for func in self.original_functions:
10620 if not func.InAnyPepperExtension():
10621 continue
10623 interface = self.interface_info[func.GetInfo('pepper_interface') or '']
10625 file.Write("%s GL_APIENTRY gl%s(%s) {\n" %
10626 (func.return_type, func.GetPepperName(),
10627 func.MakeTypedPepperArgString("")))
10628 return_str = "" if func.return_type == "void" else "return "
10629 interface_str = "glGet%sInterfacePPAPI()" % interface.GetName()
10630 original_arg = func.MakeOriginalArgString("")
10631 context_arg = "glGetCurrentContextPPAPI()"
10632 if len(original_arg):
10633 arg = context_arg + ", " + original_arg
10634 else:
10635 arg = context_arg
10636 if interface.GetName():
10637 file.Write(" const struct %s* ext = %s;\n" %
10638 (interface.GetStructName(), interface_str))
10639 file.Write(" if (ext)\n")
10640 file.Write(" %sext->%s(%s);\n" %
10641 (return_str, func.GetPepperName(), arg))
10642 if return_str:
10643 file.Write(" %s0;\n" % return_str)
10644 else:
10645 file.Write(" %s%s->%s(%s);\n" %
10646 (return_str, interface_str, func.GetPepperName(), arg))
10647 file.Write("}\n\n")
10648 file.Close()
10649 self.generated_cpp_filenames.append(file.filename)
10651 def WriteMojoGLCallVisitor(self, filename):
10652 """Provides the GL implementation for mojo"""
10653 file = CWriter(filename)
10654 file.Write(_LICENSE)
10655 file.Write(_DO_NOT_EDIT_WARNING)
10657 for func in self.original_functions:
10658 if not func.IsCoreGLFunction():
10659 continue
10660 file.Write("VISIT_GL_CALL(%s, %s, (%s), (%s))\n" %
10661 (func.name, func.return_type,
10662 func.MakeTypedOriginalArgString(""),
10663 func.MakeOriginalArgString("")))
10665 file.Close()
10666 self.generated_cpp_filenames.append(file.filename)
10668 def WriteMojoGLCallVisitorForExtension(self, filename, extension):
10669 """Provides the GL implementation for mojo for a particular extension"""
10670 file = CWriter(filename)
10671 file.Write(_LICENSE)
10672 file.Write(_DO_NOT_EDIT_WARNING)
10674 for func in self.original_functions:
10675 if func.GetInfo("extension") != extension:
10676 continue
10677 file.Write("VISIT_GL_CALL(%s, %s, (%s), (%s))\n" %
10678 (func.name, func.return_type,
10679 func.MakeTypedOriginalArgString(""),
10680 func.MakeOriginalArgString("")))
10682 file.Close()
10683 self.generated_cpp_filenames.append(file.filename)
10685 def Format(generated_files):
10686 formatter = "clang-format"
10687 if platform.system() == "Windows":
10688 formatter += ".bat"
10689 for filename in generated_files:
10690 call([formatter, "-i", "-style=chromium", filename])
10692 def main(argv):
10693 """This is the main function."""
10694 parser = OptionParser()
10695 parser.add_option(
10696 "--output-dir",
10697 help="base directory for resulting files, under chrome/src. default is "
10698 "empty. Use this if you want the result stored under gen.")
10699 parser.add_option(
10700 "-v", "--verbose", action="store_true",
10701 help="prints more output.")
10703 (options, args) = parser.parse_args(args=argv)
10705 # Add in states and capabilites to GLState
10706 gl_state_valid = _NAMED_TYPE_INFO['GLState']['valid']
10707 for state_name in sorted(_STATES.keys()):
10708 state = _STATES[state_name]
10709 if 'extension_flag' in state:
10710 continue
10711 if 'enum' in state:
10712 if not state['enum'] in gl_state_valid:
10713 gl_state_valid.append(state['enum'])
10714 else:
10715 for item in state['states']:
10716 if 'extension_flag' in item:
10717 continue
10718 if not item['enum'] in gl_state_valid:
10719 gl_state_valid.append(item['enum'])
10720 for capability in _CAPABILITY_FLAGS:
10721 valid_value = "GL_%s" % capability['name'].upper()
10722 if not valid_value in gl_state_valid:
10723 gl_state_valid.append(valid_value)
10725 # This script lives under gpu/command_buffer, cd to base directory.
10726 os.chdir(os.path.dirname(__file__) + "/../..")
10727 base_dir = os.getcwd()
10728 gen = GLGenerator(options.verbose)
10729 gen.ParseGLH("gpu/command_buffer/cmd_buffer_functions.txt")
10731 # Support generating files under gen/
10732 if options.output_dir != None:
10733 os.chdir(options.output_dir)
10735 gen.WritePepperGLES2Interface("ppapi/api/ppb_opengles2.idl", False)
10736 gen.WritePepperGLES2Interface("ppapi/api/dev/ppb_opengles2ext_dev.idl", True)
10737 gen.WriteGLES2ToPPAPIBridge("ppapi/lib/gl/gles2/gles2.c")
10738 gen.WritePepperGLES2Implementation(
10739 "ppapi/shared_impl/ppb_opengles2_shared.cc")
10740 os.chdir(base_dir)
10741 gen.WriteCommandIds("gpu/command_buffer/common/gles2_cmd_ids_autogen.h")
10742 gen.WriteFormat("gpu/command_buffer/common/gles2_cmd_format_autogen.h")
10743 gen.WriteFormatTest(
10744 "gpu/command_buffer/common/gles2_cmd_format_test_autogen.h")
10745 gen.WriteGLES2InterfaceHeader(
10746 "gpu/command_buffer/client/gles2_interface_autogen.h")
10747 gen.WriteMojoGLES2ImplHeader(
10748 "mojo/gpu/mojo_gles2_impl_autogen.h")
10749 gen.WriteMojoGLES2Impl(
10750 "mojo/gpu/mojo_gles2_impl_autogen.cc")
10751 gen.WriteGLES2InterfaceStub(
10752 "gpu/command_buffer/client/gles2_interface_stub_autogen.h")
10753 gen.WriteGLES2InterfaceStubImpl(
10754 "gpu/command_buffer/client/gles2_interface_stub_impl_autogen.h")
10755 gen.WriteGLES2ImplementationHeader(
10756 "gpu/command_buffer/client/gles2_implementation_autogen.h")
10757 gen.WriteGLES2Implementation(
10758 "gpu/command_buffer/client/gles2_implementation_impl_autogen.h")
10759 gen.WriteGLES2ImplementationUnitTests(
10760 "gpu/command_buffer/client/gles2_implementation_unittest_autogen.h")
10761 gen.WriteGLES2TraceImplementationHeader(
10762 "gpu/command_buffer/client/gles2_trace_implementation_autogen.h")
10763 gen.WriteGLES2TraceImplementation(
10764 "gpu/command_buffer/client/gles2_trace_implementation_impl_autogen.h")
10765 gen.WriteGLES2CLibImplementation(
10766 "gpu/command_buffer/client/gles2_c_lib_autogen.h")
10767 gen.WriteCmdHelperHeader(
10768 "gpu/command_buffer/client/gles2_cmd_helper_autogen.h")
10769 gen.WriteServiceImplementation(
10770 "gpu/command_buffer/service/gles2_cmd_decoder_autogen.h")
10771 gen.WriteServiceContextStateHeader(
10772 "gpu/command_buffer/service/context_state_autogen.h")
10773 gen.WriteServiceContextStateImpl(
10774 "gpu/command_buffer/service/context_state_impl_autogen.h")
10775 gen.WriteClientContextStateHeader(
10776 "gpu/command_buffer/client/client_context_state_autogen.h")
10777 gen.WriteClientContextStateImpl(
10778 "gpu/command_buffer/client/client_context_state_impl_autogen.h")
10779 gen.WriteServiceUnitTests(
10780 "gpu/command_buffer/service/gles2_cmd_decoder_unittest_%d_autogen.h")
10781 gen.WriteServiceUnitTestsForExtensions(
10782 "gpu/command_buffer/service/"
10783 "gles2_cmd_decoder_unittest_extensions_autogen.h")
10784 gen.WriteServiceUtilsHeader(
10785 "gpu/command_buffer/service/gles2_cmd_validation_autogen.h")
10786 gen.WriteServiceUtilsImplementation(
10787 "gpu/command_buffer/service/"
10788 "gles2_cmd_validation_implementation_autogen.h")
10789 gen.WriteCommonUtilsHeader(
10790 "gpu/command_buffer/common/gles2_cmd_utils_autogen.h")
10791 gen.WriteCommonUtilsImpl(
10792 "gpu/command_buffer/common/gles2_cmd_utils_implementation_autogen.h")
10793 gen.WriteGLES2Header("gpu/GLES2/gl2chromium_autogen.h")
10794 mojo_gles2_prefix = ("third_party/mojo/src/mojo/public/c/gles2/"
10795 "gles2_call_visitor")
10796 gen.WriteMojoGLCallVisitor(mojo_gles2_prefix + "_autogen.h")
10797 gen.WriteMojoGLCallVisitorForExtension(
10798 mojo_gles2_prefix + "_chromium_texture_mailbox_autogen.h",
10799 "CHROMIUM_texture_mailbox")
10800 gen.WriteMojoGLCallVisitorForExtension(
10801 mojo_gles2_prefix + "_chromium_sync_point_autogen.h",
10802 "CHROMIUM_sync_point")
10803 gen.WriteMojoGLCallVisitorForExtension(
10804 mojo_gles2_prefix + "_chromium_sub_image_autogen.h",
10805 "CHROMIUM_sub_image")
10806 gen.WriteMojoGLCallVisitorForExtension(
10807 mojo_gles2_prefix + "_chromium_miscellaneous_autogen.h",
10808 "CHROMIUM_miscellaneous")
10809 gen.WriteMojoGLCallVisitorForExtension(
10810 mojo_gles2_prefix + "_occlusion_query_ext_autogen.h",
10811 "occlusion_query_EXT")
10813 Format(gen.generated_cpp_filenames)
10815 if gen.errors > 0:
10816 print "%d errors" % gen.errors
10817 return 1
10818 return 0
10821 if __name__ == '__main__':
10822 sys.exit(main(sys.argv[1:]))