Updating trunk VERSION from 2139.0 to 2140.0
[chromium-blink-merge.git] / gpu / command_buffer / build_gles2_cmd_buffer.py
blob6720998d258605c89f98880ac01d2167c17786b5
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 from optparse import OptionParser
14 from subprocess import call
16 _SIZE_OF_UINT32 = 4
17 _SIZE_OF_COMMAND_HEADER = 4
18 _FIRST_SPECIFIC_COMMAND_ID = 256
20 _LICENSE = """// Copyright 2014 The Chromium Authors. All rights reserved.
21 // Use of this source code is governed by a BSD-style license that can be
22 // found in the LICENSE file.
24 """
26 _DO_NOT_EDIT_WARNING = """// This file is auto-generated from
27 // gpu/command_buffer/build_gles2_cmd_buffer.py
28 // It's formatted by clang-format using chromium coding style:
29 // clang-format -i -style=chromium filename
30 // DO NOT EDIT!
32 """
34 # This string is copied directly out of the gl2.h file from GLES2.0
36 # Edits:
38 # *) Any argument that is a resourceID has been changed to GLid<Type>.
39 # (not pointer arguments) and if it's allowed to be zero it's GLidZero<Type>
40 # If it's allowed to not exist it's GLidBind<Type>
42 # *) All GLenums have been changed to GLenumTypeOfEnum
44 _GL_TYPES = {
45 'GLenum': 'unsigned int',
46 'GLboolean': 'unsigned char',
47 'GLbitfield': 'unsigned int',
48 'GLbyte': 'signed char',
49 'GLshort': 'short',
50 'GLint': 'int',
51 'GLsizei': 'int',
52 'GLubyte': 'unsigned char',
53 'GLushort': 'unsigned short',
54 'GLuint': 'unsigned int',
55 'GLfloat': 'float',
56 'GLclampf': 'float',
57 'GLvoid': 'void',
58 'GLfixed': 'int',
59 'GLclampx': 'int'
62 _GL_TYPES_32 = {
63 'GLintptr': 'long int',
64 'GLsizeiptr': 'long int'
67 _GL_TYPES_64 = {
68 'GLintptr': 'long long int',
69 'GLsizeiptr': 'long long int'
72 # Capabilites selected with glEnable
73 _CAPABILITY_FLAGS = [
74 {'name': 'blend'},
75 {'name': 'cull_face'},
76 {'name': 'depth_test', 'state_flag': 'framebuffer_state_.clear_state_dirty'},
77 {'name': 'dither', 'default': True},
78 {'name': 'polygon_offset_fill'},
79 {'name': 'sample_alpha_to_coverage'},
80 {'name': 'sample_coverage'},
81 {'name': 'scissor_test'},
82 {'name': 'stencil_test',
83 'state_flag': 'framebuffer_state_.clear_state_dirty'},
86 _STATES = {
87 'ClearColor': {
88 'type': 'Normal',
89 'func': 'ClearColor',
90 'enum': 'GL_COLOR_CLEAR_VALUE',
91 'states': [
92 {'name': 'color_clear_red', 'type': 'GLfloat', 'default': '0.0f'},
93 {'name': 'color_clear_green', 'type': 'GLfloat', 'default': '0.0f'},
94 {'name': 'color_clear_blue', 'type': 'GLfloat', 'default': '0.0f'},
95 {'name': 'color_clear_alpha', 'type': 'GLfloat', 'default': '0.0f'},
98 'ClearDepthf': {
99 'type': 'Normal',
100 'func': 'ClearDepth',
101 'enum': 'GL_DEPTH_CLEAR_VALUE',
102 'states': [
103 {'name': 'depth_clear', 'type': 'GLclampf', 'default': '1.0f'},
106 'ColorMask': {
107 'type': 'Normal',
108 'func': 'ColorMask',
109 'enum': 'GL_COLOR_WRITEMASK',
110 'states': [
112 'name': 'color_mask_red',
113 'type': 'GLboolean',
114 'default': 'true',
115 'cached': True
118 'name': 'color_mask_green',
119 'type': 'GLboolean',
120 'default': 'true',
121 'cached': True
124 'name': 'color_mask_blue',
125 'type': 'GLboolean',
126 'default': 'true',
127 'cached': True
130 'name': 'color_mask_alpha',
131 'type': 'GLboolean',
132 'default': 'true',
133 'cached': True
136 'state_flag': 'framebuffer_state_.clear_state_dirty',
138 'ClearStencil': {
139 'type': 'Normal',
140 'func': 'ClearStencil',
141 'enum': 'GL_STENCIL_CLEAR_VALUE',
142 'states': [
143 {'name': 'stencil_clear', 'type': 'GLint', 'default': '0'},
146 'BlendColor': {
147 'type': 'Normal',
148 'func': 'BlendColor',
149 'enum': 'GL_BLEND_COLOR',
150 'states': [
151 {'name': 'blend_color_red', 'type': 'GLfloat', 'default': '0.0f'},
152 {'name': 'blend_color_green', 'type': 'GLfloat', 'default': '0.0f'},
153 {'name': 'blend_color_blue', 'type': 'GLfloat', 'default': '0.0f'},
154 {'name': 'blend_color_alpha', 'type': 'GLfloat', 'default': '0.0f'},
157 'BlendEquation': {
158 'type': 'SrcDst',
159 'func': 'BlendEquationSeparate',
160 'states': [
162 'name': 'blend_equation_rgb',
163 'type': 'GLenum',
164 'enum': 'GL_BLEND_EQUATION_RGB',
165 'default': 'GL_FUNC_ADD',
168 'name': 'blend_equation_alpha',
169 'type': 'GLenum',
170 'enum': 'GL_BLEND_EQUATION_ALPHA',
171 'default': 'GL_FUNC_ADD',
175 'BlendFunc': {
176 'type': 'SrcDst',
177 'func': 'BlendFuncSeparate',
178 'states': [
180 'name': 'blend_source_rgb',
181 'type': 'GLenum',
182 'enum': 'GL_BLEND_SRC_RGB',
183 'default': 'GL_ONE',
186 'name': 'blend_dest_rgb',
187 'type': 'GLenum',
188 'enum': 'GL_BLEND_DST_RGB',
189 'default': 'GL_ZERO',
192 'name': 'blend_source_alpha',
193 'type': 'GLenum',
194 'enum': 'GL_BLEND_SRC_ALPHA',
195 'default': 'GL_ONE',
198 'name': 'blend_dest_alpha',
199 'type': 'GLenum',
200 'enum': 'GL_BLEND_DST_ALPHA',
201 'default': 'GL_ZERO',
205 'PolygonOffset': {
206 'type': 'Normal',
207 'func': 'PolygonOffset',
208 'states': [
210 'name': 'polygon_offset_factor',
211 'type': 'GLfloat',
212 'enum': 'GL_POLYGON_OFFSET_FACTOR',
213 'default': '0.0f',
216 'name': 'polygon_offset_units',
217 'type': 'GLfloat',
218 'enum': 'GL_POLYGON_OFFSET_UNITS',
219 'default': '0.0f',
223 'CullFace': {
224 'type': 'Normal',
225 'func': 'CullFace',
226 'enum': 'GL_CULL_FACE_MODE',
227 'states': [
229 'name': 'cull_mode',
230 'type': 'GLenum',
231 'default': 'GL_BACK',
235 'FrontFace': {
236 'type': 'Normal',
237 'func': 'FrontFace',
238 'enum': 'GL_FRONT_FACE',
239 'states': [{'name': 'front_face', 'type': 'GLenum', 'default': 'GL_CCW'}],
241 'DepthFunc': {
242 'type': 'Normal',
243 'func': 'DepthFunc',
244 'enum': 'GL_DEPTH_FUNC',
245 'states': [{'name': 'depth_func', 'type': 'GLenum', 'default': 'GL_LESS'}],
247 'DepthRange': {
248 'type': 'Normal',
249 'func': 'DepthRange',
250 'enum': 'GL_DEPTH_RANGE',
251 'states': [
252 {'name': 'z_near', 'type': 'GLclampf', 'default': '0.0f'},
253 {'name': 'z_far', 'type': 'GLclampf', 'default': '1.0f'},
256 'SampleCoverage': {
257 'type': 'Normal',
258 'func': 'SampleCoverage',
259 'states': [
261 'name': 'sample_coverage_value',
262 'type': 'GLclampf',
263 'enum': 'GL_SAMPLE_COVERAGE_VALUE',
264 'default': '1.0f',
267 'name': 'sample_coverage_invert',
268 'type': 'GLboolean',
269 'enum': 'GL_SAMPLE_COVERAGE_INVERT',
270 'default': 'false',
274 'StencilMask': {
275 'type': 'FrontBack',
276 'func': 'StencilMaskSeparate',
277 'state_flag': 'framebuffer_state_.clear_state_dirty',
278 'states': [
280 'name': 'stencil_front_writemask',
281 'type': 'GLuint',
282 'enum': 'GL_STENCIL_WRITEMASK',
283 'default': '0xFFFFFFFFU',
284 'cached': True,
287 'name': 'stencil_back_writemask',
288 'type': 'GLuint',
289 'enum': 'GL_STENCIL_BACK_WRITEMASK',
290 'default': '0xFFFFFFFFU',
291 'cached': True,
295 'StencilOp': {
296 'type': 'FrontBack',
297 'func': 'StencilOpSeparate',
298 'states': [
300 'name': 'stencil_front_fail_op',
301 'type': 'GLenum',
302 'enum': 'GL_STENCIL_FAIL',
303 'default': 'GL_KEEP',
306 'name': 'stencil_front_z_fail_op',
307 'type': 'GLenum',
308 'enum': 'GL_STENCIL_PASS_DEPTH_FAIL',
309 'default': 'GL_KEEP',
312 'name': 'stencil_front_z_pass_op',
313 'type': 'GLenum',
314 'enum': 'GL_STENCIL_PASS_DEPTH_PASS',
315 'default': 'GL_KEEP',
318 'name': 'stencil_back_fail_op',
319 'type': 'GLenum',
320 'enum': 'GL_STENCIL_BACK_FAIL',
321 'default': 'GL_KEEP',
324 'name': 'stencil_back_z_fail_op',
325 'type': 'GLenum',
326 'enum': 'GL_STENCIL_BACK_PASS_DEPTH_FAIL',
327 'default': 'GL_KEEP',
330 'name': 'stencil_back_z_pass_op',
331 'type': 'GLenum',
332 'enum': 'GL_STENCIL_BACK_PASS_DEPTH_PASS',
333 'default': 'GL_KEEP',
337 'StencilFunc': {
338 'type': 'FrontBack',
339 'func': 'StencilFuncSeparate',
340 'states': [
342 'name': 'stencil_front_func',
343 'type': 'GLenum',
344 'enum': 'GL_STENCIL_FUNC',
345 'default': 'GL_ALWAYS',
348 'name': 'stencil_front_ref',
349 'type': 'GLint',
350 'enum': 'GL_STENCIL_REF',
351 'default': '0',
354 'name': 'stencil_front_mask',
355 'type': 'GLuint',
356 'enum': 'GL_STENCIL_VALUE_MASK',
357 'default': '0xFFFFFFFFU',
360 'name': 'stencil_back_func',
361 'type': 'GLenum',
362 'enum': 'GL_STENCIL_BACK_FUNC',
363 'default': 'GL_ALWAYS',
366 'name': 'stencil_back_ref',
367 'type': 'GLint',
368 'enum': 'GL_STENCIL_BACK_REF',
369 'default': '0',
372 'name': 'stencil_back_mask',
373 'type': 'GLuint',
374 'enum': 'GL_STENCIL_BACK_VALUE_MASK',
375 'default': '0xFFFFFFFFU',
379 'Hint': {
380 'type': 'NamedParameter',
381 'func': 'Hint',
382 'states': [
384 'name': 'hint_generate_mipmap',
385 'type': 'GLenum',
386 'enum': 'GL_GENERATE_MIPMAP_HINT',
387 'default': 'GL_DONT_CARE'
390 'name': 'hint_fragment_shader_derivative',
391 'type': 'GLenum',
392 'enum': 'GL_FRAGMENT_SHADER_DERIVATIVE_HINT_OES',
393 'default': 'GL_DONT_CARE',
394 'extension_flag': 'oes_standard_derivatives'
398 'PixelStore': {
399 'type': 'NamedParameter',
400 'func': 'PixelStorei',
401 'states': [
403 'name': 'pack_alignment',
404 'type': 'GLint',
405 'enum': 'GL_PACK_ALIGNMENT',
406 'default': '4'
409 'name': 'unpack_alignment',
410 'type': 'GLint',
411 'enum': 'GL_UNPACK_ALIGNMENT',
412 'default': '4'
416 # TODO: Consider implemenenting these states
417 # GL_ACTIVE_TEXTURE
418 'LineWidth': {
419 'type': 'Normal',
420 'func': 'LineWidth',
421 'enum': 'GL_LINE_WIDTH',
422 'states': [
424 'name': 'line_width',
425 'type': 'GLfloat',
426 'default': '1.0f',
427 'range_checks': [{'check': "<= 0.0f", 'test_value': "0.0f"}],
428 'nan_check': True,
431 'DepthMask': {
432 'type': 'Normal',
433 'func': 'DepthMask',
434 'enum': 'GL_DEPTH_WRITEMASK',
435 'states': [
437 'name': 'depth_mask',
438 'type': 'GLboolean',
439 'default': 'true',
440 'cached': True
443 'state_flag': 'framebuffer_state_.clear_state_dirty',
445 'Scissor': {
446 'type': 'Normal',
447 'func': 'Scissor',
448 'enum': 'GL_SCISSOR_BOX',
449 'states': [
450 # NOTE: These defaults reset at GLES2DecoderImpl::Initialization.
452 'name': 'scissor_x',
453 'type': 'GLint',
454 'default': '0',
455 'expected': 'kViewportX',
458 'name': 'scissor_y',
459 'type': 'GLint',
460 'default': '0',
461 'expected': 'kViewportY',
464 'name': 'scissor_width',
465 'type': 'GLsizei',
466 'default': '1',
467 'expected': 'kViewportWidth',
470 'name': 'scissor_height',
471 'type': 'GLsizei',
472 'default': '1',
473 'expected': 'kViewportHeight',
477 'Viewport': {
478 'type': 'Normal',
479 'func': 'Viewport',
480 'enum': 'GL_VIEWPORT',
481 'states': [
482 # NOTE: These defaults reset at GLES2DecoderImpl::Initialization.
484 'name': 'viewport_x',
485 'type': 'GLint',
486 'default': '0',
487 'expected': 'kViewportX',
490 'name': 'viewport_y',
491 'type': 'GLint',
492 'default': '0',
493 'expected': 'kViewportY',
496 'name': 'viewport_width',
497 'type': 'GLsizei',
498 'default': '1',
499 'expected': 'kViewportWidth',
502 'name': 'viewport_height',
503 'type': 'GLsizei',
504 'default': '1',
505 'expected': 'kViewportHeight',
509 'MatrixValuesCHROMIUM': {
510 'type': 'NamedParameter',
511 'func': 'MatrixLoadfEXT',
512 'states': [
513 { 'enum': 'GL_PATH_MODELVIEW_MATRIX_CHROMIUM',
514 'enum_set': 'GL_PATH_MODELVIEW_CHROMIUM',
515 'name': 'modelview_matrix',
516 'type': 'GLfloat',
517 'default': [
518 '1.0f', '0.0f','0.0f','0.0f',
519 '0.0f', '1.0f','0.0f','0.0f',
520 '0.0f', '0.0f','1.0f','0.0f',
521 '0.0f', '0.0f','0.0f','1.0f',
523 'extension_flag': 'chromium_path_rendering',
525 { 'enum': 'GL_PATH_PROJECTION_MATRIX_CHROMIUM',
526 'enum_set': 'GL_PATH_PROJECTION_CHROMIUM',
527 'name': 'projection_matrix',
528 'type': 'GLfloat',
529 'default': [
530 '1.0f', '0.0f','0.0f','0.0f',
531 '0.0f', '1.0f','0.0f','0.0f',
532 '0.0f', '0.0f','1.0f','0.0f',
533 '0.0f', '0.0f','0.0f','1.0f',
535 'extension_flag': 'chromium_path_rendering',
541 # Named type info object represents a named type that is used in OpenGL call
542 # arguments. Each named type defines a set of valid OpenGL call arguments. The
543 # named types are used in 'cmd_buffer_functions.txt'.
544 # type: The actual GL type of the named type.
545 # valid: The list of values that are valid for both the client and the service.
546 # invalid: Examples of invalid values for the type. At least these values
547 # should be tested to be invalid.
548 # is_complete: The list of valid values of type are final and will not be
549 # modified during runtime.
550 _NAMED_TYPE_INFO = {
551 'BlitFilter': {
552 'type': 'GLenum',
553 'valid': [
554 'GL_NEAREST',
555 'GL_LINEAR',
557 'invalid': [
558 'GL_LINEAR_MIPMAP_LINEAR',
561 'FrameBufferTarget': {
562 'type': 'GLenum',
563 'valid': [
564 'GL_FRAMEBUFFER',
566 'invalid': [
567 'GL_DRAW_FRAMEBUFFER' ,
568 'GL_READ_FRAMEBUFFER' ,
571 'RenderBufferTarget': {
572 'type': 'GLenum',
573 'valid': [
574 'GL_RENDERBUFFER',
576 'invalid': [
577 'GL_FRAMEBUFFER',
580 'BufferTarget': {
581 'type': 'GLenum',
582 'valid': [
583 'GL_ARRAY_BUFFER',
584 'GL_ELEMENT_ARRAY_BUFFER',
586 'invalid': [
587 'GL_RENDERBUFFER',
590 'BufferUsage': {
591 'type': 'GLenum',
592 'valid': [
593 'GL_STREAM_DRAW',
594 'GL_STATIC_DRAW',
595 'GL_DYNAMIC_DRAW',
597 'invalid': [
598 'GL_STATIC_READ',
601 'CompressedTextureFormat': {
602 'type': 'GLenum',
603 'valid': [
606 'GLState': {
607 'type': 'GLenum',
608 'valid': [
609 # NOTE: State an Capability entries added later.
610 'GL_ACTIVE_TEXTURE',
611 'GL_ALIASED_LINE_WIDTH_RANGE',
612 'GL_ALIASED_POINT_SIZE_RANGE',
613 'GL_ALPHA_BITS',
614 'GL_ARRAY_BUFFER_BINDING',
615 'GL_BLUE_BITS',
616 'GL_COMPRESSED_TEXTURE_FORMATS',
617 'GL_CURRENT_PROGRAM',
618 'GL_DEPTH_BITS',
619 'GL_DEPTH_RANGE',
620 'GL_ELEMENT_ARRAY_BUFFER_BINDING',
621 'GL_FRAMEBUFFER_BINDING',
622 'GL_GENERATE_MIPMAP_HINT',
623 'GL_GREEN_BITS',
624 'GL_IMPLEMENTATION_COLOR_READ_FORMAT',
625 'GL_IMPLEMENTATION_COLOR_READ_TYPE',
626 'GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS',
627 'GL_MAX_CUBE_MAP_TEXTURE_SIZE',
628 'GL_MAX_FRAGMENT_UNIFORM_VECTORS',
629 'GL_MAX_RENDERBUFFER_SIZE',
630 'GL_MAX_TEXTURE_IMAGE_UNITS',
631 'GL_MAX_TEXTURE_SIZE',
632 'GL_MAX_VARYING_VECTORS',
633 'GL_MAX_VERTEX_ATTRIBS',
634 'GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS',
635 'GL_MAX_VERTEX_UNIFORM_VECTORS',
636 'GL_MAX_VIEWPORT_DIMS',
637 'GL_NUM_COMPRESSED_TEXTURE_FORMATS',
638 'GL_NUM_SHADER_BINARY_FORMATS',
639 'GL_PACK_ALIGNMENT',
640 'GL_RED_BITS',
641 'GL_RENDERBUFFER_BINDING',
642 'GL_SAMPLE_BUFFERS',
643 'GL_SAMPLE_COVERAGE_INVERT',
644 'GL_SAMPLE_COVERAGE_VALUE',
645 'GL_SAMPLES',
646 'GL_SCISSOR_BOX',
647 'GL_SHADER_BINARY_FORMATS',
648 'GL_SHADER_COMPILER',
649 'GL_SUBPIXEL_BITS',
650 'GL_STENCIL_BITS',
651 'GL_TEXTURE_BINDING_2D',
652 'GL_TEXTURE_BINDING_CUBE_MAP',
653 'GL_UNPACK_ALIGNMENT',
654 'GL_UNPACK_FLIP_Y_CHROMIUM',
655 'GL_UNPACK_PREMULTIPLY_ALPHA_CHROMIUM',
656 'GL_UNPACK_UNPREMULTIPLY_ALPHA_CHROMIUM',
657 'GL_BIND_GENERATES_RESOURCE_CHROMIUM',
658 # we can add this because we emulate it if the driver does not support it.
659 'GL_VERTEX_ARRAY_BINDING_OES',
660 'GL_VIEWPORT',
662 'invalid': [
663 'GL_FOG_HINT',
666 'GetTexParamTarget': {
667 'type': 'GLenum',
668 'valid': [
669 'GL_TEXTURE_2D',
670 'GL_TEXTURE_CUBE_MAP',
672 'invalid': [
673 'GL_PROXY_TEXTURE_CUBE_MAP',
676 'TextureTarget': {
677 'type': 'GLenum',
678 'valid': [
679 'GL_TEXTURE_2D',
680 'GL_TEXTURE_CUBE_MAP_POSITIVE_X',
681 'GL_TEXTURE_CUBE_MAP_NEGATIVE_X',
682 'GL_TEXTURE_CUBE_MAP_POSITIVE_Y',
683 'GL_TEXTURE_CUBE_MAP_NEGATIVE_Y',
684 'GL_TEXTURE_CUBE_MAP_POSITIVE_Z',
685 'GL_TEXTURE_CUBE_MAP_NEGATIVE_Z',
687 'invalid': [
688 'GL_PROXY_TEXTURE_CUBE_MAP',
691 'TextureBindTarget': {
692 'type': 'GLenum',
693 'valid': [
694 'GL_TEXTURE_2D',
695 'GL_TEXTURE_CUBE_MAP',
697 'invalid': [
698 'GL_TEXTURE_1D',
699 'GL_TEXTURE_3D',
702 'ShaderType': {
703 'type': 'GLenum',
704 'valid': [
705 'GL_VERTEX_SHADER',
706 'GL_FRAGMENT_SHADER',
708 'invalid': [
709 'GL_GEOMETRY_SHADER',
712 'FaceType': {
713 'type': 'GLenum',
714 'valid': [
715 'GL_FRONT',
716 'GL_BACK',
717 'GL_FRONT_AND_BACK',
720 'FaceMode': {
721 'type': 'GLenum',
722 'valid': [
723 'GL_CW',
724 'GL_CCW',
727 'CmpFunction': {
728 'type': 'GLenum',
729 'valid': [
730 'GL_NEVER',
731 'GL_LESS',
732 'GL_EQUAL',
733 'GL_LEQUAL',
734 'GL_GREATER',
735 'GL_NOTEQUAL',
736 'GL_GEQUAL',
737 'GL_ALWAYS',
740 'Equation': {
741 'type': 'GLenum',
742 'valid': [
743 'GL_FUNC_ADD',
744 'GL_FUNC_SUBTRACT',
745 'GL_FUNC_REVERSE_SUBTRACT',
747 'invalid': [
748 'GL_MIN',
749 'GL_MAX',
752 'SrcBlendFactor': {
753 'type': 'GLenum',
754 'valid': [
755 'GL_ZERO',
756 'GL_ONE',
757 'GL_SRC_COLOR',
758 'GL_ONE_MINUS_SRC_COLOR',
759 'GL_DST_COLOR',
760 'GL_ONE_MINUS_DST_COLOR',
761 'GL_SRC_ALPHA',
762 'GL_ONE_MINUS_SRC_ALPHA',
763 'GL_DST_ALPHA',
764 'GL_ONE_MINUS_DST_ALPHA',
765 'GL_CONSTANT_COLOR',
766 'GL_ONE_MINUS_CONSTANT_COLOR',
767 'GL_CONSTANT_ALPHA',
768 'GL_ONE_MINUS_CONSTANT_ALPHA',
769 'GL_SRC_ALPHA_SATURATE',
772 'DstBlendFactor': {
773 'type': 'GLenum',
774 'valid': [
775 'GL_ZERO',
776 'GL_ONE',
777 'GL_SRC_COLOR',
778 'GL_ONE_MINUS_SRC_COLOR',
779 'GL_DST_COLOR',
780 'GL_ONE_MINUS_DST_COLOR',
781 'GL_SRC_ALPHA',
782 'GL_ONE_MINUS_SRC_ALPHA',
783 'GL_DST_ALPHA',
784 'GL_ONE_MINUS_DST_ALPHA',
785 'GL_CONSTANT_COLOR',
786 'GL_ONE_MINUS_CONSTANT_COLOR',
787 'GL_CONSTANT_ALPHA',
788 'GL_ONE_MINUS_CONSTANT_ALPHA',
791 'Capability': {
792 'type': 'GLenum',
793 'valid': ["GL_%s" % cap['name'].upper() for cap in _CAPABILITY_FLAGS],
794 'invalid': [
795 'GL_CLIP_PLANE0',
796 'GL_POINT_SPRITE',
799 'DrawMode': {
800 'type': 'GLenum',
801 'valid': [
802 'GL_POINTS',
803 'GL_LINE_STRIP',
804 'GL_LINE_LOOP',
805 'GL_LINES',
806 'GL_TRIANGLE_STRIP',
807 'GL_TRIANGLE_FAN',
808 'GL_TRIANGLES',
810 'invalid': [
811 'GL_QUADS',
812 'GL_POLYGON',
815 'IndexType': {
816 'type': 'GLenum',
817 'valid': [
818 'GL_UNSIGNED_BYTE',
819 'GL_UNSIGNED_SHORT',
821 'invalid': [
822 'GL_UNSIGNED_INT',
823 'GL_INT',
826 'GetMaxIndexType': {
827 'type': 'GLenum',
828 'valid': [
829 'GL_UNSIGNED_BYTE',
830 'GL_UNSIGNED_SHORT',
831 'GL_UNSIGNED_INT',
833 'invalid': [
834 'GL_INT',
837 'Attachment': {
838 'type': 'GLenum',
839 'valid': [
840 'GL_COLOR_ATTACHMENT0',
841 'GL_DEPTH_ATTACHMENT',
842 'GL_STENCIL_ATTACHMENT',
845 'BackbufferAttachment': {
846 'type': 'GLenum',
847 'valid': [
848 'GL_COLOR_EXT',
849 'GL_DEPTH_EXT',
850 'GL_STENCIL_EXT',
853 'BufferParameter': {
854 'type': 'GLenum',
855 'valid': [
856 'GL_BUFFER_SIZE',
857 'GL_BUFFER_USAGE',
859 'invalid': [
860 'GL_PIXEL_PACK_BUFFER',
863 'FrameBufferParameter': {
864 'type': 'GLenum',
865 'valid': [
866 'GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE',
867 'GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME',
868 'GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL',
869 'GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE',
872 'MatrixMode': {
873 'type': 'GLenum',
874 'valid': [
875 'GL_PATH_PROJECTION_CHROMIUM',
876 'GL_PATH_MODELVIEW_CHROMIUM',
879 'ProgramParameter': {
880 'type': 'GLenum',
881 'valid': [
882 'GL_DELETE_STATUS',
883 'GL_LINK_STATUS',
884 'GL_VALIDATE_STATUS',
885 'GL_INFO_LOG_LENGTH',
886 'GL_ATTACHED_SHADERS',
887 'GL_ACTIVE_ATTRIBUTES',
888 'GL_ACTIVE_ATTRIBUTE_MAX_LENGTH',
889 'GL_ACTIVE_UNIFORMS',
890 'GL_ACTIVE_UNIFORM_MAX_LENGTH',
893 'QueryObjectParameter': {
894 'type': 'GLenum',
895 'valid': [
896 'GL_QUERY_RESULT_EXT',
897 'GL_QUERY_RESULT_AVAILABLE_EXT',
900 'QueryParameter': {
901 'type': 'GLenum',
902 'valid': [
903 'GL_CURRENT_QUERY_EXT',
906 'QueryTarget': {
907 'type': 'GLenum',
908 'valid': [
909 'GL_ANY_SAMPLES_PASSED_EXT',
910 'GL_ANY_SAMPLES_PASSED_CONSERVATIVE_EXT',
911 'GL_COMMANDS_ISSUED_CHROMIUM',
912 'GL_LATENCY_QUERY_CHROMIUM',
913 'GL_ASYNC_PIXEL_UNPACK_COMPLETED_CHROMIUM',
914 'GL_ASYNC_PIXEL_PACK_COMPLETED_CHROMIUM',
915 'GL_COMMANDS_COMPLETED_CHROMIUM',
918 'RenderBufferParameter': {
919 'type': 'GLenum',
920 'valid': [
921 'GL_RENDERBUFFER_RED_SIZE',
922 'GL_RENDERBUFFER_GREEN_SIZE',
923 'GL_RENDERBUFFER_BLUE_SIZE',
924 'GL_RENDERBUFFER_ALPHA_SIZE',
925 'GL_RENDERBUFFER_DEPTH_SIZE',
926 'GL_RENDERBUFFER_STENCIL_SIZE',
927 'GL_RENDERBUFFER_WIDTH',
928 'GL_RENDERBUFFER_HEIGHT',
929 'GL_RENDERBUFFER_INTERNAL_FORMAT',
932 'ShaderParameter': {
933 'type': 'GLenum',
934 'valid': [
935 'GL_SHADER_TYPE',
936 'GL_DELETE_STATUS',
937 'GL_COMPILE_STATUS',
938 'GL_INFO_LOG_LENGTH',
939 'GL_SHADER_SOURCE_LENGTH',
940 'GL_TRANSLATED_SHADER_SOURCE_LENGTH_ANGLE',
943 'ShaderPrecision': {
944 'type': 'GLenum',
945 'valid': [
946 'GL_LOW_FLOAT',
947 'GL_MEDIUM_FLOAT',
948 'GL_HIGH_FLOAT',
949 'GL_LOW_INT',
950 'GL_MEDIUM_INT',
951 'GL_HIGH_INT',
954 'StringType': {
955 'type': 'GLenum',
956 'valid': [
957 'GL_VENDOR',
958 'GL_RENDERER',
959 'GL_VERSION',
960 'GL_SHADING_LANGUAGE_VERSION',
961 'GL_EXTENSIONS',
964 'TextureParameter': {
965 'type': 'GLenum',
966 'valid': [
967 'GL_TEXTURE_MAG_FILTER',
968 'GL_TEXTURE_MIN_FILTER',
969 'GL_TEXTURE_POOL_CHROMIUM',
970 'GL_TEXTURE_WRAP_S',
971 'GL_TEXTURE_WRAP_T',
973 'invalid': [
974 'GL_GENERATE_MIPMAP',
977 'TexturePool': {
978 'type': 'GLenum',
979 'valid': [
980 'GL_TEXTURE_POOL_MANAGED_CHROMIUM',
981 'GL_TEXTURE_POOL_UNMANAGED_CHROMIUM',
984 'TextureWrapMode': {
985 'type': 'GLenum',
986 'valid': [
987 'GL_CLAMP_TO_EDGE',
988 'GL_MIRRORED_REPEAT',
989 'GL_REPEAT',
992 'TextureMinFilterMode': {
993 'type': 'GLenum',
994 'valid': [
995 'GL_NEAREST',
996 'GL_LINEAR',
997 'GL_NEAREST_MIPMAP_NEAREST',
998 'GL_LINEAR_MIPMAP_NEAREST',
999 'GL_NEAREST_MIPMAP_LINEAR',
1000 'GL_LINEAR_MIPMAP_LINEAR',
1003 'TextureMagFilterMode': {
1004 'type': 'GLenum',
1005 'valid': [
1006 'GL_NEAREST',
1007 'GL_LINEAR',
1010 'TextureUsage': {
1011 'type': 'GLenum',
1012 'valid': [
1013 'GL_NONE',
1014 'GL_FRAMEBUFFER_ATTACHMENT_ANGLE',
1017 'VertexAttribute': {
1018 'type': 'GLenum',
1019 'valid': [
1020 # some enum that the decoder actually passes through to GL needs
1021 # to be the first listed here since it's used in unit tests.
1022 'GL_VERTEX_ATTRIB_ARRAY_NORMALIZED',
1023 'GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING',
1024 'GL_VERTEX_ATTRIB_ARRAY_ENABLED',
1025 'GL_VERTEX_ATTRIB_ARRAY_SIZE',
1026 'GL_VERTEX_ATTRIB_ARRAY_STRIDE',
1027 'GL_VERTEX_ATTRIB_ARRAY_TYPE',
1028 'GL_CURRENT_VERTEX_ATTRIB',
1031 'VertexPointer': {
1032 'type': 'GLenum',
1033 'valid': [
1034 'GL_VERTEX_ATTRIB_ARRAY_POINTER',
1037 'HintTarget': {
1038 'type': 'GLenum',
1039 'valid': [
1040 'GL_GENERATE_MIPMAP_HINT',
1042 'invalid': [
1043 'GL_PERSPECTIVE_CORRECTION_HINT',
1046 'HintMode': {
1047 'type': 'GLenum',
1048 'valid': [
1049 'GL_FASTEST',
1050 'GL_NICEST',
1051 'GL_DONT_CARE',
1054 'PixelStore': {
1055 'type': 'GLenum',
1056 'valid': [
1057 'GL_PACK_ALIGNMENT',
1058 'GL_UNPACK_ALIGNMENT',
1059 'GL_UNPACK_FLIP_Y_CHROMIUM',
1060 'GL_UNPACK_PREMULTIPLY_ALPHA_CHROMIUM',
1061 'GL_UNPACK_UNPREMULTIPLY_ALPHA_CHROMIUM',
1063 'invalid': [
1064 'GL_PACK_SWAP_BYTES',
1065 'GL_UNPACK_SWAP_BYTES',
1068 'PixelStoreAlignment': {
1069 'type': 'GLint',
1070 'valid': [
1071 '1',
1072 '2',
1073 '4',
1074 '8',
1076 'invalid': [
1077 '3',
1078 '9',
1081 'ReadPixelFormat': {
1082 'type': 'GLenum',
1083 'valid': [
1084 'GL_ALPHA',
1085 'GL_RGB',
1086 'GL_RGBA',
1089 'PixelType': {
1090 'type': 'GLenum',
1091 'valid': [
1092 'GL_UNSIGNED_BYTE',
1093 'GL_UNSIGNED_SHORT_5_6_5',
1094 'GL_UNSIGNED_SHORT_4_4_4_4',
1095 'GL_UNSIGNED_SHORT_5_5_5_1',
1097 'invalid': [
1098 'GL_SHORT',
1099 'GL_INT',
1102 'ReadPixelType': {
1103 'type': 'GLenum',
1104 'valid': [
1105 'GL_UNSIGNED_BYTE',
1106 'GL_UNSIGNED_SHORT_5_6_5',
1107 'GL_UNSIGNED_SHORT_4_4_4_4',
1108 'GL_UNSIGNED_SHORT_5_5_5_1',
1110 'invalid': [
1111 'GL_SHORT',
1112 'GL_INT',
1115 'RenderBufferFormat': {
1116 'type': 'GLenum',
1117 'valid': [
1118 'GL_RGBA4',
1119 'GL_RGB565',
1120 'GL_RGB5_A1',
1121 'GL_DEPTH_COMPONENT16',
1122 'GL_STENCIL_INDEX8',
1125 'ShaderBinaryFormat': {
1126 'type': 'GLenum',
1127 'valid': [
1130 'StencilOp': {
1131 'type': 'GLenum',
1132 'valid': [
1133 'GL_KEEP',
1134 'GL_ZERO',
1135 'GL_REPLACE',
1136 'GL_INCR',
1137 'GL_INCR_WRAP',
1138 'GL_DECR',
1139 'GL_DECR_WRAP',
1140 'GL_INVERT',
1143 'TextureFormat': {
1144 'type': 'GLenum',
1145 'valid': [
1146 'GL_ALPHA',
1147 'GL_LUMINANCE',
1148 'GL_LUMINANCE_ALPHA',
1149 'GL_RGB',
1150 'GL_RGBA',
1152 'invalid': [
1153 'GL_BGRA',
1154 'GL_BGR',
1157 'TextureInternalFormat': {
1158 'type': 'GLenum',
1159 'valid': [
1160 'GL_ALPHA',
1161 'GL_LUMINANCE',
1162 'GL_LUMINANCE_ALPHA',
1163 'GL_RGB',
1164 'GL_RGBA',
1166 'invalid': [
1167 'GL_BGRA',
1168 'GL_BGR',
1171 'TextureInternalFormatStorage': {
1172 'type': 'GLenum',
1173 'valid': [
1174 'GL_RGB565',
1175 'GL_RGBA4',
1176 'GL_RGB5_A1',
1177 'GL_ALPHA8_EXT',
1178 'GL_LUMINANCE8_EXT',
1179 'GL_LUMINANCE8_ALPHA8_EXT',
1180 'GL_RGB8_OES',
1181 'GL_RGBA8_OES',
1184 'VertexAttribType': {
1185 'type': 'GLenum',
1186 'valid': [
1187 'GL_BYTE',
1188 'GL_UNSIGNED_BYTE',
1189 'GL_SHORT',
1190 'GL_UNSIGNED_SHORT',
1191 # 'GL_FIXED', // This is not available on Desktop GL.
1192 'GL_FLOAT',
1194 'invalid': [
1195 'GL_DOUBLE',
1198 'TextureBorder': {
1199 'type': 'GLint',
1200 'is_complete': True,
1201 'valid': [
1202 '0',
1204 'invalid': [
1205 '1',
1208 'VertexAttribSize': {
1209 'type': 'GLint',
1210 'valid': [
1211 '1',
1212 '2',
1213 '3',
1214 '4',
1216 'invalid': [
1217 '0',
1218 '5',
1221 'ZeroOnly': {
1222 'type': 'GLint',
1223 'is_complete': True,
1224 'valid': [
1225 '0',
1227 'invalid': [
1228 '1',
1231 'FalseOnly': {
1232 'type': 'GLboolean',
1233 'is_complete': True,
1234 'valid': [
1235 'false',
1237 'invalid': [
1238 'true',
1241 'ResetStatus': {
1242 'type': 'GLenum',
1243 'valid': [
1244 'GL_GUILTY_CONTEXT_RESET_ARB',
1245 'GL_INNOCENT_CONTEXT_RESET_ARB',
1246 'GL_UNKNOWN_CONTEXT_RESET_ARB',
1251 # This table specifies the different pepper interfaces that are supported for
1252 # GL commands. 'dev' is true if it's a dev interface.
1253 _PEPPER_INTERFACES = [
1254 {'name': '', 'dev': False},
1255 {'name': 'InstancedArrays', 'dev': False},
1256 {'name': 'FramebufferBlit', 'dev': False},
1257 {'name': 'FramebufferMultisample', 'dev': False},
1258 {'name': 'ChromiumEnableFeature', 'dev': False},
1259 {'name': 'ChromiumMapSub', 'dev': False},
1260 {'name': 'Query', 'dev': False},
1261 {'name': 'VertexArrayObject', 'dev': False},
1262 {'name': 'DrawBuffers', 'dev': True},
1265 # A function info object specifies the type and other special data for the
1266 # command that will be generated. A base function info object is generated by
1267 # parsing the "cmd_buffer_functions.txt", one for each function in the
1268 # file. These function info objects can be augmented and their values can be
1269 # overridden by adding an object to the table below.
1271 # Must match function names specified in "cmd_buffer_functions.txt".
1273 # cmd_comment: A comment added to the cmd format.
1274 # type: defines which handler will be used to generate code.
1275 # decoder_func: defines which function to call in the decoder to execute the
1276 # corresponding GL command. If not specified the GL command will
1277 # be called directly.
1278 # gl_test_func: GL function that is expected to be called when testing.
1279 # cmd_args: The arguments to use for the command. This overrides generating
1280 # them based on the GL function arguments.
1281 # gen_cmd: Whether or not this function geneates a command. Default = True.
1282 # data_transfer_methods: Array of methods that are used for transfering the
1283 # pointer data. Possible values: 'immediate', 'shm', 'bucket'.
1284 # The default is 'immediate' if the command has one pointer
1285 # argument, otherwise 'shm'. One command is generated for each
1286 # transfer method. Affects only commands which are not of type
1287 # 'HandWritten', 'GETn' or 'GLcharN'.
1288 # Note: the command arguments that affect this are the final args,
1289 # taking cmd_args override into consideration.
1290 # impl_func: Whether or not to generate the GLES2Implementation part of this
1291 # command.
1292 # impl_decl: Whether or not to generate the GLES2Implementation declaration
1293 # for this command.
1294 # needs_size: If true a data_size field is added to the command.
1295 # count: The number of units per element. For PUTn or PUT types.
1296 # unit_test: If False no service side unit test will be generated.
1297 # client_test: If False no client side unit test will be generated.
1298 # expectation: If False the unit test will have no expected calls.
1299 # gen_func: Name of function that generates GL resource for corresponding
1300 # bind function.
1301 # states: array of states that get set by this function corresponding to
1302 # the given arguments
1303 # state_flag: name of flag that is set to true when function is called.
1304 # no_gl: no GL function is called.
1305 # valid_args: A dictionary of argument indices to args to use in unit tests
1306 # when they can not be automatically determined.
1307 # pepper_interface: The pepper interface that is used for this extension
1308 # pepper_name: The name of the function as exposed to pepper.
1309 # pepper_args: A string representing the argument list (what would appear in
1310 # C/C++ between the parentheses for the function declaration)
1311 # that the Pepper API expects for this function. Use this only if
1312 # the stable Pepper API differs from the GLES2 argument list.
1313 # invalid_test: False if no invalid test needed.
1314 # shadowed: True = the value is shadowed so no glGetXXX call will be made.
1315 # first_element_only: For PUT types, True if only the first element of an
1316 # array is used and we end up calling the single value
1317 # corresponding function. eg. TexParameteriv -> TexParameteri
1318 # extension: Function is an extension to GL and should not be exposed to
1319 # pepper unless pepper_interface is defined.
1320 # extension_flag: Function is an extension and should be enabled only when
1321 # the corresponding feature info flag is enabled. Implies
1322 # 'extension': True.
1323 # not_shared: For GENn types, True if objects can't be shared between contexts
1325 _FUNCTION_INFO = {
1326 'ActiveTexture': {
1327 'decoder_func': 'DoActiveTexture',
1328 'unit_test': False,
1329 'impl_func': False,
1330 'client_test': False,
1332 'AttachShader': {'decoder_func': 'DoAttachShader'},
1333 'BindAttribLocation': {
1334 'type': 'GLchar',
1335 'data_transfer_methods': ['bucket'],
1336 'needs_size': True,
1338 'BindBuffer': {
1339 'type': 'Bind',
1340 'decoder_func': 'DoBindBuffer',
1341 'gen_func': 'GenBuffersARB',
1343 'BindFramebuffer': {
1344 'type': 'Bind',
1345 'decoder_func': 'DoBindFramebuffer',
1346 'gl_test_func': 'glBindFramebufferEXT',
1347 'gen_func': 'GenFramebuffersEXT',
1348 'trace_level': 1,
1350 'BindRenderbuffer': {
1351 'type': 'Bind',
1352 'decoder_func': 'DoBindRenderbuffer',
1353 'gl_test_func': 'glBindRenderbufferEXT',
1354 'gen_func': 'GenRenderbuffersEXT',
1356 'BindTexture': {
1357 'type': 'Bind',
1358 'decoder_func': 'DoBindTexture',
1359 'gen_func': 'GenTextures',
1360 # TODO(gman): remove this once client side caching works.
1361 'client_test': False,
1362 'trace_level': 1,
1364 'BlitFramebufferCHROMIUM': {
1365 'decoder_func': 'DoBlitFramebufferCHROMIUM',
1366 'unit_test': False,
1367 'extension_flag': 'chromium_framebuffer_multisample',
1368 'pepper_interface': 'FramebufferBlit',
1369 'pepper_name': 'BlitFramebufferEXT',
1370 'defer_reads': True,
1371 'defer_draws': True,
1372 'trace_level': 1,
1374 'BufferData': {
1375 'type': 'Manual',
1376 'data_transfer_methods': ['shm'],
1377 'client_test': False,
1379 'BufferSubData': {
1380 'type': 'Data',
1381 'client_test': False,
1382 'decoder_func': 'DoBufferSubData',
1383 'data_transfer_methods': ['shm'],
1385 'CheckFramebufferStatus': {
1386 'type': 'Is',
1387 'decoder_func': 'DoCheckFramebufferStatus',
1388 'gl_test_func': 'glCheckFramebufferStatusEXT',
1389 'error_value': 'GL_FRAMEBUFFER_UNSUPPORTED',
1390 'result': ['GLenum'],
1392 'Clear': {
1393 'decoder_func': 'DoClear',
1394 'defer_draws': True,
1395 'trace_level': 1,
1397 'ClearColor': {
1398 'type': 'StateSet',
1399 'state': 'ClearColor',
1401 'ClearDepthf': {
1402 'type': 'StateSet',
1403 'state': 'ClearDepthf',
1404 'decoder_func': 'glClearDepth',
1405 'gl_test_func': 'glClearDepth',
1406 'valid_args': {
1407 '0': '0.5f'
1410 'ColorMask': {
1411 'type': 'StateSet',
1412 'state': 'ColorMask',
1413 'no_gl': True,
1414 'expectation': False,
1416 'ConsumeTextureCHROMIUM': {
1417 'decoder_func': 'DoConsumeTextureCHROMIUM',
1418 'impl_func': False,
1419 'type': 'PUT',
1420 'count': 64, # GL_MAILBOX_SIZE_CHROMIUM
1421 'unit_test': False,
1422 'client_test': False,
1423 'extension': "CHROMIUM_texture_mailbox",
1424 'chromium': True,
1425 'trace_level': 1,
1427 'CreateAndConsumeTextureCHROMIUM': {
1428 'decoder_func': 'DoCreateAndConsumeTextureCHROMIUM',
1429 'impl_func': False,
1430 'type': 'HandWritten',
1431 'data_transfer_methods': ['immediate'],
1432 'unit_test': False,
1433 'client_test': False,
1434 'extension': "CHROMIUM_texture_mailbox",
1435 'chromium': True,
1437 'ClearStencil': {
1438 'type': 'StateSet',
1439 'state': 'ClearStencil',
1441 'EnableFeatureCHROMIUM': {
1442 'type': 'Custom',
1443 'data_transfer_methods': ['shm'],
1444 'decoder_func': 'DoEnableFeatureCHROMIUM',
1445 'expectation': False,
1446 'cmd_args': 'GLuint bucket_id, GLint* result',
1447 'result': ['GLint'],
1448 'extension': True,
1449 'chromium': True,
1450 'pepper_interface': 'ChromiumEnableFeature',
1452 'CompileShader': {'decoder_func': 'DoCompileShader', 'unit_test': False},
1453 'CompressedTexImage2D': {
1454 'type': 'Manual',
1455 'data_transfer_methods': ['bucket', 'shm'],
1457 'CompressedTexSubImage2D': {
1458 'type': 'Data',
1459 'data_transfer_methods': ['bucket', 'shm'],
1460 'decoder_func': 'DoCompressedTexSubImage2D',
1462 'CopyTexImage2D': {
1463 'decoder_func': 'DoCopyTexImage2D',
1464 'unit_test': False,
1465 'defer_reads': True,
1467 'CopyTexSubImage2D': {
1468 'decoder_func': 'DoCopyTexSubImage2D',
1469 'defer_reads': True,
1471 'CreateImageCHROMIUM': {
1472 'type': 'Manual',
1473 'cmd_args':
1474 'GLsizei width, GLsizei height, GLenum internalformat, GLenum usage',
1475 'result': ['GLuint'],
1476 'client_test': False,
1477 'gen_cmd': False,
1478 'expectation': False,
1479 'extension': True,
1480 'chromium': True,
1482 'DestroyImageCHROMIUM': {
1483 'type': 'Manual',
1484 'client_test': False,
1485 'gen_cmd': False,
1486 'extension': True,
1487 'chromium': True,
1489 'GetImageParameterivCHROMIUM': {
1490 'type': 'Manual',
1491 'client_test': False,
1492 'gen_cmd': False,
1493 'expectation': False,
1494 'extension': True,
1495 'chromium': True,
1497 'CreateProgram': {
1498 'type': 'Create',
1499 'client_test': False,
1501 'CreateShader': {
1502 'type': 'Create',
1503 'client_test': False,
1505 'BlendColor': {
1506 'type': 'StateSet',
1507 'state': 'BlendColor',
1509 'BlendEquation': {
1510 'type': 'StateSetRGBAlpha',
1511 'state': 'BlendEquation',
1512 'valid_args': {
1513 '0': 'GL_FUNC_SUBTRACT'
1516 'BlendEquationSeparate': {
1517 'type': 'StateSet',
1518 'state': 'BlendEquation',
1519 'valid_args': {
1520 '0': 'GL_FUNC_SUBTRACT'
1523 'BlendFunc': {
1524 'type': 'StateSetRGBAlpha',
1525 'state': 'BlendFunc',
1527 'BlendFuncSeparate': {
1528 'type': 'StateSet',
1529 'state': 'BlendFunc',
1531 'SampleCoverage': {'decoder_func': 'DoSampleCoverage'},
1532 'StencilFunc': {
1533 'type': 'StateSetFrontBack',
1534 'state': 'StencilFunc',
1536 'StencilFuncSeparate': {
1537 'type': 'StateSetFrontBackSeparate',
1538 'state': 'StencilFunc',
1540 'StencilOp': {
1541 'type': 'StateSetFrontBack',
1542 'state': 'StencilOp',
1543 'valid_args': {
1544 '1': 'GL_INCR'
1547 'StencilOpSeparate': {
1548 'type': 'StateSetFrontBackSeparate',
1549 'state': 'StencilOp',
1550 'valid_args': {
1551 '1': 'GL_INCR'
1554 'Hint': {
1555 'type': 'StateSetNamedParameter',
1556 'state': 'Hint',
1558 'CullFace': {'type': 'StateSet', 'state': 'CullFace'},
1559 'FrontFace': {'type': 'StateSet', 'state': 'FrontFace'},
1560 'DepthFunc': {'type': 'StateSet', 'state': 'DepthFunc'},
1561 'LineWidth': {
1562 'type': 'StateSet',
1563 'state': 'LineWidth',
1564 'valid_args': {
1565 '0': '0.5f'
1568 'PolygonOffset': {
1569 'type': 'StateSet',
1570 'state': 'PolygonOffset',
1572 'DeleteBuffers': {
1573 'type': 'DELn',
1574 'gl_test_func': 'glDeleteBuffersARB',
1575 'resource_type': 'Buffer',
1576 'resource_types': 'Buffers',
1578 'DeleteFramebuffers': {
1579 'type': 'DELn',
1580 'gl_test_func': 'glDeleteFramebuffersEXT',
1581 'resource_type': 'Framebuffer',
1582 'resource_types': 'Framebuffers',
1584 'DeleteProgram': {'type': 'Delete', 'decoder_func': 'DoDeleteProgram'},
1585 'DeleteRenderbuffers': {
1586 'type': 'DELn',
1587 'gl_test_func': 'glDeleteRenderbuffersEXT',
1588 'resource_type': 'Renderbuffer',
1589 'resource_types': 'Renderbuffers',
1591 'DeleteShader': {'type': 'Delete', 'decoder_func': 'DoDeleteShader'},
1592 'DeleteSharedIdsCHROMIUM': {
1593 'type': 'Custom',
1594 'decoder_func': 'DoDeleteSharedIdsCHROMIUM',
1595 'impl_func': False,
1596 'expectation': False,
1597 'data_transfer_methods': ['shm'],
1598 'extension': True,
1599 'chromium': True,
1601 'DeleteTextures': {
1602 'type': 'DELn',
1603 'resource_type': 'Texture',
1604 'resource_types': 'Textures',
1606 'DepthRangef': {
1607 'decoder_func': 'DoDepthRangef',
1608 'gl_test_func': 'glDepthRange',
1610 'DepthMask': {
1611 'type': 'StateSet',
1612 'state': 'DepthMask',
1613 'no_gl': True,
1614 'expectation': False,
1616 'DetachShader': {'decoder_func': 'DoDetachShader'},
1617 'Disable': {
1618 'decoder_func': 'DoDisable',
1619 'impl_func': False,
1620 'client_test': False,
1622 'DisableVertexAttribArray': {
1623 'decoder_func': 'DoDisableVertexAttribArray',
1624 'impl_decl': False,
1626 'DrawArrays': {
1627 'type': 'Manual',
1628 'cmd_args': 'GLenumDrawMode mode, GLint first, GLsizei count',
1629 'defer_draws': True,
1630 'trace_level': 2,
1632 'DrawElements': {
1633 'type': 'Manual',
1634 'cmd_args': 'GLenumDrawMode mode, GLsizei count, '
1635 'GLenumIndexType type, GLuint index_offset',
1636 'client_test': False,
1637 'defer_draws': True,
1638 'trace_level': 2,
1640 'Enable': {
1641 'decoder_func': 'DoEnable',
1642 'impl_func': False,
1643 'client_test': False,
1645 'EnableVertexAttribArray': {
1646 'decoder_func': 'DoEnableVertexAttribArray',
1647 'impl_decl': False,
1649 'Finish': {
1650 'impl_func': False,
1651 'client_test': False,
1652 'decoder_func': 'DoFinish',
1653 'defer_reads': True,
1655 'Flush': {
1656 'impl_func': False,
1657 'decoder_func': 'DoFlush',
1659 'FramebufferRenderbuffer': {
1660 'decoder_func': 'DoFramebufferRenderbuffer',
1661 'gl_test_func': 'glFramebufferRenderbufferEXT',
1663 'FramebufferTexture2D': {
1664 'decoder_func': 'DoFramebufferTexture2D',
1665 'gl_test_func': 'glFramebufferTexture2DEXT',
1666 'trace_level': 1,
1668 'FramebufferTexture2DMultisampleEXT': {
1669 'decoder_func': 'DoFramebufferTexture2DMultisample',
1670 'gl_test_func': 'glFramebufferTexture2DMultisampleEXT',
1671 'expectation': False,
1672 'unit_test': False,
1673 'extension_flag': 'multisampled_render_to_texture',
1674 'trace_level': 1,
1676 'GenerateMipmap': {
1677 'decoder_func': 'DoGenerateMipmap',
1678 'gl_test_func': 'glGenerateMipmapEXT',
1680 'GenBuffers': {
1681 'type': 'GENn',
1682 'gl_test_func': 'glGenBuffersARB',
1683 'resource_type': 'Buffer',
1684 'resource_types': 'Buffers',
1686 'GenMailboxCHROMIUM': {
1687 'type': 'HandWritten',
1688 'impl_func': False,
1689 'extension': "CHROMIUM_texture_mailbox",
1690 'chromium': True,
1692 'GenFramebuffers': {
1693 'type': 'GENn',
1694 'gl_test_func': 'glGenFramebuffersEXT',
1695 'resource_type': 'Framebuffer',
1696 'resource_types': 'Framebuffers',
1698 'GenRenderbuffers': {
1699 'type': 'GENn', 'gl_test_func': 'glGenRenderbuffersEXT',
1700 'resource_type': 'Renderbuffer',
1701 'resource_types': 'Renderbuffers',
1703 'GenTextures': {
1704 'type': 'GENn',
1705 'gl_test_func': 'glGenTextures',
1706 'resource_type': 'Texture',
1707 'resource_types': 'Textures',
1709 'GenSharedIdsCHROMIUM': {
1710 'type': 'Custom',
1711 'decoder_func': 'DoGenSharedIdsCHROMIUM',
1712 'impl_func': False,
1713 'expectation': False,
1714 'data_transfer_methods': ['shm'],
1715 'extension': True,
1716 'chromium': True,
1718 'GetActiveAttrib': {
1719 'type': 'Custom',
1720 'data_transfer_methods': ['shm'],
1721 'cmd_args':
1722 'GLidProgram program, GLuint index, uint32_t name_bucket_id, '
1723 'void* result',
1724 'result': [
1725 'int32_t success',
1726 'int32_t size',
1727 'uint32_t type',
1730 'GetActiveUniform': {
1731 'type': 'Custom',
1732 'data_transfer_methods': ['shm'],
1733 'cmd_args':
1734 'GLidProgram program, GLuint index, uint32_t name_bucket_id, '
1735 'void* result',
1736 'result': [
1737 'int32_t success',
1738 'int32_t size',
1739 'uint32_t type',
1742 'GetAttachedShaders': {
1743 'type': 'Custom',
1744 'data_transfer_methods': ['shm'],
1745 'cmd_args': 'GLidProgram program, void* result, uint32_t result_size',
1746 'result': ['SizedResult<GLuint>'],
1748 'GetAttribLocation': {
1749 'type': 'Custom',
1750 'data_transfer_methods': ['shm'],
1751 'cmd_args':
1752 'GLidProgram program, uint32_t name_bucket_id, GLint* location',
1753 'result': ['GLint'],
1754 'error_return': -1, # http://www.opengl.org/sdk/docs/man/xhtml/glGetAttribLocation.xml
1756 'GetBooleanv': {
1757 'type': 'GETn',
1758 'result': ['SizedResult<GLboolean>'],
1759 'decoder_func': 'DoGetBooleanv',
1760 'gl_test_func': 'glGetBooleanv',
1762 'GetBufferParameteriv': {
1763 'type': 'GETn',
1764 'result': ['SizedResult<GLint>'],
1765 'decoder_func': 'DoGetBufferParameteriv',
1766 'expectation': False,
1767 'shadowed': True,
1769 'GetError': {
1770 'type': 'Is',
1771 'decoder_func': 'GetErrorState()->GetGLError',
1772 'impl_func': False,
1773 'result': ['GLenum'],
1774 'client_test': False,
1776 'GetFloatv': {
1777 'type': 'GETn',
1778 'result': ['SizedResult<GLfloat>'],
1779 'decoder_func': 'DoGetFloatv',
1780 'gl_test_func': 'glGetFloatv',
1782 'GetFramebufferAttachmentParameteriv': {
1783 'type': 'GETn',
1784 'decoder_func': 'DoGetFramebufferAttachmentParameteriv',
1785 'gl_test_func': 'glGetFramebufferAttachmentParameterivEXT',
1786 'result': ['SizedResult<GLint>'],
1788 'GetIntegerv': {
1789 'type': 'GETn',
1790 'result': ['SizedResult<GLint>'],
1791 'decoder_func': 'DoGetIntegerv',
1792 'client_test': False,
1794 'GetMaxValueInBufferCHROMIUM': {
1795 'type': 'Is',
1796 'decoder_func': 'DoGetMaxValueInBufferCHROMIUM',
1797 'result': ['GLuint'],
1798 'unit_test': False,
1799 'client_test': False,
1800 'extension': True,
1801 'chromium': True,
1802 'impl_func': False,
1804 'GetMultipleIntegervCHROMIUM': {
1805 'type': 'Custom',
1806 'data_transfer_methods': ['shm'],
1807 'expectation': False,
1808 'extension': True,
1809 'chromium': True,
1810 'client_test': False,
1812 'GetProgramiv': {
1813 'type': 'GETn',
1814 'decoder_func': 'DoGetProgramiv',
1815 'result': ['SizedResult<GLint>'],
1816 'expectation': False,
1818 'GetProgramInfoCHROMIUM': {
1819 'type': 'Custom',
1820 'expectation': False,
1821 'impl_func': False,
1822 'extension': True,
1823 'chromium': True,
1824 'client_test': False,
1825 'cmd_args': 'GLidProgram program, uint32_t bucket_id',
1826 'result': [
1827 'uint32_t link_status',
1828 'uint32_t num_attribs',
1829 'uint32_t num_uniforms',
1832 'GetProgramInfoLog': {
1833 'type': 'STRn',
1834 'expectation': False,
1836 'GetRenderbufferParameteriv': {
1837 'type': 'GETn',
1838 'decoder_func': 'DoGetRenderbufferParameteriv',
1839 'gl_test_func': 'glGetRenderbufferParameterivEXT',
1840 'result': ['SizedResult<GLint>'],
1842 'GetShaderiv': {
1843 'type': 'GETn',
1844 'decoder_func': 'DoGetShaderiv',
1845 'result': ['SizedResult<GLint>'],
1847 'GetShaderInfoLog': {
1848 'type': 'STRn',
1849 'get_len_func': 'glGetShaderiv',
1850 'get_len_enum': 'GL_INFO_LOG_LENGTH',
1851 'unit_test': False,
1853 'GetShaderPrecisionFormat': {
1854 'type': 'Custom',
1855 'data_transfer_methods': ['shm'],
1856 'cmd_args':
1857 'GLenumShaderType shadertype, GLenumShaderPrecision precisiontype, '
1858 'void* result',
1859 'result': [
1860 'int32_t success',
1861 'int32_t min_range',
1862 'int32_t max_range',
1863 'int32_t precision',
1866 'GetShaderSource': {
1867 'type': 'STRn',
1868 'get_len_func': 'DoGetShaderiv',
1869 'get_len_enum': 'GL_SHADER_SOURCE_LENGTH',
1870 'unit_test': False,
1871 'client_test': False,
1873 'GetString': {
1874 'type': 'Custom',
1875 'client_test': False,
1876 'cmd_args': 'GLenumStringType name, uint32_t bucket_id',
1878 'GetTexParameterfv': {
1879 'type': 'GETn',
1880 'decoder_func': 'DoGetTexParameterfv',
1881 'result': ['SizedResult<GLfloat>']
1883 'GetTexParameteriv': {
1884 'type': 'GETn',
1885 'decoder_func': 'DoGetTexParameteriv',
1886 'result': ['SizedResult<GLint>']
1888 'GetTranslatedShaderSourceANGLE': {
1889 'type': 'STRn',
1890 'get_len_func': 'DoGetShaderiv',
1891 'get_len_enum': 'GL_TRANSLATED_SHADER_SOURCE_LENGTH_ANGLE',
1892 'unit_test': False,
1893 'extension': True,
1895 'GetUniformfv': {
1896 'type': 'Custom',
1897 'data_transfer_methods': ['shm'],
1898 'result': ['SizedResult<GLfloat>'],
1900 'GetUniformiv': {
1901 'type': 'Custom',
1902 'data_transfer_methods': ['shm'],
1903 'result': ['SizedResult<GLint>'],
1905 'GetUniformLocation': {
1906 'type': 'Custom',
1907 'data_transfer_methods': ['shm'],
1908 'cmd_args':
1909 'GLidProgram program, uint32_t name_bucket_id, GLint* location',
1910 'result': ['GLint'],
1911 'error_return': -1, # http://www.opengl.org/sdk/docs/man/xhtml/glGetUniformLocation.xml
1913 'GetVertexAttribfv': {
1914 'type': 'GETn',
1915 'result': ['SizedResult<GLfloat>'],
1916 'impl_decl': False,
1917 'decoder_func': 'DoGetVertexAttribfv',
1918 'expectation': False,
1919 'client_test': False,
1921 'GetVertexAttribiv': {
1922 'type': 'GETn',
1923 'result': ['SizedResult<GLint>'],
1924 'impl_decl': False,
1925 'decoder_func': 'DoGetVertexAttribiv',
1926 'expectation': False,
1927 'client_test': False,
1929 'GetVertexAttribPointerv': {
1930 'type': 'Custom',
1931 'data_transfer_methods': ['shm'],
1932 'result': ['SizedResult<GLuint>'],
1933 'client_test': False,
1935 'IsBuffer': {
1936 'type': 'Is',
1937 'decoder_func': 'DoIsBuffer',
1938 'expectation': False,
1940 'IsEnabled': {
1941 'type': 'Is',
1942 'decoder_func': 'DoIsEnabled',
1943 'impl_func': False,
1944 'expectation': False,
1946 'IsFramebuffer': {
1947 'type': 'Is',
1948 'decoder_func': 'DoIsFramebuffer',
1949 'expectation': False,
1951 'IsProgram': {
1952 'type': 'Is',
1953 'decoder_func': 'DoIsProgram',
1954 'expectation': False,
1956 'IsRenderbuffer': {
1957 'type': 'Is',
1958 'decoder_func': 'DoIsRenderbuffer',
1959 'expectation': False,
1961 'IsShader': {
1962 'type': 'Is',
1963 'decoder_func': 'DoIsShader',
1964 'expectation': False,
1966 'IsTexture': {
1967 'type': 'Is',
1968 'decoder_func': 'DoIsTexture',
1969 'expectation': False,
1971 'LinkProgram': {
1972 'decoder_func': 'DoLinkProgram',
1973 'impl_func': False,
1975 'MapBufferCHROMIUM': {
1976 'gen_cmd': False,
1977 'extension': True,
1978 'chromium': True,
1979 'client_test': False,
1981 'MapBufferSubDataCHROMIUM': {
1982 'gen_cmd': False,
1983 'extension': True,
1984 'chromium': True,
1985 'client_test': False,
1986 'pepper_interface': 'ChromiumMapSub',
1988 'MapImageCHROMIUM': {
1989 'gen_cmd': False,
1990 'extension': True,
1991 'chromium': True,
1992 'client_test': False,
1994 'MapTexSubImage2DCHROMIUM': {
1995 'gen_cmd': False,
1996 'extension': True,
1997 'chromium': True,
1998 'client_test': False,
1999 'pepper_interface': 'ChromiumMapSub',
2001 'PixelStorei': {'type': 'Manual'},
2002 'PostSubBufferCHROMIUM': {
2003 'type': 'Custom',
2004 'impl_func': False,
2005 'unit_test': False,
2006 'client_test': False,
2007 'extension': True,
2008 'chromium': True,
2010 'ProduceTextureCHROMIUM': {
2011 'decoder_func': 'DoProduceTextureCHROMIUM',
2012 'impl_func': False,
2013 'type': 'PUT',
2014 'count': 64, # GL_MAILBOX_SIZE_CHROMIUM
2015 'unit_test': False,
2016 'client_test': False,
2017 'extension': "CHROMIUM_texture_mailbox",
2018 'chromium': True,
2019 'trace_level': 1,
2021 'ProduceTextureDirectCHROMIUM': {
2022 'decoder_func': 'DoProduceTextureDirectCHROMIUM',
2023 'impl_func': False,
2024 'type': 'PUT',
2025 'count': 64, # GL_MAILBOX_SIZE_CHROMIUM
2026 'unit_test': False,
2027 'client_test': False,
2028 'extension': "CHROMIUM_texture_mailbox",
2029 'chromium': True,
2030 'trace_level': 1,
2032 'RenderbufferStorage': {
2033 'decoder_func': 'DoRenderbufferStorage',
2034 'gl_test_func': 'glRenderbufferStorageEXT',
2035 'expectation': False,
2037 'RenderbufferStorageMultisampleCHROMIUM': {
2038 'cmd_comment':
2039 '// GL_CHROMIUM_framebuffer_multisample\n',
2040 'decoder_func': 'DoRenderbufferStorageMultisampleCHROMIUM',
2041 'gl_test_func': 'glRenderbufferStorageMultisampleCHROMIUM',
2042 'expectation': False,
2043 'unit_test': False,
2044 'extension_flag': 'chromium_framebuffer_multisample',
2045 'pepper_interface': 'FramebufferMultisample',
2046 'pepper_name': 'RenderbufferStorageMultisampleEXT',
2048 'RenderbufferStorageMultisampleEXT': {
2049 'cmd_comment':
2050 '// GL_EXT_multisampled_render_to_texture\n',
2051 'decoder_func': 'DoRenderbufferStorageMultisampleEXT',
2052 'gl_test_func': 'glRenderbufferStorageMultisampleEXT',
2053 'expectation': False,
2054 'unit_test': False,
2055 'extension_flag': 'multisampled_render_to_texture',
2057 'ReadPixels': {
2058 'cmd_comment':
2059 '// ReadPixels has the result separated from the pixel buffer so that\n'
2060 '// it is easier to specify the result going to some specific place\n'
2061 '// that exactly fits the rectangle of pixels.\n',
2062 'type': 'Custom',
2063 'data_transfer_methods': ['shm'],
2064 'impl_func': False,
2065 'client_test': False,
2066 'cmd_args':
2067 'GLint x, GLint y, GLsizei width, GLsizei height, '
2068 'GLenumReadPixelFormat format, GLenumReadPixelType type, '
2069 'uint32_t pixels_shm_id, uint32_t pixels_shm_offset, '
2070 'uint32_t result_shm_id, uint32_t result_shm_offset, '
2071 'GLboolean async',
2072 'result': ['uint32_t'],
2073 'defer_reads': True,
2075 'RegisterSharedIdsCHROMIUM': {
2076 'type': 'Custom',
2077 'decoder_func': 'DoRegisterSharedIdsCHROMIUM',
2078 'impl_func': False,
2079 'expectation': False,
2080 'data_transfer_methods': ['shm'],
2081 'extension': True,
2082 'chromium': True,
2084 'ReleaseShaderCompiler': {
2085 'decoder_func': 'DoReleaseShaderCompiler',
2086 'unit_test': False,
2088 'ShaderBinary': {
2089 'type': 'Custom',
2090 'client_test': False,
2092 'ShaderSource': {
2093 'type': 'Manual',
2094 'data_transfer_methods': ['bucket'],
2095 'needs_size': True,
2096 'client_test': False,
2097 'cmd_args':
2098 'GLuint shader, const char* data',
2099 'pepper_args':
2100 'GLuint shader, GLsizei count, const char** str, const GLint* length',
2102 'StencilMask': {
2103 'type': 'StateSetFrontBack',
2104 'state': 'StencilMask',
2105 'no_gl': True,
2106 'expectation': False,
2108 'StencilMaskSeparate': {
2109 'type': 'StateSetFrontBackSeparate',
2110 'state': 'StencilMask',
2111 'no_gl': True,
2112 'expectation': False,
2114 'SwapBuffers': {
2115 'impl_func': False,
2116 'decoder_func': 'DoSwapBuffers',
2117 'unit_test': False,
2118 'client_test': False,
2119 'extension': True,
2120 'trace_level': 1,
2122 'TexImage2D': {
2123 'type': 'Manual',
2124 'data_transfer_methods': ['shm'],
2125 'client_test': False,
2127 'TexParameterf': {
2128 'decoder_func': 'DoTexParameterf',
2129 'valid_args': {
2130 '2': 'GL_NEAREST'
2133 'TexParameteri': {
2134 'decoder_func': 'DoTexParameteri',
2135 'valid_args': {
2136 '2': 'GL_NEAREST'
2139 'TexParameterfv': {
2140 'type': 'PUT',
2141 'data_value': 'GL_NEAREST',
2142 'count': 1,
2143 'decoder_func': 'DoTexParameterfv',
2144 'gl_test_func': 'glTexParameterf',
2145 'first_element_only': True,
2147 'TexParameteriv': {
2148 'type': 'PUT',
2149 'data_value': 'GL_NEAREST',
2150 'count': 1,
2151 'decoder_func': 'DoTexParameteriv',
2152 'gl_test_func': 'glTexParameteri',
2153 'first_element_only': True,
2155 'TexSubImage2D': {
2156 'type': 'Manual',
2157 'data_transfer_methods': ['shm'],
2158 'client_test': False,
2159 'cmd_args': 'GLenumTextureTarget target, GLint level, '
2160 'GLint xoffset, GLint yoffset, '
2161 'GLsizei width, GLsizei height, '
2162 'GLenumTextureFormat format, GLenumPixelType type, '
2163 'const void* pixels, GLboolean internal'
2165 'Uniform1f': {'type': 'PUTXn', 'count': 1},
2166 'Uniform1fv': {
2167 'type': 'PUTn',
2168 'count': 1,
2169 'decoder_func': 'DoUniform1fv',
2171 'Uniform1i': {'decoder_func': 'DoUniform1i', 'unit_test': False},
2172 'Uniform1iv': {
2173 'type': 'PUTn',
2174 'count': 1,
2175 'decoder_func': 'DoUniform1iv',
2176 'unit_test': False,
2178 'Uniform2i': {'type': 'PUTXn', 'count': 2},
2179 'Uniform2f': {'type': 'PUTXn', 'count': 2},
2180 'Uniform2fv': {
2181 'type': 'PUTn',
2182 'count': 2,
2183 'decoder_func': 'DoUniform2fv',
2185 'Uniform2iv': {
2186 'type': 'PUTn',
2187 'count': 2,
2188 'decoder_func': 'DoUniform2iv',
2190 'Uniform3i': {'type': 'PUTXn', 'count': 3},
2191 'Uniform3f': {'type': 'PUTXn', 'count': 3},
2192 'Uniform3fv': {
2193 'type': 'PUTn',
2194 'count': 3,
2195 'decoder_func': 'DoUniform3fv',
2197 'Uniform3iv': {
2198 'type': 'PUTn',
2199 'count': 3,
2200 'decoder_func': 'DoUniform3iv',
2202 'Uniform4i': {'type': 'PUTXn', 'count': 4},
2203 'Uniform4f': {'type': 'PUTXn', 'count': 4},
2204 'Uniform4fv': {
2205 'type': 'PUTn',
2206 'count': 4,
2207 'decoder_func': 'DoUniform4fv',
2209 'Uniform4iv': {
2210 'type': 'PUTn',
2211 'count': 4,
2212 'decoder_func': 'DoUniform4iv',
2214 'UniformMatrix2fv': {
2215 'type': 'PUTn',
2216 'count': 4,
2217 'decoder_func': 'DoUniformMatrix2fv',
2219 'UniformMatrix3fv': {
2220 'type': 'PUTn',
2221 'count': 9,
2222 'decoder_func': 'DoUniformMatrix3fv',
2224 'UniformMatrix4fv': {
2225 'type': 'PUTn',
2226 'count': 16,
2227 'decoder_func': 'DoUniformMatrix4fv',
2229 'UnmapBufferCHROMIUM': {
2230 'gen_cmd': False,
2231 'extension': True,
2232 'chromium': True,
2233 'client_test': False,
2235 'UnmapBufferSubDataCHROMIUM': {
2236 'gen_cmd': False,
2237 'extension': True,
2238 'chromium': True,
2239 'client_test': False,
2240 'pepper_interface': 'ChromiumMapSub',
2242 'UnmapImageCHROMIUM': {
2243 'gen_cmd': False,
2244 'extension': True,
2245 'chromium': True,
2246 'client_test': False,
2248 'UnmapTexSubImage2DCHROMIUM': {
2249 'gen_cmd': False,
2250 'extension': True,
2251 'chromium': True,
2252 'client_test': False,
2253 'pepper_interface': 'ChromiumMapSub',
2255 'UseProgram': {
2256 'type': 'Bind',
2257 'decoder_func': 'DoUseProgram',
2259 'ValidateProgram': {'decoder_func': 'DoValidateProgram'},
2260 'VertexAttrib1f': {'decoder_func': 'DoVertexAttrib1f'},
2261 'VertexAttrib1fv': {
2262 'type': 'PUT',
2263 'count': 1,
2264 'decoder_func': 'DoVertexAttrib1fv',
2266 'VertexAttrib2f': {'decoder_func': 'DoVertexAttrib2f'},
2267 'VertexAttrib2fv': {
2268 'type': 'PUT',
2269 'count': 2,
2270 'decoder_func': 'DoVertexAttrib2fv',
2272 'VertexAttrib3f': {'decoder_func': 'DoVertexAttrib3f'},
2273 'VertexAttrib3fv': {
2274 'type': 'PUT',
2275 'count': 3,
2276 'decoder_func': 'DoVertexAttrib3fv',
2278 'VertexAttrib4f': {'decoder_func': 'DoVertexAttrib4f'},
2279 'VertexAttrib4fv': {
2280 'type': 'PUT',
2281 'count': 4,
2282 'decoder_func': 'DoVertexAttrib4fv',
2284 'VertexAttribPointer': {
2285 'type': 'Manual',
2286 'cmd_args': 'GLuint indx, GLintVertexAttribSize size, '
2287 'GLenumVertexAttribType type, GLboolean normalized, '
2288 'GLsizei stride, GLuint offset',
2289 'client_test': False,
2291 'Scissor': {
2292 'type': 'StateSet',
2293 'state': 'Scissor',
2295 'Viewport': {
2296 'decoder_func': 'DoViewport',
2298 'ResizeCHROMIUM': {
2299 'type': 'Custom',
2300 'impl_func': False,
2301 'unit_test': False,
2302 'extension': True,
2303 'chromium': True,
2305 'GetRequestableExtensionsCHROMIUM': {
2306 'type': 'Custom',
2307 'impl_func': False,
2308 'cmd_args': 'uint32_t bucket_id',
2309 'extension': True,
2310 'chromium': True,
2312 'RequestExtensionCHROMIUM': {
2313 'type': 'Custom',
2314 'impl_func': False,
2315 'client_test': False,
2316 'cmd_args': 'uint32_t bucket_id',
2317 'extension': True,
2318 'chromium': True,
2320 'RateLimitOffscreenContextCHROMIUM': {
2321 'gen_cmd': False,
2322 'extension': True,
2323 'chromium': True,
2324 'client_test': False,
2326 'CreateStreamTextureCHROMIUM': {
2327 'type': 'HandWritten',
2328 'impl_func': False,
2329 'gen_cmd': False,
2330 'extension': True,
2331 'chromium': True,
2333 'TexImageIOSurface2DCHROMIUM': {
2334 'decoder_func': 'DoTexImageIOSurface2DCHROMIUM',
2335 'unit_test': False,
2336 'extension': True,
2337 'chromium': True,
2339 'CopyTextureCHROMIUM': {
2340 'decoder_func': 'DoCopyTextureCHROMIUM',
2341 'unit_test': False,
2342 'extension': True,
2343 'chromium': True,
2345 'TexStorage2DEXT': {
2346 'unit_test': False,
2347 'extension': True,
2348 'decoder_func': 'DoTexStorage2DEXT',
2350 'DrawArraysInstancedANGLE': {
2351 'type': 'Manual',
2352 'cmd_args': 'GLenumDrawMode mode, GLint first, GLsizei count, '
2353 'GLsizei primcount',
2354 'extension': True,
2355 'unit_test': False,
2356 'pepper_interface': 'InstancedArrays',
2357 'defer_draws': True,
2359 'DrawBuffersEXT': {
2360 'type': 'PUTn',
2361 'decoder_func': 'DoDrawBuffersEXT',
2362 'count': 1,
2363 'client_test': False,
2364 'unit_test': False,
2365 # could use 'extension_flag': 'ext_draw_buffers' but currently expected to
2366 # work without.
2367 'extension': True,
2368 'pepper_interface': 'DrawBuffers',
2370 'DrawElementsInstancedANGLE': {
2371 'type': 'Manual',
2372 'cmd_args': 'GLenumDrawMode mode, GLsizei count, '
2373 'GLenumIndexType type, GLuint index_offset, GLsizei primcount',
2374 'extension': True,
2375 'unit_test': False,
2376 'client_test': False,
2377 'pepper_interface': 'InstancedArrays',
2378 'defer_draws': True,
2380 'VertexAttribDivisorANGLE': {
2381 'type': 'Manual',
2382 'cmd_args': 'GLuint index, GLuint divisor',
2383 'extension': True,
2384 'unit_test': False,
2385 'pepper_interface': 'InstancedArrays',
2387 'GenQueriesEXT': {
2388 'type': 'GENn',
2389 'gl_test_func': 'glGenQueriesARB',
2390 'resource_type': 'Query',
2391 'resource_types': 'Queries',
2392 'unit_test': False,
2393 'pepper_interface': 'Query',
2394 'not_shared': 'True',
2396 'DeleteQueriesEXT': {
2397 'type': 'DELn',
2398 'gl_test_func': 'glDeleteQueriesARB',
2399 'resource_type': 'Query',
2400 'resource_types': 'Queries',
2401 'unit_test': False,
2402 'pepper_interface': 'Query',
2404 'IsQueryEXT': {
2405 'gen_cmd': False,
2406 'client_test': False,
2407 'pepper_interface': 'Query',
2409 'BeginQueryEXT': {
2410 'type': 'Manual',
2411 'cmd_args': 'GLenumQueryTarget target, GLidQuery id, void* sync_data',
2412 'data_transfer_methods': ['shm'],
2413 'gl_test_func': 'glBeginQuery',
2414 'pepper_interface': 'Query',
2416 'EndQueryEXT': {
2417 'type': 'Manual',
2418 'cmd_args': 'GLenumQueryTarget target, GLuint submit_count',
2419 'gl_test_func': 'glEndnQuery',
2420 'client_test': False,
2421 'pepper_interface': 'Query',
2423 'GetQueryivEXT': {
2424 'gen_cmd': False,
2425 'client_test': False,
2426 'gl_test_func': 'glGetQueryiv',
2427 'pepper_interface': 'Query',
2429 'GetQueryObjectuivEXT': {
2430 'gen_cmd': False,
2431 'client_test': False,
2432 'gl_test_func': 'glGetQueryObjectuiv',
2433 'pepper_interface': 'Query',
2435 'BindUniformLocationCHROMIUM': {
2436 'type': 'GLchar',
2437 'extension': True,
2438 'data_transfer_methods': ['bucket'],
2439 'needs_size': True,
2440 'gl_test_func': 'DoBindUniformLocationCHROMIUM',
2442 'InsertEventMarkerEXT': {
2443 'type': 'GLcharN',
2444 'decoder_func': 'DoInsertEventMarkerEXT',
2445 'expectation': False,
2446 'extension': True,
2448 'PushGroupMarkerEXT': {
2449 'type': 'GLcharN',
2450 'decoder_func': 'DoPushGroupMarkerEXT',
2451 'expectation': False,
2452 'extension': True,
2454 'PopGroupMarkerEXT': {
2455 'decoder_func': 'DoPopGroupMarkerEXT',
2456 'expectation': False,
2457 'extension': True,
2458 'impl_func': False,
2461 'GenVertexArraysOES': {
2462 'type': 'GENn',
2463 'extension': True,
2464 'gl_test_func': 'glGenVertexArraysOES',
2465 'resource_type': 'VertexArray',
2466 'resource_types': 'VertexArrays',
2467 'unit_test': False,
2468 'pepper_interface': 'VertexArrayObject',
2470 'BindVertexArrayOES': {
2471 'type': 'Bind',
2472 'extension': True,
2473 'gl_test_func': 'glBindVertexArrayOES',
2474 'decoder_func': 'DoBindVertexArrayOES',
2475 'gen_func': 'GenVertexArraysOES',
2476 'unit_test': False,
2477 'client_test': False,
2478 'pepper_interface': 'VertexArrayObject',
2480 'DeleteVertexArraysOES': {
2481 'type': 'DELn',
2482 'extension': True,
2483 'gl_test_func': 'glDeleteVertexArraysOES',
2484 'resource_type': 'VertexArray',
2485 'resource_types': 'VertexArrays',
2486 'unit_test': False,
2487 'pepper_interface': 'VertexArrayObject',
2489 'IsVertexArrayOES': {
2490 'type': 'Is',
2491 'extension': True,
2492 'gl_test_func': 'glIsVertexArrayOES',
2493 'decoder_func': 'DoIsVertexArrayOES',
2494 'expectation': False,
2495 'unit_test': False,
2496 'pepper_interface': 'VertexArrayObject',
2498 'BindTexImage2DCHROMIUM': {
2499 'decoder_func': 'DoBindTexImage2DCHROMIUM',
2500 'unit_test': False,
2501 'extension': True,
2502 'chromium': True,
2504 'ReleaseTexImage2DCHROMIUM': {
2505 'decoder_func': 'DoReleaseTexImage2DCHROMIUM',
2506 'unit_test': False,
2507 'extension': True,
2508 'chromium': True,
2510 'ShallowFinishCHROMIUM': {
2511 'impl_func': False,
2512 'gen_cmd': False,
2513 'extension': True,
2514 'chromium': True,
2515 'client_test': False,
2517 'ShallowFlushCHROMIUM': {
2518 'impl_func': False,
2519 'gen_cmd': False,
2520 'extension': True,
2521 'chromium': True,
2522 'client_test': False,
2524 'TraceBeginCHROMIUM': {
2525 'type': 'Custom',
2526 'impl_func': False,
2527 'client_test': False,
2528 'cmd_args': 'GLuint bucket_id',
2529 'extension': True,
2530 'chromium': True,
2532 'TraceEndCHROMIUM': {
2533 'impl_func': False,
2534 'client_test': False,
2535 'decoder_func': 'DoTraceEndCHROMIUM',
2536 'unit_test': False,
2537 'extension': True,
2538 'chromium': True,
2540 'AsyncTexImage2DCHROMIUM': {
2541 'type': 'Manual',
2542 'data_transfer_methods': ['shm'],
2543 'client_test': False,
2544 'cmd_args': 'GLenumTextureTarget target, GLint level, '
2545 'GLintTextureInternalFormat internalformat, '
2546 'GLsizei width, GLsizei height, '
2547 'GLintTextureBorder border, '
2548 'GLenumTextureFormat format, GLenumPixelType type, '
2549 'const void* pixels, '
2550 'uint32_t async_upload_token, '
2551 'void* sync_data',
2552 'extension': True,
2553 'chromium': True,
2555 'AsyncTexSubImage2DCHROMIUM': {
2556 'type': 'Manual',
2557 'data_transfer_methods': ['shm'],
2558 'client_test': False,
2559 'cmd_args': 'GLenumTextureTarget target, GLint level, '
2560 'GLint xoffset, GLint yoffset, '
2561 'GLsizei width, GLsizei height, '
2562 'GLenumTextureFormat format, GLenumPixelType type, '
2563 'const void* data, '
2564 'uint32_t async_upload_token, '
2565 'void* sync_data',
2566 'extension': True,
2567 'chromium': True,
2569 'WaitAsyncTexImage2DCHROMIUM': {
2570 'type': 'Manual',
2571 'client_test': False,
2572 'extension': True,
2573 'chromium': True,
2575 'WaitAllAsyncTexImage2DCHROMIUM': {
2576 'type': 'Manual',
2577 'client_test': False,
2578 'extension': True,
2579 'chromium': True,
2581 'DiscardFramebufferEXT': {
2582 'type': 'PUTn',
2583 'count': 1,
2584 'cmd_args': 'GLenum target, GLsizei count, '
2585 'const GLenum* attachments',
2586 'decoder_func': 'DoDiscardFramebufferEXT',
2587 'unit_test': False,
2588 'client_test': False,
2589 'extension_flag': 'ext_discard_framebuffer',
2591 'LoseContextCHROMIUM': {
2592 'decoder_func': 'DoLoseContextCHROMIUM',
2593 'unit_test': False,
2594 'extension': True,
2595 'chromium': True,
2597 'InsertSyncPointCHROMIUM': {
2598 'type': 'HandWritten',
2599 'impl_func': False,
2600 'extension': "CHROMIUM_sync_point",
2601 'chromium': True,
2603 'WaitSyncPointCHROMIUM': {
2604 'type': 'Custom',
2605 'impl_func': True,
2606 'extension': "CHROMIUM_sync_point",
2607 'chromium': True,
2608 'trace_level': 1,
2610 'DiscardBackbufferCHROMIUM': {
2611 'type': 'Custom',
2612 'impl_func': True,
2613 'extension': True,
2614 'chromium': True,
2616 'ScheduleOverlayPlaneCHROMIUM': {
2617 'type': 'Custom',
2618 'impl_func': True,
2619 'unit_test': False,
2620 'client_test': False,
2621 'extension': True,
2622 'chromium': True,
2624 'MatrixLoadfCHROMIUM': {
2625 'type': 'PUT',
2626 'count': 16,
2627 'data_type': 'GLfloat',
2628 'decoder_func': 'DoMatrixLoadfCHROMIUM',
2629 'gl_test_func': 'glMatrixLoadfEXT',
2630 'chromium': True,
2631 'extension': True,
2632 'extension_flag': 'chromium_path_rendering',
2634 'MatrixLoadIdentityCHROMIUM': {
2635 'decoder_func': 'DoMatrixLoadIdentityCHROMIUM',
2636 'gl_test_func': 'glMatrixLoadIdentityEXT',
2637 'chromium': True,
2638 'extension': True,
2639 'extension_flag': 'chromium_path_rendering',
2644 def Grouper(n, iterable, fillvalue=None):
2645 """Collect data into fixed-length chunks or blocks"""
2646 args = [iter(iterable)] * n
2647 return itertools.izip_longest(fillvalue=fillvalue, *args)
2650 def SplitWords(input_string):
2651 """Transforms a input_string into a list of lower-case components.
2653 Args:
2654 input_string: the input string.
2656 Returns:
2657 a list of lower-case words.
2659 if input_string.find('_') > -1:
2660 # 'some_TEXT_' -> 'some text'
2661 return input_string.replace('_', ' ').strip().lower().split()
2662 else:
2663 if re.search('[A-Z]', input_string) and re.search('[a-z]', input_string):
2664 # mixed case.
2665 # look for capitalization to cut input_strings
2666 # 'SomeText' -> 'Some Text'
2667 input_string = re.sub('([A-Z])', r' \1', input_string).strip()
2668 # 'Vector3' -> 'Vector 3'
2669 input_string = re.sub('([^0-9])([0-9])', r'\1 \2', input_string)
2670 return input_string.lower().split()
2673 def Lower(words):
2674 """Makes a lower-case identifier from words.
2676 Args:
2677 words: a list of lower-case words.
2679 Returns:
2680 the lower-case identifier.
2682 return '_'.join(words)
2685 def ToUnderscore(input_string):
2686 """converts CamelCase to camel_case."""
2687 words = SplitWords(input_string)
2688 return Lower(words)
2690 def CachedStateName(item):
2691 if item.get('cached', False):
2692 return 'cached_' + item['name']
2693 return item['name']
2695 def ToGLExtensionString(extension_flag):
2696 """Returns GL-type extension string of a extension flag."""
2697 if extension_flag == "oes_compressed_etc1_rgb8_texture":
2698 return "OES_compressed_ETC1_RGB8_texture" # Fixup inconsitency with rgb8,
2699 # unfortunate.
2700 uppercase_words = [ 'img', 'ext', 'arb', 'chromium', 'oes', 'amd', 'bgra8888',
2701 'egl', 'atc', 'etc1', 'angle']
2702 parts = extension_flag.split('_')
2703 return "_".join(
2704 [part.upper() if part in uppercase_words else part for part in parts])
2706 def ToCamelCase(input_string):
2707 """converts ABC_underscore_case to ABCUnderscoreCase."""
2708 return ''.join(w[0].upper() + w[1:] for w in input_string.split('_'))
2710 def GetGLGetTypeConversion(result_type, value_type, value):
2711 """Makes a gl compatible type conversion string for accessing state variables.
2713 Useful when accessing state variables through glGetXXX calls.
2714 glGet documetation (for example, the manual pages):
2715 [...] If glGetIntegerv is called, [...] most floating-point values are
2716 rounded to the nearest integer value. [...]
2718 Args:
2719 result_type: the gl type to be obtained
2720 value_type: the GL type of the state variable
2721 value: the name of the state variable
2723 Returns:
2724 String that converts the state variable to desired GL type according to GL
2725 rules.
2728 if result_type == 'GLint':
2729 if value_type == 'GLfloat':
2730 return 'static_cast<GLint>(round(%s))' % value
2731 return 'static_cast<%s>(%s)' % (result_type, value)
2733 class CWriter(object):
2734 """Writes to a file formatting it for Google's style guidelines."""
2736 def __init__(self, filename):
2737 self.filename = filename
2738 self.content = []
2740 def Write(self, string):
2741 """Writes a string to a file spliting if it's > 80 characters."""
2742 lines = string.splitlines()
2743 num_lines = len(lines)
2744 for ii in range(0, num_lines):
2745 self.content.append(lines[ii])
2746 if ii < (num_lines - 1) or string[-1] == '\n':
2747 self.content.append('\n')
2749 def Close(self):
2750 """Close the file."""
2751 content = "".join(self.content)
2752 write_file = True
2753 if os.path.exists(self.filename):
2754 old_file = open(self.filename, "rb");
2755 old_content = old_file.read()
2756 old_file.close();
2757 if content == old_content:
2758 write_file = False
2759 if write_file:
2760 file = open(self.filename, "wb")
2761 file.write(content)
2762 file.close()
2765 class CHeaderWriter(CWriter):
2766 """Writes a C Header file."""
2768 _non_alnum_re = re.compile(r'[^a-zA-Z0-9]')
2770 def __init__(self, filename, file_comment = None):
2771 CWriter.__init__(self, filename)
2773 base = os.path.abspath(filename)
2774 while os.path.basename(base) != 'src':
2775 new_base = os.path.dirname(base)
2776 assert new_base != base # Prevent infinite loop.
2777 base = new_base
2779 hpath = os.path.relpath(filename, base)
2780 self.guard = self._non_alnum_re.sub('_', hpath).upper() + '_'
2782 self.Write(_LICENSE)
2783 self.Write(_DO_NOT_EDIT_WARNING)
2784 if not file_comment == None:
2785 self.Write(file_comment)
2786 self.Write("#ifndef %s\n" % self.guard)
2787 self.Write("#define %s\n\n" % self.guard)
2789 def Close(self):
2790 self.Write("#endif // %s\n\n" % self.guard)
2791 CWriter.Close(self)
2793 class TypeHandler(object):
2794 """This class emits code for a particular type of function."""
2796 _remove_expected_call_re = re.compile(r' EXPECT_CALL.*?;\n', re.S)
2798 def __init__(self):
2799 pass
2801 def InitFunction(self, func):
2802 """Add or adjust anything type specific for this function."""
2803 if func.GetInfo('needs_size') and not func.name.endswith('Bucket'):
2804 func.AddCmdArg(DataSizeArgument('data_size'))
2806 def NeedsDataTransferFunction(self, func):
2807 """Overriden from TypeHandler."""
2808 return func.num_pointer_args >= 1
2810 def WriteStruct(self, func, file):
2811 """Writes a structure that matches the arguments to a function."""
2812 comment = func.GetInfo('cmd_comment')
2813 if not comment == None:
2814 file.Write(comment)
2815 file.Write("struct %s {\n" % func.name)
2816 file.Write(" typedef %s ValueType;\n" % func.name)
2817 file.Write(" static const CommandId kCmdId = k%s;\n" % func.name)
2818 func.WriteCmdArgFlag(file)
2819 func.WriteCmdFlag(file)
2820 file.Write("\n")
2821 result = func.GetInfo('result')
2822 if not result == None:
2823 if len(result) == 1:
2824 file.Write(" typedef %s Result;\n\n" % result[0])
2825 else:
2826 file.Write(" struct Result {\n")
2827 for line in result:
2828 file.Write(" %s;\n" % line)
2829 file.Write(" };\n\n")
2831 func.WriteCmdComputeSize(file)
2832 func.WriteCmdSetHeader(file)
2833 func.WriteCmdInit(file)
2834 func.WriteCmdSet(file)
2836 file.Write(" gpu::CommandHeader header;\n")
2837 args = func.GetCmdArgs()
2838 for arg in args:
2839 file.Write(" %s %s;\n" % (arg.cmd_type, arg.name))
2841 consts = func.GetCmdConstants()
2842 for const in consts:
2843 file.Write(" static const %s %s = %s;\n" %
2844 (const.cmd_type, const.name, const.GetConstantValue()))
2846 file.Write("};\n")
2847 file.Write("\n")
2849 size = len(args) * _SIZE_OF_UINT32 + _SIZE_OF_COMMAND_HEADER
2850 file.Write("COMPILE_ASSERT(sizeof(%s) == %d,\n" % (func.name, size))
2851 file.Write(" Sizeof_%s_is_not_%d);\n" % (func.name, size))
2852 file.Write("COMPILE_ASSERT(offsetof(%s, header) == 0,\n" % func.name)
2853 file.Write(" OffsetOf_%s_header_not_0);\n" % func.name)
2854 offset = _SIZE_OF_COMMAND_HEADER
2855 for arg in args:
2856 file.Write("COMPILE_ASSERT(offsetof(%s, %s) == %d,\n" %
2857 (func.name, arg.name, offset))
2858 file.Write(" OffsetOf_%s_%s_not_%d);\n" %
2859 (func.name, arg.name, offset))
2860 offset += _SIZE_OF_UINT32
2861 if not result == None and len(result) > 1:
2862 offset = 0;
2863 for line in result:
2864 parts = line.split()
2865 name = parts[-1]
2866 check = """
2867 COMPILE_ASSERT(offsetof(%(cmd_name)s::Result, %(field_name)s) == %(offset)d,
2868 OffsetOf_%(cmd_name)s_Result_%(field_name)s_not_%(offset)d);
2870 file.Write((check.strip() + "\n") % {
2871 'cmd_name': func.name,
2872 'field_name': name,
2873 'offset': offset,
2875 offset += _SIZE_OF_UINT32
2876 file.Write("\n")
2878 def WriteHandlerImplementation(self, func, file):
2879 """Writes the handler implementation for this command."""
2880 file.Write(" %s(%s);\n" %
2881 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
2883 def WriteCmdSizeTest(self, func, file):
2884 """Writes the size test for a command."""
2885 file.Write(" EXPECT_EQ(sizeof(cmd), cmd.header.size * 4u);\n")
2887 def WriteFormatTest(self, func, file):
2888 """Writes a format test for a command."""
2889 file.Write("TEST_F(GLES2FormatTest, %s) {\n" % func.name)
2890 file.Write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
2891 (func.name, func.name))
2892 file.Write(" void* next_cmd = cmd.Set(\n")
2893 file.Write(" &cmd")
2894 args = func.GetCmdArgs()
2895 for value, arg in enumerate(args):
2896 file.Write(",\n static_cast<%s>(%d)" % (arg.type, value + 11))
2897 file.Write(");\n")
2898 file.Write(" EXPECT_EQ(static_cast<uint32_t>(cmds::%s::kCmdId),\n" %
2899 func.name)
2900 file.Write(" cmd.header.command);\n")
2901 func.type_handler.WriteCmdSizeTest(func, file)
2902 for value, arg in enumerate(args):
2903 file.Write(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);\n" %
2904 (arg.type, value + 11, arg.name))
2905 file.Write(" CheckBytesWrittenMatchesExpectedSize(\n")
2906 file.Write(" next_cmd, sizeof(cmd));\n")
2907 file.Write("}\n")
2908 file.Write("\n")
2910 def WriteImmediateFormatTest(self, func, file):
2911 """Writes a format test for an immediate version of a command."""
2912 pass
2914 def WriteBucketFormatTest(self, func, file):
2915 """Writes a format test for a bucket version of a command."""
2916 pass
2918 def WriteGetDataSizeCode(self, func, file):
2919 """Writes the code to set data_size used in validation"""
2920 pass
2922 def WriteImmediateCmdSizeTest(self, func, file):
2923 """Writes a size test for an immediate version of a command."""
2924 file.Write(" // TODO(gman): Compute correct size.\n")
2925 file.Write(" EXPECT_EQ(sizeof(cmd), cmd.header.size * 4u);\n")
2927 def WriteImmediateHandlerImplementation (self, func, file):
2928 """Writes the handler impl for the immediate version of a command."""
2929 file.Write(" %s(%s);\n" %
2930 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
2932 def WriteBucketHandlerImplementation (self, func, file):
2933 """Writes the handler impl for the bucket version of a command."""
2934 file.Write(" %s(%s);\n" %
2935 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
2937 def WriteServiceImplementation(self, func, file):
2938 """Writes the service implementation for a command."""
2939 file.Write(
2940 "error::Error GLES2DecoderImpl::Handle%s(\n" % func.name)
2941 file.Write(
2942 " uint32_t immediate_data_size, const gles2::cmds::%s& c) {\n" %
2943 func.name)
2944 self.WriteHandlerExtensionCheck(func, file)
2945 self.WriteHandlerDeferReadWrite(func, file);
2946 if len(func.GetOriginalArgs()) > 0:
2947 last_arg = func.GetLastOriginalArg()
2948 all_but_last_arg = func.GetOriginalArgs()[:-1]
2949 for arg in all_but_last_arg:
2950 arg.WriteGetCode(file)
2951 self.WriteGetDataSizeCode(func, file)
2952 last_arg.WriteGetCode(file)
2953 func.WriteHandlerValidation(file)
2954 func.WriteHandlerImplementation(file)
2955 file.Write(" return error::kNoError;\n")
2956 file.Write("}\n")
2957 file.Write("\n")
2959 def WriteImmediateServiceImplementation(self, func, file):
2960 """Writes the service implementation for an immediate version of command."""
2961 file.Write(
2962 "error::Error GLES2DecoderImpl::Handle%s(\n" % func.name)
2963 file.Write(
2964 " uint32_t immediate_data_size, const gles2::cmds::%s& c) {\n" %
2965 func.name)
2966 self.WriteHandlerExtensionCheck(func, file)
2967 self.WriteHandlerDeferReadWrite(func, file);
2968 last_arg = func.GetLastOriginalArg()
2969 all_but_last_arg = func.GetOriginalArgs()[:-1]
2970 for arg in all_but_last_arg:
2971 arg.WriteGetCode(file)
2972 self.WriteGetDataSizeCode(func, file)
2973 last_arg.WriteGetCode(file)
2974 func.WriteHandlerValidation(file)
2975 func.WriteHandlerImplementation(file)
2976 file.Write(" return error::kNoError;\n")
2977 file.Write("}\n")
2978 file.Write("\n")
2980 def WriteBucketServiceImplementation(self, func, file):
2981 """Writes the service implementation for a bucket version of command."""
2982 file.Write(
2983 "error::Error GLES2DecoderImpl::Handle%s(\n" % func.name)
2984 file.Write(
2985 " uint32_t immediate_data_size, const gles2::cmds::%s& c) {\n" %
2986 func.name)
2987 self.WriteHandlerExtensionCheck(func, file)
2988 self.WriteHandlerDeferReadWrite(func, file);
2989 last_arg = func.GetLastOriginalArg()
2990 all_but_last_arg = func.GetOriginalArgs()[:-1]
2991 for arg in all_but_last_arg:
2992 arg.WriteGetCode(file)
2993 self.WriteGetDataSizeCode(func, file)
2994 last_arg.WriteGetCode(file)
2995 func.WriteHandlerValidation(file)
2996 func.WriteHandlerImplementation(file)
2997 file.Write(" return error::kNoError;\n")
2998 file.Write("}\n")
2999 file.Write("\n")
3001 def WriteHandlerExtensionCheck(self, func, file):
3002 if func.GetInfo('extension_flag'):
3003 file.Write(" if (!features().%s) {\n" % func.GetInfo('extension_flag'))
3004 file.Write(" LOCAL_SET_GL_ERROR(GL_INVALID_OPERATION, \"gl%s\","
3005 " \"function not available\");\n" % func.original_name)
3006 file.Write(" return error::kNoError;")
3007 file.Write(" }\n\n")
3009 def WriteHandlerDeferReadWrite(self, func, file):
3010 """Writes the code to handle deferring reads or writes."""
3011 defer_draws = func.GetInfo('defer_draws')
3012 defer_reads = func.GetInfo('defer_reads')
3013 if defer_draws or defer_reads:
3014 file.Write(" error::Error error;\n")
3015 if defer_draws:
3016 file.Write(" error = WillAccessBoundFramebufferForDraw();\n")
3017 file.Write(" if (error != error::kNoError)\n")
3018 file.Write(" return error;\n")
3019 if defer_reads:
3020 file.Write(" error = WillAccessBoundFramebufferForRead();\n")
3021 file.Write(" if (error != error::kNoError)\n")
3022 file.Write(" return error;\n")
3024 def WriteValidUnitTest(self, func, file, test, *extras):
3025 """Writes a valid unit test for the service implementation."""
3026 if func.GetInfo('expectation') == False:
3027 test = self._remove_expected_call_re.sub('', test)
3028 name = func.name
3029 arg_strings = [
3030 arg.GetValidArg(func) \
3031 for arg in func.GetOriginalArgs() if not arg.IsConstant()
3033 gl_arg_strings = [
3034 arg.GetValidGLArg(func) \
3035 for arg in func.GetOriginalArgs()
3037 gl_func_name = func.GetGLTestFunctionName()
3038 vars = {
3039 'name':name,
3040 'gl_func_name': gl_func_name,
3041 'args': ", ".join(arg_strings),
3042 'gl_args': ", ".join(gl_arg_strings),
3044 for extra in extras:
3045 vars.update(extra)
3046 old_test = ""
3047 while (old_test != test):
3048 old_test = test
3049 test = test % vars
3050 file.Write(test % vars)
3052 def WriteInvalidUnitTest(self, func, file, test, *extras):
3053 """Writes an invalid unit test for the service implementation."""
3054 for invalid_arg_index, invalid_arg in enumerate(func.GetOriginalArgs()):
3055 # Service implementation does not test constants, as they are not part of
3056 # the call in the service side.
3057 if invalid_arg.IsConstant():
3058 continue
3060 num_invalid_values = invalid_arg.GetNumInvalidValues(func)
3061 for value_index in range(0, num_invalid_values):
3062 arg_strings = []
3063 parse_result = "kNoError"
3064 gl_error = None
3065 for arg in func.GetOriginalArgs():
3066 if arg.IsConstant():
3067 continue
3068 if invalid_arg is arg:
3069 (arg_string, parse_result, gl_error) = arg.GetInvalidArg(
3070 value_index)
3071 else:
3072 arg_string = arg.GetValidArg(func)
3073 arg_strings.append(arg_string)
3074 gl_arg_strings = []
3075 for arg in func.GetOriginalArgs():
3076 gl_arg_strings.append("_")
3077 gl_func_name = func.GetGLTestFunctionName()
3078 gl_error_test = ''
3079 if not gl_error == None:
3080 gl_error_test = '\n EXPECT_EQ(%s, GetGLError());' % gl_error
3082 vars = {
3083 'name': func.name,
3084 'arg_index': invalid_arg_index,
3085 'value_index': value_index,
3086 'gl_func_name': gl_func_name,
3087 'args': ", ".join(arg_strings),
3088 'all_but_last_args': ", ".join(arg_strings[:-1]),
3089 'gl_args': ", ".join(gl_arg_strings),
3090 'parse_result': parse_result,
3091 'gl_error_test': gl_error_test,
3093 for extra in extras:
3094 vars.update(extra)
3095 file.Write(test % vars)
3097 def WriteServiceUnitTest(self, func, file, *extras):
3098 """Writes the service unit test for a command."""
3100 if func.name == 'Enable':
3101 valid_test = """
3102 TEST_P(%(test_name)s, %(name)sValidArgs) {
3103 SetupExpectationsForEnableDisable(%(gl_args)s, true);
3104 SpecializedSetup<cmds::%(name)s, 0>(true);
3105 cmds::%(name)s cmd;
3106 cmd.Init(%(args)s);
3107 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
3108 EXPECT_EQ(GL_NO_ERROR, GetGLError());
3111 elif func.name == 'Disable':
3112 valid_test = """
3113 TEST_P(%(test_name)s, %(name)sValidArgs) {
3114 SetupExpectationsForEnableDisable(%(gl_args)s, false);
3115 SpecializedSetup<cmds::%(name)s, 0>(true);
3116 cmds::%(name)s cmd;
3117 cmd.Init(%(args)s);
3118 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
3119 EXPECT_EQ(GL_NO_ERROR, GetGLError());
3122 else:
3123 valid_test = """
3124 TEST_P(%(test_name)s, %(name)sValidArgs) {
3125 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
3126 SpecializedSetup<cmds::%(name)s, 0>(true);
3127 cmds::%(name)s cmd;
3128 cmd.Init(%(args)s);
3129 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
3130 EXPECT_EQ(GL_NO_ERROR, GetGLError());
3133 self.WriteValidUnitTest(func, file, valid_test, *extras)
3135 invalid_test = """
3136 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
3137 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
3138 SpecializedSetup<cmds::%(name)s, 0>(false);
3139 cmds::%(name)s cmd;
3140 cmd.Init(%(args)s);
3141 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
3144 self.WriteInvalidUnitTest(func, file, invalid_test, *extras)
3146 def WriteImmediateServiceUnitTest(self, func, file, *extras):
3147 """Writes the service unit test for an immediate command."""
3148 file.Write("// TODO(gman): %s\n" % func.name)
3150 def WriteImmediateValidationCode(self, func, file):
3151 """Writes the validation code for an immediate version of a command."""
3152 pass
3154 def WriteBucketServiceUnitTest(self, func, file, *extras):
3155 """Writes the service unit test for a bucket command."""
3156 file.Write("// TODO(gman): %s\n" % func.name)
3158 def WriteBucketValidationCode(self, func, file):
3159 """Writes the validation code for a bucket version of a command."""
3160 file.Write("// TODO(gman): %s\n" % func.name)
3162 def WriteGLES2ImplementationDeclaration(self, func, file):
3163 """Writes the GLES2 Implemention declaration."""
3164 impl_decl = func.GetInfo('impl_decl')
3165 if impl_decl == None or impl_decl == True:
3166 file.Write("virtual %s %s(%s) OVERRIDE;\n" %
3167 (func.return_type, func.original_name,
3168 func.MakeTypedOriginalArgString("")))
3169 file.Write("\n")
3171 def WriteGLES2CLibImplementation(self, func, file):
3172 file.Write("%s GLES2%s(%s) {\n" %
3173 (func.return_type, func.name,
3174 func.MakeTypedOriginalArgString("")))
3175 result_string = "return "
3176 if func.return_type == "void":
3177 result_string = ""
3178 file.Write(" %sgles2::GetGLContext()->%s(%s);\n" %
3179 (result_string, func.original_name,
3180 func.MakeOriginalArgString("")))
3181 file.Write("}\n")
3183 def WriteGLES2Header(self, func, file):
3184 """Writes a re-write macro for GLES"""
3185 file.Write("#define gl%s GLES2_GET_FUN(%s)\n" %(func.name, func.name))
3187 def WriteClientGLCallLog(self, func, file):
3188 """Writes a logging macro for the client side code."""
3189 comma = ""
3190 if len(func.GetOriginalArgs()):
3191 comma = " << "
3192 file.Write(
3193 ' GPU_CLIENT_LOG("[" << GetLogPrefix() << "] gl%s("%s%s << ")");\n' %
3194 (func.original_name, comma, func.MakeLogArgString()))
3196 def WriteClientGLReturnLog(self, func, file):
3197 """Writes the return value logging code."""
3198 if func.return_type != "void":
3199 file.Write(' GPU_CLIENT_LOG("return:" << result)\n')
3201 def WriteGLES2ImplementationHeader(self, func, file):
3202 """Writes the GLES2 Implemention."""
3203 self.WriteGLES2ImplementationDeclaration(func, file)
3205 def WriteGLES2TraceImplementationHeader(self, func, file):
3206 """Writes the GLES2 Trace Implemention header."""
3207 file.Write("virtual %s %s(%s) OVERRIDE;\n" %
3208 (func.return_type, func.original_name,
3209 func.MakeTypedOriginalArgString("")))
3211 def WriteGLES2TraceImplementation(self, func, file):
3212 """Writes the GLES2 Trace Implemention."""
3213 file.Write("%s GLES2TraceImplementation::%s(%s) {\n" %
3214 (func.return_type, func.original_name,
3215 func.MakeTypedOriginalArgString("")))
3216 result_string = "return "
3217 if func.return_type == "void":
3218 result_string = ""
3219 file.Write(' TRACE_EVENT_BINARY_EFFICIENT0("gpu", "GLES2Trace::%s");\n' %
3220 func.name)
3221 file.Write(" %sgl_->%s(%s);\n" %
3222 (result_string, func.name, func.MakeOriginalArgString("")))
3223 file.Write("}\n")
3224 file.Write("\n")
3226 def WriteGLES2Implementation(self, func, file):
3227 """Writes the GLES2 Implemention."""
3228 impl_func = func.GetInfo('impl_func')
3229 impl_decl = func.GetInfo('impl_decl')
3230 gen_cmd = func.GetInfo('gen_cmd')
3231 if (func.can_auto_generate and
3232 (impl_func == None or impl_func == True) and
3233 (impl_decl == None or impl_decl == True) and
3234 (gen_cmd == None or gen_cmd == True)):
3235 file.Write("%s GLES2Implementation::%s(%s) {\n" %
3236 (func.return_type, func.original_name,
3237 func.MakeTypedOriginalArgString("")))
3238 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
3239 self.WriteClientGLCallLog(func, file)
3240 func.WriteDestinationInitalizationValidation(file)
3241 for arg in func.GetOriginalArgs():
3242 arg.WriteClientSideValidationCode(file, func)
3243 file.Write(" helper_->%s(%s);\n" %
3244 (func.name, func.MakeHelperArgString("")))
3245 file.Write(" CheckGLError();\n")
3246 self.WriteClientGLReturnLog(func, file)
3247 file.Write("}\n")
3248 file.Write("\n")
3250 def WriteGLES2InterfaceHeader(self, func, file):
3251 """Writes the GLES2 Interface."""
3252 file.Write("virtual %s %s(%s) = 0;\n" %
3253 (func.return_type, func.original_name,
3254 func.MakeTypedOriginalArgString("")))
3256 def WriteGLES2InterfaceStub(self, func, file):
3257 """Writes the GLES2 Interface stub declaration."""
3258 file.Write("virtual %s %s(%s) OVERRIDE;\n" %
3259 (func.return_type, func.original_name,
3260 func.MakeTypedOriginalArgString("")))
3262 def WriteGLES2InterfaceStubImpl(self, func, file):
3263 """Writes the GLES2 Interface stub declaration."""
3264 args = func.GetOriginalArgs()
3265 arg_string = ", ".join(
3266 ["%s /* %s */" % (arg.type, arg.name) for arg in args])
3267 file.Write("%s GLES2InterfaceStub::%s(%s) {\n" %
3268 (func.return_type, func.original_name, arg_string))
3269 if func.return_type != "void":
3270 file.Write(" return 0;\n")
3271 file.Write("}\n")
3273 def WriteGLES2ImplementationUnitTest(self, func, file):
3274 """Writes the GLES2 Implemention unit test."""
3275 client_test = func.GetInfo('client_test')
3276 if (func.can_auto_generate and
3277 (client_test == None or client_test == True)):
3278 code = """
3279 TEST_F(GLES2ImplementationTest, %(name)s) {
3280 struct Cmds {
3281 cmds::%(name)s cmd;
3283 Cmds expected;
3284 expected.cmd.Init(%(cmd_args)s);
3286 gl_->%(name)s(%(args)s);
3287 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
3290 cmd_arg_strings = [
3291 arg.GetValidClientSideCmdArg(func) for arg in func.GetCmdArgs()
3294 gl_arg_strings = [
3295 arg.GetValidClientSideArg(func) for arg in func.GetOriginalArgs()
3298 file.Write(code % {
3299 'name': func.name,
3300 'args': ", ".join(gl_arg_strings),
3301 'cmd_args': ", ".join(cmd_arg_strings),
3304 # Test constants for invalid values, as they are not tested by the
3305 # service.
3306 constants = [arg for arg in func.GetOriginalArgs() if arg.IsConstant()]
3307 if constants:
3308 code = """
3309 TEST_F(GLES2ImplementationTest, %(name)sInvalidConstantArg%(invalid_index)d) {
3310 gl_->%(name)s(%(args)s);
3311 EXPECT_TRUE(NoCommandsWritten());
3312 EXPECT_EQ(%(gl_error)s, CheckError());
3315 for invalid_arg in constants:
3316 gl_arg_strings = []
3317 invalid = invalid_arg.GetInvalidArg(func)
3318 for arg in func.GetOriginalArgs():
3319 if arg is invalid_arg:
3320 gl_arg_strings.append(invalid[0])
3321 else:
3322 gl_arg_strings.append(arg.GetValidClientSideArg(func))
3324 file.Write(code % {
3325 'name': func.name,
3326 'invalid_index': func.GetOriginalArgs().index(invalid_arg),
3327 'args': ", ".join(gl_arg_strings),
3328 'gl_error': invalid[2],
3330 else:
3331 if client_test != False:
3332 file.Write("// TODO: Implement unit test for %s\n" % func.name)
3334 def WriteDestinationInitalizationValidation(self, func, file):
3335 """Writes the client side destintion initialization validation."""
3336 for arg in func.GetOriginalArgs():
3337 arg.WriteDestinationInitalizationValidation(file, func)
3339 def WriteTraceEvent(self, func, file):
3340 file.Write(' TRACE_EVENT0("gpu", "GLES2Implementation::%s");\n' %
3341 func.original_name)
3343 def WriteImmediateCmdComputeSize(self, func, file):
3344 """Writes the size computation code for the immediate version of a cmd."""
3345 file.Write(" static uint32_t ComputeSize(uint32_t size_in_bytes) {\n")
3346 file.Write(" return static_cast<uint32_t>(\n")
3347 file.Write(" sizeof(ValueType) + // NOLINT\n")
3348 file.Write(" RoundSizeToMultipleOfEntries(size_in_bytes));\n")
3349 file.Write(" }\n")
3350 file.Write("\n")
3352 def WriteImmediateCmdSetHeader(self, func, file):
3353 """Writes the SetHeader function for the immediate version of a cmd."""
3354 file.Write(" void SetHeader(uint32_t size_in_bytes) {\n")
3355 file.Write(" header.SetCmdByTotalSize<ValueType>(size_in_bytes);\n")
3356 file.Write(" }\n")
3357 file.Write("\n")
3359 def WriteImmediateCmdInit(self, func, file):
3360 """Writes the Init function for the immediate version of a command."""
3361 raise NotImplementedError(func.name)
3363 def WriteImmediateCmdSet(self, func, file):
3364 """Writes the Set function for the immediate version of a command."""
3365 raise NotImplementedError(func.name)
3367 def WriteCmdHelper(self, func, file):
3368 """Writes the cmd helper definition for a cmd."""
3369 code = """ void %(name)s(%(typed_args)s) {
3370 gles2::cmds::%(name)s* c = GetCmdSpace<gles2::cmds::%(name)s>();
3371 if (c) {
3372 c->Init(%(args)s);
3377 file.Write(code % {
3378 "name": func.name,
3379 "typed_args": func.MakeTypedCmdArgString(""),
3380 "args": func.MakeCmdArgString(""),
3383 def WriteImmediateCmdHelper(self, func, file):
3384 """Writes the cmd helper definition for the immediate version of a cmd."""
3385 code = """ void %(name)s(%(typed_args)s) {
3386 const uint32_t s = 0; // TODO(gman): compute correct size
3387 gles2::cmds::%(name)s* c =
3388 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(s);
3389 if (c) {
3390 c->Init(%(args)s);
3395 file.Write(code % {
3396 "name": func.name,
3397 "typed_args": func.MakeTypedCmdArgString(""),
3398 "args": func.MakeCmdArgString(""),
3402 class StateSetHandler(TypeHandler):
3403 """Handler for commands that simply set state."""
3405 def __init__(self):
3406 TypeHandler.__init__(self)
3408 def WriteHandlerImplementation(self, func, file):
3409 """Overrriden from TypeHandler."""
3410 state_name = func.GetInfo('state')
3411 state = _STATES[state_name]
3412 states = state['states']
3413 args = func.GetOriginalArgs()
3414 for ndx,item in enumerate(states):
3415 code = []
3416 if 'range_checks' in item:
3417 for range_check in item['range_checks']:
3418 code.append("%s %s" % (args[ndx].name, range_check['check']))
3419 if 'nan_check' in item:
3420 # Drivers might generate an INVALID_VALUE error when a value is set
3421 # to NaN. This is allowed behavior under GLES 3.0 section 2.1.1 or
3422 # OpenGL 4.5 section 2.3.4.1 - providing NaN allows undefined results.
3423 # Make this behavior consistent within Chromium, and avoid leaking GL
3424 # errors by generating the error in the command buffer instead of
3425 # letting the GL driver generate it.
3426 code.append("base::IsNaN(%s)" % args[ndx].name)
3427 if len(code):
3428 file.Write(" if (%s) {\n" % " ||\n ".join(code))
3429 file.Write(
3430 ' LOCAL_SET_GL_ERROR(GL_INVALID_VALUE,'
3431 ' "%s", "%s out of range");\n' %
3432 (func.name, args[ndx].name))
3433 file.Write(" return error::kNoError;\n")
3434 file.Write(" }\n")
3435 code = []
3436 for ndx,item in enumerate(states):
3437 code.append("state_.%s != %s" % (item['name'], args[ndx].name))
3438 file.Write(" if (%s) {\n" % " ||\n ".join(code))
3439 for ndx,item in enumerate(states):
3440 file.Write(" state_.%s = %s;\n" % (item['name'], args[ndx].name))
3441 if 'state_flag' in state:
3442 file.Write(" %s = true;\n" % state['state_flag'])
3443 if not func.GetInfo("no_gl"):
3444 for ndx,item in enumerate(states):
3445 if item.get('cached', False):
3446 file.Write(" state_.%s = %s;\n" %
3447 (CachedStateName(item), args[ndx].name))
3448 file.Write(" %s(%s);\n" %
3449 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
3450 file.Write(" }\n")
3452 def WriteServiceUnitTest(self, func, file, *extras):
3453 """Overrriden from TypeHandler."""
3454 TypeHandler.WriteServiceUnitTest(self, func, file, *extras)
3455 state_name = func.GetInfo('state')
3456 state = _STATES[state_name]
3457 states = state['states']
3458 for ndx,item in enumerate(states):
3459 if 'range_checks' in item:
3460 for check_ndx, range_check in enumerate(item['range_checks']):
3461 valid_test = """
3462 TEST_P(%(test_name)s, %(name)sInvalidValue%(ndx)d_%(check_ndx)d) {
3463 SpecializedSetup<cmds::%(name)s, 0>(false);
3464 cmds::%(name)s cmd;
3465 cmd.Init(%(args)s);
3466 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
3467 EXPECT_EQ(GL_INVALID_VALUE, GetGLError());
3470 name = func.name
3471 arg_strings = [
3472 arg.GetValidArg(func) \
3473 for arg in func.GetOriginalArgs() if not arg.IsConstant()
3476 arg_strings[ndx] = range_check['test_value']
3477 vars = {
3478 'name': name,
3479 'ndx': ndx,
3480 'check_ndx': check_ndx,
3481 'args': ", ".join(arg_strings),
3483 for extra in extras:
3484 vars.update(extra)
3485 file.Write(valid_test % vars)
3486 if 'nan_check' in item:
3487 valid_test = """
3488 TEST_P(%(test_name)s, %(name)sNaNValue%(ndx)d) {
3489 SpecializedSetup<cmds::%(name)s, 0>(false);
3490 cmds::%(name)s cmd;
3491 cmd.Init(%(args)s);
3492 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
3493 EXPECT_EQ(GL_INVALID_VALUE, GetGLError());
3496 name = func.name
3497 arg_strings = [
3498 arg.GetValidArg(func) \
3499 for arg in func.GetOriginalArgs() if not arg.IsConstant()
3502 arg_strings[ndx] = 'nanf("")'
3503 vars = {
3504 'name': name,
3505 'ndx': ndx,
3506 'args': ", ".join(arg_strings),
3508 for extra in extras:
3509 vars.update(extra)
3510 file.Write(valid_test % vars)
3513 class StateSetRGBAlphaHandler(TypeHandler):
3514 """Handler for commands that simply set state that have rgb/alpha."""
3516 def __init__(self):
3517 TypeHandler.__init__(self)
3519 def WriteHandlerImplementation(self, func, file):
3520 """Overrriden from TypeHandler."""
3521 state_name = func.GetInfo('state')
3522 state = _STATES[state_name]
3523 states = state['states']
3524 args = func.GetOriginalArgs()
3525 num_args = len(args)
3526 code = []
3527 for ndx,item in enumerate(states):
3528 code.append("state_.%s != %s" % (item['name'], args[ndx % num_args].name))
3529 file.Write(" if (%s) {\n" % " ||\n ".join(code))
3530 for ndx, item in enumerate(states):
3531 file.Write(" state_.%s = %s;\n" %
3532 (item['name'], args[ndx % num_args].name))
3533 if 'state_flag' in state:
3534 file.Write(" %s = true;\n" % state['state_flag'])
3535 if not func.GetInfo("no_gl"):
3536 file.Write(" %s(%s);\n" %
3537 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
3538 file.Write(" }\n")
3541 class StateSetFrontBackSeparateHandler(TypeHandler):
3542 """Handler for commands that simply set state that have front/back."""
3544 def __init__(self):
3545 TypeHandler.__init__(self)
3547 def WriteHandlerImplementation(self, func, file):
3548 """Overrriden from TypeHandler."""
3549 state_name = func.GetInfo('state')
3550 state = _STATES[state_name]
3551 states = state['states']
3552 args = func.GetOriginalArgs()
3553 face = args[0].name
3554 num_args = len(args)
3555 file.Write(" bool changed = false;\n")
3556 for group_ndx, group in enumerate(Grouper(num_args - 1, states)):
3557 file.Write(" if (%s == %s || %s == GL_FRONT_AND_BACK) {\n" %
3558 (face, ('GL_FRONT', 'GL_BACK')[group_ndx], face))
3559 code = []
3560 for ndx, item in enumerate(group):
3561 code.append("state_.%s != %s" % (item['name'], args[ndx + 1].name))
3562 file.Write(" changed |= %s;\n" % " ||\n ".join(code))
3563 file.Write(" }\n")
3564 file.Write(" if (changed) {\n")
3565 for group_ndx, group in enumerate(Grouper(num_args - 1, states)):
3566 file.Write(" if (%s == %s || %s == GL_FRONT_AND_BACK) {\n" %
3567 (face, ('GL_FRONT', 'GL_BACK')[group_ndx], face))
3568 for ndx, item in enumerate(group):
3569 file.Write(" state_.%s = %s;\n" %
3570 (item['name'], args[ndx + 1].name))
3571 file.Write(" }\n")
3572 if 'state_flag' in state:
3573 file.Write(" %s = true;\n" % state['state_flag'])
3574 if not func.GetInfo("no_gl"):
3575 file.Write(" %s(%s);\n" %
3576 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
3577 file.Write(" }\n")
3580 class StateSetFrontBackHandler(TypeHandler):
3581 """Handler for commands that simply set state that set both front/back."""
3583 def __init__(self):
3584 TypeHandler.__init__(self)
3586 def WriteHandlerImplementation(self, func, file):
3587 """Overrriden from TypeHandler."""
3588 state_name = func.GetInfo('state')
3589 state = _STATES[state_name]
3590 states = state['states']
3591 args = func.GetOriginalArgs()
3592 num_args = len(args)
3593 code = []
3594 for group_ndx, group in enumerate(Grouper(num_args, states)):
3595 for ndx, item in enumerate(group):
3596 code.append("state_.%s != %s" % (item['name'], args[ndx].name))
3597 file.Write(" if (%s) {\n" % " ||\n ".join(code))
3598 for group_ndx, group in enumerate(Grouper(num_args, states)):
3599 for ndx, item in enumerate(group):
3600 file.Write(" state_.%s = %s;\n" % (item['name'], args[ndx].name))
3601 if 'state_flag' in state:
3602 file.Write(" %s = true;\n" % state['state_flag'])
3603 if not func.GetInfo("no_gl"):
3604 file.Write(" %s(%s);\n" %
3605 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
3606 file.Write(" }\n")
3609 class StateSetNamedParameter(TypeHandler):
3610 """Handler for commands that set a state chosen with an enum parameter."""
3612 def __init__(self):
3613 TypeHandler.__init__(self)
3615 def WriteHandlerImplementation(self, func, file):
3616 """Overridden from TypeHandler."""
3617 state_name = func.GetInfo('state')
3618 state = _STATES[state_name]
3619 states = state['states']
3620 args = func.GetOriginalArgs()
3621 num_args = len(args)
3622 assert num_args == 2
3623 file.Write(" switch (%s) {\n" % args[0].name)
3624 for state in states:
3625 file.Write(" case %s:\n" % state['enum'])
3626 file.Write(" if (state_.%s != %s) {\n" %
3627 (state['name'], args[1].name))
3628 file.Write(" state_.%s = %s;\n" % (state['name'], args[1].name))
3629 if not func.GetInfo("no_gl"):
3630 file.Write(" %s(%s);\n" %
3631 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
3632 file.Write(" }\n")
3633 file.Write(" break;\n")
3634 file.Write(" default:\n")
3635 file.Write(" NOTREACHED();\n")
3636 file.Write(" }\n")
3639 class CustomHandler(TypeHandler):
3640 """Handler for commands that are auto-generated but require minor tweaks."""
3642 def __init__(self):
3643 TypeHandler.__init__(self)
3645 def WriteServiceImplementation(self, func, file):
3646 """Overrriden from TypeHandler."""
3647 pass
3649 def WriteImmediateServiceImplementation(self, func, file):
3650 """Overrriden from TypeHandler."""
3651 pass
3653 def WriteBucketServiceImplementation(self, func, file):
3654 """Overrriden from TypeHandler."""
3655 pass
3657 def WriteServiceUnitTest(self, func, file, *extras):
3658 """Overrriden from TypeHandler."""
3659 file.Write("// TODO(gman): %s\n\n" % func.name)
3661 def WriteImmediateServiceUnitTest(self, func, file, *extras):
3662 """Overrriden from TypeHandler."""
3663 file.Write("// TODO(gman): %s\n\n" % func.name)
3665 def WriteImmediateCmdGetTotalSize(self, func, file):
3666 """Overrriden from TypeHandler."""
3667 file.Write(
3668 " uint32_t total_size = 0; // TODO(gman): get correct size.\n")
3670 def WriteImmediateCmdInit(self, func, file):
3671 """Overrriden from TypeHandler."""
3672 file.Write(" void Init(%s) {\n" % func.MakeTypedCmdArgString("_"))
3673 self.WriteImmediateCmdGetTotalSize(func, file)
3674 file.Write(" SetHeader(total_size);\n")
3675 args = func.GetCmdArgs()
3676 for arg in args:
3677 file.Write(" %s = _%s;\n" % (arg.name, arg.name))
3678 file.Write(" }\n")
3679 file.Write("\n")
3681 def WriteImmediateCmdSet(self, func, file):
3682 """Overrriden from TypeHandler."""
3683 copy_args = func.MakeCmdArgString("_", False)
3684 file.Write(" void* Set(void* cmd%s) {\n" %
3685 func.MakeTypedCmdArgString("_", True))
3686 self.WriteImmediateCmdGetTotalSize(func, file)
3687 file.Write(" static_cast<ValueType*>(cmd)->Init(%s);\n" % copy_args)
3688 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
3689 "cmd, total_size);\n")
3690 file.Write(" }\n")
3691 file.Write("\n")
3694 class TodoHandler(CustomHandler):
3695 """Handle for commands that are not yet implemented."""
3697 def NeedsDataTransferFunction(self, func):
3698 """Overriden from TypeHandler."""
3699 return False
3701 def WriteImmediateFormatTest(self, func, file):
3702 """Overrriden from TypeHandler."""
3703 pass
3705 def WriteGLES2ImplementationUnitTest(self, func, file):
3706 """Overrriden from TypeHandler."""
3707 pass
3709 def WriteGLES2Implementation(self, func, file):
3710 """Overrriden from TypeHandler."""
3711 file.Write("%s GLES2Implementation::%s(%s) {\n" %
3712 (func.return_type, func.original_name,
3713 func.MakeTypedOriginalArgString("")))
3714 file.Write(" // TODO: for now this is a no-op\n")
3715 file.Write(
3716 " SetGLError("
3717 "GL_INVALID_OPERATION, \"gl%s\", \"not implemented\");\n" %
3718 func.name)
3719 if func.return_type != "void":
3720 file.Write(" return 0;\n")
3721 file.Write("}\n")
3722 file.Write("\n")
3724 def WriteServiceImplementation(self, func, file):
3725 """Overrriden from TypeHandler."""
3726 file.Write(
3727 "error::Error GLES2DecoderImpl::Handle%s(\n" % func.name)
3728 file.Write(
3729 " uint32_t immediate_data_size, const gles2::cmds::%s& c) {\n" %
3730 func.name)
3731 file.Write(" // TODO: for now this is a no-op\n")
3732 file.Write(
3733 " LOCAL_SET_GL_ERROR("
3734 "GL_INVALID_OPERATION, \"gl%s\", \"not implemented\");\n" %
3735 func.name)
3736 file.Write(" return error::kNoError;\n")
3737 file.Write("}\n")
3738 file.Write("\n")
3741 class HandWrittenHandler(CustomHandler):
3742 """Handler for comands where everything must be written by hand."""
3744 def InitFunction(self, func):
3745 """Add or adjust anything type specific for this function."""
3746 CustomHandler.InitFunction(self, func)
3747 func.can_auto_generate = False
3749 def NeedsDataTransferFunction(self, func):
3750 """Overriden from TypeHandler."""
3751 # If specified explicitly, force the data transfer method.
3752 if func.GetInfo('data_transfer_methods'):
3753 return True
3754 return False
3756 def WriteStruct(self, func, file):
3757 """Overrriden from TypeHandler."""
3758 pass
3760 def WriteDocs(self, func, file):
3761 """Overrriden from TypeHandler."""
3762 pass
3764 def WriteServiceUnitTest(self, func, file, *extras):
3765 """Overrriden from TypeHandler."""
3766 file.Write("// TODO(gman): %s\n\n" % func.name)
3768 def WriteImmediateServiceUnitTest(self, func, file, *extras):
3769 """Overrriden from TypeHandler."""
3770 file.Write("// TODO(gman): %s\n\n" % func.name)
3772 def WriteBucketServiceUnitTest(self, func, file, *extras):
3773 """Overrriden from TypeHandler."""
3774 file.Write("// TODO(gman): %s\n\n" % func.name)
3776 def WriteServiceImplementation(self, func, file):
3777 """Overrriden from TypeHandler."""
3778 pass
3780 def WriteImmediateServiceImplementation(self, func, file):
3781 """Overrriden from TypeHandler."""
3782 pass
3784 def WriteBucketServiceImplementation(self, func, file):
3785 """Overrriden from TypeHandler."""
3786 pass
3788 def WriteImmediateCmdHelper(self, func, file):
3789 """Overrriden from TypeHandler."""
3790 pass
3792 def WriteBucketCmdHelper(self, func, file):
3793 """Overrriden from TypeHandler."""
3794 pass
3796 def WriteCmdHelper(self, func, file):
3797 """Overrriden from TypeHandler."""
3798 pass
3800 def WriteFormatTest(self, func, file):
3801 """Overrriden from TypeHandler."""
3802 file.Write("// TODO(gman): Write test for %s\n" % func.name)
3804 def WriteImmediateFormatTest(self, func, file):
3805 """Overrriden from TypeHandler."""
3806 file.Write("// TODO(gman): Write test for %s\n" % func.name)
3808 def WriteBucketFormatTest(self, func, file):
3809 """Overrriden from TypeHandler."""
3810 file.Write("// TODO(gman): Write test for %s\n" % func.name)
3814 class ManualHandler(CustomHandler):
3815 """Handler for commands who's handlers must be written by hand."""
3817 def __init__(self):
3818 CustomHandler.__init__(self)
3820 def InitFunction(self, func):
3821 """Overrriden from TypeHandler."""
3822 if (func.name == 'CompressedTexImage2DBucket'):
3823 func.cmd_args = func.cmd_args[:-1]
3824 func.AddCmdArg(Argument('bucket_id', 'GLuint'))
3825 else:
3826 CustomHandler.InitFunction(self, func)
3828 def WriteServiceImplementation(self, func, file):
3829 """Overrriden from TypeHandler."""
3830 pass
3832 def WriteBucketServiceImplementation(self, func, file):
3833 """Overrriden from TypeHandler."""
3834 pass
3836 def WriteServiceUnitTest(self, func, file, *extras):
3837 """Overrriden from TypeHandler."""
3838 file.Write("// TODO(gman): %s\n\n" % func.name)
3840 def WriteImmediateServiceUnitTest(self, func, file, *extras):
3841 """Overrriden from TypeHandler."""
3842 file.Write("// TODO(gman): %s\n\n" % func.name)
3844 def WriteImmediateServiceImplementation(self, func, file):
3845 """Overrriden from TypeHandler."""
3846 pass
3848 def WriteImmediateFormatTest(self, func, file):
3849 """Overrriden from TypeHandler."""
3850 file.Write("// TODO(gman): Implement test for %s\n" % func.name)
3852 def WriteGLES2Implementation(self, func, file):
3853 """Overrriden from TypeHandler."""
3854 if func.GetInfo('impl_func'):
3855 super(ManualHandler, self).WriteGLES2Implementation(func, file)
3857 def WriteGLES2ImplementationHeader(self, func, file):
3858 """Overrriden from TypeHandler."""
3859 file.Write("virtual %s %s(%s) OVERRIDE;\n" %
3860 (func.return_type, func.original_name,
3861 func.MakeTypedOriginalArgString("")))
3862 file.Write("\n")
3864 def WriteImmediateCmdGetTotalSize(self, func, file):
3865 """Overrriden from TypeHandler."""
3866 # TODO(gman): Move this data to _FUNCTION_INFO?
3867 CustomHandler.WriteImmediateCmdGetTotalSize(self, func, file)
3870 class DataHandler(TypeHandler):
3871 """Handler for glBufferData, glBufferSubData, glTexImage2D, glTexSubImage2D,
3872 glCompressedTexImage2D, glCompressedTexImageSub2D."""
3873 def __init__(self):
3874 TypeHandler.__init__(self)
3876 def InitFunction(self, func):
3877 """Overrriden from TypeHandler."""
3878 if func.name == 'CompressedTexSubImage2DBucket':
3879 func.cmd_args = func.cmd_args[:-1]
3880 func.AddCmdArg(Argument('bucket_id', 'GLuint'))
3882 def WriteGetDataSizeCode(self, func, file):
3883 """Overrriden from TypeHandler."""
3884 # TODO(gman): Move this data to _FUNCTION_INFO?
3885 name = func.name
3886 if name.endswith("Immediate"):
3887 name = name[0:-9]
3888 if name == 'BufferData' or name == 'BufferSubData':
3889 file.Write(" uint32_t data_size = size;\n")
3890 elif (name == 'CompressedTexImage2D' or
3891 name == 'CompressedTexSubImage2D'):
3892 file.Write(" uint32_t data_size = imageSize;\n")
3893 elif (name == 'CompressedTexSubImage2DBucket'):
3894 file.Write(" Bucket* bucket = GetBucket(c.bucket_id);\n")
3895 file.Write(" uint32_t data_size = bucket->size();\n")
3896 file.Write(" GLsizei imageSize = data_size;\n")
3897 elif name == 'TexImage2D' or name == 'TexSubImage2D':
3898 code = """ uint32_t data_size;
3899 if (!GLES2Util::ComputeImageDataSize(
3900 width, height, format, type, unpack_alignment_, &data_size)) {
3901 return error::kOutOfBounds;
3904 file.Write(code)
3905 else:
3906 file.Write(
3907 "// uint32_t data_size = 0; // TODO(gman): get correct size!\n")
3909 def WriteImmediateCmdGetTotalSize(self, func, file):
3910 """Overrriden from TypeHandler."""
3911 pass
3913 def WriteImmediateCmdSizeTest(self, func, file):
3914 """Overrriden from TypeHandler."""
3915 file.Write(" EXPECT_EQ(sizeof(cmd), total_size);\n")
3917 def WriteImmediateCmdInit(self, func, file):
3918 """Overrriden from TypeHandler."""
3919 file.Write(" void Init(%s) {\n" % func.MakeTypedCmdArgString("_"))
3920 self.WriteImmediateCmdGetTotalSize(func, file)
3921 file.Write(" SetHeader(total_size);\n")
3922 args = func.GetCmdArgs()
3923 for arg in args:
3924 file.Write(" %s = _%s;\n" % (arg.name, arg.name))
3925 file.Write(" }\n")
3926 file.Write("\n")
3928 def WriteImmediateCmdSet(self, func, file):
3929 """Overrriden from TypeHandler."""
3930 copy_args = func.MakeCmdArgString("_", False)
3931 file.Write(" void* Set(void* cmd%s) {\n" %
3932 func.MakeTypedCmdArgString("_", True))
3933 self.WriteImmediateCmdGetTotalSize(func, file)
3934 file.Write(" static_cast<ValueType*>(cmd)->Init(%s);\n" % copy_args)
3935 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
3936 "cmd, total_size);\n")
3937 file.Write(" }\n")
3938 file.Write("\n")
3940 def WriteImmediateFormatTest(self, func, file):
3941 """Overrriden from TypeHandler."""
3942 # TODO(gman): Remove this exception.
3943 file.Write("// TODO(gman): Implement test for %s\n" % func.name)
3944 return
3946 def WriteServiceUnitTest(self, func, file, *extras):
3947 """Overrriden from TypeHandler."""
3948 file.Write("// TODO(gman): %s\n\n" % func.name)
3950 def WriteImmediateServiceUnitTest(self, func, file, *extras):
3951 """Overrriden from TypeHandler."""
3952 file.Write("// TODO(gman): %s\n\n" % func.name)
3954 def WriteBucketServiceImplementation(self, func, file):
3955 """Overrriden from TypeHandler."""
3956 if not func.name == 'CompressedTexSubImage2DBucket':
3957 TypeHandler.WriteBucketServiceImplemenation(self, func, file)
3960 class BindHandler(TypeHandler):
3961 """Handler for glBind___ type functions."""
3963 def __init__(self):
3964 TypeHandler.__init__(self)
3966 def WriteServiceUnitTest(self, func, file, *extras):
3967 """Overrriden from TypeHandler."""
3969 if len(func.GetOriginalArgs()) == 1:
3970 valid_test = """
3971 TEST_P(%(test_name)s, %(name)sValidArgs) {
3972 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
3973 SpecializedSetup<cmds::%(name)s, 0>(true);
3974 cmds::%(name)s cmd;
3975 cmd.Init(%(args)s);
3976 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
3977 EXPECT_EQ(GL_NO_ERROR, GetGLError());
3980 if func.GetInfo("gen_func"):
3981 valid_test += """
3982 TEST_P(%(test_name)s, %(name)sValidArgsNewId) {
3983 EXPECT_CALL(*gl_, %(gl_func_name)s(kNewServiceId));
3984 EXPECT_CALL(*gl_, %(gl_gen_func_name)s(1, _))
3985 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
3986 SpecializedSetup<cmds::%(name)s, 0>(true);
3987 cmds::%(name)s cmd;
3988 cmd.Init(kNewClientId);
3989 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
3990 EXPECT_EQ(GL_NO_ERROR, GetGLError());
3991 EXPECT_TRUE(Get%(resource_type)s(kNewClientId) != NULL);
3994 self.WriteValidUnitTest(func, file, valid_test, {
3995 'resource_type': func.GetOriginalArgs()[0].resource_type,
3996 'gl_gen_func_name': func.GetInfo("gen_func"),
3997 }, *extras)
3998 else:
3999 valid_test = """
4000 TEST_P(%(test_name)s, %(name)sValidArgs) {
4001 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
4002 SpecializedSetup<cmds::%(name)s, 0>(true);
4003 cmds::%(name)s cmd;
4004 cmd.Init(%(args)s);
4005 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4006 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4009 if func.GetInfo("gen_func"):
4010 valid_test += """
4011 TEST_P(%(test_name)s, %(name)sValidArgsNewId) {
4012 EXPECT_CALL(*gl_, %(gl_func_name)s(%(first_gl_arg)s, kNewServiceId));
4013 EXPECT_CALL(*gl_, %(gl_gen_func_name)s(1, _))
4014 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
4015 SpecializedSetup<cmds::%(name)s, 0>(true);
4016 cmds::%(name)s cmd;
4017 cmd.Init(%(first_arg)s, kNewClientId);
4018 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4019 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4020 EXPECT_TRUE(Get%(resource_type)s(kNewClientId) != NULL);
4023 self.WriteValidUnitTest(func, file, valid_test, {
4024 'first_arg': func.GetOriginalArgs()[0].GetValidArg(func),
4025 'first_gl_arg': func.GetOriginalArgs()[0].GetValidGLArg(func),
4026 'resource_type': func.GetOriginalArgs()[1].resource_type,
4027 'gl_gen_func_name': func.GetInfo("gen_func"),
4028 }, *extras)
4030 invalid_test = """
4031 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
4032 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
4033 SpecializedSetup<cmds::%(name)s, 0>(false);
4034 cmds::%(name)s cmd;
4035 cmd.Init(%(args)s);
4036 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
4039 self.WriteInvalidUnitTest(func, file, invalid_test, *extras)
4041 def WriteGLES2Implementation(self, func, file):
4042 """Writes the GLES2 Implemention."""
4044 impl_func = func.GetInfo('impl_func')
4045 impl_decl = func.GetInfo('impl_decl')
4047 if (func.can_auto_generate and
4048 (impl_func == None or impl_func == True) and
4049 (impl_decl == None or impl_decl == True)):
4051 file.Write("%s GLES2Implementation::%s(%s) {\n" %
4052 (func.return_type, func.original_name,
4053 func.MakeTypedOriginalArgString("")))
4054 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
4055 func.WriteDestinationInitalizationValidation(file)
4056 self.WriteClientGLCallLog(func, file)
4057 for arg in func.GetOriginalArgs():
4058 arg.WriteClientSideValidationCode(file, func)
4060 code = """ if (Is%(type)sReservedId(%(id)s)) {
4061 SetGLError(GL_INVALID_OPERATION, "%(name)s\", \"%(id)s reserved id");
4062 return;
4064 if (%(name)sHelper(%(arg_string)s)) {
4065 helper_->%(name)s(%(arg_string)s);
4067 CheckGLError();
4071 name_arg = None
4072 if len(func.GetOriginalArgs()) == 1:
4073 # Bind functions that have no target (like BindVertexArrayOES)
4074 name_arg = func.GetOriginalArgs()[0]
4075 else:
4076 # Bind functions that have both a target and a name (like BindTexture)
4077 name_arg = func.GetOriginalArgs()[1]
4079 file.Write(code % {
4080 'name': func.name,
4081 'arg_string': func.MakeOriginalArgString(""),
4082 'id': name_arg.name,
4083 'type': name_arg.resource_type,
4084 'lc_type': name_arg.resource_type.lower(),
4087 def WriteGLES2ImplementationUnitTest(self, func, file):
4088 """Overrriden from TypeHandler."""
4089 client_test = func.GetInfo('client_test')
4090 if client_test == False:
4091 return
4092 code = """
4093 TEST_F(GLES2ImplementationTest, %(name)s) {
4094 struct Cmds {
4095 cmds::%(name)s cmd;
4097 Cmds expected;
4098 expected.cmd.Init(%(cmd_args)s);
4100 gl_->%(name)s(%(args)s);
4101 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
4102 ClearCommands();
4103 gl_->%(name)s(%(args)s);
4104 EXPECT_TRUE(NoCommandsWritten());
4107 cmd_arg_strings = [
4108 arg.GetValidClientSideCmdArg(func) for arg in func.GetCmdArgs()
4110 gl_arg_strings = [
4111 arg.GetValidClientSideArg(func) for arg in func.GetOriginalArgs()
4114 file.Write(code % {
4115 'name': func.name,
4116 'args': ", ".join(gl_arg_strings),
4117 'cmd_args': ", ".join(cmd_arg_strings),
4121 class GENnHandler(TypeHandler):
4122 """Handler for glGen___ type functions."""
4124 def __init__(self):
4125 TypeHandler.__init__(self)
4127 def InitFunction(self, func):
4128 """Overrriden from TypeHandler."""
4129 pass
4131 def WriteGetDataSizeCode(self, func, file):
4132 """Overrriden from TypeHandler."""
4133 code = """ uint32_t data_size;
4134 if (!SafeMultiplyUint32(n, sizeof(GLuint), &data_size)) {
4135 return error::kOutOfBounds;
4138 file.Write(code)
4140 def WriteHandlerImplementation (self, func, file):
4141 """Overrriden from TypeHandler."""
4142 file.Write(" if (!%sHelper(n, %s)) {\n"
4143 " return error::kInvalidArguments;\n"
4144 " }\n" %
4145 (func.name, func.GetLastOriginalArg().name))
4147 def WriteImmediateHandlerImplementation(self, func, file):
4148 """Overrriden from TypeHandler."""
4149 file.Write(" if (!%sHelper(n, %s)) {\n"
4150 " return error::kInvalidArguments;\n"
4151 " }\n" %
4152 (func.original_name, func.GetLastOriginalArg().name))
4154 def WriteGLES2Implementation(self, func, file):
4155 """Overrriden from TypeHandler."""
4156 log_code = (""" GPU_CLIENT_LOG_CODE_BLOCK({
4157 for (GLsizei i = 0; i < n; ++i) {
4158 GPU_CLIENT_LOG(" " << i << ": " << %s[i]);
4160 });""" % func.GetOriginalArgs()[1].name)
4161 args = {
4162 'log_code': log_code,
4163 'return_type': func.return_type,
4164 'name': func.original_name,
4165 'typed_args': func.MakeTypedOriginalArgString(""),
4166 'args': func.MakeOriginalArgString(""),
4167 'resource_types': func.GetInfo('resource_types'),
4168 'count_name': func.GetOriginalArgs()[0].name,
4170 file.Write(
4171 "%(return_type)s GLES2Implementation::%(name)s(%(typed_args)s) {\n" %
4172 args)
4173 func.WriteDestinationInitalizationValidation(file)
4174 self.WriteClientGLCallLog(func, file)
4175 for arg in func.GetOriginalArgs():
4176 arg.WriteClientSideValidationCode(file, func)
4177 not_shared = func.GetInfo('not_shared')
4178 if not_shared:
4179 alloc_code = (
4180 """ IdAllocatorInterface* id_allocator = GetIdAllocator(id_namespaces::k%s);
4181 for (GLsizei ii = 0; ii < n; ++ii)
4182 %s[ii] = id_allocator->AllocateID();""" %
4183 (func.GetInfo('resource_types'), func.GetOriginalArgs()[1].name))
4184 else:
4185 alloc_code = (""" GetIdHandler(id_namespaces::k%(resource_types)s)->
4186 MakeIds(this, 0, %(args)s);""" % args)
4187 args['alloc_code'] = alloc_code
4189 code = """ GPU_CLIENT_SINGLE_THREAD_CHECK();
4190 %(alloc_code)s
4191 %(name)sHelper(%(args)s);
4192 helper_->%(name)sImmediate(%(args)s);
4193 if (share_group_->bind_generates_resource())
4194 helper_->CommandBufferHelper::Flush();
4195 %(log_code)s
4196 CheckGLError();
4200 file.Write(code % args)
4202 def WriteGLES2ImplementationUnitTest(self, func, file):
4203 """Overrriden from TypeHandler."""
4204 code = """
4205 TEST_F(GLES2ImplementationTest, %(name)s) {
4206 GLuint ids[2] = { 0, };
4207 struct Cmds {
4208 cmds::%(name)sImmediate gen;
4209 GLuint data[2];
4211 Cmds expected;
4212 expected.gen.Init(arraysize(ids), &ids[0]);
4213 expected.data[0] = k%(types)sStartId;
4214 expected.data[1] = k%(types)sStartId + 1;
4215 gl_->%(name)s(arraysize(ids), &ids[0]);
4216 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
4217 EXPECT_EQ(k%(types)sStartId, ids[0]);
4218 EXPECT_EQ(k%(types)sStartId + 1, ids[1]);
4221 file.Write(code % {
4222 'name': func.name,
4223 'types': func.GetInfo('resource_types'),
4226 def WriteServiceUnitTest(self, func, file, *extras):
4227 """Overrriden from TypeHandler."""
4228 valid_test = """
4229 TEST_P(%(test_name)s, %(name)sValidArgs) {
4230 EXPECT_CALL(*gl_, %(gl_func_name)s(1, _))
4231 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
4232 GetSharedMemoryAs<GLuint*>()[0] = kNewClientId;
4233 SpecializedSetup<cmds::%(name)s, 0>(true);
4234 cmds::%(name)s cmd;
4235 cmd.Init(%(args)s);
4236 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4237 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4238 EXPECT_TRUE(Get%(resource_name)s(kNewClientId) != NULL);
4241 self.WriteValidUnitTest(func, file, valid_test, {
4242 'resource_name': func.GetInfo('resource_type'),
4243 }, *extras)
4244 invalid_test = """
4245 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
4246 EXPECT_CALL(*gl_, %(gl_func_name)s(_, _)).Times(0);
4247 GetSharedMemoryAs<GLuint*>()[0] = client_%(resource_name)s_id_;
4248 SpecializedSetup<cmds::%(name)s, 0>(false);
4249 cmds::%(name)s cmd;
4250 cmd.Init(%(args)s);
4251 EXPECT_EQ(error::kInvalidArguments, ExecuteCmd(cmd));
4254 self.WriteValidUnitTest(func, file, invalid_test, {
4255 'resource_name': func.GetInfo('resource_type').lower(),
4256 }, *extras)
4258 def WriteImmediateServiceUnitTest(self, func, file, *extras):
4259 """Overrriden from TypeHandler."""
4260 valid_test = """
4261 TEST_P(%(test_name)s, %(name)sValidArgs) {
4262 EXPECT_CALL(*gl_, %(gl_func_name)s(1, _))
4263 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
4264 cmds::%(name)s* cmd = GetImmediateAs<cmds::%(name)s>();
4265 GLuint temp = kNewClientId;
4266 SpecializedSetup<cmds::%(name)s, 0>(true);
4267 cmd->Init(1, &temp);
4268 EXPECT_EQ(error::kNoError,
4269 ExecuteImmediateCmd(*cmd, sizeof(temp)));
4270 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4271 EXPECT_TRUE(Get%(resource_name)s(kNewClientId) != NULL);
4274 self.WriteValidUnitTest(func, file, valid_test, {
4275 'resource_name': func.GetInfo('resource_type'),
4276 }, *extras)
4277 invalid_test = """
4278 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
4279 EXPECT_CALL(*gl_, %(gl_func_name)s(_, _)).Times(0);
4280 cmds::%(name)s* cmd = GetImmediateAs<cmds::%(name)s>();
4281 SpecializedSetup<cmds::%(name)s, 0>(false);
4282 cmd->Init(1, &client_%(resource_name)s_id_);
4283 EXPECT_EQ(error::kInvalidArguments,
4284 ExecuteImmediateCmd(*cmd, sizeof(&client_%(resource_name)s_id_)));
4287 self.WriteValidUnitTest(func, file, invalid_test, {
4288 'resource_name': func.GetInfo('resource_type').lower(),
4289 }, *extras)
4291 def WriteImmediateCmdComputeSize(self, func, file):
4292 """Overrriden from TypeHandler."""
4293 file.Write(" static uint32_t ComputeDataSize(GLsizei n) {\n")
4294 file.Write(
4295 " return static_cast<uint32_t>(sizeof(GLuint) * n); // NOLINT\n")
4296 file.Write(" }\n")
4297 file.Write("\n")
4298 file.Write(" static uint32_t ComputeSize(GLsizei n) {\n")
4299 file.Write(" return static_cast<uint32_t>(\n")
4300 file.Write(" sizeof(ValueType) + ComputeDataSize(n)); // NOLINT\n")
4301 file.Write(" }\n")
4302 file.Write("\n")
4304 def WriteImmediateCmdSetHeader(self, func, file):
4305 """Overrriden from TypeHandler."""
4306 file.Write(" void SetHeader(GLsizei n) {\n")
4307 file.Write(" header.SetCmdByTotalSize<ValueType>(ComputeSize(n));\n")
4308 file.Write(" }\n")
4309 file.Write("\n")
4311 def WriteImmediateCmdInit(self, func, file):
4312 """Overrriden from TypeHandler."""
4313 last_arg = func.GetLastOriginalArg()
4314 file.Write(" void Init(%s, %s _%s) {\n" %
4315 (func.MakeTypedCmdArgString("_"),
4316 last_arg.type, last_arg.name))
4317 file.Write(" SetHeader(_n);\n")
4318 args = func.GetCmdArgs()
4319 for arg in args:
4320 file.Write(" %s = _%s;\n" % (arg.name, arg.name))
4321 file.Write(" memcpy(ImmediateDataAddress(this),\n")
4322 file.Write(" _%s, ComputeDataSize(_n));\n" % last_arg.name)
4323 file.Write(" }\n")
4324 file.Write("\n")
4326 def WriteImmediateCmdSet(self, func, file):
4327 """Overrriden from TypeHandler."""
4328 last_arg = func.GetLastOriginalArg()
4329 copy_args = func.MakeCmdArgString("_", False)
4330 file.Write(" void* Set(void* cmd%s, %s _%s) {\n" %
4331 (func.MakeTypedCmdArgString("_", True),
4332 last_arg.type, last_arg.name))
4333 file.Write(" static_cast<ValueType*>(cmd)->Init(%s, _%s);\n" %
4334 (copy_args, last_arg.name))
4335 file.Write(" const uint32_t size = ComputeSize(_n);\n")
4336 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
4337 "cmd, size);\n")
4338 file.Write(" }\n")
4339 file.Write("\n")
4341 def WriteImmediateCmdHelper(self, func, file):
4342 """Overrriden from TypeHandler."""
4343 code = """ void %(name)s(%(typed_args)s) {
4344 const uint32_t size = gles2::cmds::%(name)s::ComputeSize(n);
4345 gles2::cmds::%(name)s* c =
4346 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
4347 if (c) {
4348 c->Init(%(args)s);
4353 file.Write(code % {
4354 "name": func.name,
4355 "typed_args": func.MakeTypedOriginalArgString(""),
4356 "args": func.MakeOriginalArgString(""),
4359 def WriteImmediateFormatTest(self, func, file):
4360 """Overrriden from TypeHandler."""
4361 file.Write("TEST_F(GLES2FormatTest, %s) {\n" % func.name)
4362 file.Write(" static GLuint ids[] = { 12, 23, 34, };\n")
4363 file.Write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
4364 (func.name, func.name))
4365 file.Write(" void* next_cmd = cmd.Set(\n")
4366 file.Write(" &cmd, static_cast<GLsizei>(arraysize(ids)), ids);\n")
4367 file.Write(" EXPECT_EQ(static_cast<uint32_t>(cmds::%s::kCmdId),\n" %
4368 func.name)
4369 file.Write(" cmd.header.command);\n")
4370 file.Write(" EXPECT_EQ(sizeof(cmd) +\n")
4371 file.Write(" RoundSizeToMultipleOfEntries(cmd.n * 4u),\n")
4372 file.Write(" cmd.header.size * 4u);\n")
4373 file.Write(" EXPECT_EQ(static_cast<GLsizei>(arraysize(ids)), cmd.n);\n");
4374 file.Write(" CheckBytesWrittenMatchesExpectedSize(\n")
4375 file.Write(" next_cmd, sizeof(cmd) +\n")
4376 file.Write(" RoundSizeToMultipleOfEntries(arraysize(ids) * 4u));\n")
4377 file.Write(" // TODO(gman): Check that ids were inserted;\n")
4378 file.Write("}\n")
4379 file.Write("\n")
4382 class CreateHandler(TypeHandler):
4383 """Handler for glCreate___ type functions."""
4385 def __init__(self):
4386 TypeHandler.__init__(self)
4388 def InitFunction(self, func):
4389 """Overrriden from TypeHandler."""
4390 func.AddCmdArg(Argument("client_id", 'uint32_t'))
4392 def WriteServiceUnitTest(self, func, file, *extras):
4393 """Overrriden from TypeHandler."""
4394 valid_test = """
4395 TEST_P(%(test_name)s, %(name)sValidArgs) {
4396 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s))
4397 .WillOnce(Return(kNewServiceId));
4398 SpecializedSetup<cmds::%(name)s, 0>(true);
4399 cmds::%(name)s cmd;
4400 cmd.Init(%(args)s%(comma)skNewClientId);
4401 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4402 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4403 EXPECT_TRUE(Get%(resource_type)s(kNewClientId) != NULL);
4406 comma = ""
4407 if len(func.GetOriginalArgs()):
4408 comma =", "
4409 self.WriteValidUnitTest(func, file, valid_test, {
4410 'comma': comma,
4411 'resource_type': func.name[6:],
4412 }, *extras)
4413 invalid_test = """
4414 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
4415 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
4416 SpecializedSetup<cmds::%(name)s, 0>(false);
4417 cmds::%(name)s cmd;
4418 cmd.Init(%(args)s%(comma)skNewClientId);
4419 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));%(gl_error_test)s
4422 self.WriteInvalidUnitTest(func, file, invalid_test, {
4423 'comma': comma,
4424 }, *extras)
4426 def WriteHandlerImplementation (self, func, file):
4427 """Overrriden from TypeHandler."""
4428 file.Write(" uint32_t client_id = c.client_id;\n")
4429 file.Write(" if (!%sHelper(%s)) {\n" %
4430 (func.name, func.MakeCmdArgString("")))
4431 file.Write(" return error::kInvalidArguments;\n")
4432 file.Write(" }\n")
4434 def WriteGLES2Implementation(self, func, file):
4435 """Overrriden from TypeHandler."""
4436 file.Write("%s GLES2Implementation::%s(%s) {\n" %
4437 (func.return_type, func.original_name,
4438 func.MakeTypedOriginalArgString("")))
4439 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
4440 func.WriteDestinationInitalizationValidation(file)
4441 self.WriteClientGLCallLog(func, file)
4442 for arg in func.GetOriginalArgs():
4443 arg.WriteClientSideValidationCode(file, func)
4444 file.Write(" GLuint client_id;\n")
4445 file.Write(
4446 " GetIdHandler(id_namespaces::kProgramsAndShaders)->\n")
4447 file.Write(" MakeIds(this, 0, 1, &client_id);\n")
4448 file.Write(" helper_->%s(%s);\n" %
4449 (func.name, func.MakeCmdArgString("")))
4450 file.Write(' GPU_CLIENT_LOG("returned " << client_id);\n')
4451 file.Write(" CheckGLError();\n")
4452 file.Write(" return client_id;\n")
4453 file.Write("}\n")
4454 file.Write("\n")
4457 class DeleteHandler(TypeHandler):
4458 """Handler for glDelete___ single resource type functions."""
4460 def __init__(self):
4461 TypeHandler.__init__(self)
4463 def WriteServiceImplementation(self, func, file):
4464 """Overrriden from TypeHandler."""
4465 pass
4467 def WriteGLES2Implementation(self, func, file):
4468 """Overrriden from TypeHandler."""
4469 file.Write("%s GLES2Implementation::%s(%s) {\n" %
4470 (func.return_type, func.original_name,
4471 func.MakeTypedOriginalArgString("")))
4472 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
4473 func.WriteDestinationInitalizationValidation(file)
4474 self.WriteClientGLCallLog(func, file)
4475 for arg in func.GetOriginalArgs():
4476 arg.WriteClientSideValidationCode(file, func)
4477 file.Write(
4478 " GPU_CLIENT_DCHECK(%s != 0);\n" % func.GetOriginalArgs()[-1].name)
4479 file.Write(" %sHelper(%s);\n" %
4480 (func.original_name, func.GetOriginalArgs()[-1].name))
4481 file.Write(" CheckGLError();\n")
4482 file.Write("}\n")
4483 file.Write("\n")
4486 class DELnHandler(TypeHandler):
4487 """Handler for glDelete___ type functions."""
4489 def __init__(self):
4490 TypeHandler.__init__(self)
4492 def WriteGetDataSizeCode(self, func, file):
4493 """Overrriden from TypeHandler."""
4494 code = """ uint32_t data_size;
4495 if (!SafeMultiplyUint32(n, sizeof(GLuint), &data_size)) {
4496 return error::kOutOfBounds;
4499 file.Write(code)
4501 def WriteGLES2ImplementationUnitTest(self, func, file):
4502 """Overrriden from TypeHandler."""
4503 code = """
4504 TEST_F(GLES2ImplementationTest, %(name)s) {
4505 GLuint ids[2] = { k%(types)sStartId, k%(types)sStartId + 1 };
4506 struct Cmds {
4507 cmds::%(name)sImmediate del;
4508 GLuint data[2];
4510 Cmds expected;
4511 expected.del.Init(arraysize(ids), &ids[0]);
4512 expected.data[0] = k%(types)sStartId;
4513 expected.data[1] = k%(types)sStartId + 1;
4514 gl_->%(name)s(arraysize(ids), &ids[0]);
4515 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
4518 file.Write(code % {
4519 'name': func.name,
4520 'types': func.GetInfo('resource_types'),
4523 def WriteServiceUnitTest(self, func, file, *extras):
4524 """Overrriden from TypeHandler."""
4525 valid_test = """
4526 TEST_P(%(test_name)s, %(name)sValidArgs) {
4527 EXPECT_CALL(
4528 *gl_,
4529 %(gl_func_name)s(1, Pointee(kService%(upper_resource_name)sId)))
4530 .Times(1);
4531 GetSharedMemoryAs<GLuint*>()[0] = client_%(resource_name)s_id_;
4532 SpecializedSetup<cmds::%(name)s, 0>(true);
4533 cmds::%(name)s cmd;
4534 cmd.Init(%(args)s);
4535 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4536 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4537 EXPECT_TRUE(
4538 Get%(upper_resource_name)s(client_%(resource_name)s_id_) == NULL);
4541 self.WriteValidUnitTest(func, file, valid_test, {
4542 'resource_name': func.GetInfo('resource_type').lower(),
4543 'upper_resource_name': func.GetInfo('resource_type'),
4544 }, *extras)
4545 invalid_test = """
4546 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
4547 GetSharedMemoryAs<GLuint*>()[0] = kInvalidClientId;
4548 SpecializedSetup<cmds::%(name)s, 0>(false);
4549 cmds::%(name)s cmd;
4550 cmd.Init(%(args)s);
4551 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4554 self.WriteValidUnitTest(func, file, invalid_test, *extras)
4556 def WriteImmediateServiceUnitTest(self, func, file, *extras):
4557 """Overrriden from TypeHandler."""
4558 valid_test = """
4559 TEST_P(%(test_name)s, %(name)sValidArgs) {
4560 EXPECT_CALL(
4561 *gl_,
4562 %(gl_func_name)s(1, Pointee(kService%(upper_resource_name)sId)))
4563 .Times(1);
4564 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
4565 SpecializedSetup<cmds::%(name)s, 0>(true);
4566 cmd.Init(1, &client_%(resource_name)s_id_);
4567 EXPECT_EQ(error::kNoError,
4568 ExecuteImmediateCmd(cmd, sizeof(client_%(resource_name)s_id_)));
4569 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4570 EXPECT_TRUE(
4571 Get%(upper_resource_name)s(client_%(resource_name)s_id_) == NULL);
4574 self.WriteValidUnitTest(func, file, valid_test, {
4575 'resource_name': func.GetInfo('resource_type').lower(),
4576 'upper_resource_name': func.GetInfo('resource_type'),
4577 }, *extras)
4578 invalid_test = """
4579 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
4580 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
4581 SpecializedSetup<cmds::%(name)s, 0>(false);
4582 GLuint temp = kInvalidClientId;
4583 cmd.Init(1, &temp);
4584 EXPECT_EQ(error::kNoError,
4585 ExecuteImmediateCmd(cmd, sizeof(temp)));
4588 self.WriteValidUnitTest(func, file, invalid_test, *extras)
4590 def WriteHandlerImplementation (self, func, file):
4591 """Overrriden from TypeHandler."""
4592 file.Write(" %sHelper(n, %s);\n" %
4593 (func.name, func.GetLastOriginalArg().name))
4595 def WriteImmediateHandlerImplementation (self, func, file):
4596 """Overrriden from TypeHandler."""
4597 file.Write(" %sHelper(n, %s);\n" %
4598 (func.original_name, func.GetLastOriginalArg().name))
4600 def WriteGLES2Implementation(self, func, file):
4601 """Overrriden from TypeHandler."""
4602 impl_decl = func.GetInfo('impl_decl')
4603 if impl_decl == None or impl_decl == True:
4604 args = {
4605 'return_type': func.return_type,
4606 'name': func.original_name,
4607 'typed_args': func.MakeTypedOriginalArgString(""),
4608 'args': func.MakeOriginalArgString(""),
4609 'resource_type': func.GetInfo('resource_type').lower(),
4610 'count_name': func.GetOriginalArgs()[0].name,
4612 file.Write(
4613 "%(return_type)s GLES2Implementation::%(name)s(%(typed_args)s) {\n" %
4614 args)
4615 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
4616 func.WriteDestinationInitalizationValidation(file)
4617 self.WriteClientGLCallLog(func, file)
4618 file.Write(""" GPU_CLIENT_LOG_CODE_BLOCK({
4619 for (GLsizei i = 0; i < n; ++i) {
4620 GPU_CLIENT_LOG(" " << i << ": " << %s[i]);
4623 """ % func.GetOriginalArgs()[1].name)
4624 file.Write(""" GPU_CLIENT_DCHECK_CODE_BLOCK({
4625 for (GLsizei i = 0; i < n; ++i) {
4626 DCHECK(%s[i] != 0);
4629 """ % func.GetOriginalArgs()[1].name)
4630 for arg in func.GetOriginalArgs():
4631 arg.WriteClientSideValidationCode(file, func)
4632 code = """ %(name)sHelper(%(args)s);
4633 CheckGLError();
4637 file.Write(code % args)
4639 def WriteImmediateCmdComputeSize(self, func, file):
4640 """Overrriden from TypeHandler."""
4641 file.Write(" static uint32_t ComputeDataSize(GLsizei n) {\n")
4642 file.Write(
4643 " return static_cast<uint32_t>(sizeof(GLuint) * n); // NOLINT\n")
4644 file.Write(" }\n")
4645 file.Write("\n")
4646 file.Write(" static uint32_t ComputeSize(GLsizei n) {\n")
4647 file.Write(" return static_cast<uint32_t>(\n")
4648 file.Write(" sizeof(ValueType) + ComputeDataSize(n)); // NOLINT\n")
4649 file.Write(" }\n")
4650 file.Write("\n")
4652 def WriteImmediateCmdSetHeader(self, func, file):
4653 """Overrriden from TypeHandler."""
4654 file.Write(" void SetHeader(GLsizei n) {\n")
4655 file.Write(" header.SetCmdByTotalSize<ValueType>(ComputeSize(n));\n")
4656 file.Write(" }\n")
4657 file.Write("\n")
4659 def WriteImmediateCmdInit(self, func, file):
4660 """Overrriden from TypeHandler."""
4661 last_arg = func.GetLastOriginalArg()
4662 file.Write(" void Init(%s, %s _%s) {\n" %
4663 (func.MakeTypedCmdArgString("_"),
4664 last_arg.type, last_arg.name))
4665 file.Write(" SetHeader(_n);\n")
4666 args = func.GetCmdArgs()
4667 for arg in args:
4668 file.Write(" %s = _%s;\n" % (arg.name, arg.name))
4669 file.Write(" memcpy(ImmediateDataAddress(this),\n")
4670 file.Write(" _%s, ComputeDataSize(_n));\n" % last_arg.name)
4671 file.Write(" }\n")
4672 file.Write("\n")
4674 def WriteImmediateCmdSet(self, func, file):
4675 """Overrriden from TypeHandler."""
4676 last_arg = func.GetLastOriginalArg()
4677 copy_args = func.MakeCmdArgString("_", False)
4678 file.Write(" void* Set(void* cmd%s, %s _%s) {\n" %
4679 (func.MakeTypedCmdArgString("_", True),
4680 last_arg.type, last_arg.name))
4681 file.Write(" static_cast<ValueType*>(cmd)->Init(%s, _%s);\n" %
4682 (copy_args, last_arg.name))
4683 file.Write(" const uint32_t size = ComputeSize(_n);\n")
4684 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
4685 "cmd, size);\n")
4686 file.Write(" }\n")
4687 file.Write("\n")
4689 def WriteImmediateCmdHelper(self, func, file):
4690 """Overrriden from TypeHandler."""
4691 code = """ void %(name)s(%(typed_args)s) {
4692 const uint32_t size = gles2::cmds::%(name)s::ComputeSize(n);
4693 gles2::cmds::%(name)s* c =
4694 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
4695 if (c) {
4696 c->Init(%(args)s);
4701 file.Write(code % {
4702 "name": func.name,
4703 "typed_args": func.MakeTypedOriginalArgString(""),
4704 "args": func.MakeOriginalArgString(""),
4707 def WriteImmediateFormatTest(self, func, file):
4708 """Overrriden from TypeHandler."""
4709 file.Write("TEST_F(GLES2FormatTest, %s) {\n" % func.name)
4710 file.Write(" static GLuint ids[] = { 12, 23, 34, };\n")
4711 file.Write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
4712 (func.name, func.name))
4713 file.Write(" void* next_cmd = cmd.Set(\n")
4714 file.Write(" &cmd, static_cast<GLsizei>(arraysize(ids)), ids);\n")
4715 file.Write(" EXPECT_EQ(static_cast<uint32_t>(cmds::%s::kCmdId),\n" %
4716 func.name)
4717 file.Write(" cmd.header.command);\n")
4718 file.Write(" EXPECT_EQ(sizeof(cmd) +\n")
4719 file.Write(" RoundSizeToMultipleOfEntries(cmd.n * 4u),\n")
4720 file.Write(" cmd.header.size * 4u);\n")
4721 file.Write(" EXPECT_EQ(static_cast<GLsizei>(arraysize(ids)), cmd.n);\n");
4722 file.Write(" CheckBytesWrittenMatchesExpectedSize(\n")
4723 file.Write(" next_cmd, sizeof(cmd) +\n")
4724 file.Write(" RoundSizeToMultipleOfEntries(arraysize(ids) * 4u));\n")
4725 file.Write(" // TODO(gman): Check that ids were inserted;\n")
4726 file.Write("}\n")
4727 file.Write("\n")
4730 class GETnHandler(TypeHandler):
4731 """Handler for GETn for glGetBooleanv, glGetFloatv, ... type functions."""
4733 def __init__(self):
4734 TypeHandler.__init__(self)
4736 def NeedsDataTransferFunction(self, func):
4737 """Overriden from TypeHandler."""
4738 return False
4740 def WriteServiceImplementation(self, func, file):
4741 """Overrriden from TypeHandler."""
4742 file.Write(
4743 "error::Error GLES2DecoderImpl::Handle%s(\n" % func.name)
4744 file.Write(
4745 " uint32_t immediate_data_size, const gles2::cmds::%s& c) {\n" %
4746 func.name)
4747 last_arg = func.GetLastOriginalArg()
4749 all_but_last_args = func.GetOriginalArgs()[:-1]
4750 for arg in all_but_last_args:
4751 arg.WriteGetCode(file)
4753 code = """ typedef cmds::%(func_name)s::Result Result;
4754 GLsizei num_values = 0;
4755 GetNumValuesReturnedForGLGet(pname, &num_values);
4756 Result* result = GetSharedMemoryAs<Result*>(
4757 c.params_shm_id, c.params_shm_offset, Result::ComputeSize(num_values));
4758 %(last_arg_type)s params = result ? result->GetData() : NULL;
4760 file.Write(code % {
4761 'last_arg_type': last_arg.type,
4762 'func_name': func.name,
4764 func.WriteHandlerValidation(file)
4765 code = """ // Check that the client initialized the result.
4766 if (result->size != 0) {
4767 return error::kInvalidArguments;
4770 shadowed = func.GetInfo('shadowed')
4771 if not shadowed:
4772 file.Write(' LOCAL_COPY_REAL_GL_ERRORS_TO_WRAPPER("%s");\n' % func.name)
4773 file.Write(code)
4774 func.WriteHandlerImplementation(file)
4775 if shadowed:
4776 code = """ result->SetNumResults(num_values);
4777 return error::kNoError;
4780 else:
4781 code = """ GLenum error = glGetError();
4782 if (error == GL_NO_ERROR) {
4783 result->SetNumResults(num_values);
4784 } else {
4785 LOCAL_SET_GL_ERROR(error, "%(func_name)s", "");
4787 return error::kNoError;
4791 file.Write(code % {'func_name': func.name})
4793 def WriteGLES2Implementation(self, func, file):
4794 """Overrriden from TypeHandler."""
4795 impl_decl = func.GetInfo('impl_decl')
4796 if impl_decl == None or impl_decl == True:
4797 file.Write("%s GLES2Implementation::%s(%s) {\n" %
4798 (func.return_type, func.original_name,
4799 func.MakeTypedOriginalArgString("")))
4800 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
4801 func.WriteDestinationInitalizationValidation(file)
4802 self.WriteClientGLCallLog(func, file)
4803 for arg in func.GetOriginalArgs():
4804 arg.WriteClientSideValidationCode(file, func)
4805 all_but_last_args = func.GetOriginalArgs()[:-1]
4806 arg_string = (
4807 ", ".join(["%s" % arg.name for arg in all_but_last_args]))
4808 all_arg_string = (
4809 ", ".join([
4810 "%s" % arg.name
4811 for arg in func.GetOriginalArgs() if not arg.IsConstant()]))
4812 self.WriteTraceEvent(func, file)
4813 code = """ if (%(func_name)sHelper(%(all_arg_string)s)) {
4814 return;
4816 typedef cmds::%(func_name)s::Result Result;
4817 Result* result = GetResultAs<Result*>();
4818 if (!result) {
4819 return;
4821 result->SetNumResults(0);
4822 helper_->%(func_name)s(%(arg_string)s,
4823 GetResultShmId(), GetResultShmOffset());
4824 WaitForCmd();
4825 result->CopyResult(params);
4826 GPU_CLIENT_LOG_CODE_BLOCK({
4827 for (int32_t i = 0; i < result->GetNumResults(); ++i) {
4828 GPU_CLIENT_LOG(" " << i << ": " << result->GetData()[i]);
4831 CheckGLError();
4834 file.Write(code % {
4835 'func_name': func.name,
4836 'arg_string': arg_string,
4837 'all_arg_string': all_arg_string,
4840 def WriteGLES2ImplementationUnitTest(self, func, file):
4841 """Writes the GLES2 Implemention unit test."""
4842 code = """
4843 TEST_F(GLES2ImplementationTest, %(name)s) {
4844 struct Cmds {
4845 cmds::%(name)s cmd;
4847 typedef cmds::%(name)s::Result Result;
4848 Result::Type result = 0;
4849 Cmds expected;
4850 ExpectedMemoryInfo result1 = GetExpectedResultMemory(4);
4851 expected.cmd.Init(%(cmd_args)s, result1.id, result1.offset);
4852 EXPECT_CALL(*command_buffer(), OnFlush())
4853 .WillOnce(SetMemory(result1.ptr, SizedResultHelper<Result::Type>(1)))
4854 .RetiresOnSaturation();
4855 gl_->%(name)s(%(args)s, &result);
4856 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
4857 EXPECT_EQ(static_cast<Result::Type>(1), result);
4860 first_cmd_arg = func.GetCmdArgs()[0].GetValidNonCachedClientSideCmdArg(func)
4861 if not first_cmd_arg:
4862 return
4864 first_gl_arg = func.GetCmdArgs()[0].GetValidNonCachedClientSideArg(func)
4865 cmd_arg_strings = [first_cmd_arg]
4866 for arg in func.GetCmdArgs()[1:-2]:
4867 cmd_arg_strings.append(arg.GetValidClientSideCmdArg(func))
4868 gl_arg_strings = [first_gl_arg]
4869 for arg in func.GetOriginalArgs()[1:-1]:
4870 gl_arg_strings.append(arg.GetValidClientSideArg(func))
4872 file.Write(code % {
4873 'name': func.name,
4874 'args': ", ".join(gl_arg_strings),
4875 'cmd_args': ", ".join(cmd_arg_strings),
4878 def WriteServiceUnitTest(self, func, file, *extras):
4879 """Overrriden from TypeHandler."""
4880 valid_test = """
4881 TEST_P(%(test_name)s, %(name)sValidArgs) {
4882 EXPECT_CALL(*gl_, GetError())
4883 .WillOnce(Return(GL_NO_ERROR))
4884 .WillOnce(Return(GL_NO_ERROR))
4885 .RetiresOnSaturation();
4886 SpecializedSetup<cmds::%(name)s, 0>(true);
4887 typedef cmds::%(name)s::Result Result;
4888 Result* result = static_cast<Result*>(shared_memory_address_);
4889 EXPECT_CALL(*gl_, %(gl_func_name)s(%(local_gl_args)s));
4890 result->size = 0;
4891 cmds::%(name)s cmd;
4892 cmd.Init(%(args)s);
4893 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4894 EXPECT_EQ(decoder_->GetGLES2Util()->GLGetNumValuesReturned(
4895 %(valid_pname)s),
4896 result->GetNumResults());
4897 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4900 gl_arg_strings = []
4901 valid_pname = ''
4902 for arg in func.GetOriginalArgs()[:-1]:
4903 arg_value = arg.GetValidGLArg(func)
4904 gl_arg_strings.append(arg_value)
4905 if arg.name == 'pname':
4906 valid_pname = arg_value
4907 if func.GetInfo('gl_test_func') == 'glGetIntegerv':
4908 gl_arg_strings.append("_")
4909 else:
4910 gl_arg_strings.append("result->GetData()")
4912 self.WriteValidUnitTest(func, file, valid_test, {
4913 'local_gl_args': ", ".join(gl_arg_strings),
4914 'valid_pname': valid_pname,
4915 }, *extras)
4917 invalid_test = """
4918 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
4919 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
4920 SpecializedSetup<cmds::%(name)s, 0>(false);
4921 cmds::%(name)s::Result* result =
4922 static_cast<cmds::%(name)s::Result*>(shared_memory_address_);
4923 result->size = 0;
4924 cmds::%(name)s cmd;
4925 cmd.Init(%(args)s);
4926 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));
4927 EXPECT_EQ(0u, result->size);%(gl_error_test)s
4930 self.WriteInvalidUnitTest(func, file, invalid_test, *extras)
4932 class ArrayArgTypeHandler(TypeHandler):
4933 """Base class for type handlers that handle args that are arrays"""
4935 def __init__(self):
4936 TypeHandler.__init__(self)
4938 def GetArrayType(self, func):
4939 """Returns the type of the element in the element array being PUT to."""
4940 for arg in func.GetOriginalArgs():
4941 if arg.IsPointer():
4942 element_type = arg.GetPointedType()
4943 return element_type
4945 # Special case: array type handler is used for a function that is forwarded
4946 # to the actual array type implementation
4947 element_type = func.GetOriginalArgs()[-1].type
4948 assert all(arg.type == element_type \
4949 for arg in func.GetOriginalArgs()[-self.GetArrayCount(func):])
4950 return element_type
4952 def GetArrayCount(self, func):
4953 """Returns the count of the elements in the array being PUT to."""
4954 return func.GetInfo('count')
4956 class PUTHandler(ArrayArgTypeHandler):
4957 """Handler for glTexParameter_v, glVertexAttrib_v functions."""
4959 def __init__(self):
4960 ArrayArgTypeHandler.__init__(self)
4962 def WriteServiceUnitTest(self, func, file, *extras):
4963 """Writes the service unit test for a command."""
4964 expected_call = "EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));"
4965 if func.GetInfo("first_element_only"):
4966 gl_arg_strings = [
4967 arg.GetValidGLArg(func) for arg in func.GetOriginalArgs()
4969 gl_arg_strings[-1] = "*" + gl_arg_strings[-1]
4970 expected_call = ("EXPECT_CALL(*gl_, %%(gl_func_name)s(%s));" %
4971 ", ".join(gl_arg_strings))
4972 valid_test = """
4973 TEST_P(%(test_name)s, %(name)sValidArgs) {
4974 SpecializedSetup<cmds::%(name)s, 0>(true);
4975 cmds::%(name)s cmd;
4976 cmd.Init(%(args)s);
4977 GetSharedMemoryAs<%(data_type)s*>()[0] = %(data_value)s;
4978 %(expected_call)s
4979 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4980 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4983 extra = {
4984 'data_type': self.GetArrayType(func),
4985 'data_value': func.GetInfo('data_value') or '0',
4986 'expected_call': expected_call,
4988 self.WriteValidUnitTest(func, file, valid_test, extra, *extras)
4990 invalid_test = """
4991 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
4992 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
4993 SpecializedSetup<cmds::%(name)s, 0>(false);
4994 cmds::%(name)s cmd;
4995 cmd.Init(%(args)s);
4996 GetSharedMemoryAs<%(data_type)s*>()[0] = %(data_value)s;
4997 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
5000 self.WriteInvalidUnitTest(func, file, invalid_test, extra, *extras)
5002 def WriteImmediateServiceUnitTest(self, func, file, *extras):
5003 """Writes the service unit test for a command."""
5004 valid_test = """
5005 TEST_P(%(test_name)s, %(name)sValidArgs) {
5006 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
5007 SpecializedSetup<cmds::%(name)s, 0>(true);
5008 %(data_type)s temp[%(data_count)s] = { %(data_value)s, };
5009 cmd.Init(%(gl_args)s, &temp[0]);
5010 EXPECT_CALL(
5011 *gl_,
5012 %(gl_func_name)s(%(gl_args)s, %(data_ref)sreinterpret_cast<
5013 %(data_type)s*>(ImmediateDataAddress(&cmd))));
5014 EXPECT_EQ(error::kNoError,
5015 ExecuteImmediateCmd(cmd, sizeof(temp)));
5016 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5019 gl_arg_strings = [
5020 arg.GetValidGLArg(func) for arg in func.GetOriginalArgs()[0:-1]
5022 gl_any_strings = ["_"] * len(gl_arg_strings)
5024 extra = {
5025 'data_ref': ("*" if func.GetInfo('first_element_only') else ""),
5026 'data_type': self.GetArrayType(func),
5027 'data_count': self.GetArrayCount(func),
5028 'data_value': func.GetInfo('data_value') or '0',
5029 'gl_args': ", ".join(gl_arg_strings),
5030 'gl_any_args': ", ".join(gl_any_strings),
5032 self.WriteValidUnitTest(func, file, valid_test, extra, *extras)
5034 invalid_test = """
5035 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
5036 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
5037 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_any_args)s, _)).Times(0);
5038 SpecializedSetup<cmds::%(name)s, 0>(false);
5039 %(data_type)s temp[%(data_count)s] = { %(data_value)s, };
5040 cmd.Init(%(all_but_last_args)s, &temp[0]);
5041 EXPECT_EQ(error::%(parse_result)s,
5042 ExecuteImmediateCmd(cmd, sizeof(temp)));%(gl_error_test)s
5045 self.WriteInvalidUnitTest(func, file, invalid_test, extra, *extras)
5047 def WriteGetDataSizeCode(self, func, file):
5048 """Overrriden from TypeHandler."""
5049 code = """ uint32_t data_size;
5050 if (!ComputeDataSize(1, sizeof(%s), %d, &data_size)) {
5051 return error::kOutOfBounds;
5054 file.Write(code % (self.GetArrayType(func), self.GetArrayCount(func)))
5055 if func.IsImmediate():
5056 file.Write(" if (data_size > immediate_data_size) {\n")
5057 file.Write(" return error::kOutOfBounds;\n")
5058 file.Write(" }\n")
5060 def WriteGLES2Implementation(self, func, file):
5061 """Overrriden from TypeHandler."""
5062 impl_func = func.GetInfo('impl_func')
5063 if (impl_func != None and impl_func != True):
5064 return;
5065 file.Write("%s GLES2Implementation::%s(%s) {\n" %
5066 (func.return_type, func.original_name,
5067 func.MakeTypedOriginalArgString("")))
5068 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
5069 func.WriteDestinationInitalizationValidation(file)
5070 self.WriteClientGLCallLog(func, file)
5071 last_arg_name = func.GetLastOriginalArg().name
5072 values_str = ' << ", " << '.join(
5073 ["%s[%d]" % (last_arg_name, ndx) \
5074 for ndx in range(0, self.GetArrayCount(func))])
5075 file.Write(' GPU_CLIENT_LOG("values: " << %s);\n' % values_str)
5076 for arg in func.GetOriginalArgs():
5077 arg.WriteClientSideValidationCode(file, func)
5078 file.Write(" helper_->%sImmediate(%s);\n" %
5079 (func.name, func.MakeOriginalArgString("")))
5080 file.Write(" CheckGLError();\n")
5081 file.Write("}\n")
5082 file.Write("\n")
5084 def WriteGLES2ImplementationUnitTest(self, func, file):
5085 """Writes the GLES2 Implemention unit test."""
5086 client_test = func.GetInfo('client_test')
5087 if (client_test != None and client_test != True):
5088 return;
5089 code = """
5090 TEST_F(GLES2ImplementationTest, %(name)s) {
5091 %(type)s data[%(count)d] = {0};
5092 struct Cmds {
5093 cmds::%(name)sImmediate cmd;
5094 %(type)s data[%(count)d];
5097 for (int jj = 0; jj < %(count)d; ++jj) {
5098 data[jj] = static_cast<%(type)s>(jj);
5100 Cmds expected;
5101 expected.cmd.Init(%(cmd_args)s, &data[0]);
5102 gl_->%(name)s(%(args)s, &data[0]);
5103 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
5106 cmd_arg_strings = [
5107 arg.GetValidClientSideCmdArg(func) for arg in func.GetCmdArgs()[0:-2]
5109 gl_arg_strings = [
5110 arg.GetValidClientSideArg(func) for arg in func.GetOriginalArgs()[0:-1]
5113 file.Write(code % {
5114 'name': func.name,
5115 'type': self.GetArrayType(func),
5116 'count': self.GetArrayCount(func),
5117 'args': ", ".join(gl_arg_strings),
5118 'cmd_args': ", ".join(cmd_arg_strings),
5121 def WriteImmediateCmdComputeSize(self, func, file):
5122 """Overrriden from TypeHandler."""
5123 file.Write(" static uint32_t ComputeDataSize() {\n")
5124 file.Write(" return static_cast<uint32_t>(\n")
5125 file.Write(" sizeof(%s) * %d); // NOLINT\n" %
5126 (self.GetArrayType(func), self.GetArrayCount(func)))
5127 file.Write(" }\n")
5128 file.Write("\n")
5129 file.Write(" static uint32_t ComputeSize() {\n")
5130 file.Write(" return static_cast<uint32_t>(\n")
5131 file.Write(
5132 " sizeof(ValueType) + ComputeDataSize()); // NOLINT\n")
5133 file.Write(" }\n")
5134 file.Write("\n")
5136 def WriteImmediateCmdSetHeader(self, func, file):
5137 """Overrriden from TypeHandler."""
5138 file.Write(" void SetHeader() {\n")
5139 file.Write(
5140 " header.SetCmdByTotalSize<ValueType>(ComputeSize());\n")
5141 file.Write(" }\n")
5142 file.Write("\n")
5144 def WriteImmediateCmdInit(self, func, file):
5145 """Overrriden from TypeHandler."""
5146 last_arg = func.GetLastOriginalArg()
5147 file.Write(" void Init(%s, %s _%s) {\n" %
5148 (func.MakeTypedCmdArgString("_"),
5149 last_arg.type, last_arg.name))
5150 file.Write(" SetHeader();\n")
5151 args = func.GetCmdArgs()
5152 for arg in args:
5153 file.Write(" %s = _%s;\n" % (arg.name, arg.name))
5154 file.Write(" memcpy(ImmediateDataAddress(this),\n")
5155 file.Write(" _%s, ComputeDataSize());\n" % last_arg.name)
5156 file.Write(" }\n")
5157 file.Write("\n")
5159 def WriteImmediateCmdSet(self, func, file):
5160 """Overrriden from TypeHandler."""
5161 last_arg = func.GetLastOriginalArg()
5162 copy_args = func.MakeCmdArgString("_", False)
5163 file.Write(" void* Set(void* cmd%s, %s _%s) {\n" %
5164 (func.MakeTypedCmdArgString("_", True),
5165 last_arg.type, last_arg.name))
5166 file.Write(" static_cast<ValueType*>(cmd)->Init(%s, _%s);\n" %
5167 (copy_args, last_arg.name))
5168 file.Write(" const uint32_t size = ComputeSize();\n")
5169 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
5170 "cmd, size);\n")
5171 file.Write(" }\n")
5172 file.Write("\n")
5174 def WriteImmediateCmdHelper(self, func, file):
5175 """Overrriden from TypeHandler."""
5176 code = """ void %(name)s(%(typed_args)s) {
5177 const uint32_t size = gles2::cmds::%(name)s::ComputeSize();
5178 gles2::cmds::%(name)s* c =
5179 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
5180 if (c) {
5181 c->Init(%(args)s);
5186 file.Write(code % {
5187 "name": func.name,
5188 "typed_args": func.MakeTypedOriginalArgString(""),
5189 "args": func.MakeOriginalArgString(""),
5192 def WriteImmediateFormatTest(self, func, file):
5193 """Overrriden from TypeHandler."""
5194 file.Write("TEST_F(GLES2FormatTest, %s) {\n" % func.name)
5195 file.Write(" const int kSomeBaseValueToTestWith = 51;\n")
5196 file.Write(" static %s data[] = {\n" % self.GetArrayType(func))
5197 for v in range(0, self.GetArrayCount(func)):
5198 file.Write(" static_cast<%s>(kSomeBaseValueToTestWith + %d),\n" %
5199 (self.GetArrayType(func), v))
5200 file.Write(" };\n")
5201 file.Write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
5202 (func.name, func.name))
5203 file.Write(" void* next_cmd = cmd.Set(\n")
5204 file.Write(" &cmd")
5205 args = func.GetCmdArgs()
5206 for value, arg in enumerate(args):
5207 file.Write(",\n static_cast<%s>(%d)" % (arg.type, value + 11))
5208 file.Write(",\n data);\n")
5209 args = func.GetCmdArgs()
5210 file.Write(" EXPECT_EQ(static_cast<uint32_t>(cmds::%s::kCmdId),\n"
5211 % func.name)
5212 file.Write(" cmd.header.command);\n")
5213 file.Write(" EXPECT_EQ(sizeof(cmd) +\n")
5214 file.Write(" RoundSizeToMultipleOfEntries(sizeof(data)),\n")
5215 file.Write(" cmd.header.size * 4u);\n")
5216 for value, arg in enumerate(args):
5217 file.Write(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);\n" %
5218 (arg.type, value + 11, arg.name))
5219 file.Write(" CheckBytesWrittenMatchesExpectedSize(\n")
5220 file.Write(" next_cmd, sizeof(cmd) +\n")
5221 file.Write(" RoundSizeToMultipleOfEntries(sizeof(data)));\n")
5222 file.Write(" // TODO(gman): Check that data was inserted;\n")
5223 file.Write("}\n")
5224 file.Write("\n")
5227 class PUTnHandler(ArrayArgTypeHandler):
5228 """Handler for PUTn 'glUniform__v' type functions."""
5230 def __init__(self):
5231 ArrayArgTypeHandler.__init__(self)
5233 def WriteServiceUnitTest(self, func, file, *extras):
5234 """Overridden from TypeHandler."""
5235 ArrayArgTypeHandler.WriteServiceUnitTest(self, func, file, *extras)
5237 valid_test = """
5238 TEST_P(%(test_name)s, %(name)sValidArgsCountTooLarge) {
5239 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
5240 SpecializedSetup<cmds::%(name)s, 0>(true);
5241 cmds::%(name)s cmd;
5242 cmd.Init(%(args)s);
5243 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5244 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5247 gl_arg_strings = []
5248 arg_strings = []
5249 for count, arg in enumerate(func.GetOriginalArgs()):
5250 # hardcoded to match unit tests.
5251 if count == 0:
5252 # the location of the second element of the 2nd uniform.
5253 # defined in GLES2DecoderBase::SetupShaderForUniform
5254 gl_arg_strings.append("3")
5255 arg_strings.append("ProgramManager::MakeFakeLocation(1, 1)")
5256 elif count == 1:
5257 # the number of elements that gl will be called with.
5258 gl_arg_strings.append("3")
5259 # the number of elements requested in the command.
5260 arg_strings.append("5")
5261 else:
5262 gl_arg_strings.append(arg.GetValidGLArg(func))
5263 if not arg.IsConstant():
5264 arg_strings.append(arg.GetValidArg(func))
5265 extra = {
5266 'gl_args': ", ".join(gl_arg_strings),
5267 'args': ", ".join(arg_strings),
5269 self.WriteValidUnitTest(func, file, valid_test, extra, *extras)
5271 def WriteImmediateServiceUnitTest(self, func, file, *extras):
5272 """Overridden from TypeHandler."""
5273 valid_test = """
5274 TEST_P(%(test_name)s, %(name)sValidArgs) {
5275 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
5276 EXPECT_CALL(
5277 *gl_,
5278 %(gl_func_name)s(%(gl_args)s,
5279 reinterpret_cast<%(data_type)s*>(ImmediateDataAddress(&cmd))));
5280 SpecializedSetup<cmds::%(name)s, 0>(true);
5281 %(data_type)s temp[%(data_count)s * 2] = { 0, };
5282 cmd.Init(%(args)s, &temp[0]);
5283 EXPECT_EQ(error::kNoError,
5284 ExecuteImmediateCmd(cmd, sizeof(temp)));
5285 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5288 gl_arg_strings = []
5289 gl_any_strings = []
5290 arg_strings = []
5291 for arg in func.GetOriginalArgs()[0:-1]:
5292 gl_arg_strings.append(arg.GetValidGLArg(func))
5293 gl_any_strings.append("_")
5294 if not arg.IsConstant():
5295 arg_strings.append(arg.GetValidArg(func))
5296 extra = {
5297 'data_type': self.GetArrayType(func),
5298 'data_count': self.GetArrayCount(func),
5299 'args': ", ".join(arg_strings),
5300 'gl_args': ", ".join(gl_arg_strings),
5301 'gl_any_args': ", ".join(gl_any_strings),
5303 self.WriteValidUnitTest(func, file, valid_test, extra, *extras)
5305 invalid_test = """
5306 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
5307 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
5308 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_any_args)s, _)).Times(0);
5309 SpecializedSetup<cmds::%(name)s, 0>(false);
5310 %(data_type)s temp[%(data_count)s * 2] = { 0, };
5311 cmd.Init(%(all_but_last_args)s, &temp[0]);
5312 EXPECT_EQ(error::%(parse_result)s,
5313 ExecuteImmediateCmd(cmd, sizeof(temp)));%(gl_error_test)s
5316 self.WriteInvalidUnitTest(func, file, invalid_test, extra, *extras)
5318 def WriteGetDataSizeCode(self, func, file):
5319 """Overrriden from TypeHandler."""
5320 code = """ uint32_t data_size;
5321 if (!ComputeDataSize(count, sizeof(%s), %d, &data_size)) {
5322 return error::kOutOfBounds;
5325 file.Write(code % (self.GetArrayType(func), self.GetArrayCount(func)))
5326 if func.IsImmediate():
5327 file.Write(" if (data_size > immediate_data_size) {\n")
5328 file.Write(" return error::kOutOfBounds;\n")
5329 file.Write(" }\n")
5331 def WriteGLES2Implementation(self, func, file):
5332 """Overrriden from TypeHandler."""
5333 file.Write("%s GLES2Implementation::%s(%s) {\n" %
5334 (func.return_type, func.original_name,
5335 func.MakeTypedOriginalArgString("")))
5336 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
5337 func.WriteDestinationInitalizationValidation(file)
5338 self.WriteClientGLCallLog(func, file)
5339 last_arg_name = func.GetLastOriginalArg().name
5340 file.Write(""" GPU_CLIENT_LOG_CODE_BLOCK({
5341 for (GLsizei i = 0; i < count; ++i) {
5342 """)
5343 values_str = ' << ", " << '.join(
5344 ["%s[%d + i * %d]" % (
5345 last_arg_name, ndx, self.GetArrayCount(func)) for ndx in range(
5346 0, self.GetArrayCount(func))])
5347 file.Write(' GPU_CLIENT_LOG(" " << i << ": " << %s);\n' % values_str)
5348 file.Write(" }\n });\n")
5349 for arg in func.GetOriginalArgs():
5350 arg.WriteClientSideValidationCode(file, func)
5351 file.Write(" helper_->%sImmediate(%s);\n" %
5352 (func.name, func.MakeInitString("")))
5353 file.Write(" CheckGLError();\n")
5354 file.Write("}\n")
5355 file.Write("\n")
5357 def WriteGLES2ImplementationUnitTest(self, func, file):
5358 """Writes the GLES2 Implemention unit test."""
5359 code = """
5360 TEST_F(GLES2ImplementationTest, %(name)s) {
5361 %(type)s data[%(count_param)d][%(count)d] = {{0}};
5362 struct Cmds {
5363 cmds::%(name)sImmediate cmd;
5364 %(type)s data[%(count_param)d][%(count)d];
5367 Cmds expected;
5368 for (int ii = 0; ii < %(count_param)d; ++ii) {
5369 for (int jj = 0; jj < %(count)d; ++jj) {
5370 data[ii][jj] = static_cast<%(type)s>(ii * %(count)d + jj);
5373 expected.cmd.Init(%(cmd_args)s, &data[0][0]);
5374 gl_->%(name)s(%(args)s, &data[0][0]);
5375 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
5378 cmd_arg_strings = [
5379 arg.GetValidClientSideCmdArg(func) for arg in func.GetCmdArgs()[0:-2]
5381 gl_arg_strings = []
5382 count_param = 0
5383 for arg in func.GetOriginalArgs()[0:-1]:
5384 valid_value = arg.GetValidClientSideArg(func)
5385 gl_arg_strings.append(valid_value)
5386 if arg.name == "count":
5387 count_param = int(valid_value)
5388 file.Write(code % {
5389 'name': func.name,
5390 'type': self.GetArrayType(func),
5391 'count': self.GetArrayCount(func),
5392 'args': ", ".join(gl_arg_strings),
5393 'cmd_args': ", ".join(cmd_arg_strings),
5394 'count_param': count_param,
5397 # Test constants for invalid values, as they are not tested by the
5398 # service.
5399 constants = [
5400 arg for arg in func.GetOriginalArgs()[0:-1] if arg.IsConstant()
5402 if not constants:
5403 return
5405 code = """
5406 TEST_F(GLES2ImplementationTest, %(name)sInvalidConstantArg%(invalid_index)d) {
5407 %(type)s data[%(count_param)d][%(count)d] = {{0}};
5408 for (int ii = 0; ii < %(count_param)d; ++ii) {
5409 for (int jj = 0; jj < %(count)d; ++jj) {
5410 data[ii][jj] = static_cast<%(type)s>(ii * %(count)d + jj);
5413 gl_->%(name)s(%(args)s, &data[0][0]);
5414 EXPECT_TRUE(NoCommandsWritten());
5415 EXPECT_EQ(%(gl_error)s, CheckError());
5418 for invalid_arg in constants:
5419 gl_arg_strings = []
5420 invalid = invalid_arg.GetInvalidArg(func)
5421 for arg in func.GetOriginalArgs()[0:-1]:
5422 if arg is invalid_arg:
5423 gl_arg_strings.append(invalid[0])
5424 else:
5425 valid_value = arg.GetValidClientSideArg(func)
5426 gl_arg_strings.append(valid_value)
5427 if arg.name == "count":
5428 count_param = int(valid_value)
5430 file.Write(code % {
5431 'name': func.name,
5432 'invalid_index': func.GetOriginalArgs().index(invalid_arg),
5433 'type': self.GetArrayType(func),
5434 'count': self.GetArrayCount(func),
5435 'args': ", ".join(gl_arg_strings),
5436 'gl_error': invalid[2],
5437 'count_param': count_param,
5441 def WriteImmediateCmdComputeSize(self, func, file):
5442 """Overrriden from TypeHandler."""
5443 file.Write(" static uint32_t ComputeDataSize(GLsizei count) {\n")
5444 file.Write(" return static_cast<uint32_t>(\n")
5445 file.Write(" sizeof(%s) * %d * count); // NOLINT\n" %
5446 (self.GetArrayType(func), self.GetArrayCount(func)))
5447 file.Write(" }\n")
5448 file.Write("\n")
5449 file.Write(" static uint32_t ComputeSize(GLsizei count) {\n")
5450 file.Write(" return static_cast<uint32_t>(\n")
5451 file.Write(
5452 " sizeof(ValueType) + ComputeDataSize(count)); // NOLINT\n")
5453 file.Write(" }\n")
5454 file.Write("\n")
5456 def WriteImmediateCmdSetHeader(self, func, file):
5457 """Overrriden from TypeHandler."""
5458 file.Write(" void SetHeader(GLsizei count) {\n")
5459 file.Write(
5460 " header.SetCmdByTotalSize<ValueType>(ComputeSize(count));\n")
5461 file.Write(" }\n")
5462 file.Write("\n")
5464 def WriteImmediateCmdInit(self, func, file):
5465 """Overrriden from TypeHandler."""
5466 last_arg = func.GetLastOriginalArg()
5467 file.Write(" void Init(%s, %s _%s) {\n" %
5468 (func.MakeTypedCmdArgString("_"),
5469 last_arg.type, last_arg.name))
5470 file.Write(" SetHeader(_count);\n")
5471 args = func.GetCmdArgs()
5472 for arg in args:
5473 file.Write(" %s = _%s;\n" % (arg.name, arg.name))
5474 file.Write(" memcpy(ImmediateDataAddress(this),\n")
5475 file.Write(" _%s, ComputeDataSize(_count));\n" % last_arg.name)
5476 file.Write(" }\n")
5477 file.Write("\n")
5479 def WriteImmediateCmdSet(self, func, file):
5480 """Overrriden from TypeHandler."""
5481 last_arg = func.GetLastOriginalArg()
5482 copy_args = func.MakeCmdArgString("_", False)
5483 file.Write(" void* Set(void* cmd%s, %s _%s) {\n" %
5484 (func.MakeTypedCmdArgString("_", True),
5485 last_arg.type, last_arg.name))
5486 file.Write(" static_cast<ValueType*>(cmd)->Init(%s, _%s);\n" %
5487 (copy_args, last_arg.name))
5488 file.Write(" const uint32_t size = ComputeSize(_count);\n")
5489 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
5490 "cmd, size);\n")
5491 file.Write(" }\n")
5492 file.Write("\n")
5494 def WriteImmediateCmdHelper(self, func, file):
5495 """Overrriden from TypeHandler."""
5496 code = """ void %(name)s(%(typed_args)s) {
5497 const uint32_t size = gles2::cmds::%(name)s::ComputeSize(count);
5498 gles2::cmds::%(name)s* c =
5499 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
5500 if (c) {
5501 c->Init(%(args)s);
5506 file.Write(code % {
5507 "name": func.name,
5508 "typed_args": func.MakeTypedInitString(""),
5509 "args": func.MakeInitString("")
5512 def WriteImmediateFormatTest(self, func, file):
5513 """Overrriden from TypeHandler."""
5514 args = func.GetCmdArgs()
5515 count_param = 0
5516 for arg in args:
5517 if arg.name == "count":
5518 count_param = int(arg.GetValidClientSideCmdArg(func))
5519 file.Write("TEST_F(GLES2FormatTest, %s) {\n" % func.name)
5520 file.Write(" const int kSomeBaseValueToTestWith = 51;\n")
5521 file.Write(" static %s data[] = {\n" % self.GetArrayType(func))
5522 for v in range(0, self.GetArrayCount(func) * count_param):
5523 file.Write(" static_cast<%s>(kSomeBaseValueToTestWith + %d),\n" %
5524 (self.GetArrayType(func), v))
5525 file.Write(" };\n")
5526 file.Write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
5527 (func.name, func.name))
5528 file.Write(" const GLsizei kNumElements = %d;\n" % count_param)
5529 file.Write(" const size_t kExpectedCmdSize =\n")
5530 file.Write(" sizeof(cmd) + kNumElements * sizeof(%s) * %d;\n" %
5531 (self.GetArrayType(func), self.GetArrayCount(func)))
5532 file.Write(" void* next_cmd = cmd.Set(\n")
5533 file.Write(" &cmd")
5534 for value, arg in enumerate(args):
5535 file.Write(",\n static_cast<%s>(%d)" % (arg.type, value + 1))
5536 file.Write(",\n data);\n")
5537 file.Write(" EXPECT_EQ(static_cast<uint32_t>(cmds::%s::kCmdId),\n" %
5538 func.name)
5539 file.Write(" cmd.header.command);\n")
5540 file.Write(" EXPECT_EQ(kExpectedCmdSize, cmd.header.size * 4u);\n")
5541 for value, arg in enumerate(args):
5542 file.Write(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);\n" %
5543 (arg.type, value + 1, arg.name))
5544 file.Write(" CheckBytesWrittenMatchesExpectedSize(\n")
5545 file.Write(" next_cmd, sizeof(cmd) +\n")
5546 file.Write(" RoundSizeToMultipleOfEntries(sizeof(data)));\n")
5547 file.Write(" // TODO(gman): Check that data was inserted;\n")
5548 file.Write("}\n")
5549 file.Write("\n")
5552 class PUTXnHandler(ArrayArgTypeHandler):
5553 """Handler for glUniform?f functions."""
5554 def __init__(self):
5555 ArrayArgTypeHandler.__init__(self)
5557 def WriteHandlerImplementation(self, func, file):
5558 """Overrriden from TypeHandler."""
5559 code = """ %(type)s temp[%(count)s] = { %(values)s};
5560 Do%(name)sv(%(location)s, 1, &temp[0]);
5562 values = ""
5563 args = func.GetOriginalArgs()
5564 count = int(self.GetArrayCount(func))
5565 num_args = len(args)
5566 for ii in range(count):
5567 values += "%s, " % args[len(args) - count + ii].name
5569 file.Write(code % {
5570 'name': func.name,
5571 'count': self.GetArrayCount(func),
5572 'type': self.GetArrayType(func),
5573 'location': args[0].name,
5574 'args': func.MakeOriginalArgString(""),
5575 'values': values,
5578 def WriteServiceUnitTest(self, func, file, *extras):
5579 """Overrriden from TypeHandler."""
5580 valid_test = """
5581 TEST_P(%(test_name)s, %(name)sValidArgs) {
5582 EXPECT_CALL(*gl_, %(name)sv(%(local_args)s));
5583 SpecializedSetup<cmds::%(name)s, 0>(true);
5584 cmds::%(name)s cmd;
5585 cmd.Init(%(args)s);
5586 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5587 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5590 args = func.GetOriginalArgs()
5591 local_args = "%s, 1, _" % args[0].GetValidGLArg(func)
5592 self.WriteValidUnitTest(func, file, valid_test, {
5593 'name': func.name,
5594 'count': self.GetArrayCount(func),
5595 'local_args': local_args,
5596 }, *extras)
5598 invalid_test = """
5599 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
5600 EXPECT_CALL(*gl_, %(name)sv(_, _, _).Times(0);
5601 SpecializedSetup<cmds::%(name)s, 0>(false);
5602 cmds::%(name)s cmd;
5603 cmd.Init(%(args)s);
5604 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
5607 self.WriteInvalidUnitTest(func, file, invalid_test, {
5608 'name': func.GetInfo('name'),
5609 'count': self.GetArrayCount(func),
5613 class GLcharHandler(CustomHandler):
5614 """Handler for functions that pass a single string ."""
5616 def __init__(self):
5617 CustomHandler.__init__(self)
5619 def WriteImmediateCmdComputeSize(self, func, file):
5620 """Overrriden from TypeHandler."""
5621 file.Write(" static uint32_t ComputeSize(uint32_t data_size) {\n")
5622 file.Write(" return static_cast<uint32_t>(\n")
5623 file.Write(" sizeof(ValueType) + data_size); // NOLINT\n")
5624 file.Write(" }\n")
5626 def WriteImmediateCmdSetHeader(self, func, file):
5627 """Overrriden from TypeHandler."""
5628 code = """
5629 void SetHeader(uint32_t data_size) {
5630 header.SetCmdBySize<ValueType>(data_size);
5633 file.Write(code)
5635 def WriteImmediateCmdInit(self, func, file):
5636 """Overrriden from TypeHandler."""
5637 last_arg = func.GetLastOriginalArg()
5638 args = func.GetCmdArgs()
5639 set_code = []
5640 for arg in args:
5641 set_code.append(" %s = _%s;" % (arg.name, arg.name))
5642 code = """
5643 void Init(%(typed_args)s, uint32_t _data_size) {
5644 SetHeader(_data_size);
5645 %(set_code)s
5646 memcpy(ImmediateDataAddress(this), _%(last_arg)s, _data_size);
5650 file.Write(code % {
5651 "typed_args": func.MakeTypedArgString("_"),
5652 "set_code": "\n".join(set_code),
5653 "last_arg": last_arg.name
5656 def WriteImmediateCmdSet(self, func, file):
5657 """Overrriden from TypeHandler."""
5658 last_arg = func.GetLastOriginalArg()
5659 file.Write(" void* Set(void* cmd%s, uint32_t _data_size) {\n" %
5660 func.MakeTypedCmdArgString("_", True))
5661 file.Write(" static_cast<ValueType*>(cmd)->Init(%s, _data_size);\n" %
5662 func.MakeCmdArgString("_"))
5663 file.Write(" return NextImmediateCmdAddress<ValueType>("
5664 "cmd, _data_size);\n")
5665 file.Write(" }\n")
5666 file.Write("\n")
5668 def WriteImmediateCmdHelper(self, func, file):
5669 """Overrriden from TypeHandler."""
5670 code = """ void %(name)s(%(typed_args)s) {
5671 const uint32_t data_size = strlen(name);
5672 gles2::cmds::%(name)s* c =
5673 GetImmediateCmdSpace<gles2::cmds::%(name)s>(data_size);
5674 if (c) {
5675 c->Init(%(args)s, data_size);
5680 file.Write(code % {
5681 "name": func.name,
5682 "typed_args": func.MakeTypedOriginalArgString(""),
5683 "args": func.MakeOriginalArgString(""),
5687 def WriteImmediateFormatTest(self, func, file):
5688 """Overrriden from TypeHandler."""
5689 init_code = []
5690 check_code = []
5691 all_but_last_arg = func.GetCmdArgs()[:-1]
5692 for value, arg in enumerate(all_but_last_arg):
5693 init_code.append(" static_cast<%s>(%d)," % (arg.type, value + 11))
5694 for value, arg in enumerate(all_but_last_arg):
5695 check_code.append(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);" %
5696 (arg.type, value + 11, arg.name))
5697 code = """
5698 TEST_F(GLES2FormatTest, %(func_name)s) {
5699 cmds::%(func_name)s& cmd = *GetBufferAs<cmds::%(func_name)s>();
5700 static const char* const test_str = \"test string\";
5701 void* next_cmd = cmd.Set(
5702 &cmd,
5703 %(init_code)s
5704 test_str,
5705 strlen(test_str));
5706 EXPECT_EQ(static_cast<uint32_t>(cmds::%(func_name)s::kCmdId),
5707 cmd.header.command);
5708 EXPECT_EQ(sizeof(cmd) +
5709 RoundSizeToMultipleOfEntries(strlen(test_str)),
5710 cmd.header.size * 4u);
5711 EXPECT_EQ(static_cast<char*>(next_cmd),
5712 reinterpret_cast<char*>(&cmd) + sizeof(cmd) +
5713 RoundSizeToMultipleOfEntries(strlen(test_str)));
5714 %(check_code)s
5715 EXPECT_EQ(static_cast<uint32_t>(strlen(test_str)), cmd.data_size);
5716 EXPECT_EQ(0, memcmp(test_str, ImmediateDataAddress(&cmd), strlen(test_str)));
5717 CheckBytesWritten(
5718 next_cmd,
5719 sizeof(cmd) + RoundSizeToMultipleOfEntries(strlen(test_str)),
5720 sizeof(cmd) + strlen(test_str));
5724 file.Write(code % {
5725 'func_name': func.name,
5726 'init_code': "\n".join(init_code),
5727 'check_code': "\n".join(check_code),
5731 class GLcharNHandler(CustomHandler):
5732 """Handler for functions that pass a single string with an optional len."""
5734 def __init__(self):
5735 CustomHandler.__init__(self)
5737 def InitFunction(self, func):
5738 """Overrriden from TypeHandler."""
5739 func.cmd_args = []
5740 func.AddCmdArg(Argument('bucket_id', 'GLuint'))
5742 def NeedsDataTransferFunction(self, func):
5743 """Overriden from TypeHandler."""
5744 return False
5746 def AddBucketFunction(self, generator, func):
5747 """Overrriden from TypeHandler."""
5748 pass
5750 def WriteServiceImplementation(self, func, file):
5751 """Overrriden from TypeHandler."""
5752 file.Write("""error::Error GLES2DecoderImpl::Handle%(name)s(
5753 uint32_t immediate_data_size, const gles2::cmds::%(name)s& c) {
5754 GLuint bucket_id = static_cast<GLuint>(c.%(bucket_id)s);
5755 Bucket* bucket = GetBucket(bucket_id);
5756 if (!bucket || bucket->size() == 0) {
5757 return error::kInvalidArguments;
5759 std::string str;
5760 if (!bucket->GetAsString(&str)) {
5761 return error::kInvalidArguments;
5763 %(gl_func_name)s(0, str.c_str());
5764 return error::kNoError;
5767 """ % {
5768 'name': func.name,
5769 'gl_func_name': func.GetGLFunctionName(),
5770 'bucket_id': func.cmd_args[0].name,
5774 class IsHandler(TypeHandler):
5775 """Handler for glIs____ type and glGetError functions."""
5777 def __init__(self):
5778 TypeHandler.__init__(self)
5780 def InitFunction(self, func):
5781 """Overrriden from TypeHandler."""
5782 func.AddCmdArg(Argument("result_shm_id", 'uint32_t'))
5783 func.AddCmdArg(Argument("result_shm_offset", 'uint32_t'))
5784 if func.GetInfo('result') == None:
5785 func.AddInfo('result', ['uint32_t'])
5787 def WriteServiceUnitTest(self, func, file, *extras):
5788 """Overrriden from TypeHandler."""
5789 valid_test = """
5790 TEST_P(%(test_name)s, %(name)sValidArgs) {
5791 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
5792 SpecializedSetup<cmds::%(name)s, 0>(true);
5793 cmds::%(name)s cmd;
5794 cmd.Init(%(args)s%(comma)sshared_memory_id_, shared_memory_offset_);
5795 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5796 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5799 comma = ""
5800 if len(func.GetOriginalArgs()):
5801 comma =", "
5802 self.WriteValidUnitTest(func, file, valid_test, {
5803 'comma': comma,
5804 }, *extras)
5806 invalid_test = """
5807 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
5808 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
5809 SpecializedSetup<cmds::%(name)s, 0>(false);
5810 cmds::%(name)s cmd;
5811 cmd.Init(%(args)s%(comma)sshared_memory_id_, shared_memory_offset_);
5812 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
5815 self.WriteInvalidUnitTest(func, file, invalid_test, {
5816 'comma': comma,
5817 }, *extras)
5819 invalid_test = """
5820 TEST_P(%(test_name)s, %(name)sInvalidArgsBadSharedMemoryId) {
5821 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
5822 SpecializedSetup<cmds::%(name)s, 0>(false);
5823 cmds::%(name)s cmd;
5824 cmd.Init(%(args)s%(comma)skInvalidSharedMemoryId, shared_memory_offset_);
5825 EXPECT_EQ(error::kOutOfBounds, ExecuteCmd(cmd));
5826 cmd.Init(%(args)s%(comma)sshared_memory_id_, kInvalidSharedMemoryOffset);
5827 EXPECT_EQ(error::kOutOfBounds, ExecuteCmd(cmd));
5830 self.WriteValidUnitTest(func, file, invalid_test, {
5831 'comma': comma,
5832 }, *extras)
5834 def WriteServiceImplementation(self, func, file):
5835 """Overrriden from TypeHandler."""
5836 file.Write(
5837 "error::Error GLES2DecoderImpl::Handle%s(\n" % func.name)
5838 file.Write(
5839 " uint32_t immediate_data_size, const gles2::cmds::%s& c) {\n" %
5840 func.name)
5841 args = func.GetOriginalArgs()
5842 for arg in args:
5843 arg.WriteGetCode(file)
5845 code = """ typedef cmds::%(func_name)s::Result Result;
5846 Result* result_dst = GetSharedMemoryAs<Result*>(
5847 c.result_shm_id, c.result_shm_offset, sizeof(*result_dst));
5848 if (!result_dst) {
5849 return error::kOutOfBounds;
5852 file.Write(code % {'func_name': func.name})
5853 func.WriteHandlerValidation(file)
5854 file.Write(" *result_dst = %s(%s);\n" %
5855 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
5856 file.Write(" return error::kNoError;\n")
5857 file.Write("}\n")
5858 file.Write("\n")
5860 def WriteGLES2Implementation(self, func, file):
5861 """Overrriden from TypeHandler."""
5862 impl_func = func.GetInfo('impl_func')
5863 if impl_func == None or impl_func == True:
5864 error_value = func.GetInfo("error_value") or "GL_FALSE"
5865 file.Write("%s GLES2Implementation::%s(%s) {\n" %
5866 (func.return_type, func.original_name,
5867 func.MakeTypedOriginalArgString("")))
5868 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
5869 self.WriteTraceEvent(func, file)
5870 func.WriteDestinationInitalizationValidation(file)
5871 self.WriteClientGLCallLog(func, file)
5872 file.Write(" typedef cmds::%s::Result Result;\n" % func.name)
5873 file.Write(" Result* result = GetResultAs<Result*>();\n")
5874 file.Write(" if (!result) {\n")
5875 file.Write(" return %s;\n" % error_value)
5876 file.Write(" }\n")
5877 file.Write(" *result = 0;\n")
5878 arg_string = func.MakeOriginalArgString("")
5879 comma = ""
5880 if len(arg_string) > 0:
5881 comma = ", "
5882 file.Write(
5883 " helper_->%s(%s%sGetResultShmId(), GetResultShmOffset());\n" %
5884 (func.name, arg_string, comma))
5885 file.Write(" WaitForCmd();\n")
5886 file.Write(" %s result_value = *result;\n" % func.return_type)
5887 file.Write(' GPU_CLIENT_LOG("returned " << result_value);\n')
5888 file.Write(" CheckGLError();\n")
5889 file.Write(" return result_value;\n")
5890 file.Write("}\n")
5891 file.Write("\n")
5893 def WriteGLES2ImplementationUnitTest(self, func, file):
5894 """Overrriden from TypeHandler."""
5895 client_test = func.GetInfo('client_test')
5896 if client_test == None or client_test == True:
5897 code = """
5898 TEST_F(GLES2ImplementationTest, %(name)s) {
5899 struct Cmds {
5900 cmds::%(name)s cmd;
5903 Cmds expected;
5904 ExpectedMemoryInfo result1 =
5905 GetExpectedResultMemory(sizeof(cmds::%(name)s::Result));
5906 expected.cmd.Init(1, result1.id, result1.offset);
5908 EXPECT_CALL(*command_buffer(), OnFlush())
5909 .WillOnce(SetMemory(result1.ptr, uint32_t(1)))
5910 .RetiresOnSaturation();
5912 GLboolean result = gl_->%(name)s(1);
5913 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
5914 EXPECT_TRUE(result);
5917 file.Write(code % {
5918 'name': func.name,
5922 class STRnHandler(TypeHandler):
5923 """Handler for GetProgramInfoLog, GetShaderInfoLog, GetShaderSource, and
5924 GetTranslatedShaderSourceANGLE."""
5926 def __init__(self):
5927 TypeHandler.__init__(self)
5929 def InitFunction(self, func):
5930 """Overrriden from TypeHandler."""
5931 # remove all but the first cmd args.
5932 cmd_args = func.GetCmdArgs()
5933 func.ClearCmdArgs()
5934 func.AddCmdArg(cmd_args[0])
5935 # add on a bucket id.
5936 func.AddCmdArg(Argument('bucket_id', 'uint32_t'))
5938 def WriteGLES2Implementation(self, func, file):
5939 """Overrriden from TypeHandler."""
5940 code_1 = """%(return_type)s GLES2Implementation::%(func_name)s(%(args)s) {
5941 GPU_CLIENT_SINGLE_THREAD_CHECK();
5943 code_2 = """ GPU_CLIENT_LOG("[" << GetLogPrefix()
5944 << "] gl%(func_name)s" << "("
5945 << %(arg0)s << ", "
5946 << %(arg1)s << ", "
5947 << static_cast<void*>(%(arg2)s) << ", "
5948 << static_cast<void*>(%(arg3)s) << ")");
5949 helper_->SetBucketSize(kResultBucketId, 0);
5950 helper_->%(func_name)s(%(id_name)s, kResultBucketId);
5951 std::string str;
5952 GLsizei max_size = 0;
5953 if (GetBucketAsString(kResultBucketId, &str)) {
5954 if (bufsize > 0) {
5955 max_size =
5956 std::min(static_cast<size_t>(%(bufsize_name)s) - 1, str.size());
5957 memcpy(%(dest_name)s, str.c_str(), max_size);
5958 %(dest_name)s[max_size] = '\\0';
5959 GPU_CLIENT_LOG("------\\n" << %(dest_name)s << "\\n------");
5962 if (%(length_name)s != NULL) {
5963 *%(length_name)s = max_size;
5965 CheckGLError();
5968 args = func.GetOriginalArgs()
5969 str_args = {
5970 'return_type': func.return_type,
5971 'func_name': func.original_name,
5972 'args': func.MakeTypedOriginalArgString(""),
5973 'id_name': args[0].name,
5974 'bufsize_name': args[1].name,
5975 'length_name': args[2].name,
5976 'dest_name': args[3].name,
5977 'arg0': args[0].name,
5978 'arg1': args[1].name,
5979 'arg2': args[2].name,
5980 'arg3': args[3].name,
5982 file.Write(code_1 % str_args)
5983 func.WriteDestinationInitalizationValidation(file)
5984 file.Write(code_2 % str_args)
5986 def WriteServiceUnitTest(self, func, file, *extras):
5987 """Overrriden from TypeHandler."""
5988 valid_test = """
5989 TEST_P(%(test_name)s, %(name)sValidArgs) {
5990 const char* kInfo = "hello";
5991 const uint32_t kBucketId = 123;
5992 SpecializedSetup<cmds::%(name)s, 0>(true);
5993 %(expect_len_code)s
5994 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s))
5995 .WillOnce(DoAll(SetArgumentPointee<2>(strlen(kInfo)),
5996 SetArrayArgument<3>(kInfo, kInfo + strlen(kInfo) + 1)));
5997 cmds::%(name)s cmd;
5998 cmd.Init(%(args)s);
5999 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
6000 CommonDecoder::Bucket* bucket = decoder_->GetBucket(kBucketId);
6001 ASSERT_TRUE(bucket != NULL);
6002 EXPECT_EQ(strlen(kInfo) + 1, bucket->size());
6003 EXPECT_EQ(0, memcmp(bucket->GetData(0, bucket->size()), kInfo,
6004 bucket->size()));
6005 EXPECT_EQ(GL_NO_ERROR, GetGLError());
6008 args = func.GetOriginalArgs()
6009 id_name = args[0].GetValidGLArg(func)
6010 get_len_func = func.GetInfo('get_len_func')
6011 get_len_enum = func.GetInfo('get_len_enum')
6012 sub = {
6013 'id_name': id_name,
6014 'get_len_func': get_len_func,
6015 'get_len_enum': get_len_enum,
6016 'gl_args': '%s, strlen(kInfo) + 1, _, _' %
6017 args[0].GetValidGLArg(func),
6018 'args': '%s, kBucketId' % args[0].GetValidArg(func),
6019 'expect_len_code': '',
6021 if get_len_func and get_len_func[0:2] == 'gl':
6022 sub['expect_len_code'] = (
6023 " EXPECT_CALL(*gl_, %s(%s, %s, _))\n"
6024 " .WillOnce(SetArgumentPointee<2>(strlen(kInfo) + 1));") % (
6025 get_len_func[2:], id_name, get_len_enum)
6026 self.WriteValidUnitTest(func, file, valid_test, sub, *extras)
6028 invalid_test = """
6029 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
6030 const uint32_t kBucketId = 123;
6031 EXPECT_CALL(*gl_, %(gl_func_name)s(_, _, _, _))
6032 .Times(0);
6033 cmds::%(name)s cmd;
6034 cmd.Init(kInvalidClientId, kBucketId);
6035 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
6036 EXPECT_EQ(GL_INVALID_VALUE, GetGLError());
6039 self.WriteValidUnitTest(func, file, invalid_test, *extras)
6041 def WriteServiceImplementation(self, func, file):
6042 """Overrriden from TypeHandler."""
6043 pass
6045 class NamedType(object):
6046 """A class that represents a type of an argument in a client function.
6048 A type of an argument that is to be passed through in the command buffer
6049 command. Currently used only for the arguments that are specificly named in
6050 the 'cmd_buffer_functions.txt' file, mostly enums.
6053 def __init__(self, info):
6054 assert not 'is_complete' in info or info['is_complete'] == True
6055 self.info = info
6056 self.valid = info['valid']
6057 if 'invalid' in info:
6058 self.invalid = info['invalid']
6059 else:
6060 self.invalid = []
6062 def GetType(self):
6063 return self.info['type']
6065 def GetInvalidValues(self):
6066 return self.invalid
6068 def GetValidValues(self):
6069 return self.valid
6071 def IsConstant(self):
6072 if not 'is_complete' in self.info:
6073 return False
6075 return len(self.GetValidValues()) == 1
6077 def GetConstantValue(self):
6078 return self.GetValidValues()[0]
6080 class Argument(object):
6081 """A class that represents a function argument."""
6083 cmd_type_map_ = {
6084 'GLenum': 'uint32_t',
6085 'GLint': 'int32_t',
6086 'GLintptr': 'int32_t',
6087 'GLsizei': 'int32_t',
6088 'GLsizeiptr': 'int32_t',
6089 'GLfloat': 'float',
6090 'GLclampf': 'float',
6092 need_validation_ = ['GLsizei*', 'GLboolean*', 'GLenum*', 'GLint*']
6094 def __init__(self, name, type):
6095 self.name = name
6096 self.optional = type.endswith("Optional*")
6097 if self.optional:
6098 type = type[:-9] + "*"
6099 self.type = type
6101 if type in self.cmd_type_map_:
6102 self.cmd_type = self.cmd_type_map_[type]
6103 else:
6104 self.cmd_type = 'uint32_t'
6106 def IsPointer(self):
6107 """Returns true if argument is a pointer."""
6108 return False
6110 def IsConstant(self):
6111 """Returns true if the argument has only one valid value."""
6112 return False
6114 def AddCmdArgs(self, args):
6115 """Adds command arguments for this argument to the given list."""
6116 if not self.IsConstant():
6117 return args.append(self)
6119 def AddInitArgs(self, args):
6120 """Adds init arguments for this argument to the given list."""
6121 if not self.IsConstant():
6122 return args.append(self)
6124 def GetValidArg(self, func):
6125 """Gets a valid value for this argument."""
6126 valid_arg = func.GetValidArg(self)
6127 if valid_arg != None:
6128 return valid_arg
6130 index = func.GetOriginalArgs().index(self)
6131 return str(index + 1)
6133 def GetValidClientSideArg(self, func):
6134 """Gets a valid value for this argument."""
6135 valid_arg = func.GetValidArg(self)
6136 if valid_arg != None:
6137 return valid_arg
6139 index = func.GetOriginalArgs().index(self)
6140 return str(index + 1)
6142 def GetValidClientSideCmdArg(self, func):
6143 """Gets a valid value for this argument."""
6144 valid_arg = func.GetValidArg(self)
6145 if valid_arg != None:
6146 return valid_arg
6147 try:
6148 index = func.GetOriginalArgs().index(self)
6149 return str(index + 1)
6150 except ValueError:
6151 pass
6152 index = func.GetCmdArgs().index(self)
6153 return str(index + 1)
6155 def GetValidGLArg(self, func):
6156 """Gets a valid GL value for this argument."""
6157 return self.GetValidArg(func)
6159 def GetValidNonCachedClientSideArg(self, func):
6160 """Returns a valid value for this argument in a GL call.
6161 Using the value will produce a command buffer service invocation.
6162 Returns None if there is no such value."""
6163 return '123'
6165 def GetValidNonCachedClientSideCmdArg(self, func):
6166 """Returns a valid value for this argument in a command buffer command.
6167 Calling the GL function with the value returned by
6168 GetValidNonCachedClientSideArg will result in a command buffer command
6169 that contains the value returned by this function. """
6170 return '123'
6172 def GetNumInvalidValues(self, func):
6173 """returns the number of invalid values to be tested."""
6174 return 0
6176 def GetInvalidArg(self, index):
6177 """returns an invalid value and expected parse result by index."""
6178 return ("---ERROR0---", "---ERROR2---", None)
6180 def GetLogArg(self):
6181 """Get argument appropriate for LOG macro."""
6182 if self.type == 'GLboolean':
6183 return 'GLES2Util::GetStringBool(%s)' % self.name
6184 if self.type == 'GLenum':
6185 return 'GLES2Util::GetStringEnum(%s)' % self.name
6186 return self.name
6188 def WriteGetCode(self, file):
6189 """Writes the code to get an argument from a command structure."""
6190 file.Write(" %s %s = static_cast<%s>(c.%s);\n" %
6191 (self.type, self.name, self.type, self.name))
6193 def WriteValidationCode(self, file, func):
6194 """Writes the validation code for an argument."""
6195 pass
6197 def WriteClientSideValidationCode(self, file, func):
6198 """Writes the validation code for an argument."""
6199 pass
6201 def WriteDestinationInitalizationValidation(self, file, func):
6202 """Writes the client side destintion initialization validation."""
6203 pass
6205 def WriteDestinationInitalizationValidatationIfNeeded(self, file, func):
6206 """Writes the client side destintion initialization validation if needed."""
6207 parts = self.type.split(" ")
6208 if len(parts) > 1:
6209 return
6210 if parts[0] in self.need_validation_:
6211 file.Write(
6212 " GPU_CLIENT_VALIDATE_DESTINATION_%sINITALIZATION(%s, %s);\n" %
6213 ("OPTIONAL_" if self.optional else "", self.type[:-1], self.name))
6216 def WriteGetAddress(self, file):
6217 """Writes the code to get the address this argument refers to."""
6218 pass
6220 def GetImmediateVersion(self):
6221 """Gets the immediate version of this argument."""
6222 return self
6224 def GetBucketVersion(self):
6225 """Gets the bucket version of this argument."""
6226 return self
6229 class BoolArgument(Argument):
6230 """class for GLboolean"""
6232 def __init__(self, name, type):
6233 Argument.__init__(self, name, 'GLboolean')
6235 def GetValidArg(self, func):
6236 """Gets a valid value for this argument."""
6237 return 'true'
6239 def GetValidClientSideArg(self, func):
6240 """Gets a valid value for this argument."""
6241 return 'true'
6243 def GetValidClientSideCmdArg(self, func):
6244 """Gets a valid value for this argument."""
6245 return 'true'
6247 def GetValidGLArg(self, func):
6248 """Gets a valid GL value for this argument."""
6249 return 'true'
6252 class UniformLocationArgument(Argument):
6253 """class for uniform locations."""
6255 def __init__(self, name):
6256 Argument.__init__(self, name, "GLint")
6258 def WriteGetCode(self, file):
6259 """Writes the code to get an argument from a command structure."""
6260 code = """ %s %s = static_cast<%s>(c.%s);
6262 file.Write(code % (self.type, self.name, self.type, self.name))
6264 class DataSizeArgument(Argument):
6265 """class for data_size which Bucket commands do not need."""
6267 def __init__(self, name):
6268 Argument.__init__(self, name, "uint32_t")
6270 def GetBucketVersion(self):
6271 return None
6274 class SizeArgument(Argument):
6275 """class for GLsizei and GLsizeiptr."""
6277 def __init__(self, name, type):
6278 Argument.__init__(self, name, type)
6280 def GetNumInvalidValues(self, func):
6281 """overridden from Argument."""
6282 if func.IsImmediate():
6283 return 0
6284 return 1
6286 def GetInvalidArg(self, index):
6287 """overridden from Argument."""
6288 return ("-1", "kNoError", "GL_INVALID_VALUE")
6290 def WriteValidationCode(self, file, func):
6291 """overridden from Argument."""
6292 file.Write(" if (%s < 0) {\n" % self.name)
6293 file.Write(
6294 " LOCAL_SET_GL_ERROR(GL_INVALID_VALUE, \"gl%s\", \"%s < 0\");\n" %
6295 (func.original_name, self.name))
6296 file.Write(" return error::kNoError;\n")
6297 file.Write(" }\n")
6299 def WriteClientSideValidationCode(self, file, func):
6300 """overridden from Argument."""
6301 file.Write(" if (%s < 0) {\n" % self.name)
6302 file.Write(
6303 " SetGLError(GL_INVALID_VALUE, \"gl%s\", \"%s < 0\");\n" %
6304 (func.original_name, self.name))
6305 file.Write(" return;\n")
6306 file.Write(" }\n")
6309 class SizeNotNegativeArgument(SizeArgument):
6310 """class for GLsizeiNotNegative. It's NEVER allowed to be negative"""
6312 def __init__(self, name, type, gl_type):
6313 SizeArgument.__init__(self, name, gl_type)
6315 def GetInvalidArg(self, index):
6316 """overridden from SizeArgument."""
6317 return ("-1", "kOutOfBounds", "GL_NO_ERROR")
6319 def WriteValidationCode(self, file, func):
6320 """overridden from SizeArgument."""
6321 pass
6324 class EnumBaseArgument(Argument):
6325 """Base class for EnumArgument, IntArgument and ValidatedBoolArgument"""
6327 def __init__(self, name, gl_type, type, gl_error):
6328 Argument.__init__(self, name, gl_type)
6330 self.local_type = type
6331 self.gl_error = gl_error
6332 name = type[len(gl_type):]
6333 self.type_name = name
6334 self.named_type = NamedType(_NAMED_TYPE_INFO[name])
6336 def IsConstant(self):
6337 return self.named_type.IsConstant()
6339 def GetConstantValue(self):
6340 return self.named_type.GetConstantValue()
6342 def WriteValidationCode(self, file, func):
6343 if self.named_type.IsConstant():
6344 return
6345 file.Write(" if (!validators_->%s.IsValid(%s)) {\n" %
6346 (ToUnderscore(self.type_name), self.name))
6347 if self.gl_error == "GL_INVALID_ENUM":
6348 file.Write(
6349 " LOCAL_SET_GL_ERROR_INVALID_ENUM(\"gl%s\", %s, \"%s\");\n" %
6350 (func.original_name, self.name, self.name))
6351 else:
6352 file.Write(
6353 " LOCAL_SET_GL_ERROR(%s, \"gl%s\", \"%s %s\");\n" %
6354 (self.gl_error, func.original_name, self.name, self.gl_error))
6355 file.Write(" return error::kNoError;\n")
6356 file.Write(" }\n")
6358 def WriteClientSideValidationCode(self, file, func):
6359 if not self.named_type.IsConstant():
6360 return
6361 file.Write(" if (%s != %s) {" % (self.name,
6362 self.GetConstantValue()))
6363 file.Write(
6364 " SetGLError(%s, \"gl%s\", \"%s %s\");\n" %
6365 (self.gl_error, func.original_name, self.name, self.gl_error))
6366 if func.return_type == "void":
6367 file.Write(" return;\n")
6368 else:
6369 file.Write(" return %s;\n" % func.GetErrorReturnString())
6370 file.Write(" }\n")
6372 def GetValidArg(self, func):
6373 valid_arg = func.GetValidArg(self)
6374 if valid_arg != None:
6375 return valid_arg
6376 valid = self.named_type.GetValidValues()
6377 if valid:
6378 num_valid = len(valid)
6379 return valid[0]
6381 index = func.GetOriginalArgs().index(self)
6382 return str(index + 1)
6384 def GetValidClientSideArg(self, func):
6385 """Gets a valid value for this argument."""
6386 return self.GetValidArg(func)
6388 def GetValidClientSideCmdArg(self, func):
6389 """Gets a valid value for this argument."""
6390 valid_arg = func.GetValidArg(self)
6391 if valid_arg != None:
6392 return valid_arg
6394 valid = self.named_type.GetValidValues()
6395 if valid:
6396 num_valid = len(valid)
6397 return valid[0]
6399 try:
6400 index = func.GetOriginalArgs().index(self)
6401 return str(index + 1)
6402 except ValueError:
6403 pass
6404 index = func.GetCmdArgs().index(self)
6405 return str(index + 1)
6407 def GetValidGLArg(self, func):
6408 """Gets a valid value for this argument."""
6409 return self.GetValidArg(func)
6411 def GetNumInvalidValues(self, func):
6412 """returns the number of invalid values to be tested."""
6413 return len(self.named_type.GetInvalidValues())
6415 def GetInvalidArg(self, index):
6416 """returns an invalid value by index."""
6417 invalid = self.named_type.GetInvalidValues()
6418 if invalid:
6419 num_invalid = len(invalid)
6420 if index >= num_invalid:
6421 index = num_invalid - 1
6422 return (invalid[index], "kNoError", self.gl_error)
6423 return ("---ERROR1---", "kNoError", self.gl_error)
6426 class EnumArgument(EnumBaseArgument):
6427 """A class that represents a GLenum argument"""
6429 def __init__(self, name, type):
6430 EnumBaseArgument.__init__(self, name, "GLenum", type, "GL_INVALID_ENUM")
6432 def GetLogArg(self):
6433 """Overridden from Argument."""
6434 return ("GLES2Util::GetString%s(%s)" %
6435 (self.type_name, self.name))
6438 class IntArgument(EnumBaseArgument):
6439 """A class for a GLint argument that can only except specific values.
6441 For example glTexImage2D takes a GLint for its internalformat
6442 argument instead of a GLenum.
6445 def __init__(self, name, type):
6446 EnumBaseArgument.__init__(self, name, "GLint", type, "GL_INVALID_VALUE")
6449 class ValidatedBoolArgument(EnumBaseArgument):
6450 """A class for a GLboolean argument that can only except specific values.
6452 For example glUniformMatrix takes a GLboolean for it's transpose but it
6453 must be false.
6456 def __init__(self, name, type):
6457 EnumBaseArgument.__init__(self, name, "GLboolean", type, "GL_INVALID_VALUE")
6459 def GetLogArg(self):
6460 """Overridden from Argument."""
6461 return 'GLES2Util::GetStringBool(%s)' % self.name
6464 class ImmediatePointerArgument(Argument):
6465 """A class that represents an immediate argument to a function.
6467 An immediate argument is one where the data follows the command.
6470 def __init__(self, name, type):
6471 Argument.__init__(self, name, type)
6473 def IsPointer(self):
6474 return True
6476 def GetPointedType(self):
6477 match = re.match('(const\s+)?(?P<element_type>[\w]+)\s*\*', self.type)
6478 assert match
6479 return match.groupdict()['element_type']
6481 def AddCmdArgs(self, args):
6482 """Overridden from Argument."""
6483 pass
6485 def WriteGetCode(self, file):
6486 """Overridden from Argument."""
6487 file.Write(
6488 " %s %s = GetImmediateDataAs<%s>(\n" %
6489 (self.type, self.name, self.type))
6490 file.Write(" c, data_size, immediate_data_size);\n")
6492 def WriteValidationCode(self, file, func):
6493 """Overridden from Argument."""
6494 file.Write(" if (%s == NULL) {\n" % self.name)
6495 file.Write(" return error::kOutOfBounds;\n")
6496 file.Write(" }\n")
6498 def GetImmediateVersion(self):
6499 """Overridden from Argument."""
6500 return None
6502 def WriteDestinationInitalizationValidation(self, file, func):
6503 """Overridden from Argument."""
6504 self.WriteDestinationInitalizationValidatationIfNeeded(file, func)
6506 def GetLogArg(self):
6507 """Overridden from Argument."""
6508 return "static_cast<const void*>(%s)" % self.name
6511 class BucketPointerArgument(Argument):
6512 """A class that represents an bucket argument to a function."""
6514 def __init__(self, name, type):
6515 Argument.__init__(self, name, type)
6517 def AddCmdArgs(self, args):
6518 """Overridden from Argument."""
6519 pass
6521 def WriteGetCode(self, file):
6522 """Overridden from Argument."""
6523 file.Write(
6524 " %s %s = bucket->GetData(0, data_size);\n" %
6525 (self.type, self.name))
6527 def WriteValidationCode(self, file, func):
6528 """Overridden from Argument."""
6529 pass
6531 def GetImmediateVersion(self):
6532 """Overridden from Argument."""
6533 return None
6535 def WriteDestinationInitalizationValidation(self, file, func):
6536 """Overridden from Argument."""
6537 self.WriteDestinationInitalizationValidatationIfNeeded(file, func)
6539 def GetLogArg(self):
6540 """Overridden from Argument."""
6541 return "static_cast<const void*>(%s)" % self.name
6544 class PointerArgument(Argument):
6545 """A class that represents a pointer argument to a function."""
6547 def __init__(self, name, type):
6548 Argument.__init__(self, name, type)
6550 def IsPointer(self):
6551 """Returns true if argument is a pointer."""
6552 return True
6554 def GetPointedType(self):
6555 match = re.match('(const\s+)?(?P<element_type>[\w]+)\s*\*', self.type)
6556 assert match
6557 return match.groupdict()['element_type']
6559 def GetValidArg(self, func):
6560 """Overridden from Argument."""
6561 return "shared_memory_id_, shared_memory_offset_"
6563 def GetValidGLArg(self, func):
6564 """Overridden from Argument."""
6565 return "reinterpret_cast<%s>(shared_memory_address_)" % self.type
6567 def GetNumInvalidValues(self, func):
6568 """Overridden from Argument."""
6569 return 2
6571 def GetInvalidArg(self, index):
6572 """Overridden from Argument."""
6573 if index == 0:
6574 return ("kInvalidSharedMemoryId, 0", "kOutOfBounds", None)
6575 else:
6576 return ("shared_memory_id_, kInvalidSharedMemoryOffset",
6577 "kOutOfBounds", None)
6579 def GetLogArg(self):
6580 """Overridden from Argument."""
6581 return "static_cast<const void*>(%s)" % self.name
6583 def AddCmdArgs(self, args):
6584 """Overridden from Argument."""
6585 args.append(Argument("%s_shm_id" % self.name, 'uint32_t'))
6586 args.append(Argument("%s_shm_offset" % self.name, 'uint32_t'))
6588 def WriteGetCode(self, file):
6589 """Overridden from Argument."""
6590 file.Write(
6591 " %s %s = GetSharedMemoryAs<%s>(\n" %
6592 (self.type, self.name, self.type))
6593 file.Write(
6594 " c.%s_shm_id, c.%s_shm_offset, data_size);\n" %
6595 (self.name, self.name))
6597 def WriteGetAddress(self, file):
6598 """Overridden from Argument."""
6599 file.Write(
6600 " %s %s = GetSharedMemoryAs<%s>(\n" %
6601 (self.type, self.name, self.type))
6602 file.Write(
6603 " %s_shm_id, %s_shm_offset, %s_size);\n" %
6604 (self.name, self.name, self.name))
6606 def WriteValidationCode(self, file, func):
6607 """Overridden from Argument."""
6608 file.Write(" if (%s == NULL) {\n" % self.name)
6609 file.Write(" return error::kOutOfBounds;\n")
6610 file.Write(" }\n")
6612 def GetImmediateVersion(self):
6613 """Overridden from Argument."""
6614 return ImmediatePointerArgument(self.name, self.type)
6616 def GetBucketVersion(self):
6617 """Overridden from Argument."""
6618 if self.type == "const char*":
6619 return InputStringBucketArgument(self.name, self.type)
6620 return BucketPointerArgument(self.name, self.type)
6622 def WriteDestinationInitalizationValidation(self, file, func):
6623 """Overridden from Argument."""
6624 self.WriteDestinationInitalizationValidatationIfNeeded(file, func)
6627 class InputStringBucketArgument(Argument):
6628 """An string input argument where the string is passed in a bucket."""
6630 def __init__(self, name, type):
6631 Argument.__init__(self, name + "_bucket_id", "uint32_t")
6633 def WriteGetCode(self, file):
6634 """Overridden from Argument."""
6635 code = """
6636 Bucket* %(name)s_bucket = GetBucket(c.%(name)s);
6637 if (!%(name)s_bucket) {
6638 return error::kInvalidArguments;
6640 std::string %(name)s_str;
6641 if (!%(name)s_bucket->GetAsString(&%(name)s_str)) {
6642 return error::kInvalidArguments;
6644 const char* %(name)s = %(name)s_str.c_str();
6646 file.Write(code % {
6647 'name': self.name,
6650 def GetValidArg(self, func):
6651 return "kNameBucketId"
6653 def GetValidGLArg(self, func):
6654 return "_"
6657 class ResourceIdArgument(Argument):
6658 """A class that represents a resource id argument to a function."""
6660 def __init__(self, name, type):
6661 match = re.match("(GLid\w+)", type)
6662 self.resource_type = match.group(1)[4:]
6663 type = type.replace(match.group(1), "GLuint")
6664 Argument.__init__(self, name, type)
6666 def WriteGetCode(self, file):
6667 """Overridden from Argument."""
6668 file.Write(" %s %s = c.%s;\n" % (self.type, self.name, self.name))
6670 def GetValidArg(self, func):
6671 return "client_%s_id_" % self.resource_type.lower()
6673 def GetValidGLArg(self, func):
6674 return "kService%sId" % self.resource_type
6677 class ResourceIdBindArgument(Argument):
6678 """Represents a resource id argument to a bind function."""
6680 def __init__(self, name, type):
6681 match = re.match("(GLidBind\w+)", type)
6682 self.resource_type = match.group(1)[8:]
6683 type = type.replace(match.group(1), "GLuint")
6684 Argument.__init__(self, name, type)
6686 def WriteGetCode(self, file):
6687 """Overridden from Argument."""
6688 code = """ %(type)s %(name)s = c.%(name)s;
6690 file.Write(code % {'type': self.type, 'name': self.name})
6692 def GetValidArg(self, func):
6693 return "client_%s_id_" % self.resource_type.lower()
6695 def GetValidGLArg(self, func):
6696 return "kService%sId" % self.resource_type
6699 class ResourceIdZeroArgument(Argument):
6700 """Represents a resource id argument to a function that can be zero."""
6702 def __init__(self, name, type):
6703 match = re.match("(GLidZero\w+)", type)
6704 self.resource_type = match.group(1)[8:]
6705 type = type.replace(match.group(1), "GLuint")
6706 Argument.__init__(self, name, type)
6708 def WriteGetCode(self, file):
6709 """Overridden from Argument."""
6710 file.Write(" %s %s = c.%s;\n" % (self.type, self.name, self.name))
6712 def GetValidArg(self, func):
6713 return "client_%s_id_" % self.resource_type.lower()
6715 def GetValidGLArg(self, func):
6716 return "kService%sId" % self.resource_type
6718 def GetNumInvalidValues(self, func):
6719 """returns the number of invalid values to be tested."""
6720 return 1
6722 def GetInvalidArg(self, index):
6723 """returns an invalid value by index."""
6724 return ("kInvalidClientId", "kNoError", "GL_INVALID_VALUE")
6727 class Function(object):
6728 """A class that represents a function."""
6730 type_handlers = {
6731 '': TypeHandler(),
6732 'Bind': BindHandler(),
6733 'Create': CreateHandler(),
6734 'Custom': CustomHandler(),
6735 'Data': DataHandler(),
6736 'Delete': DeleteHandler(),
6737 'DELn': DELnHandler(),
6738 'GENn': GENnHandler(),
6739 'GETn': GETnHandler(),
6740 'GLchar': GLcharHandler(),
6741 'GLcharN': GLcharNHandler(),
6742 'HandWritten': HandWrittenHandler(),
6743 'Is': IsHandler(),
6744 'Manual': ManualHandler(),
6745 'PUT': PUTHandler(),
6746 'PUTn': PUTnHandler(),
6747 'PUTXn': PUTXnHandler(),
6748 'StateSet': StateSetHandler(),
6749 'StateSetRGBAlpha': StateSetRGBAlphaHandler(),
6750 'StateSetFrontBack': StateSetFrontBackHandler(),
6751 'StateSetFrontBackSeparate': StateSetFrontBackSeparateHandler(),
6752 'StateSetNamedParameter': StateSetNamedParameter(),
6753 'STRn': STRnHandler(),
6754 'Todo': TodoHandler(),
6757 def __init__(self, name, info):
6758 self.name = name
6759 self.original_name = info['original_name']
6761 self.original_args = self.ParseArgs(info['original_args'])
6763 if 'cmd_args' in info:
6764 self.args_for_cmds = self.ParseArgs(info['cmd_args'])
6765 else:
6766 self.args_for_cmds = self.original_args[:]
6768 self.return_type = info['return_type']
6769 if self.return_type != 'void':
6770 self.return_arg = CreateArg(info['return_type'] + " result")
6771 else:
6772 self.return_arg = None
6774 self.num_pointer_args = sum(
6775 [1 for arg in self.args_for_cmds if arg.IsPointer()])
6776 self.info = info
6777 self.type_handler = self.type_handlers[info['type']]
6778 self.can_auto_generate = (self.num_pointer_args == 0 and
6779 info['return_type'] == "void")
6780 self.InitFunction()
6782 def ParseArgs(self, arg_string):
6783 """Parses a function arg string."""
6784 args = []
6785 parts = arg_string.split(',')
6786 for arg_string in parts:
6787 arg = CreateArg(arg_string)
6788 if arg:
6789 args.append(arg)
6790 return args
6792 def IsType(self, type_name):
6793 """Returns true if function is a certain type."""
6794 return self.info['type'] == type_name
6796 def InitFunction(self):
6797 """Creates command args and calls the init function for the type handler.
6799 Creates argument lists for command buffer commands, eg. self.cmd_args and
6800 self.init_args.
6801 Calls the type function initialization.
6802 Override to create different kind of command buffer command argument lists.
6804 self.cmd_args = []
6805 for arg in self.args_for_cmds:
6806 arg.AddCmdArgs(self.cmd_args)
6808 self.init_args = []
6809 for arg in self.args_for_cmds:
6810 arg.AddInitArgs(self.init_args)
6812 if self.return_arg:
6813 self.init_args.append(self.return_arg)
6815 self.type_handler.InitFunction(self)
6817 def IsImmediate(self):
6818 """Returns whether the function is immediate data function or not."""
6819 return False
6821 def GetInfo(self, name, default = None):
6822 """Returns a value from the function info for this function."""
6823 if name in self.info:
6824 return self.info[name]
6825 return default
6827 def GetValidArg(self, arg):
6828 """Gets a valid argument value for the parameter arg from the function info
6829 if one exists."""
6830 try:
6831 index = self.GetOriginalArgs().index(arg)
6832 except ValueError:
6833 return None
6835 valid_args = self.GetInfo('valid_args')
6836 if valid_args and str(index) in valid_args:
6837 return valid_args[str(index)]
6838 return None
6840 def AddInfo(self, name, value):
6841 """Adds an info."""
6842 self.info[name] = value
6844 def IsExtension(self):
6845 return self.GetInfo('extension') or self.GetInfo('extension_flag')
6847 def IsCoreGLFunction(self):
6848 return (not self.IsExtension() and
6849 not self.GetInfo('pepper_interface'))
6851 def InPepperInterface(self, interface):
6852 ext = self.GetInfo('pepper_interface')
6853 if not interface.GetName():
6854 return self.IsCoreGLFunction()
6855 return ext == interface.GetName()
6857 def InAnyPepperExtension(self):
6858 return self.IsCoreGLFunction() or self.GetInfo('pepper_interface')
6860 def GetErrorReturnString(self):
6861 if self.GetInfo("error_return"):
6862 return self.GetInfo("error_return")
6863 elif self.return_type == "GLboolean":
6864 return "GL_FALSE"
6865 elif "*" in self.return_type:
6866 return "NULL"
6867 return "0"
6869 def GetGLFunctionName(self):
6870 """Gets the function to call to execute GL for this command."""
6871 if self.GetInfo('decoder_func'):
6872 return self.GetInfo('decoder_func')
6873 return "gl%s" % self.original_name
6875 def GetGLTestFunctionName(self):
6876 gl_func_name = self.GetInfo('gl_test_func')
6877 if gl_func_name == None:
6878 gl_func_name = self.GetGLFunctionName()
6879 if gl_func_name.startswith("gl"):
6880 gl_func_name = gl_func_name[2:]
6881 else:
6882 gl_func_name = self.original_name
6883 return gl_func_name
6885 def GetDataTransferMethods(self):
6886 return self.GetInfo('data_transfer_methods',
6887 ['immediate' if self.num_pointer_args == 1 else 'shm'])
6889 def AddCmdArg(self, arg):
6890 """Adds a cmd argument to this function."""
6891 self.cmd_args.append(arg)
6893 def GetCmdArgs(self):
6894 """Gets the command args for this function."""
6895 return self.cmd_args
6897 def ClearCmdArgs(self):
6898 """Clears the command args for this function."""
6899 self.cmd_args = []
6901 def GetCmdConstants(self):
6902 """Gets the constants for this function."""
6903 return [arg for arg in self.args_for_cmds if arg.IsConstant()]
6905 def GetInitArgs(self):
6906 """Gets the init args for this function."""
6907 return self.init_args
6909 def GetOriginalArgs(self):
6910 """Gets the original arguments to this function."""
6911 return self.original_args
6913 def GetLastOriginalArg(self):
6914 """Gets the last original argument to this function."""
6915 return self.original_args[len(self.original_args) - 1]
6917 def __MaybePrependComma(self, arg_string, add_comma):
6918 """Adds a comma if arg_string is not empty and add_comma is true."""
6919 comma = ""
6920 if add_comma and len(arg_string):
6921 comma = ", "
6922 return "%s%s" % (comma, arg_string)
6924 def MakeTypedOriginalArgString(self, prefix, add_comma = False):
6925 """Gets a list of arguments as they are in GL."""
6926 args = self.GetOriginalArgs()
6927 arg_string = ", ".join(
6928 ["%s %s%s" % (arg.type, prefix, arg.name) for arg in args])
6929 return self.__MaybePrependComma(arg_string, add_comma)
6931 def MakeOriginalArgString(self, prefix, add_comma = False, separator = ", "):
6932 """Gets the list of arguments as they are in GL."""
6933 args = self.GetOriginalArgs()
6934 arg_string = separator.join(
6935 ["%s%s" % (prefix, arg.name) for arg in args])
6936 return self.__MaybePrependComma(arg_string, add_comma)
6938 def MakeTypedHelperArgString(self, prefix, add_comma = False):
6939 """Gets a list of typed GL arguments after removing unneeded arguments."""
6940 args = self.GetOriginalArgs()
6941 arg_string = ", ".join(
6942 ["%s %s%s" % (
6943 arg.type,
6944 prefix,
6945 arg.name,
6946 ) for arg in args if not arg.IsConstant()])
6947 return self.__MaybePrependComma(arg_string, add_comma)
6949 def MakeHelperArgString(self, prefix, add_comma = False, separator = ", "):
6950 """Gets a list of GL arguments after removing unneeded arguments."""
6951 args = self.GetOriginalArgs()
6952 arg_string = separator.join(
6953 ["%s%s" % (prefix, arg.name)
6954 for arg in args if not arg.IsConstant()])
6955 return self.__MaybePrependComma(arg_string, add_comma)
6957 def MakeTypedPepperArgString(self, prefix):
6958 """Gets a list of arguments as they need to be for Pepper."""
6959 if self.GetInfo("pepper_args"):
6960 return self.GetInfo("pepper_args")
6961 else:
6962 return self.MakeTypedOriginalArgString(prefix, False)
6964 def GetPepperName(self):
6965 if self.GetInfo("pepper_name"):
6966 return self.GetInfo("pepper_name")
6967 return self.name
6969 def MakeTypedCmdArgString(self, prefix, add_comma = False):
6970 """Gets a typed list of arguments as they need to be for command buffers."""
6971 args = self.GetCmdArgs()
6972 arg_string = ", ".join(
6973 ["%s %s%s" % (arg.type, prefix, arg.name) for arg in args])
6974 return self.__MaybePrependComma(arg_string, add_comma)
6976 def MakeCmdArgString(self, prefix, add_comma = False):
6977 """Gets the list of arguments as they need to be for command buffers."""
6978 args = self.GetCmdArgs()
6979 arg_string = ", ".join(
6980 ["%s%s" % (prefix, arg.name) for arg in args])
6981 return self.__MaybePrependComma(arg_string, add_comma)
6983 def MakeTypedInitString(self, prefix, add_comma = False):
6984 """Gets a typed list of arguments as they need to be for cmd Init/Set."""
6985 args = self.GetInitArgs()
6986 arg_string = ", ".join(
6987 ["%s %s%s" % (arg.type, prefix, arg.name) for arg in args])
6988 return self.__MaybePrependComma(arg_string, add_comma)
6990 def MakeInitString(self, prefix, add_comma = False):
6991 """Gets the list of arguments as they need to be for cmd Init/Set."""
6992 args = self.GetInitArgs()
6993 arg_string = ", ".join(
6994 ["%s%s" % (prefix, arg.name) for arg in args])
6995 return self.__MaybePrependComma(arg_string, add_comma)
6997 def MakeLogArgString(self):
6998 """Makes a string of the arguments for the LOG macros"""
6999 args = self.GetOriginalArgs()
7000 return ' << ", " << '.join([arg.GetLogArg() for arg in args])
7002 def WriteCommandDescription(self, file):
7003 """Writes a description of the command."""
7004 file.Write("//! Command that corresponds to gl%s.\n" % self.original_name)
7006 def WriteHandlerValidation(self, file):
7007 """Writes validation code for the function."""
7008 for arg in self.GetOriginalArgs():
7009 arg.WriteValidationCode(file, self)
7010 self.WriteValidationCode(file)
7012 def WriteHandlerImplementation(self, file):
7013 """Writes the handler implementation for this command."""
7014 self.type_handler.WriteHandlerImplementation(self, file)
7016 def WriteValidationCode(self, file):
7017 """Writes the validation code for a command."""
7018 pass
7020 def WriteCmdFlag(self, file):
7021 """Writes the cmd cmd_flags constant."""
7022 flags = []
7023 # By default trace only at the highest level 3.
7024 trace_level = int(self.GetInfo('trace_level', default = 3))
7025 if trace_level not in xrange(0, 4):
7026 raise KeyError("Unhandled trace_level: %d" % trace_level)
7028 flags.append('CMD_FLAG_SET_TRACE_LEVEL(%d)' % trace_level)
7030 if len(flags) > 0:
7031 cmd_flags = ' | '.join(flags)
7032 else:
7033 cmd_flags = 0
7035 file.Write(" static const uint8 cmd_flags = %s;\n" % cmd_flags)
7038 def WriteCmdArgFlag(self, file):
7039 """Writes the cmd kArgFlags constant."""
7040 file.Write(" static const cmd::ArgFlags kArgFlags = cmd::kFixed;\n")
7042 def WriteCmdComputeSize(self, file):
7043 """Writes the ComputeSize function for the command."""
7044 file.Write(" static uint32_t ComputeSize() {\n")
7045 file.Write(
7046 " return static_cast<uint32_t>(sizeof(ValueType)); // NOLINT\n")
7047 file.Write(" }\n")
7048 file.Write("\n")
7050 def WriteCmdSetHeader(self, file):
7051 """Writes the cmd's SetHeader function."""
7052 file.Write(" void SetHeader() {\n")
7053 file.Write(" header.SetCmd<ValueType>();\n")
7054 file.Write(" }\n")
7055 file.Write("\n")
7057 def WriteCmdInit(self, file):
7058 """Writes the cmd's Init function."""
7059 file.Write(" void Init(%s) {\n" % self.MakeTypedCmdArgString("_"))
7060 file.Write(" SetHeader();\n")
7061 args = self.GetCmdArgs()
7062 for arg in args:
7063 file.Write(" %s = _%s;\n" % (arg.name, arg.name))
7064 file.Write(" }\n")
7065 file.Write("\n")
7067 def WriteCmdSet(self, file):
7068 """Writes the cmd's Set function."""
7069 copy_args = self.MakeCmdArgString("_", False)
7070 file.Write(" void* Set(void* cmd%s) {\n" %
7071 self.MakeTypedCmdArgString("_", True))
7072 file.Write(" static_cast<ValueType*>(cmd)->Init(%s);\n" % copy_args)
7073 file.Write(" return NextCmdAddress<ValueType>(cmd);\n")
7074 file.Write(" }\n")
7075 file.Write("\n")
7077 def WriteStruct(self, file):
7078 self.type_handler.WriteStruct(self, file)
7080 def WriteDocs(self, file):
7081 self.type_handler.WriteDocs(self, file)
7083 def WriteCmdHelper(self, file):
7084 """Writes the cmd's helper."""
7085 self.type_handler.WriteCmdHelper(self, file)
7087 def WriteServiceImplementation(self, file):
7088 """Writes the service implementation for a command."""
7089 self.type_handler.WriteServiceImplementation(self, file)
7091 def WriteServiceUnitTest(self, file, *extras):
7092 """Writes the service implementation for a command."""
7093 self.type_handler.WriteServiceUnitTest(self, file, *extras)
7095 def WriteGLES2CLibImplementation(self, file):
7096 """Writes the GLES2 C Lib Implemention."""
7097 self.type_handler.WriteGLES2CLibImplementation(self, file)
7099 def WriteGLES2InterfaceHeader(self, file):
7100 """Writes the GLES2 Interface declaration."""
7101 self.type_handler.WriteGLES2InterfaceHeader(self, file)
7103 def WriteGLES2InterfaceStub(self, file):
7104 """Writes the GLES2 Interface Stub declaration."""
7105 self.type_handler.WriteGLES2InterfaceStub(self, file)
7107 def WriteGLES2InterfaceStubImpl(self, file):
7108 """Writes the GLES2 Interface Stub declaration."""
7109 self.type_handler.WriteGLES2InterfaceStubImpl(self, file)
7111 def WriteGLES2ImplementationHeader(self, file):
7112 """Writes the GLES2 Implemention declaration."""
7113 self.type_handler.WriteGLES2ImplementationHeader(self, file)
7115 def WriteGLES2Implementation(self, file):
7116 """Writes the GLES2 Implemention definition."""
7117 self.type_handler.WriteGLES2Implementation(self, file)
7119 def WriteGLES2TraceImplementationHeader(self, file):
7120 """Writes the GLES2 Trace Implemention declaration."""
7121 self.type_handler.WriteGLES2TraceImplementationHeader(self, file)
7123 def WriteGLES2TraceImplementation(self, file):
7124 """Writes the GLES2 Trace Implemention definition."""
7125 self.type_handler.WriteGLES2TraceImplementation(self, file)
7127 def WriteGLES2Header(self, file):
7128 """Writes the GLES2 Implemention unit test."""
7129 self.type_handler.WriteGLES2Header(self, file)
7131 def WriteGLES2ImplementationUnitTest(self, file):
7132 """Writes the GLES2 Implemention unit test."""
7133 self.type_handler.WriteGLES2ImplementationUnitTest(self, file)
7135 def WriteDestinationInitalizationValidation(self, file):
7136 """Writes the client side destintion initialization validation."""
7137 self.type_handler.WriteDestinationInitalizationValidation(self, file)
7139 def WriteFormatTest(self, file):
7140 """Writes the cmd's format test."""
7141 self.type_handler.WriteFormatTest(self, file)
7144 class PepperInterface(object):
7145 """A class that represents a function."""
7147 def __init__(self, info):
7148 self.name = info["name"]
7149 self.dev = info["dev"]
7151 def GetName(self):
7152 return self.name
7154 def GetInterfaceName(self):
7155 upperint = ""
7156 dev = ""
7157 if self.name:
7158 upperint = "_" + self.name.upper()
7159 if self.dev:
7160 dev = "_DEV"
7161 return "PPB_OPENGLES2%s%s_INTERFACE" % (upperint, dev)
7163 def GetInterfaceString(self):
7164 dev = ""
7165 if self.dev:
7166 dev = "(Dev)"
7167 return "PPB_OpenGLES2%s%s" % (self.name, dev)
7169 def GetStructName(self):
7170 dev = ""
7171 if self.dev:
7172 dev = "_Dev"
7173 return "PPB_OpenGLES2%s%s" % (self.name, dev)
7176 class ImmediateFunction(Function):
7177 """A class that represnets an immediate function command."""
7179 def __init__(self, func):
7180 Function.__init__(
7181 self,
7182 "%sImmediate" % func.name,
7183 func.info)
7185 def InitFunction(self):
7186 # Override args in original_args and args_for_cmds with immediate versions
7187 # of the args.
7189 new_original_args = []
7190 for arg in self.original_args:
7191 new_arg = arg.GetImmediateVersion()
7192 if new_arg:
7193 new_original_args.append(new_arg)
7194 self.original_args = new_original_args
7196 new_args_for_cmds = []
7197 for arg in self.args_for_cmds:
7198 new_arg = arg.GetImmediateVersion()
7199 if new_arg:
7200 new_args_for_cmds.append(new_arg)
7202 self.args_for_cmds = new_args_for_cmds
7204 Function.InitFunction(self)
7206 def IsImmediate(self):
7207 return True
7209 def WriteCommandDescription(self, file):
7210 """Overridden from Function"""
7211 file.Write("//! Immediate version of command that corresponds to gl%s.\n" %
7212 self.original_name)
7214 def WriteServiceImplementation(self, file):
7215 """Overridden from Function"""
7216 self.type_handler.WriteImmediateServiceImplementation(self, file)
7218 def WriteHandlerImplementation(self, file):
7219 """Overridden from Function"""
7220 self.type_handler.WriteImmediateHandlerImplementation(self, file)
7222 def WriteServiceUnitTest(self, file, *extras):
7223 """Writes the service implementation for a command."""
7224 self.type_handler.WriteImmediateServiceUnitTest(self, file, *extras)
7226 def WriteValidationCode(self, file):
7227 """Overridden from Function"""
7228 self.type_handler.WriteImmediateValidationCode(self, file)
7230 def WriteCmdArgFlag(self, file):
7231 """Overridden from Function"""
7232 file.Write(" static const cmd::ArgFlags kArgFlags = cmd::kAtLeastN;\n")
7234 def WriteCmdComputeSize(self, file):
7235 """Overridden from Function"""
7236 self.type_handler.WriteImmediateCmdComputeSize(self, file)
7238 def WriteCmdSetHeader(self, file):
7239 """Overridden from Function"""
7240 self.type_handler.WriteImmediateCmdSetHeader(self, file)
7242 def WriteCmdInit(self, file):
7243 """Overridden from Function"""
7244 self.type_handler.WriteImmediateCmdInit(self, file)
7246 def WriteCmdSet(self, file):
7247 """Overridden from Function"""
7248 self.type_handler.WriteImmediateCmdSet(self, file)
7250 def WriteCmdHelper(self, file):
7251 """Overridden from Function"""
7252 self.type_handler.WriteImmediateCmdHelper(self, file)
7254 def WriteFormatTest(self, file):
7255 """Overridden from Function"""
7256 self.type_handler.WriteImmediateFormatTest(self, file)
7259 class BucketFunction(Function):
7260 """A class that represnets a bucket version of a function command."""
7262 def __init__(self, func):
7263 Function.__init__(
7264 self,
7265 "%sBucket" % func.name,
7266 func.info)
7268 def InitFunction(self):
7269 # Override args in original_args and args_for_cmds with bucket versions
7270 # of the args.
7272 new_original_args = []
7273 for arg in self.original_args:
7274 new_arg = arg.GetBucketVersion()
7275 if new_arg:
7276 new_original_args.append(new_arg)
7277 self.original_args = new_original_args
7279 new_args_for_cmds = []
7280 for arg in self.args_for_cmds:
7281 new_arg = arg.GetBucketVersion()
7282 if new_arg:
7283 new_args_for_cmds.append(new_arg)
7285 self.args_for_cmds = new_args_for_cmds
7287 Function.InitFunction(self)
7289 def WriteCommandDescription(self, file):
7290 """Overridden from Function"""
7291 file.Write("//! Bucket version of command that corresponds to gl%s.\n" %
7292 self.original_name)
7294 def WriteServiceImplementation(self, file):
7295 """Overridden from Function"""
7296 self.type_handler.WriteBucketServiceImplementation(self, file)
7298 def WriteHandlerImplementation(self, file):
7299 """Overridden from Function"""
7300 self.type_handler.WriteBucketHandlerImplementation(self, file)
7302 def WriteServiceUnitTest(self, file, *extras):
7303 """Writes the service implementation for a command."""
7304 self.type_handler.WriteBucketServiceUnitTest(self, file, *extras)
7307 def CreateArg(arg_string):
7308 """Creates an Argument."""
7309 arg_parts = arg_string.split()
7310 if len(arg_parts) == 1 and arg_parts[0] == 'void':
7311 return None
7312 # Is this a pointer argument?
7313 elif arg_string.find('*') >= 0:
7314 return PointerArgument(
7315 arg_parts[-1],
7316 " ".join(arg_parts[0:-1]))
7317 # Is this a resource argument? Must come after pointer check.
7318 elif arg_parts[0].startswith('GLidBind'):
7319 return ResourceIdBindArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
7320 elif arg_parts[0].startswith('GLidZero'):
7321 return ResourceIdZeroArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
7322 elif arg_parts[0].startswith('GLid'):
7323 return ResourceIdArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
7324 elif arg_parts[0].startswith('GLenum') and len(arg_parts[0]) > 6:
7325 return EnumArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
7326 elif arg_parts[0].startswith('GLboolean') and len(arg_parts[0]) > 9:
7327 return ValidatedBoolArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
7328 elif arg_parts[0].startswith('GLboolean'):
7329 return BoolArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
7330 elif arg_parts[0].startswith('GLintUniformLocation'):
7331 return UniformLocationArgument(arg_parts[-1])
7332 elif (arg_parts[0].startswith('GLint') and len(arg_parts[0]) > 5 and
7333 not arg_parts[0].startswith('GLintptr')):
7334 return IntArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
7335 elif (arg_parts[0].startswith('GLsizeiNotNegative') or
7336 arg_parts[0].startswith('GLintptrNotNegative')):
7337 return SizeNotNegativeArgument(arg_parts[-1],
7338 " ".join(arg_parts[0:-1]),
7339 arg_parts[0][0:-11])
7340 elif arg_parts[0].startswith('GLsize'):
7341 return SizeArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
7342 else:
7343 return Argument(arg_parts[-1], " ".join(arg_parts[0:-1]))
7346 class GLGenerator(object):
7347 """A class to generate GL command buffers."""
7349 _function_re = re.compile(r'GL_APICALL(.*?)GL_APIENTRY (.*?) \((.*?)\);')
7351 def __init__(self, verbose):
7352 self.original_functions = []
7353 self.functions = []
7354 self.verbose = verbose
7355 self.errors = 0
7356 self.pepper_interfaces = []
7357 self.interface_info = {}
7359 for interface in _PEPPER_INTERFACES:
7360 interface = PepperInterface(interface)
7361 self.pepper_interfaces.append(interface)
7362 self.interface_info[interface.GetName()] = interface
7364 def AddFunction(self, func):
7365 """Adds a function."""
7366 self.functions.append(func)
7368 def GetFunctionInfo(self, name):
7369 """Gets a type info for the given function name."""
7370 if name in _FUNCTION_INFO:
7371 func_info = _FUNCTION_INFO[name].copy()
7372 else:
7373 func_info = {}
7375 if not 'type' in func_info:
7376 func_info['type'] = ''
7378 return func_info
7380 def Log(self, msg):
7381 """Prints something if verbose is true."""
7382 if self.verbose:
7383 print msg
7385 def Error(self, msg):
7386 """Prints an error."""
7387 print "Error: %s" % msg
7388 self.errors += 1
7390 def WriteLicense(self, file):
7391 """Writes the license."""
7392 file.Write(_LICENSE)
7394 def WriteNamespaceOpen(self, file):
7395 """Writes the code for the namespace."""
7396 file.Write("namespace gpu {\n")
7397 file.Write("namespace gles2 {\n")
7398 file.Write("\n")
7400 def WriteNamespaceClose(self, file):
7401 """Writes the code to close the namespace."""
7402 file.Write("} // namespace gles2\n")
7403 file.Write("} // namespace gpu\n")
7404 file.Write("\n")
7406 def ParseGLH(self, filename):
7407 """Parses the cmd_buffer_functions.txt file and extracts the functions"""
7408 f = open(filename, "r")
7409 functions = f.read()
7410 f.close()
7411 for line in functions.splitlines():
7412 match = self._function_re.match(line)
7413 if match:
7414 func_name = match.group(2)[2:]
7415 func_info = self.GetFunctionInfo(func_name)
7416 if func_info['type'] == 'Noop':
7417 continue
7419 parsed_func_info = {
7420 'original_name': func_name,
7421 'original_args': match.group(3),
7422 'return_type': match.group(1).strip(),
7425 for k in parsed_func_info.keys():
7426 if not k in func_info:
7427 func_info[k] = parsed_func_info[k]
7429 f = Function(func_name, func_info)
7430 self.original_functions.append(f)
7432 #for arg in f.GetOriginalArgs():
7433 # if not isinstance(arg, EnumArgument) and arg.type == 'GLenum':
7434 # self.Log("%s uses bare GLenum %s." % (func_name, arg.name))
7436 gen_cmd = f.GetInfo('gen_cmd')
7437 if gen_cmd == True or gen_cmd == None:
7438 if f.type_handler.NeedsDataTransferFunction(f):
7439 methods = f.GetDataTransferMethods()
7440 if 'immediate' in methods:
7441 self.AddFunction(ImmediateFunction(f))
7442 if 'bucket' in methods:
7443 self.AddFunction(BucketFunction(f))
7444 if 'shm' in methods:
7445 self.AddFunction(f)
7446 else:
7447 self.AddFunction(f)
7449 self.Log("Auto Generated Functions : %d" %
7450 len([f for f in self.functions if f.can_auto_generate or
7451 (not f.IsType('') and not f.IsType('Custom') and
7452 not f.IsType('Todo'))]))
7454 funcs = [f for f in self.functions if not f.can_auto_generate and
7455 (f.IsType('') or f.IsType('Custom') or f.IsType('Todo'))]
7456 self.Log("Non Auto Generated Functions: %d" % len(funcs))
7458 for f in funcs:
7459 self.Log(" %-10s %-20s gl%s" % (f.info['type'], f.return_type, f.name))
7461 def WriteCommandIds(self, filename):
7462 """Writes the command buffer format"""
7463 file = CHeaderWriter(filename)
7464 file.Write("#define GLES2_COMMAND_LIST(OP) \\\n")
7465 id = 256
7466 for func in self.functions:
7467 file.Write(" %-60s /* %d */ \\\n" %
7468 ("OP(%s)" % func.name, id))
7469 id += 1
7470 file.Write("\n")
7472 file.Write("enum CommandId {\n")
7473 file.Write(" kStartPoint = cmd::kLastCommonId, "
7474 "// All GLES2 commands start after this.\n")
7475 file.Write("#define GLES2_CMD_OP(name) k ## name,\n")
7476 file.Write(" GLES2_COMMAND_LIST(GLES2_CMD_OP)\n")
7477 file.Write("#undef GLES2_CMD_OP\n")
7478 file.Write(" kNumCommands\n")
7479 file.Write("};\n")
7480 file.Write("\n")
7481 file.Close()
7483 def WriteFormat(self, filename):
7484 """Writes the command buffer format"""
7485 file = CHeaderWriter(filename)
7486 for func in self.functions:
7487 if True:
7488 #gen_cmd = func.GetInfo('gen_cmd')
7489 #if gen_cmd == True or gen_cmd == None:
7490 func.WriteStruct(file)
7491 file.Write("\n")
7492 file.Close()
7494 def WriteDocs(self, filename):
7495 """Writes the command buffer doc version of the commands"""
7496 file = CWriter(filename)
7497 for func in self.functions:
7498 if True:
7499 #gen_cmd = func.GetInfo('gen_cmd')
7500 #if gen_cmd == True or gen_cmd == None:
7501 func.WriteDocs(file)
7502 file.Write("\n")
7503 file.Close()
7505 def WriteFormatTest(self, filename):
7506 """Writes the command buffer format test."""
7507 file = CHeaderWriter(
7508 filename,
7509 "// This file contains unit tests for gles2 commmands\n"
7510 "// It is included by gles2_cmd_format_test.cc\n"
7511 "\n")
7513 for func in self.functions:
7514 if True:
7515 #gen_cmd = func.GetInfo('gen_cmd')
7516 #if gen_cmd == True or gen_cmd == None:
7517 func.WriteFormatTest(file)
7519 file.Close()
7521 def WriteCmdHelperHeader(self, filename):
7522 """Writes the gles2 command helper."""
7523 file = CHeaderWriter(filename)
7525 for func in self.functions:
7526 if True:
7527 #gen_cmd = func.GetInfo('gen_cmd')
7528 #if gen_cmd == True or gen_cmd == None:
7529 func.WriteCmdHelper(file)
7531 file.Close()
7533 def WriteServiceContextStateHeader(self, filename):
7534 """Writes the service context state header."""
7535 file = CHeaderWriter(
7536 filename,
7537 "// It is included by context_state.h\n")
7538 file.Write("struct EnableFlags {\n")
7539 file.Write(" EnableFlags();\n")
7540 for capability in _CAPABILITY_FLAGS:
7541 file.Write(" bool %s;\n" % capability['name'])
7542 file.Write(" bool cached_%s;\n" % capability['name'])
7543 file.Write("};\n\n")
7545 for state_name in sorted(_STATES.keys()):
7546 state = _STATES[state_name]
7547 for item in state['states']:
7548 if isinstance(item['default'], list):
7549 file.Write("%s %s[%d];\n" % (item['type'], item['name'],
7550 len(item['default'])))
7551 else:
7552 file.Write("%s %s;\n" % (item['type'], item['name']))
7554 if item.get('cached', False):
7555 if isinstance(item['default'], list):
7556 file.Write("%s cached_%s[%d];\n" % (item['type'], item['name'],
7557 len(item['default'])))
7558 else:
7559 file.Write("%s cached_%s;\n" % (item['type'], item['name']))
7561 file.Write("\n")
7563 file.Write("""
7564 inline void SetDeviceCapabilityState(GLenum cap, bool enable) {
7565 switch (cap) {
7566 """)
7567 for capability in _CAPABILITY_FLAGS:
7568 file.Write("""\
7569 case GL_%s:
7570 """ % capability['name'].upper())
7571 file.Write("""\
7572 if (enable_flags.cached_%(name)s == enable &&
7573 !ignore_cached_state)
7574 return;
7575 enable_flags.cached_%(name)s = enable;
7576 break;
7577 """ % capability)
7579 file.Write("""\
7580 default:
7581 NOTREACHED();
7582 return;
7584 if (enable)
7585 glEnable(cap);
7586 else
7587 glDisable(cap);
7589 """)
7591 file.Close()
7593 def WriteClientContextStateHeader(self, filename):
7594 """Writes the client context state header."""
7595 file = CHeaderWriter(
7596 filename,
7597 "// It is included by client_context_state.h\n")
7598 file.Write("struct EnableFlags {\n")
7599 file.Write(" EnableFlags();\n")
7600 for capability in _CAPABILITY_FLAGS:
7601 file.Write(" bool %s;\n" % capability['name'])
7602 file.Write("};\n\n")
7604 file.Close()
7606 def WriteContextStateGetters(self, file, class_name):
7607 """Writes the state getters."""
7608 for gl_type in ["GLint", "GLfloat"]:
7609 file.Write("""
7610 bool %s::GetStateAs%s(
7611 GLenum pname, %s* params, GLsizei* num_written) const {
7612 switch (pname) {
7613 """ % (class_name, gl_type, gl_type))
7614 for state_name in sorted(_STATES.keys()):
7615 state = _STATES[state_name]
7616 if 'enum' in state:
7617 file.Write(" case %s:\n" % state['enum'])
7618 file.Write(" *num_written = %d;\n" % len(state['states']))
7619 file.Write(" if (params) {\n")
7620 for ndx,item in enumerate(state['states']):
7621 file.Write(" params[%d] = static_cast<%s>(%s);\n" %
7622 (ndx, gl_type, item['name']))
7623 file.Write(" }\n")
7624 file.Write(" return true;\n")
7625 else:
7626 for item in state['states']:
7627 file.Write(" case %s:\n" % item['enum'])
7628 if isinstance(item['default'], list):
7629 item_len = len(item['default'])
7630 file.Write(" *num_written = %d;\n" % item_len)
7631 file.Write(" if (params) {\n")
7632 if item['type'] == gl_type:
7633 file.Write(" memcpy(params, %s, sizeof(%s) * %d);\n" %
7634 (item['name'], item['type'], item_len))
7635 else:
7636 file.Write(" for (size_t i = 0; i < %s; ++i) {\n" %
7637 item_len)
7638 file.Write(" params[i] = %s;\n" %
7639 (GetGLGetTypeConversion(gl_type, item['type'],
7640 "%s[i]" % item['name'])))
7641 file.Write(" }\n");
7642 else:
7643 file.Write(" *num_written = 1;\n")
7644 file.Write(" if (params) {\n")
7645 file.Write(" params[0] = %s;\n" %
7646 (GetGLGetTypeConversion(gl_type, item['type'],
7647 item['name'])))
7648 file.Write(" }\n")
7649 file.Write(" return true;\n")
7650 for capability in _CAPABILITY_FLAGS:
7651 file.Write(" case GL_%s:\n" % capability['name'].upper())
7652 file.Write(" *num_written = 1;\n")
7653 file.Write(" if (params) {\n")
7654 file.Write(
7655 " params[0] = static_cast<%s>(enable_flags.%s);\n" %
7656 (gl_type, capability['name']))
7657 file.Write(" }\n")
7658 file.Write(" return true;\n")
7659 file.Write(""" default:
7660 return false;
7663 """)
7665 def WriteServiceContextStateImpl(self, filename):
7666 """Writes the context state service implementation."""
7667 file = CHeaderWriter(
7668 filename,
7669 "// It is included by context_state.cc\n")
7670 code = []
7671 for capability in _CAPABILITY_FLAGS:
7672 code.append("%s(%s)" %
7673 (capability['name'],
7674 ('false', 'true')['default' in capability]))
7675 code.append("cached_%s(%s)" %
7676 (capability['name'],
7677 ('false', 'true')['default' in capability]))
7678 file.Write("ContextState::EnableFlags::EnableFlags()\n : %s {\n}\n" %
7679 ",\n ".join(code))
7680 file.Write("\n")
7682 file.Write("void ContextState::Initialize() {\n")
7683 for state_name in sorted(_STATES.keys()):
7684 state = _STATES[state_name]
7685 for item in state['states']:
7686 if isinstance(item['default'], list):
7687 for ndx, value in enumerate(item['default']):
7688 file.Write(" %s[%d] = %s;\n" % (item['name'], ndx, value))
7689 else:
7690 file.Write(" %s = %s;\n" % (item['name'], item['default']))
7691 if item.get('cached', False):
7692 if isinstance(item['default'], list):
7693 for ndx, value in enumerate(item['default']):
7694 file.Write(" cached_%s[%d] = %s;\n" % (item['name'], ndx, value))
7695 else:
7696 file.Write(" cached_%s = %s;\n" % (item['name'], item['default']))
7697 file.Write("}\n")
7699 file.Write("""
7700 void ContextState::InitCapabilities(const ContextState* prev_state) const {
7701 """)
7702 def WriteCapabilities(test_prev):
7703 for capability in _CAPABILITY_FLAGS:
7704 capability_name = capability['name']
7705 if test_prev:
7706 file.Write(""" if (prev_state->enable_flags.cached_%s !=
7707 enable_flags.cached_%s)\n""" %
7708 (capability_name, capability_name))
7709 file.Write(" EnableDisable(GL_%s, enable_flags.cached_%s);\n" %
7710 (capability_name.upper(), capability_name))
7712 file.Write(" if (prev_state) {")
7713 WriteCapabilities(True)
7714 file.Write(" } else {")
7715 WriteCapabilities(False)
7716 file.Write(" }")
7718 file.Write("""}
7720 void ContextState::InitState(const ContextState *prev_state) const {
7721 """)
7723 def WriteStates(test_prev):
7724 # We need to sort the keys so the expectations match
7725 for state_name in sorted(_STATES.keys()):
7726 state = _STATES[state_name]
7727 if state['type'] == 'FrontBack':
7728 num_states = len(state['states'])
7729 for ndx, group in enumerate(Grouper(num_states / 2, state['states'])):
7730 if test_prev:
7731 file.Write(" if (")
7732 args = []
7733 for place, item in enumerate(group):
7734 item_name = CachedStateName(item)
7735 args.append('%s' % item_name)
7736 if test_prev:
7737 if place > 0:
7738 file.Write(' ||\n')
7739 file.Write("(%s != prev_state->%s)" % (item_name, item_name))
7740 if test_prev:
7741 file.Write(")\n")
7742 file.Write(
7743 " gl%s(%s, %s);\n" %
7744 (state['func'], ('GL_FRONT', 'GL_BACK')[ndx], ", ".join(args)))
7745 elif state['type'] == 'NamedParameter':
7746 for item in state['states']:
7747 item_name = CachedStateName(item)
7749 if 'extension_flag' in item:
7750 file.Write(" if (feature_info_->feature_flags().%s) {\n " %
7751 item['extension_flag'])
7752 if test_prev:
7753 if isinstance(item['default'], list):
7754 file.Write(" if (memcmp(prev_state->%s, %s, "
7755 "sizeof(%s) * %d)) {\n" %
7756 (item_name, item_name, item['type'],
7757 len(item['default'])))
7758 else:
7759 file.Write(" if (prev_state->%s != %s) {\n " %
7760 (item_name, item_name))
7761 file.Write(" gl%s(%s, %s);\n" %
7762 (state['func'],
7763 (item['enum_set']
7764 if 'enum_set' in item else item['enum']),
7765 item['name']))
7766 if test_prev:
7767 if 'extension_flag' in item:
7768 file.Write(" ")
7769 file.Write(" }")
7770 if 'extension_flag' in item:
7771 file.Write(" }")
7772 else:
7773 if 'extension_flag' in state:
7774 file.Write(" if (feature_info_->feature_flags().%s)\n " %
7775 state['extension_flag'])
7776 if test_prev:
7777 file.Write(" if (")
7778 args = []
7779 for place, item in enumerate(state['states']):
7780 item_name = CachedStateName(item)
7781 args.append('%s' % item_name)
7782 if test_prev:
7783 if place > 0:
7784 file.Write(' ||\n')
7785 file.Write("(%s != prev_state->%s)" %
7786 (item_name, item_name))
7787 if test_prev:
7788 file.Write(" )\n")
7789 file.Write(" gl%s(%s);\n" % (state['func'], ", ".join(args)))
7791 file.Write(" if (prev_state) {")
7792 WriteStates(True)
7793 file.Write(" } else {")
7794 WriteStates(False)
7795 file.Write(" }")
7796 file.Write("}\n")
7798 file.Write("""bool ContextState::GetEnabled(GLenum cap) const {
7799 switch (cap) {
7800 """)
7801 for capability in _CAPABILITY_FLAGS:
7802 file.Write(" case GL_%s:\n" % capability['name'].upper())
7803 file.Write(" return enable_flags.%s;\n" % capability['name'])
7804 file.Write(""" default:
7805 NOTREACHED();
7806 return false;
7809 """)
7811 self.WriteContextStateGetters(file, "ContextState")
7812 file.Close()
7814 def WriteClientContextStateImpl(self, filename):
7815 """Writes the context state client side implementation."""
7816 file = CHeaderWriter(
7817 filename,
7818 "// It is included by client_context_state.cc\n")
7819 code = []
7820 for capability in _CAPABILITY_FLAGS:
7821 code.append("%s(%s)" %
7822 (capability['name'],
7823 ('false', 'true')['default' in capability]))
7824 file.Write(
7825 "ClientContextState::EnableFlags::EnableFlags()\n : %s {\n}\n" %
7826 ",\n ".join(code))
7827 file.Write("\n")
7829 file.Write("""
7830 bool ClientContextState::SetCapabilityState(
7831 GLenum cap, bool enabled, bool* changed) {
7832 *changed = false;
7833 switch (cap) {
7834 """)
7835 for capability in _CAPABILITY_FLAGS:
7836 file.Write(" case GL_%s:\n" % capability['name'].upper())
7837 file.Write(""" if (enable_flags.%(name)s != enabled) {
7838 *changed = true;
7839 enable_flags.%(name)s = enabled;
7841 return true;
7842 """ % capability)
7843 file.Write(""" default:
7844 return false;
7847 """)
7848 file.Write("""bool ClientContextState::GetEnabled(
7849 GLenum cap, bool* enabled) const {
7850 switch (cap) {
7851 """)
7852 for capability in _CAPABILITY_FLAGS:
7853 file.Write(" case GL_%s:\n" % capability['name'].upper())
7854 file.Write(" *enabled = enable_flags.%s;\n" % capability['name'])
7855 file.Write(" return true;\n")
7856 file.Write(""" default:
7857 return false;
7860 """)
7861 file.Close()
7863 def WriteServiceImplementation(self, filename):
7864 """Writes the service decorder implementation."""
7865 file = CHeaderWriter(
7866 filename,
7867 "// It is included by gles2_cmd_decoder.cc\n")
7869 for func in self.functions:
7870 if True:
7871 #gen_cmd = func.GetInfo('gen_cmd')
7872 #if gen_cmd == True or gen_cmd == None:
7873 func.WriteServiceImplementation(file)
7875 file.Write("""
7876 bool GLES2DecoderImpl::SetCapabilityState(GLenum cap, bool enabled) {
7877 switch (cap) {
7878 """)
7879 for capability in _CAPABILITY_FLAGS:
7880 file.Write(" case GL_%s:\n" % capability['name'].upper())
7881 if 'state_flag' in capability:
7883 file.Write("""\
7884 state_.enable_flags.%(name)s = enabled;
7885 if (state_.enable_flags.cached_%(name)s != enabled
7886 || state_.ignore_cached_state) {
7887 %(state_flag)s = true;
7889 return false;
7890 """ % capability)
7891 else:
7892 file.Write("""\
7893 state_.enable_flags.%(name)s = enabled;
7894 if (state_.enable_flags.cached_%(name)s != enabled
7895 || state_.ignore_cached_state) {
7896 state_.enable_flags.cached_%(name)s = enabled;
7897 return true;
7899 return false;
7900 """ % capability)
7901 file.Write(""" default:
7902 NOTREACHED();
7903 return false;
7906 """)
7907 file.Close()
7909 def WriteServiceUnitTests(self, filename):
7910 """Writes the service decorder unit tests."""
7911 num_tests = len(self.functions)
7912 FUNCTIONS_PER_FILE = 98 # hard code this so it doesn't change.
7913 count = 0
7914 for test_num in range(0, num_tests, FUNCTIONS_PER_FILE):
7915 count += 1
7916 name = filename % count
7917 file = CHeaderWriter(
7918 name,
7919 "// It is included by gles2_cmd_decoder_unittest_%d.cc\n" % count)
7920 test_name = 'GLES2DecoderTest%d' % count
7921 end = test_num + FUNCTIONS_PER_FILE
7922 if end > num_tests:
7923 end = num_tests
7924 for idx in range(test_num, end):
7925 func = self.functions[idx]
7927 # Do any filtering of the functions here, so that the functions
7928 # will not move between the numbered files if filtering properties
7929 # are changed.
7930 if func.GetInfo('extension_flag'):
7931 continue
7933 if True:
7934 #gen_cmd = func.GetInfo('gen_cmd')
7935 #if gen_cmd == True or gen_cmd == None:
7936 if func.GetInfo('unit_test') == False:
7937 file.Write("// TODO(gman): %s\n" % func.name)
7938 else:
7939 func.WriteServiceUnitTest(file, {
7940 'test_name': test_name
7943 file.Close()
7944 file = CHeaderWriter(
7945 filename % 0,
7946 "// It is included by gles2_cmd_decoder_unittest_base.cc\n")
7947 file.Write(
7948 """void GLES2DecoderTestBase::SetupInitCapabilitiesExpectations() {
7949 """)
7950 for capability in _CAPABILITY_FLAGS:
7951 file.Write(" ExpectEnableDisable(GL_%s, %s);\n" %
7952 (capability['name'].upper(),
7953 ('false', 'true')['default' in capability]))
7954 file.Write("""}
7956 void GLES2DecoderTestBase::SetupInitStateExpectations() {
7957 """)
7959 # We need to sort the keys so the expectations match
7960 for state_name in sorted(_STATES.keys()):
7961 state = _STATES[state_name]
7962 if state['type'] == 'FrontBack':
7963 num_states = len(state['states'])
7964 for ndx, group in enumerate(Grouper(num_states / 2, state['states'])):
7965 args = []
7966 for item in group:
7967 if 'expected' in item:
7968 args.append(item['expected'])
7969 else:
7970 args.append(item['default'])
7971 file.Write(
7972 " EXPECT_CALL(*gl_, %s(%s, %s))\n" %
7973 (state['func'], ('GL_FRONT', 'GL_BACK')[ndx], ", ".join(args)))
7974 file.Write(" .Times(1)\n")
7975 file.Write(" .RetiresOnSaturation();\n")
7976 elif state['type'] == 'NamedParameter':
7977 for item in state['states']:
7978 if 'extension_flag' in item:
7979 file.Write(" if (group_->feature_info()->feature_flags().%s) {\n" %
7980 item['extension_flag'])
7981 file.Write(" ")
7982 expect_value = item['default']
7983 if isinstance(expect_value, list):
7984 # TODO: Currently we do not check array values.
7985 expect_value = "_"
7987 file.Write(
7988 " EXPECT_CALL(*gl_, %s(%s, %s))\n" %
7989 (state['func'],
7990 (item['enum_set']
7991 if 'enum_set' in item else item['enum']),
7992 expect_value))
7993 file.Write(" .Times(1)\n")
7994 file.Write(" .RetiresOnSaturation();\n")
7995 if 'extension_flag' in item:
7996 file.Write(" }\n")
7997 else:
7998 if 'extension_flag' in state:
7999 file.Write(" if (group_->feature_info()->feature_flags().%s) {\n" %
8000 state['extension_flag'])
8001 file.Write(" ")
8002 args = []
8003 for item in state['states']:
8004 if 'expected' in item:
8005 args.append(item['expected'])
8006 else:
8007 args.append(item['default'])
8008 # TODO: Currently we do not check array values.
8009 args = ["_" if isinstance(arg, list) else arg for arg in args]
8010 file.Write(" EXPECT_CALL(*gl_, %s(%s))\n" %
8011 (state['func'], ", ".join(args)))
8012 file.Write(" .Times(1)\n")
8013 file.Write(" .RetiresOnSaturation();\n")
8014 if 'extension_flag' in state:
8015 file.Write(" }\n")
8016 file.Write("""}
8017 """)
8018 file.Close()
8020 def WriteServiceUnitTestsForExtensions(self, filename):
8021 """Writes the service decorder unit tests for functions with extension_flag.
8023 The functions are special in that they need a specific unit test
8024 baseclass to turn on the extension.
8026 functions = [f for f in self.functions if f.GetInfo('extension_flag')]
8027 file = CHeaderWriter(
8028 filename,
8029 "// It is included by gles2_cmd_decoder_unittest_extensions.cc\n")
8030 for func in functions:
8031 if True:
8032 if func.GetInfo('unit_test') == False:
8033 file.Write("// TODO(gman): %s\n" % func.name)
8034 else:
8035 extension = ToCamelCase(
8036 ToGLExtensionString(func.GetInfo('extension_flag')))
8037 func.WriteServiceUnitTest(file, {
8038 'test_name': 'GLES2DecoderTestWith%s' % extension
8041 file.Close()
8043 def WriteGLES2Header(self, filename):
8044 """Writes the GLES2 header."""
8045 file = CHeaderWriter(
8046 filename,
8047 "// This file contains Chromium-specific GLES2 declarations.\n\n")
8049 for func in self.original_functions:
8050 func.WriteGLES2Header(file)
8052 file.Write("\n")
8053 file.Close()
8055 def WriteGLES2CLibImplementation(self, filename):
8056 """Writes the GLES2 c lib implementation."""
8057 file = CHeaderWriter(
8058 filename,
8059 "// These functions emulate GLES2 over command buffers.\n")
8061 for func in self.original_functions:
8062 func.WriteGLES2CLibImplementation(file)
8064 file.Write("""
8065 namespace gles2 {
8067 extern const NameToFunc g_gles2_function_table[] = {
8068 """)
8069 for func in self.original_functions:
8070 file.Write(
8071 ' { "gl%s", reinterpret_cast<GLES2FunctionPointer>(gl%s), },\n' %
8072 (func.name, func.name))
8073 file.Write(""" { NULL, NULL, },
8076 } // namespace gles2
8077 """)
8078 file.Close()
8080 def WriteGLES2InterfaceHeader(self, filename):
8081 """Writes the GLES2 interface header."""
8082 file = CHeaderWriter(
8083 filename,
8084 "// This file is included by gles2_interface.h to declare the\n"
8085 "// GL api functions.\n")
8086 for func in self.original_functions:
8087 func.WriteGLES2InterfaceHeader(file)
8088 file.Close()
8090 def WriteGLES2InterfaceStub(self, filename):
8091 """Writes the GLES2 interface stub header."""
8092 file = CHeaderWriter(
8093 filename,
8094 "// This file is included by gles2_interface_stub.h.\n")
8095 for func in self.original_functions:
8096 func.WriteGLES2InterfaceStub(file)
8097 file.Close()
8099 def WriteGLES2InterfaceStubImpl(self, filename):
8100 """Writes the GLES2 interface header."""
8101 file = CHeaderWriter(
8102 filename,
8103 "// This file is included by gles2_interface_stub.cc.\n")
8104 for func in self.original_functions:
8105 func.WriteGLES2InterfaceStubImpl(file)
8106 file.Close()
8108 def WriteGLES2ImplementationHeader(self, filename):
8109 """Writes the GLES2 Implementation header."""
8110 file = CHeaderWriter(
8111 filename,
8112 "// This file is included by gles2_implementation.h to declare the\n"
8113 "// GL api functions.\n")
8114 for func in self.original_functions:
8115 func.WriteGLES2ImplementationHeader(file)
8116 file.Close()
8118 def WriteGLES2Implementation(self, filename):
8119 """Writes the GLES2 Implementation."""
8120 file = CHeaderWriter(
8121 filename,
8122 "// This file is included by gles2_implementation.cc to define the\n"
8123 "// GL api functions.\n")
8124 for func in self.original_functions:
8125 func.WriteGLES2Implementation(file)
8126 file.Close()
8128 def WriteGLES2TraceImplementationHeader(self, filename):
8129 """Writes the GLES2 Trace Implementation header."""
8130 file = CHeaderWriter(
8131 filename,
8132 "// This file is included by gles2_trace_implementation.h\n")
8133 for func in self.original_functions:
8134 func.WriteGLES2TraceImplementationHeader(file)
8135 file.Close()
8137 def WriteGLES2TraceImplementation(self, filename):
8138 """Writes the GLES2 Trace Implementation."""
8139 file = CHeaderWriter(
8140 filename,
8141 "// This file is included by gles2_trace_implementation.cc\n")
8142 for func in self.original_functions:
8143 func.WriteGLES2TraceImplementation(file)
8144 file.Close()
8146 def WriteGLES2ImplementationUnitTests(self, filename):
8147 """Writes the GLES2 helper header."""
8148 file = CHeaderWriter(
8149 filename,
8150 "// This file is included by gles2_implementation.h to declare the\n"
8151 "// GL api functions.\n")
8152 for func in self.original_functions:
8153 func.WriteGLES2ImplementationUnitTest(file)
8154 file.Close()
8156 def WriteServiceUtilsHeader(self, filename):
8157 """Writes the gles2 auto generated utility header."""
8158 file = CHeaderWriter(filename)
8159 for name in sorted(_NAMED_TYPE_INFO.keys()):
8160 named_type = NamedType(_NAMED_TYPE_INFO[name])
8161 if named_type.IsConstant():
8162 continue
8163 file.Write("ValueValidator<%s> %s;\n" %
8164 (named_type.GetType(), ToUnderscore(name)))
8165 file.Write("\n")
8166 file.Close()
8168 def WriteServiceUtilsImplementation(self, filename):
8169 """Writes the gles2 auto generated utility implementation."""
8170 file = CHeaderWriter(filename)
8171 names = sorted(_NAMED_TYPE_INFO.keys())
8172 for name in names:
8173 named_type = NamedType(_NAMED_TYPE_INFO[name])
8174 if named_type.IsConstant():
8175 continue
8176 if named_type.GetValidValues():
8177 file.Write("static const %s valid_%s_table[] = {\n" %
8178 (named_type.GetType(), ToUnderscore(name)))
8179 for value in named_type.GetValidValues():
8180 file.Write(" %s,\n" % value)
8181 file.Write("};\n")
8182 file.Write("\n")
8183 file.Write("Validators::Validators()")
8184 pre = ' : '
8185 for count, name in enumerate(names):
8186 named_type = NamedType(_NAMED_TYPE_INFO[name])
8187 if named_type.IsConstant():
8188 continue
8189 if named_type.GetValidValues():
8190 code = """%(pre)s%(name)s(
8191 valid_%(name)s_table, arraysize(valid_%(name)s_table))"""
8192 else:
8193 code = "%(pre)s%(name)s()"
8194 file.Write(code % {
8195 'name': ToUnderscore(name),
8196 'pre': pre,
8198 pre = ',\n '
8199 file.Write(" {\n");
8200 file.Write("}\n\n");
8201 file.Close()
8203 def WriteCommonUtilsHeader(self, filename):
8204 """Writes the gles2 common utility header."""
8205 file = CHeaderWriter(filename)
8206 type_infos = sorted(_NAMED_TYPE_INFO.keys())
8207 for type_info in type_infos:
8208 if _NAMED_TYPE_INFO[type_info]['type'] == 'GLenum':
8209 file.Write("static std::string GetString%s(uint32_t value);\n" %
8210 type_info)
8211 file.Write("\n")
8212 file.Close()
8214 def WriteCommonUtilsImpl(self, filename):
8215 """Writes the gles2 common utility header."""
8216 enum_re = re.compile(r'\#define\s+(GL_[a-zA-Z0-9_]+)\s+([0-9A-Fa-fx]+)')
8217 dict = {}
8218 for fname in ['../../third_party/khronos/GLES2/gl2.h',
8219 '../../third_party/khronos/GLES2/gl2ext.h',
8220 '../../gpu/GLES2/gl2chromium.h',
8221 '../../gpu/GLES2/gl2extchromium.h']:
8222 lines = open(fname).readlines()
8223 for line in lines:
8224 m = enum_re.match(line)
8225 if m:
8226 name = m.group(1)
8227 value = m.group(2)
8228 if len(value) <= 10 and not value in dict:
8229 dict[value] = name
8231 file = CHeaderWriter(filename)
8232 file.Write("static const GLES2Util::EnumToString "
8233 "enum_to_string_table[] = {\n")
8234 for value in dict:
8235 file.Write(' { %s, "%s", },\n' % (value, dict[value]))
8236 file.Write("""};
8238 const GLES2Util::EnumToString* const GLES2Util::enum_to_string_table_ =
8239 enum_to_string_table;
8240 const size_t GLES2Util::enum_to_string_table_len_ =
8241 sizeof(enum_to_string_table) / sizeof(enum_to_string_table[0]);
8243 """)
8245 enums = sorted(_NAMED_TYPE_INFO.keys())
8246 for enum in enums:
8247 if _NAMED_TYPE_INFO[enum]['type'] == 'GLenum':
8248 file.Write("std::string GLES2Util::GetString%s(uint32_t value) {\n" %
8249 enum)
8250 if len(_NAMED_TYPE_INFO[enum]['valid']) > 0:
8251 file.Write(" static const EnumToString string_table[] = {\n")
8252 for value in _NAMED_TYPE_INFO[enum]['valid']:
8253 file.Write(' { %s, "%s" },\n' % (value, value))
8254 file.Write(""" };
8255 return GLES2Util::GetQualifiedEnumString(
8256 string_table, arraysize(string_table), value);
8259 """)
8260 else:
8261 file.Write(""" return GLES2Util::GetQualifiedEnumString(
8262 NULL, 0, value);
8265 """)
8266 file.Close()
8268 def WritePepperGLES2Interface(self, filename, dev):
8269 """Writes the Pepper OpenGLES interface definition."""
8270 file = CHeaderWriter(
8271 filename,
8272 "// OpenGL ES interface.\n")
8274 file.Write("#include \"ppapi/c/pp_resource.h\"\n")
8275 if dev:
8276 file.Write("#include \"ppapi/c/ppb_opengles2.h\"\n\n")
8277 else:
8278 file.Write("\n#ifndef __gl2_h_\n")
8279 for (k, v) in _GL_TYPES.iteritems():
8280 file.Write("typedef %s %s;\n" % (v, k))
8281 file.Write("#ifdef _WIN64\n")
8282 for (k, v) in _GL_TYPES_64.iteritems():
8283 file.Write("typedef %s %s;\n" % (v, k))
8284 file.Write("#else\n")
8285 for (k, v) in _GL_TYPES_32.iteritems():
8286 file.Write("typedef %s %s;\n" % (v, k))
8287 file.Write("#endif // _WIN64\n")
8288 file.Write("#endif // __gl2_h_\n\n")
8290 for interface in self.pepper_interfaces:
8291 if interface.dev != dev:
8292 continue
8293 file.Write("#define %s_1_0 \"%s;1.0\"\n" %
8294 (interface.GetInterfaceName(), interface.GetInterfaceString()))
8295 file.Write("#define %s %s_1_0\n" %
8296 (interface.GetInterfaceName(), interface.GetInterfaceName()))
8298 file.Write("\nstruct %s {\n" % interface.GetStructName())
8299 for func in self.original_functions:
8300 if not func.InPepperInterface(interface):
8301 continue
8303 original_arg = func.MakeTypedPepperArgString("")
8304 context_arg = "PP_Resource context"
8305 if len(original_arg):
8306 arg = context_arg + ", " + original_arg
8307 else:
8308 arg = context_arg
8309 file.Write(" %s (*%s)(%s);\n" %
8310 (func.return_type, func.GetPepperName(), arg))
8311 file.Write("};\n\n")
8314 file.Close()
8316 def WritePepperGLES2Implementation(self, filename):
8317 """Writes the Pepper OpenGLES interface implementation."""
8319 file = CWriter(filename)
8320 file.Write(_LICENSE)
8321 file.Write(_DO_NOT_EDIT_WARNING)
8323 file.Write("#include \"ppapi/shared_impl/ppb_opengles2_shared.h\"\n\n")
8324 file.Write("#include \"base/logging.h\"\n")
8325 file.Write("#include \"gpu/command_buffer/client/gles2_implementation.h\"\n")
8326 file.Write("#include \"ppapi/shared_impl/ppb_graphics_3d_shared.h\"\n")
8327 file.Write("#include \"ppapi/thunk/enter.h\"\n\n")
8329 file.Write("namespace ppapi {\n\n")
8330 file.Write("namespace {\n\n")
8332 file.Write("typedef thunk::EnterResource<thunk::PPB_Graphics3D_API>"
8333 " Enter3D;\n\n")
8335 file.Write("gpu::gles2::GLES2Implementation* ToGles2Impl(Enter3D*"
8336 " enter) {\n")
8337 file.Write(" DCHECK(enter);\n")
8338 file.Write(" DCHECK(enter->succeeded());\n")
8339 file.Write(" return static_cast<PPB_Graphics3D_Shared*>(enter->object())->"
8340 "gles2_impl();\n");
8341 file.Write("}\n\n");
8343 for func in self.original_functions:
8344 if not func.InAnyPepperExtension():
8345 continue
8347 original_arg = func.MakeTypedPepperArgString("")
8348 context_arg = "PP_Resource context_id"
8349 if len(original_arg):
8350 arg = context_arg + ", " + original_arg
8351 else:
8352 arg = context_arg
8353 file.Write("%s %s(%s) {\n" %
8354 (func.return_type, func.GetPepperName(), arg))
8355 file.Write(" Enter3D enter(context_id, true);\n")
8356 file.Write(" if (enter.succeeded()) {\n")
8358 return_str = "" if func.return_type == "void" else "return "
8359 file.Write(" %sToGles2Impl(&enter)->%s(%s);\n" %
8360 (return_str, func.original_name,
8361 func.MakeOriginalArgString("")))
8362 file.Write(" }")
8363 if func.return_type == "void":
8364 file.Write("\n")
8365 else:
8366 file.Write(" else {\n")
8367 file.Write(" return %s;\n" % func.GetErrorReturnString())
8368 file.Write(" }\n")
8369 file.Write("}\n\n")
8371 file.Write("} // namespace\n")
8373 for interface in self.pepper_interfaces:
8374 file.Write("const %s* PPB_OpenGLES2_Shared::Get%sInterface() {\n" %
8375 (interface.GetStructName(), interface.GetName()))
8376 file.Write(" static const struct %s "
8377 "ppb_opengles2 = {\n" % interface.GetStructName())
8378 file.Write(" &")
8379 file.Write(",\n &".join(
8380 f.GetPepperName() for f in self.original_functions
8381 if f.InPepperInterface(interface)))
8382 file.Write("\n")
8384 file.Write(" };\n")
8385 file.Write(" return &ppb_opengles2;\n")
8386 file.Write("}\n")
8388 file.Write("} // namespace ppapi\n")
8389 file.Close()
8391 def WriteGLES2ToPPAPIBridge(self, filename):
8392 """Connects GLES2 helper library to PPB_OpenGLES2 interface"""
8394 file = CWriter(filename)
8395 file.Write(_LICENSE)
8396 file.Write(_DO_NOT_EDIT_WARNING)
8398 file.Write("#ifndef GL_GLEXT_PROTOTYPES\n")
8399 file.Write("#define GL_GLEXT_PROTOTYPES\n")
8400 file.Write("#endif\n")
8401 file.Write("#include <GLES2/gl2.h>\n")
8402 file.Write("#include <GLES2/gl2ext.h>\n")
8403 file.Write("#include \"ppapi/lib/gl/gles2/gl2ext_ppapi.h\"\n\n")
8405 for func in self.original_functions:
8406 if not func.InAnyPepperExtension():
8407 continue
8409 interface = self.interface_info[func.GetInfo('pepper_interface') or '']
8411 file.Write("%s GL_APIENTRY gl%s(%s) {\n" %
8412 (func.return_type, func.GetPepperName(),
8413 func.MakeTypedPepperArgString("")))
8414 return_str = "" if func.return_type == "void" else "return "
8415 interface_str = "glGet%sInterfacePPAPI()" % interface.GetName()
8416 original_arg = func.MakeOriginalArgString("")
8417 context_arg = "glGetCurrentContextPPAPI()"
8418 if len(original_arg):
8419 arg = context_arg + ", " + original_arg
8420 else:
8421 arg = context_arg
8422 if interface.GetName():
8423 file.Write(" const struct %s* ext = %s;\n" %
8424 (interface.GetStructName(), interface_str))
8425 file.Write(" if (ext)\n")
8426 file.Write(" %sext->%s(%s);\n" %
8427 (return_str, func.GetPepperName(), arg))
8428 if return_str:
8429 file.Write(" %s0;\n" % return_str)
8430 else:
8431 file.Write(" %s%s->%s(%s);\n" %
8432 (return_str, interface_str, func.GetPepperName(), arg))
8433 file.Write("}\n\n")
8434 file.Close()
8436 def WriteMojoGLCallVisitor(self, filename):
8437 """Provides the GL implementation for mojo"""
8438 file = CWriter(filename)
8439 file.Write(_LICENSE)
8440 file.Write(_DO_NOT_EDIT_WARNING)
8442 for func in self.original_functions:
8443 if not func.IsCoreGLFunction():
8444 continue
8445 file.Write("VISIT_GL_CALL(%s, %s, (%s), (%s))\n" %
8446 (func.name, func.return_type,
8447 func.MakeTypedOriginalArgString(""),
8448 func.MakeOriginalArgString("")))
8450 file.Close()
8452 def WriteMojoGLCallVisitorForExtension(self, filename, extension):
8453 """Provides the GL implementation for mojo for a particular extension"""
8454 file = CWriter(filename)
8455 file.Write(_LICENSE)
8456 file.Write(_DO_NOT_EDIT_WARNING)
8458 for func in self.original_functions:
8459 if func.GetInfo("extension") != extension:
8460 continue
8461 file.Write("VISIT_GL_CALL(%s, %s, (%s), (%s))\n" %
8462 (func.name, func.return_type,
8463 func.MakeTypedOriginalArgString(""),
8464 func.MakeOriginalArgString("")))
8466 file.Close()
8468 def Format(generated_files):
8469 for filename in generated_files:
8470 call(["clang-format", "-i", "-style=chromium", filename])
8472 def main(argv):
8473 """This is the main function."""
8474 parser = OptionParser()
8475 parser.add_option(
8476 "--output-dir",
8477 help="base directory for resulting files, under chrome/src. default is "
8478 "empty. Use this if you want the result stored under gen.")
8479 parser.add_option(
8480 "-v", "--verbose", action="store_true",
8481 help="prints more output.")
8483 (options, args) = parser.parse_args(args=argv)
8485 # Add in states and capabilites to GLState
8486 gl_state_valid = _NAMED_TYPE_INFO['GLState']['valid']
8487 for state_name in sorted(_STATES.keys()):
8488 state = _STATES[state_name]
8489 if 'extension_flag' in state:
8490 continue
8491 if 'enum' in state:
8492 if not state['enum'] in gl_state_valid:
8493 gl_state_valid.append(state['enum'])
8494 else:
8495 for item in state['states']:
8496 if 'extension_flag' in item:
8497 continue
8498 if not item['enum'] in gl_state_valid:
8499 gl_state_valid.append(item['enum'])
8500 for capability in _CAPABILITY_FLAGS:
8501 valid_value = "GL_%s" % capability['name'].upper()
8502 if not valid_value in gl_state_valid:
8503 gl_state_valid.append(valid_value)
8505 # This script lives under gpu/command_buffer, cd to base directory.
8506 os.chdir(os.path.dirname(__file__) + "/../..")
8508 gen = GLGenerator(options.verbose)
8509 gen.ParseGLH("gpu/command_buffer/cmd_buffer_functions.txt")
8511 # Support generating files under gen/
8512 if options.output_dir != None:
8513 os.chdir(options.output_dir)
8515 gen.WritePepperGLES2Interface("ppapi/c/ppb_opengles2.h", False)
8516 gen.WritePepperGLES2Interface("ppapi/c/dev/ppb_opengles2ext_dev.h", True)
8517 gen.WriteGLES2ToPPAPIBridge("ppapi/lib/gl/gles2/gles2.c")
8518 gen.WritePepperGLES2Implementation(
8519 "ppapi/shared_impl/ppb_opengles2_shared.cc")
8520 os.chdir("gpu/command_buffer")
8521 gen.WriteCommandIds("common/gles2_cmd_ids_autogen.h")
8522 gen.WriteFormat("common/gles2_cmd_format_autogen.h")
8523 gen.WriteFormatTest("common/gles2_cmd_format_test_autogen.h")
8524 gen.WriteGLES2InterfaceHeader("client/gles2_interface_autogen.h")
8525 gen.WriteGLES2InterfaceStub("client/gles2_interface_stub_autogen.h")
8526 gen.WriteGLES2InterfaceStubImpl(
8527 "client/gles2_interface_stub_impl_autogen.h")
8528 gen.WriteGLES2ImplementationHeader("client/gles2_implementation_autogen.h")
8529 gen.WriteGLES2Implementation("client/gles2_implementation_impl_autogen.h")
8530 gen.WriteGLES2ImplementationUnitTests(
8531 "client/gles2_implementation_unittest_autogen.h")
8532 gen.WriteGLES2TraceImplementationHeader(
8533 "client/gles2_trace_implementation_autogen.h")
8534 gen.WriteGLES2TraceImplementation(
8535 "client/gles2_trace_implementation_impl_autogen.h")
8536 gen.WriteGLES2CLibImplementation("client/gles2_c_lib_autogen.h")
8537 gen.WriteCmdHelperHeader("client/gles2_cmd_helper_autogen.h")
8538 gen.WriteServiceImplementation("service/gles2_cmd_decoder_autogen.h")
8539 gen.WriteServiceContextStateHeader("service/context_state_autogen.h")
8540 gen.WriteServiceContextStateImpl("service/context_state_impl_autogen.h")
8541 gen.WriteClientContextStateHeader("client/client_context_state_autogen.h")
8542 gen.WriteClientContextStateImpl(
8543 "client/client_context_state_impl_autogen.h")
8544 gen.WriteServiceUnitTests("service/gles2_cmd_decoder_unittest_%d_autogen.h")
8545 gen.WriteServiceUnitTestsForExtensions(
8546 "service/gles2_cmd_decoder_unittest_extensions_autogen.h")
8547 gen.WriteServiceUtilsHeader("service/gles2_cmd_validation_autogen.h")
8548 gen.WriteServiceUtilsImplementation(
8549 "service/gles2_cmd_validation_implementation_autogen.h")
8550 gen.WriteCommonUtilsHeader("common/gles2_cmd_utils_autogen.h")
8551 gen.WriteCommonUtilsImpl("common/gles2_cmd_utils_implementation_autogen.h")
8552 gen.WriteGLES2Header("../GLES2/gl2chromium_autogen.h")
8553 mojo_gles2_prefix = "../../mojo/public/c/gles2/gles2_call_visitor"
8554 gen.WriteMojoGLCallVisitor(mojo_gles2_prefix + "_autogen.h")
8555 gen.WriteMojoGLCallVisitorForExtension(
8556 mojo_gles2_prefix + "_chromium_texture_mailbox_autogen.h",
8557 "CHROMIUM_texture_mailbox")
8558 gen.WriteMojoGLCallVisitorForExtension(
8559 mojo_gles2_prefix + "_chromium_sync_point_autogen.h",
8560 "CHROMIUM_sync_point")
8562 Format([
8563 "common/gles2_cmd_format_autogen.h",
8564 "common/gles2_cmd_format_test_autogen.h",
8565 "common/gles2_cmd_ids_autogen.h",
8566 "common/gles2_cmd_utils_autogen.h",
8567 "common/gles2_cmd_utils_implementation_autogen.h",
8568 "client/client_context_state_autogen.h",
8569 "client/client_context_state_impl_autogen.h",
8570 "client/gles2_cmd_helper_autogen.h",
8571 "client/gles2_c_lib_autogen.h",
8572 "client/gles2_implementation_autogen.h",
8573 "client/gles2_implementation_impl_autogen.h",
8574 "client/gles2_implementation_unittest_autogen.h",
8575 "client/gles2_interface_autogen.h",
8576 "client/gles2_interface_stub_autogen.h",
8577 "client/gles2_interface_stub_impl_autogen.h",
8578 "client/gles2_trace_implementation_autogen.h",
8579 "client/gles2_trace_implementation_impl_autogen.h",
8580 "service/context_state_autogen.h",
8581 "service/context_state_impl_autogen.h",
8582 "service/gles2_cmd_decoder_autogen.h",
8583 "service/gles2_cmd_decoder_unittest_0_autogen.h",
8584 "service/gles2_cmd_decoder_unittest_1_autogen.h",
8585 "service/gles2_cmd_decoder_unittest_2_autogen.h",
8586 "service/gles2_cmd_decoder_unittest_3_autogen.h",
8587 "service/gles2_cmd_validation_autogen.h",
8588 "service/gles2_cmd_validation_implementation_autogen.h"])
8589 os.chdir("../..")
8590 mojo_gles2_prefix = "mojo/public/c/gles2/gles2_call_visitor"
8591 Format([
8592 "gpu/GLES2/gl2chromium_autogen.h",
8593 mojo_gles2_prefix + "_autogen.h",
8594 mojo_gles2_prefix + "_chromium_texture_mailbox_autogen.h",
8595 mojo_gles2_prefix + "_chromium_sync_point_autogen.h",
8596 "ppapi/c/dev/ppb_opengles2ext_dev.h",
8597 "ppapi/c/ppb_opengles2.h",
8598 "ppapi/lib/gl/gles2/gles2.c",
8599 "ppapi/shared_impl/ppb_opengles2_shared.cc"])
8601 if gen.errors > 0:
8602 print "%d errors" % gen.errors
8603 return 1
8604 return 0
8607 if __name__ == '__main__':
8608 sys.exit(main(sys.argv[1:]))